libcoap 4.3.5-develop-72190a8
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-2024 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#ifdef HAVE_SYS_SELECT_H
23# include <sys/select.h>
24#endif
25#ifdef HAVE_SYS_SOCKET_H
26# include <sys/socket.h>
27# define OPTVAL_T(t) (t)
28# define OPTVAL_GT(t) (t)
29#endif
30#ifdef HAVE_SYS_IOCTL_H
31#include <sys/ioctl.h>
32#endif
33#ifdef HAVE_NETINET_IN_H
34# include <netinet/in.h>
35#endif
36#ifdef HAVE_WS2TCPIP_H
37#include <ws2tcpip.h>
38# define OPTVAL_T(t) (const char*)(t)
39# define OPTVAL_GT(t) (char*)(t)
40# undef CMSG_DATA
41# define CMSG_DATA WSA_CMSG_DATA
42#endif
43#ifdef HAVE_SYS_UIO_H
44# include <sys/uio.h>
45#endif
46#ifdef HAVE_UNISTD_H
47# include <unistd.h>
48#endif
49#ifdef COAP_EPOLL_SUPPORT
50#include <sys/epoll.h>
51#include <sys/timerfd.h>
52#ifdef HAVE_LIMITS_H
53#include <limits.h>
54#endif
55#endif /* COAP_EPOLL_SUPPORT */
56
57#if !defined(WITH_CONTIKI) && !defined(RIOT_VERSION) && !defined(WITH_LWIP)
58/* define generic PKTINFO for IPv4 */
59#if defined(IP_PKTINFO)
60# define GEN_IP_PKTINFO IP_PKTINFO
61#elif defined(IP_RECVDSTADDR)
62# define GEN_IP_PKTINFO IP_RECVDSTADDR
63#else
64# error "Need IP_PKTINFO or IP_RECVDSTADDR to request ancillary data from OS."
65#endif /* IP_PKTINFO */
66
67/* define generic PKTINFO for IPv6 */
68#ifdef IPV6_RECVPKTINFO
69# define GEN_IPV6_PKTINFO IPV6_RECVPKTINFO
70#elif defined(IPV6_PKTINFO)
71# define GEN_IPV6_PKTINFO IPV6_PKTINFO
72#else
73# error "Need IPV6_PKTINFO or IPV6_RECVPKTINFO to request ancillary data from OS."
74#endif /* IPV6_RECVPKTINFO */
75#endif /* ! WITH_CONTIKI && ! RIOT_VERSION && ! WITH_LWIP */
76
77#if COAP_SERVER_SUPPORT
81}
82
83void
86}
87#endif /* COAP_SERVER_SUPPORT */
88
89#if defined(__MINGW32__)
90#if(_WIN32_WINNT >= 0x0600)
91#define CMSG_FIRSTHDR WSA_CMSG_FIRSTHDR
92#define CMSG_NXTHDR WSA_CMSG_NXTHDR
93#define CMSG_LEN WSA_CMSG_LEN
94#define CMSG_SPACE WSA_CMSG_SPACE
95#define cmsghdr _WSACMSGHDR
96#endif /* (_WIN32_WINNT>=0x0600) */
97#endif /* defined(__MINGW32__) */
98
99#if !defined(WITH_CONTIKI) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
100
101#if COAP_SERVER_SUPPORT
102int
104 const coap_address_t *listen_addr,
105 coap_address_t *bound_addr) {
106#ifndef RIOT_VERSION
107 int on = 1;
108#if COAP_IPV6_SUPPORT
109 int off = 0;
110#endif /* COAP_IPV6_SUPPORT */
111#else /* ! RIOT_VERSION */
112 struct timeval timeout = {0, 0};
113#endif /* ! RIOT_VERSION */
114#ifdef _WIN32
115 u_long u_on = 1;
116#endif
117
118 sock->fd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
119
120 if (sock->fd == COAP_INVALID_SOCKET) {
121 coap_log_warn("coap_socket_bind_udp: socket: %s\n", coap_socket_strerror());
122 goto error;
123 }
124#ifndef RIOT_VERSION
125#ifdef _WIN32
126 if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR)
127#else
128 if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR)
129#endif
130 {
131 coap_log_warn("coap_socket_bind_udp: ioctl FIONBIO: %s\n", coap_socket_strerror());
132 }
133
134 if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
135 coap_log_warn("coap_socket_bind_udp: setsockopt SO_REUSEADDR: %s\n",
137
138 switch (listen_addr->addr.sa.sa_family) {
139#if COAP_IPV4_SUPPORT
140 case AF_INET:
141 if (setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on),
142 sizeof(on)) == COAP_SOCKET_ERROR)
143 coap_log_alert("coap_socket_bind_udp: setsockopt IP_PKTINFO: %s\n",
145 break;
146#endif /* COAP_IPV4_SUPPORT */
147#if COAP_IPV6_SUPPORT
148 case AF_INET6:
149 /* Configure the socket as dual-stacked */
150 if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off),
151 sizeof(off)) == COAP_SOCKET_ERROR)
152 coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_V6ONLY: %s\n",
154#if !defined(ESPIDF_VERSION)
155 if (setsockopt(sock->fd, IPPROTO_IPV6, GEN_IPV6_PKTINFO, OPTVAL_T(&on),
156 sizeof(on)) == COAP_SOCKET_ERROR)
157 coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_PKTINFO: %s\n",
159#endif /* !defined(ESPIDF_VERSION) */
160#endif /* COAP_IPV6_SUPPORT */
161 setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on));
162 /* ignore error, because likely cause is that IPv4 is disabled at the os
163 level */
164 break;
165#if COAP_AF_UNIX_SUPPORT
166 case AF_UNIX:
167 break;
168#endif /* COAP_AF_UNIX_SUPPORT */
169 default:
170 coap_log_alert("coap_socket_bind_udp: unsupported sa_family\n");
171 break;
172 }
173#else /* RIOT_VERSION */
174 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVTIMEO, OPTVAL_T(&timeout),
175 (socklen_t)sizeof(timeout)) == COAP_SOCKET_ERROR)
176 coap_log_alert("coap_socket_bind_udp: setsockopt SO_RCVTIMEO: %s\n",
178#endif /* RIOT_VERSION */
179
180 if (bind(sock->fd, &listen_addr->addr.sa,
182 listen_addr->addr.sa.sa_family == AF_INET ?
183 (socklen_t)sizeof(struct sockaddr_in) :
184#endif /* COAP_IPV4_SUPPORT */
185 (socklen_t)listen_addr->size) == COAP_SOCKET_ERROR) {
186 coap_log_warn("coap_socket_bind_udp: bind: %s\n",
188 goto error;
189 }
190
191 bound_addr->size = (socklen_t)sizeof(*bound_addr);
192 if (getsockname(sock->fd, &bound_addr->addr.sa, &bound_addr->size) < 0) {
193 coap_log_warn("coap_socket_bind_udp: getsockname: %s\n",
195 goto error;
196 }
197#if defined(RIOT_VERSION) && defined(COAP_SERVER_SUPPORT)
198 if (sock->endpoint &&
199 bound_addr->addr.sa.sa_family == AF_INET6) {
200 bound_addr->addr.sin6.sin6_scope_id =
201 listen_addr->addr.sin6.sin6_scope_id;
202 bound_addr->addr.sin6.sin6_flowinfo = 0;
203 }
204#endif /* RIOT_VERSION && COAP_SERVER_SUPPORT */
205
206 return 1;
207
208error:
209 coap_socket_close(sock);
210 return 0;
211}
212#endif /* COAP_SERVER_SUPPORT */
213
214#if COAP_CLIENT_SUPPORT
215int
217 const coap_address_t *local_if,
218 const coap_address_t *server,
219 int default_port,
220 coap_address_t *local_addr,
221 coap_address_t *remote_addr) {
222 int on = 1;
223#if COAP_IPV6_SUPPORT
224 int off = 0;
225#endif /* COAP_IPV6_SUPPORT */
226#ifdef _WIN32
227 u_long u_on = 1;
228#endif
229 coap_address_t connect_addr;
230 int is_mcast = coap_is_mcast(server);
231 coap_address_copy(&connect_addr, server);
232
234 sock->fd = socket(connect_addr.addr.sa.sa_family, SOCK_DGRAM, 0);
235
236 if (sock->fd == COAP_INVALID_SOCKET) {
237 coap_log_warn("coap_socket_connect_udp: socket: %s\n",
239 goto error;
240 }
241
242#ifdef _WIN32
243 if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR)
244#else
245 if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR)
246#endif
247 {
248 coap_log_warn("coap_socket_connect_udp: ioctl FIONBIO: %s\n",
250 }
251
252 switch (connect_addr.addr.sa.sa_family) {
253#if COAP_IPV4_SUPPORT
254 case AF_INET:
255 if (connect_addr.addr.sin.sin_port == 0)
256 connect_addr.addr.sin.sin_port = htons(default_port);
257 break;
258#endif /* COAP_IPV4_SUPPORT */
259#if COAP_IPV6_SUPPORT
260 case AF_INET6:
261 if (connect_addr.addr.sin6.sin6_port == 0)
262 connect_addr.addr.sin6.sin6_port = htons(default_port);
263 /* Configure the socket as dual-stacked */
264 if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off),
265 sizeof(off)) == COAP_SOCKET_ERROR)
266 coap_log_warn("coap_socket_connect_udp: setsockopt IPV6_V6ONLY: %s\n",
268#endif /* COAP_IPV6_SUPPORT */
269 break;
270#if COAP_AF_UNIX_SUPPORT
271 case AF_UNIX:
272 break;
273#endif /* COAP_AF_UNIX_SUPPORT */
274 default:
275 coap_log_alert("coap_socket_connect_udp: unsupported sa_family %d\n",
276 connect_addr.addr.sa.sa_family);
277 goto error;;
278 }
279
280 if (local_if && local_if->addr.sa.sa_family) {
281 if (local_if->addr.sa.sa_family != connect_addr.addr.sa.sa_family) {
282 coap_log_warn("coap_socket_connect_udp: local address family != "
283 "remote address family\n");
284 goto error;
285 }
286 if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
287 coap_log_warn("coap_socket_connect_udp: setsockopt SO_REUSEADDR: %s\n",
289 if (bind(sock->fd, &local_if->addr.sa,
291 local_if->addr.sa.sa_family == AF_INET ?
292 (socklen_t)sizeof(struct sockaddr_in) :
293#endif /* COAP_IPV4_SUPPORT */
294 (socklen_t)local_if->size) == COAP_SOCKET_ERROR) {
295 coap_log_warn("coap_socket_connect_udp: bind: %s\n",
297 goto error;
298 }
299#if COAP_AF_UNIX_SUPPORT
300 } else if (connect_addr.addr.sa.sa_family == AF_UNIX) {
301 /* Need to bind to a local address for clarity over endpoints */
302 coap_log_warn("coap_socket_connect_udp: local address required\n");
303 goto error;
304#endif /* COAP_AF_UNIX_SUPPORT */
305 }
306
307 /* special treatment for sockets that are used for multicast communication */
308 if (is_mcast) {
309 if (!(local_if && local_if->addr.sa.sa_family)) {
310 /* Bind to a (unused) port to simplify logging */
311 coap_address_t bind_addr;
312
313 coap_address_init(&bind_addr);
314 bind_addr.addr.sa.sa_family = connect_addr.addr.sa.sa_family;
315 if (bind(sock->fd, &bind_addr.addr.sa,
317 bind_addr.addr.sa.sa_family == AF_INET ?
318 (socklen_t)sizeof(struct sockaddr_in) :
319#endif /* COAP_IPV4_SUPPORT */
320 (socklen_t)bind_addr.size) == COAP_SOCKET_ERROR) {
321 coap_log_warn("coap_socket_connect_udp: bind: %s\n",
323 goto error;
324 }
325 }
326 if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) {
327 coap_log_warn("coap_socket_connect_udp: getsockname for multicast socket: %s\n",
329 }
330 coap_address_copy(remote_addr, &connect_addr);
331 coap_address_copy(&sock->mcast_addr, &connect_addr);
333 if (coap_is_bcast(server) &&
334 setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, OPTVAL_T(&on),
335 sizeof(on)) == COAP_SOCKET_ERROR)
336 coap_log_warn("coap_socket_connect_udp: setsockopt SO_BROADCAST: %s\n",
338 return 1;
339 }
340
341 if (connect(sock->fd, &connect_addr.addr.sa, connect_addr.size) == COAP_SOCKET_ERROR) {
342#if COAP_AF_UNIX_SUPPORT
343 if (connect_addr.addr.sa.sa_family == AF_UNIX) {
344 coap_log_warn("coap_socket_connect_udp: connect: %s: %s\n",
345 connect_addr.addr.cun.sun_path, coap_socket_strerror());
346 } else
347#endif /* COAP_AF_UNIX_SUPPORT */
348 {
349 coap_log_warn("coap_socket_connect_udp: connect: %s (%d)\n",
350 coap_socket_strerror(), connect_addr.addr.sa.sa_family);
351 }
352 goto error;
353 }
354
355 if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) {
356 coap_log_warn("coap_socket_connect_udp: getsockname: %s\n",
358 }
359
360 if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) {
361 coap_log_warn("coap_socket_connect_udp: getpeername: %s\n",
363 }
364
366 return 1;
367
368error:
369 coap_socket_close(sock);
370 return 0;
371}
372#endif /* COAP_CLIENT_SUPPORT */
373
374void
376 if (sock->fd != COAP_INVALID_SOCKET) {
377#ifdef COAP_EPOLL_SUPPORT
378#if COAP_SERVER_SUPPORT
379 coap_context_t *context = sock->session ? sock->session->context :
380 sock->endpoint ? sock->endpoint->context : NULL;
381#else /* COAP_SERVER_SUPPORT */
382 coap_context_t *context = sock->session ? sock->session->context : NULL;
383#endif /* COAP_SERVER_SUPPORT */
384 if (context != NULL) {
385 int ret;
386 struct epoll_event event;
387
388 /* Kernels prior to 2.6.9 expect non NULL event parameter */
389 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, sock->fd, &event);
390 if (ret == -1 && errno != ENOENT) {
391 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
392 "coap_socket_close",
393 coap_socket_strerror(), errno);
394 }
395 }
396#if COAP_SERVER_SUPPORT
397#if COAP_AF_UNIX_SUPPORT
398 if (sock->endpoint &&
399 sock->endpoint->bind_addr.addr.sa.sa_family == AF_UNIX) {
400 /* Clean up Unix endpoint */
401 unlink(sock->endpoint->bind_addr.addr.cun.sun_path);
402 }
403#endif /* COAP_AF_UNIX_SUPPORT */
404 sock->endpoint = NULL;
405#endif /* COAP_SERVER_SUPPORT */
406#if COAP_CLIENT_SUPPORT
407#if COAP_AF_UNIX_SUPPORT
408 if (sock->session && sock->session->type == COAP_SESSION_TYPE_CLIENT &&
409 sock->session->addr_info.local.addr.sa.sa_family == AF_UNIX) {
410 /* Clean up Unix endpoint */
411 unlink(sock->session->addr_info.local.addr.cun.sun_path);
412 }
413#endif /* COAP_AF_UNIX_SUPPORT */
414#endif /* COAP_CLIENT_SUPPORT */
415 sock->session = NULL;
416#endif /* COAP_EPOLL_SUPPORT */
417 coap_closesocket(sock->fd);
418 sock->fd = COAP_INVALID_SOCKET;
419 }
420 sock->flags = COAP_SOCKET_EMPTY;
421}
422
423#ifdef COAP_EPOLL_SUPPORT
424void
426 uint32_t events,
427 const char *func) {
428 int ret;
429 struct epoll_event event;
430 coap_context_t *context;
431
432#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR
433 (void)func;
434#endif
435
436 if (sock == NULL)
437 return;
438
439#if COAP_SERVER_SUPPORT
440 context = sock->session ? sock->session->context :
441 sock->endpoint ? sock->endpoint->context : NULL;
442#else /* ! COAP_SERVER_SUPPORT */
443 context = sock->session ? sock->session->context : NULL;
444#endif /* ! COAP_SERVER_SUPPORT */
445 if (context == NULL)
446 return;
447
448 /* Needed if running 32bit as ptr is only 32bit */
449 memset(&event, 0, sizeof(event));
450 event.events = events;
451 event.data.ptr = sock;
452
453 ret = epoll_ctl(context->epfd, EPOLL_CTL_ADD, sock->fd, &event);
454 if (ret == -1) {
455 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
456 func,
457 coap_socket_strerror(), errno);
458 }
459}
460
461void
463 uint32_t events,
464 const char *func) {
465 int ret;
466 struct epoll_event event;
467 coap_context_t *context;
468
469#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR
470 (void)func;
471#endif
472
473 if (sock == NULL)
474 return;
475
476#if COAP_SERVER_SUPPORT
477 context = sock->session ? sock->session->context :
478 sock->endpoint ? sock->endpoint->context : NULL;
479#else /* COAP_SERVER_SUPPORT */
480 context = sock->session ? sock->session->context : NULL;
481#endif /* COAP_SERVER_SUPPORT */
482 if (context == NULL)
483 return;
484
485 event.events = events;
486 event.data.ptr = sock;
487
488 ret = epoll_ctl(context->epfd, EPOLL_CTL_MOD, sock->fd, &event);
489 if (ret == -1) {
490#if (COAP_MAX_LOGGING_LEVEL < COAP_LOG_ERR)
491 (void)func;
492#endif
493 coap_log_err("%s: epoll_ctl MOD failed: %s (%d)\n",
494 func,
495 coap_socket_strerror(), errno);
496 }
497}
498#endif /* COAP_EPOLL_SUPPORT */
499
500#endif /* ! WITH_CONTIKI && ! WITH_LWIP && ! RIOT_VERSION*/
501
502#ifndef WITH_CONTIKI
503void
505#if COAP_EPOLL_SUPPORT
506 if (context->eptimerfd != -1) {
507 coap_tick_t now;
508
509 coap_ticks(&now);
510 if (context->next_timeout == 0 || context->next_timeout > now + delay) {
511 struct itimerspec new_value;
512 int ret;
513
514 context->next_timeout = now + delay;
515 memset(&new_value, 0, sizeof(new_value));
516 if (delay == 0) {
517 new_value.it_value.tv_nsec = 1; /* small but not zero */
518 } else {
519 new_value.it_value.tv_sec = delay / COAP_TICKS_PER_SECOND;
520 new_value.it_value.tv_nsec = (delay % COAP_TICKS_PER_SECOND) *
521 1000000;
522 }
523 ret = timerfd_settime(context->eptimerfd, 0, &new_value, NULL);
524 if (ret == -1) {
525 coap_log_err("%s: timerfd_settime failed: %s (%d)\n",
526 "coap_update_io_timer",
527 coap_socket_strerror(), errno);
528 }
529#ifdef COAP_DEBUG_WAKEUP_TIMES
530 else {
531 coap_log_debug("****** Next wakeup time %3ld.%09ld\n",
532 new_value.it_value.tv_sec, new_value.it_value.tv_nsec);
533 }
534#endif /* COAP_DEBUG_WAKEUP_TIMES */
535 }
536 }
537#else /* ! COAP_EPOLL_SUPPORT */
538 coap_tick_t now;
539
540 coap_ticks(&now);
541 if (context->next_timeout == 0 || context->next_timeout > now + delay) {
542 context->next_timeout = now + delay;
543 }
544#endif /* ! COAP_EPOLL_SUPPORT */
545}
546#endif /* ! WITH_CONTIKI */
547
548#if !defined(WITH_CONTIKI) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
549
550#ifdef _WIN32
551static void
552coap_win_error_to_errno(void) {
553 int w_error = WSAGetLastError();
554 switch (w_error) {
555 case WSA_NOT_ENOUGH_MEMORY:
556 errno = ENOMEM;
557 break;
558 case WSA_INVALID_PARAMETER:
559 errno = EINVAL;
560 break;
561 case WSAEINTR:
562 errno = EINTR;
563 break;
564 case WSAEBADF:
565 errno = EBADF;
566 break;
567 case WSAEACCES:
568 errno = EACCES;
569 break;
570 case WSAEFAULT:
571 errno = EFAULT;
572 break;
573 case WSAEINVAL:
574 errno = EINVAL;
575 break;
576 case WSAEMFILE:
577 errno = EMFILE;
578 break;
579 case WSAEWOULDBLOCK:
580 errno = EWOULDBLOCK;
581 break;
582 case WSAENETDOWN:
583 errno = ENETDOWN;
584 break;
585 case WSAENETUNREACH:
586 errno = ENETUNREACH;
587 break;
588 case WSAENETRESET:
589 errno = ENETRESET;
590 break;
591 case WSAECONNABORTED:
592 errno = ECONNABORTED;
593 break;
594 case WSAECONNRESET:
595 errno = ECONNRESET;
596 break;
597 case WSAENOBUFS:
598 errno = ENOBUFS;
599 break;
600 case WSAETIMEDOUT:
601 errno = ETIMEDOUT;
602 break;
603 case WSAECONNREFUSED:
604 errno = ECONNREFUSED;
605 break;
606 default:
607 coap_log_err("WSAGetLastError: %d mapping to errno failed - please fix\n",
608 w_error);
609 errno = EPERM;
610 break;
611 }
612}
613#endif /* _WIN32 */
614
615/*
616 * strm
617 * return +ve Number of bytes written.
618 * 0 No data written.
619 * -1 Error (error in errno).
620 */
621ssize_t
622coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) {
623 ssize_t r;
624
626#ifdef _WIN32
627 r = send(sock->fd, (const char *)data, (int)data_len, 0);
628#else
629#ifndef MSG_NOSIGNAL
630#define MSG_NOSIGNAL 0
631#endif /* MSG_NOSIGNAL */
632 r = send(sock->fd, data, data_len, MSG_NOSIGNAL);
633#endif
634 if (r == COAP_SOCKET_ERROR) {
635#ifdef _WIN32
636 coap_win_error_to_errno();
637#endif /* _WIN32 */
638 if (errno==EAGAIN ||
639#if EAGAIN != EWOULDBLOCK
640 errno == EWOULDBLOCK ||
641#endif
642 errno == EINTR) {
644#ifdef COAP_EPOLL_SUPPORT
646 EPOLLOUT |
647 ((sock->flags & COAP_SOCKET_WANT_READ) ?
648 EPOLLIN : 0),
649 __func__);
650#endif /* COAP_EPOLL_SUPPORT */
651 return 0;
652 }
653 if (errno == EPIPE || errno == ECONNRESET) {
654 coap_log_info("coap_socket_write: send: %s\n",
656 } else {
657 coap_log_warn("coap_socket_write: send: %s\n",
659 }
660 return -1;
661 }
662 if (r < (ssize_t)data_len) {
664#ifdef COAP_EPOLL_SUPPORT
666 EPOLLOUT |
667 ((sock->flags & COAP_SOCKET_WANT_READ) ?
668 EPOLLIN : 0),
669 __func__);
670#endif /* COAP_EPOLL_SUPPORT */
671 }
672 return r;
673}
674
675/*
676 * strm
677 * return >=0 Number of bytes read.
678 * -1 Error (error in errno).
679 */
680ssize_t
681coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) {
682 ssize_t r;
683
684#ifdef _WIN32
685 r = recv(sock->fd, (char *)data, (int)data_len, 0);
686#else
687 r = recv(sock->fd, data, data_len, 0);
688#endif
689 if (r == 0) {
690 /* graceful shutdown */
691 sock->flags &= ~COAP_SOCKET_CAN_READ;
692 errno = ECONNRESET;
693 return -1;
694 } else if (r == COAP_SOCKET_ERROR) {
695 sock->flags &= ~COAP_SOCKET_CAN_READ;
696#ifdef _WIN32
697 coap_win_error_to_errno();
698#endif /* _WIN32 */
699 if (errno==EAGAIN ||
700#if EAGAIN != EWOULDBLOCK
701 errno == EWOULDBLOCK ||
702#endif
703 errno == EINTR) {
704 return 0;
705 }
706 if (errno != ECONNRESET) {
707 coap_log_warn("coap_socket_read: recv: %s\n",
709 }
710 return -1;
711 }
712 if (r < (ssize_t)data_len)
713 sock->flags &= ~COAP_SOCKET_CAN_READ;
714 return r;
715}
716
717#endif /* ! WITH_CONTIKI && ! WITH_LWIP && ! RIOT_VERSION */
718
719#if !defined(WITH_LWIP)
720#if (!defined(WITH_CONTIKI)) != ( defined(HAVE_NETINET_IN_H) || defined(HAVE_WS2TCPIP_H) )
721/* define struct in6_pktinfo and struct in_pktinfo if not available
722 FIXME: check with configure
723*/
724#if !defined(__MINGW32__) && !defined(RIOT_VERSION)
726 struct in6_addr ipi6_addr; /* src/dst IPv6 address */
727 unsigned int ipi6_ifindex; /* send/recv interface index */
728};
729
732 struct in_addr ipi_spec_dst;
733 struct in_addr ipi_addr;
734};
735#endif /* ! __MINGW32__ */
736#endif
737#endif /* ! WITH_LWIP */
738
739#if !defined(WITH_CONTIKI) && !defined(SOL_IP)
740/* Solaris expects level IPPROTO_IP for ancillary data. */
741#define SOL_IP IPPROTO_IP
742#endif
743#ifdef _WIN32
744#define COAP_SOL_IP IPPROTO_IP
745#else /* ! _WIN32 */
746#define COAP_SOL_IP SOL_IP
747#endif /* ! _WIN32 */
748
749#if defined(_WIN32)
750#include <mswsock.h>
751#if defined(__MINGW32__)
752static __thread LPFN_WSARECVMSG lpWSARecvMsg = NULL;
753#else /* ! __MINGW32__ */
754static __declspec(thread) LPFN_WSARECVMSG lpWSARecvMsg = NULL;
755#endif /* ! __MINGW32__ */
756/* Map struct WSABUF fields to their posix counterpart */
757#define msghdr _WSAMSG
758#define msg_name name
759#define msg_namelen namelen
760#define msg_iov lpBuffers
761#define msg_iovlen dwBufferCount
762#define msg_control Control.buf
763#define msg_controllen Control.len
764#define iovec _WSABUF
765#define iov_base buf
766#define iov_len len
767#define iov_len_t u_long
768#undef CMSG_DATA
769#define CMSG_DATA WSA_CMSG_DATA
770#define ipi_spec_dst ipi_addr
771#if !defined(__MINGW32__)
772#pragma warning( disable : 4116 )
773#endif /* ! __MINGW32__ */
774#else
775#define iov_len_t size_t
776#endif
777
778#if defined(_CYGWIN_ENV) || defined(__QNXNTO__)
779#define ipi_spec_dst ipi_addr
780#endif
781
782#if !defined(RIOT_VERSION) && !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
783#if COAP_CLIENT_SUPPORT
784static uint32_t cid_track_counter;
785
786static void
787coap_test_cid_tuple_change(coap_session_t *session) {
788 if (session->type == COAP_SESSION_TYPE_CLIENT &&
789 session->negotiated_cid &&
791 session->proto == COAP_PROTO_DTLS && session->context->testing_cids) {
792 if ((++cid_track_counter) % session->context->testing_cids == 0) {
793 coap_address_t local_if = session->addr_info.local;
794 uint16_t port = coap_address_get_port(&local_if);
795
796 port++;
797 coap_address_set_port(&local_if, port);
798
799 coap_socket_close(&session->sock);
800 session->sock.session = session;
801 if (!coap_socket_connect_udp(&session->sock, &local_if, &session->addr_info.remote,
802 port,
803 &session->addr_info.local,
804 &session->addr_info.remote)) {
805 coap_log_err("Tuple change for CID failed\n");
806 return;
807#ifdef COAP_EPOLL_SUPPORT
808 } else {
809 coap_epoll_ctl_add(&session->sock,
810 EPOLLIN |
811 ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ?
812 EPOLLOUT : 0),
813 __func__);
814#endif /* COAP_EPOLL_SUPPORT */
815 }
817 }
818 }
819}
820#endif /* COAP_CLIENT_SUPPORT */
821
822/*
823 * dgram
824 * return +ve Number of bytes written.
825 * -1 Error error in errno).
826 */
827ssize_t
829 const uint8_t *data, size_t datalen) {
830 ssize_t bytes_written = 0;
831
832#if COAP_CLIENT_SUPPORT
833 coap_test_cid_tuple_change(session);
834#endif /* COAP_CLIENT_SUPPORT */
835
836 if (!coap_debug_send_packet()) {
837 bytes_written = (ssize_t)datalen;
838 } else if (sock->flags & COAP_SOCKET_CONNECTED) {
839#ifdef _WIN32
840 bytes_written = send(sock->fd, (const char *)data, (int)datalen, 0);
841#else
842 bytes_written = send(sock->fd, data, datalen, 0);
843#endif
844 } else {
845#if defined(_WIN32)
846 DWORD dwNumberOfBytesSent = 0;
847 int r;
848#endif /* _WIN32 && !__MINGW32__ */
849#ifdef HAVE_STRUCT_CMSGHDR
850 /* a buffer large enough to hold all packet info types, ipv6 is the largest */
851 char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
852 struct msghdr mhdr;
853 struct iovec iov[1];
854 const void *addr = &session->addr_info.remote.addr;
855
856 assert(session);
857
858 memcpy(&iov[0].iov_base, &data, sizeof(iov[0].iov_base));
859 iov[0].iov_len = (iov_len_t)datalen;
860
861 memset(buf, 0, sizeof(buf));
862
863 memset(&mhdr, 0, sizeof(struct msghdr));
864 memcpy(&mhdr.msg_name, &addr, sizeof(mhdr.msg_name));
865 mhdr.msg_namelen = session->addr_info.remote.addr.sa.sa_family == AF_INET ?
866 (socklen_t)sizeof(struct sockaddr_in) :
867 session->addr_info.remote.size;
868
869 mhdr.msg_iov = iov;
870 mhdr.msg_iovlen = 1;
871
872 if (!coap_address_isany(&session->addr_info.local) &&
873 !coap_is_mcast(&session->addr_info.local)) {
874 switch (session->addr_info.local.addr.sa.sa_family) {
875#if COAP_IPV6_SUPPORT
876 case AF_INET6: {
877 struct cmsghdr *cmsg;
878
879#if COAP_IPV4_SUPPORT
880 if (IN6_IS_ADDR_V4MAPPED(&session->addr_info.local.addr.sin6.sin6_addr)) {
881#if defined(IP_PKTINFO)
882 struct in_pktinfo *pktinfo;
883 mhdr.msg_control = buf;
884 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
885
886 cmsg = CMSG_FIRSTHDR(&mhdr);
887 cmsg->cmsg_level = COAP_SOL_IP;
888 cmsg->cmsg_type = IP_PKTINFO;
889 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
890
891 pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
892
893 pktinfo->ipi_ifindex = session->ifindex;
894 memcpy(&pktinfo->ipi_spec_dst,
895 session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
896 sizeof(pktinfo->ipi_spec_dst));
897#elif defined(IP_SENDSRCADDR)
898 mhdr.msg_control = buf;
899 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
900
901 cmsg = CMSG_FIRSTHDR(&mhdr);
902 cmsg->cmsg_level = IPPROTO_IP;
903 cmsg->cmsg_type = IP_SENDSRCADDR;
904 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
905
906 memcpy(CMSG_DATA(cmsg),
907 session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
908 sizeof(struct in_addr));
909#endif /* IP_PKTINFO */
910 } else {
911#endif /* COAP_IPV4_SUPPORT */
912 struct in6_pktinfo *pktinfo;
913 mhdr.msg_control = buf;
914 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
915
916 cmsg = CMSG_FIRSTHDR(&mhdr);
917 cmsg->cmsg_level = IPPROTO_IPV6;
918 cmsg->cmsg_type = IPV6_PKTINFO;
919 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
920
921 pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
922
923 pktinfo->ipi6_ifindex = session->ifindex;
924 memcpy(&pktinfo->ipi6_addr,
925 &session->addr_info.local.addr.sin6.sin6_addr,
926 sizeof(pktinfo->ipi6_addr));
927#if COAP_IPV4_SUPPORT
928 }
929#endif /* COAP_IPV4_SUPPORT */
930 break;
931 }
932#endif /* COAP_IPV6_SUPPORT */
933#if COAP_IPV4_SUPPORT
934 case AF_INET: {
935#if defined(IP_PKTINFO)
936 struct cmsghdr *cmsg;
937 struct in_pktinfo *pktinfo;
938
939 mhdr.msg_control = buf;
940 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
941
942 cmsg = CMSG_FIRSTHDR(&mhdr);
943 cmsg->cmsg_level = COAP_SOL_IP;
944 cmsg->cmsg_type = IP_PKTINFO;
945 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
946
947 pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
948
949 pktinfo->ipi_ifindex = session->ifindex;
950 memcpy(&pktinfo->ipi_spec_dst,
951 &session->addr_info.local.addr.sin.sin_addr,
952 sizeof(pktinfo->ipi_spec_dst));
953#elif defined(IP_SENDSRCADDR)
954 struct cmsghdr *cmsg;
955 mhdr.msg_control = buf;
956 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
957
958 cmsg = CMSG_FIRSTHDR(&mhdr);
959 cmsg->cmsg_level = IPPROTO_IP;
960 cmsg->cmsg_type = IP_SENDSRCADDR;
961 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
962
963 memcpy(CMSG_DATA(cmsg),
964 &session->addr_info.local.addr.sin.sin_addr,
965 sizeof(struct in_addr));
966#endif /* IP_PKTINFO */
967 break;
968 }
969#endif /* COAP_IPV4_SUPPORT */
970#if COAP_AF_UNIX_SUPPORT
971 case AF_UNIX:
972 break;
973#endif /* COAP_AF_UNIX_SUPPORT */
974 default:
975 /* error */
976 coap_log_warn("protocol not supported\n");
977 return -1;
978 }
979 }
980#endif /* HAVE_STRUCT_CMSGHDR */
981
982#if defined(_WIN32)
983 r = WSASendMsg(sock->fd, &mhdr, 0 /*dwFlags*/, &dwNumberOfBytesSent, NULL /*lpOverlapped*/,
984 NULL /*lpCompletionRoutine*/);
985 if (r == 0)
986 bytes_written = (ssize_t)dwNumberOfBytesSent;
987 else {
988 bytes_written = -1;
989 coap_win_error_to_errno();
990 }
991#else /* !_WIN32 || __MINGW32__ */
992#ifdef HAVE_STRUCT_CMSGHDR
993 bytes_written = sendmsg(sock->fd, &mhdr, 0);
994#else /* ! HAVE_STRUCT_CMSGHDR */
995 bytes_written = sendto(sock->fd, (const void *)data, datalen, 0,
996 &session->addr_info.remote.addr.sa,
997 session->addr_info.remote.size);
998#endif /* ! HAVE_STRUCT_CMSGHDR */
999#endif /* !_WIN32 || __MINGW32__ */
1000 }
1001
1002 if (bytes_written < 0)
1003 coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror());
1004
1005 return bytes_written;
1006}
1007#endif /* ! RIOT_VERSION && ! WITH_LWIP && ! WITH_CONTIKI */
1008
1009#define SIN6(A) ((struct sockaddr_in6 *)(A))
1010
1011void
1012coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length) {
1013 *address = packet->payload;
1014 *length = packet->length;
1015}
1016
1017#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) && !defined(RIOT_VERSION)
1018/*
1019 * dgram
1020 * return +ve Number of bytes written.
1021 * -1 Error error in errno).
1022 * -2 ICMP error response
1023 */
1024ssize_t
1026 ssize_t len = -1;
1027
1028 assert(sock);
1029 assert(packet);
1030
1031 if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) {
1032 return -1;
1033 } else {
1034 /* clear has-data flag */
1035 sock->flags &= ~COAP_SOCKET_CAN_READ;
1036 }
1037
1038 if (sock->flags & COAP_SOCKET_CONNECTED) {
1039#ifdef _WIN32
1040 len = recv(sock->fd, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0);
1041#else
1042 len = recv(sock->fd, packet->payload, COAP_RXBUFFER_SIZE, 0);
1043#endif
1044 if (len < 0) {
1045#ifdef _WIN32
1046 coap_win_error_to_errno();
1047#endif /* _WIN32 */
1048 if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) {
1049 /* client-side ICMP destination unreachable, ignore it */
1050 coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n",
1051 sock->session ?
1052 coap_session_str(sock->session) : "",
1054 return -2;
1055 }
1056 if (errno != EAGAIN) {
1057 coap_log_warn("** %s: coap_socket_recv: %s\n",
1058 sock->session ?
1059 coap_session_str(sock->session) : "",
1061 }
1062 goto error;
1063 } else if (len > 0) {
1064 packet->length = (size_t)len;
1065 }
1066 } else {
1067#if defined(_WIN32)
1068 DWORD dwNumberOfBytesRecvd = 0;
1069 int r;
1070#endif /* _WIN32 && !__MINGW32__ */
1071#ifdef HAVE_STRUCT_CMSGHDR
1072 /* a buffer large enough to hold all packet info types, ipv6 is the largest */
1073 char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
1074 struct cmsghdr *cmsg;
1075 struct msghdr mhdr;
1076 struct iovec iov[1];
1077
1078#if defined(__MINGW32__)
1079 iov[0].iov_base = (char *) packet->payload;
1080#else
1081 iov[0].iov_base = packet->payload;
1082#endif /* defined(__MINGW32__) */
1083 iov[0].iov_len = (iov_len_t)COAP_RXBUFFER_SIZE;
1084
1085 memset(&mhdr, 0, sizeof(struct msghdr));
1086
1087 mhdr.msg_name = (struct sockaddr *)&packet->addr_info.remote.addr;
1088 mhdr.msg_namelen = sizeof(packet->addr_info.remote.addr);
1089
1090 mhdr.msg_iov = iov;
1091 mhdr.msg_iovlen = 1;
1092
1093 mhdr.msg_control = buf;
1094 mhdr.msg_controllen = sizeof(buf);
1095 /* set a big first length incase recvmsg() does not implement updating
1096 msg_control as well as preset the first cmsg with bad data */
1097 cmsg = (struct cmsghdr *)buf;
1098 cmsg->cmsg_len = CMSG_LEN(sizeof(buf));
1099 cmsg->cmsg_level = -1;
1100 cmsg->cmsg_type = -1;
1101
1102#if defined(_WIN32)
1103 if (!lpWSARecvMsg) {
1104 GUID wsaid = WSAID_WSARECVMSG;
1105 DWORD cbBytesReturned = 0;
1106 if (WSAIoctl(sock->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &wsaid, sizeof(wsaid), &lpWSARecvMsg,
1107 sizeof(lpWSARecvMsg), &cbBytesReturned, NULL, NULL) != 0) {
1108 coap_log_warn("coap_socket_recv: no WSARecvMsg\n");
1109 return -1;
1110 }
1111 }
1112 r = lpWSARecvMsg(sock->fd, &mhdr, &dwNumberOfBytesRecvd, NULL /* LPWSAOVERLAPPED */,
1113 NULL /* LPWSAOVERLAPPED_COMPLETION_ROUTINE */);
1114 if (r == 0)
1115 len = (ssize_t)dwNumberOfBytesRecvd;
1116 else if (r == COAP_SOCKET_ERROR)
1117 coap_win_error_to_errno();
1118#else
1119 len = recvmsg(sock->fd, &mhdr, 0);
1120#endif
1121
1122#else /* ! HAVE_STRUCT_CMSGHDR */
1123 len = recvfrom(sock->fd, (void *)packet->payload, COAP_RXBUFFER_SIZE, 0,
1124 &packet->addr_info.remote.addr.sa,
1125 &packet->addr_info.remote.size);
1126#endif /* ! HAVE_STRUCT_CMSGHDR */
1127
1128 if (len < 0) {
1129#ifdef _WIN32
1130 coap_win_error_to_errno();
1131#endif /* _WIN32 */
1132 if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) {
1133 /* server-side ICMP destination unreachable, ignore it. The destination address is in msg_name. */
1134 coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n",
1135 sock->session ?
1136 coap_session_str(sock->session) : "",
1138 return 0;
1139 }
1140 if (errno != EAGAIN) {
1141 coap_log_warn("coap_socket_recv: %s\n", coap_socket_strerror());
1142 }
1143 goto error;
1144 } else {
1145#ifdef HAVE_STRUCT_CMSGHDR
1146 int dst_found = 0;
1147
1148 packet->addr_info.remote.size = mhdr.msg_namelen;
1149 packet->length = (size_t)len;
1150
1151 /* Walk through ancillary data records until the local interface
1152 * is found where the data was received. */
1153 for (cmsg = CMSG_FIRSTHDR(&mhdr); cmsg; cmsg = CMSG_NXTHDR(&mhdr, cmsg)) {
1154
1155#if COAP_IPV6_SUPPORT
1156 /* get the local interface for IPv6 */
1157 if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
1158 union {
1159 uint8_t *c;
1160 struct in6_pktinfo *p;
1161 } u;
1162 u.c = CMSG_DATA(cmsg);
1163 packet->ifindex = (int)(u.p->ipi6_ifindex);
1164 memcpy(&packet->addr_info.local.addr.sin6.sin6_addr,
1165 &u.p->ipi6_addr, sizeof(struct in6_addr));
1166 dst_found = 1;
1167 break;
1168 }
1169#endif /* COAP_IPV6_SUPPORT */
1170
1171#if COAP_IPV4_SUPPORT
1172 /* local interface for IPv4 */
1173#if defined(IP_PKTINFO)
1174 if (cmsg->cmsg_level == COAP_SOL_IP && cmsg->cmsg_type == IP_PKTINFO) {
1175 union {
1176 uint8_t *c;
1177 struct in_pktinfo *p;
1178 } u;
1179 u.c = CMSG_DATA(cmsg);
1180 packet->ifindex = u.p->ipi_ifindex;
1181#if COAP_IPV6_SUPPORT
1182 if (packet->addr_info.local.addr.sa.sa_family == AF_INET6) {
1183 memset(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr, 0, 10);
1184 packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[10] = 0xff;
1185 packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[11] = 0xff;
1186 memcpy(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
1187 &u.p->ipi_addr, sizeof(struct in_addr));
1188 } else
1189#endif /* COAP_IPV6_SUPPORT */
1190 {
1191 memcpy(&packet->addr_info.local.addr.sin.sin_addr,
1192 &u.p->ipi_addr, sizeof(struct in_addr));
1193 }
1194 dst_found = 1;
1195 break;
1196 }
1197#endif /* IP_PKTINFO */
1198#if defined(IP_RECVDSTADDR)
1199 if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR) {
1200 packet->ifindex = (int)sock->fd;
1201 memcpy(&packet->addr_info.local.addr.sin.sin_addr,
1202 CMSG_DATA(cmsg), sizeof(struct in_addr));
1203 dst_found = 1;
1204 break;
1205 }
1206#endif /* IP_RECVDSTADDR */
1207#endif /* COAP_IPV4_SUPPORT */
1208 if (!dst_found) {
1209 /* cmsg_level / cmsg_type combination we do not understand
1210 (ignore preset case for bad recvmsg() not updating cmsg) */
1211 if (cmsg->cmsg_level != -1 && cmsg->cmsg_type != -1) {
1212 coap_log_debug("cmsg_level = %d and cmsg_type = %d not supported - fix\n",
1213 cmsg->cmsg_level, cmsg->cmsg_type);
1214 }
1215 }
1216 }
1217 if (!dst_found) {
1218 /* Not expected, but cmsg_level and cmsg_type don't match above and
1219 may need a new case */
1220 packet->ifindex = (int)sock->fd;
1221 if (getsockname(sock->fd, &packet->addr_info.local.addr.sa,
1222 &packet->addr_info.local.size) < 0) {
1223 coap_log_debug("Cannot determine local port\n");
1224 }
1225 }
1226#else /* ! HAVE_STRUCT_CMSGHDR */
1227 packet->length = (size_t)len;
1228 packet->ifindex = 0;
1229 if (getsockname(sock->fd, &packet->addr_info.local.addr.sa,
1230 &packet->addr_info.local.size) < 0) {
1231 coap_log_debug("Cannot determine local port\n");
1232 goto error;
1233 }
1234#endif /* ! HAVE_STRUCT_CMSGHDR */
1235 }
1236 }
1237
1238 if (len >= 0)
1239 return len;
1240error:
1241 return -1;
1242}
1243#endif /* ! WITH_LWIP && ! WITH_CONTIKI && ! RIOT_VERSION */
1244
1245COAP_API unsigned int
1247 unsigned int ret;
1248
1249 coap_lock_lock(ctx, return 0);
1250 ret = coap_io_prepare_epoll_lkd(ctx, now);
1251 coap_lock_unlock(ctx);
1252 return ret;
1253}
1254
1255unsigned int
1257#ifndef COAP_EPOLL_SUPPORT
1258 (void)ctx;
1259 (void)now;
1260 coap_log_emerg("coap_io_prepare_epoll() requires libcoap compiled for using epoll\n");
1261 return 0;
1262#else /* COAP_EPOLL_SUPPORT */
1263 coap_socket_t *sockets[1];
1264 unsigned int max_sockets = sizeof(sockets)/sizeof(sockets[0]);
1265 unsigned int num_sockets;
1266 unsigned int timeout;
1267
1269 /* Use the common logic */
1270 timeout = coap_io_prepare_io_lkd(ctx, sockets, max_sockets, &num_sockets, now);
1271 /* Save when the next expected I/O is to take place */
1272 ctx->next_timeout = timeout ? now + timeout : 0;
1273 if (ctx->eptimerfd != -1) {
1274 struct itimerspec new_value;
1275 int ret;
1276
1277 memset(&new_value, 0, sizeof(new_value));
1278 coap_ticks(&now);
1279 if (ctx->next_timeout != 0 && ctx->next_timeout > now) {
1280 coap_tick_t rem_timeout = ctx->next_timeout - now;
1281 /* Need to trigger an event on ctx->eptimerfd in the future */
1282 new_value.it_value.tv_sec = rem_timeout / COAP_TICKS_PER_SECOND;
1283 new_value.it_value.tv_nsec = (rem_timeout % COAP_TICKS_PER_SECOND) *
1284 1000000;
1285 }
1286#ifdef COAP_DEBUG_WAKEUP_TIMES
1287 coap_log_debug("****** Next wakeup time %3ld.%09ld\n",
1288 new_value.it_value.tv_sec, new_value.it_value.tv_nsec);
1289#endif /* COAP_DEBUG_WAKEUP_TIMES */
1290 /* reset, or specify a future time for eptimerfd to trigger */
1291 ret = timerfd_settime(ctx->eptimerfd, 0, &new_value, NULL);
1292 if (ret == -1) {
1293 coap_log_err("%s: timerfd_settime failed: %s (%d)\n",
1294 "coap_io_prepare_epoll",
1295 coap_socket_strerror(), errno);
1296 }
1297 }
1298 return timeout;
1299#endif /* COAP_EPOLL_SUPPORT */
1300}
1301
1302/*
1303 * return 0 No i/o pending
1304 * +ve millisecs to next i/o activity
1305 */
1306COAP_API unsigned int
1308 coap_socket_t *sockets[],
1309 unsigned int max_sockets,
1310 unsigned int *num_sockets,
1311 coap_tick_t now) {
1312 unsigned int ret;
1313
1314 coap_lock_lock(ctx, return 0);
1315 ret = coap_io_prepare_io_lkd(ctx, sockets, max_sockets, num_sockets, now);
1316 coap_lock_unlock(ctx);
1317 return ret;
1318}
1319
1320/*
1321 * return 0 No i/o pending
1322 * +ve millisecs to next i/o activity
1323 */
1324unsigned int
1326 coap_socket_t *sockets[],
1327 unsigned int max_sockets,
1328 unsigned int *num_sockets,
1329 coap_tick_t now) {
1330 coap_queue_t *nextpdu;
1331 coap_session_t *s, *rtmp;
1332 coap_tick_t timeout = 0;
1333 coap_tick_t s_timeout;
1334#if COAP_SERVER_SUPPORT
1335 int check_dtls_timeouts = 0;
1336#endif /* COAP_SERVER_SUPPORT */
1337#if defined(COAP_EPOLL_SUPPORT) || defined(WITH_LWIP) || defined(RIOT_VERSION)
1338 (void)sockets;
1339 (void)max_sockets;
1340#endif /* COAP_EPOLL_SUPPORT || WITH_LWIP || RIOT_VERSION*/
1341
1343 *num_sockets = 0;
1344
1345#if COAP_SERVER_SUPPORT
1346 /* Check to see if we need to send off any Observe requests */
1348
1349#if COAP_ASYNC_SUPPORT
1350 /* Check to see if we need to send off any Async requests */
1351 timeout = coap_check_async(ctx, now);
1352#endif /* COAP_ASYNC_SUPPORT */
1353#endif /* COAP_SERVER_SUPPORT */
1354
1355 /* Check to see if we need to send off any retransmit request */
1356 nextpdu = coap_peek_next(ctx);
1357 while (nextpdu && now >= ctx->sendqueue_basetime &&
1358 nextpdu->t <= now - ctx->sendqueue_basetime) {
1359 coap_retransmit(ctx, coap_pop_next(ctx));
1360 nextpdu = coap_peek_next(ctx);
1361 }
1362 if (nextpdu && (timeout == 0 ||
1363 nextpdu->t - (now - ctx->sendqueue_basetime) < timeout))
1364 timeout = nextpdu->t - (now - ctx->sendqueue_basetime);
1365
1366 /* Check for DTLS timeouts */
1367 if (ctx->dtls_context) {
1370 if (tls_timeout > 0) {
1371 if (tls_timeout < now + COAP_TICKS_PER_SECOND / 10)
1372 tls_timeout = now + COAP_TICKS_PER_SECOND / 10;
1373 coap_log_debug("** DTLS global timeout set to %dms\n",
1374 (int)((tls_timeout - now) * 1000 / COAP_TICKS_PER_SECOND));
1375 if (timeout == 0 || tls_timeout - now < timeout)
1376 timeout = tls_timeout - now;
1377 }
1378#if COAP_SERVER_SUPPORT
1379 } else {
1380 check_dtls_timeouts = 1;
1381#endif /* COAP_SERVER_SUPPORT */
1382 }
1383 }
1384#if COAP_PROXY_SUPPORT
1385 if (coap_proxy_check_timeouts(ctx, now, &s_timeout)) {
1386 if (timeout == 0 || s_timeout < timeout)
1387 timeout = s_timeout;
1388 }
1389#endif /* COAP_PROXY_SUPPORT */
1390#if COAP_SERVER_SUPPORT
1391 coap_endpoint_t *ep;
1392 coap_tick_t session_timeout;
1393
1394 if (ctx->session_timeout > 0)
1395 session_timeout = ctx->session_timeout * COAP_TICKS_PER_SECOND;
1396 else
1398
1399 LL_FOREACH(ctx->endpoint, ep) {
1400#if !defined(COAP_EPOLL_SUPPORT) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
1402 if (*num_sockets < max_sockets)
1403 sockets[(*num_sockets)++] = &ep->sock;
1404 }
1405#endif /* ! COAP_EPOLL_SUPPORT && ! WITH_LWIP && ! RIOT_VERSION */
1406 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1407 /* Check whether any idle server sessions should be released */
1408 if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 &&
1409 s->delayqueue == NULL &&
1410 (s->last_rx_tx + session_timeout <= now ||
1414 } else {
1415 if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 &&
1416 s->delayqueue == NULL) {
1417 s_timeout = (s->last_rx_tx + session_timeout) - now;
1418 if (timeout == 0 || s_timeout < timeout)
1419 timeout = s_timeout;
1420 }
1421 /* Make sure the session object is not deleted in any callbacks */
1423 /* Check any DTLS timeouts and expire if appropriate */
1424 if (check_dtls_timeouts && s->state == COAP_SESSION_STATE_HANDSHAKE &&
1425 s->proto == COAP_PROTO_DTLS && s->tls) {
1426 coap_tick_t tls_timeout = coap_dtls_get_timeout(s, now);
1427 while (tls_timeout > 0 && tls_timeout <= now) {
1428 coap_log_debug("** %s: DTLS retransmit timeout\n",
1429 coap_session_str(s));
1431 goto release_1;
1432
1433 if (s->tls)
1434 tls_timeout = coap_dtls_get_timeout(s, now);
1435 else {
1436 tls_timeout = 0;
1437 timeout = 1;
1438 }
1439 }
1440 if (tls_timeout > 0 && (timeout == 0 || tls_timeout - now < timeout))
1441 timeout = tls_timeout - now;
1442 }
1443 /* Check if any server large receives are missing blocks */
1444 if (s->lg_srcv) {
1445 if (coap_block_check_lg_srcv_timeouts(s, now, &s_timeout)) {
1446 if (timeout == 0 || s_timeout < timeout)
1447 timeout = s_timeout;
1448 }
1449 }
1450 /* Check if any server large sending have timed out */
1451 if (s->lg_xmit) {
1452 if (coap_block_check_lg_xmit_timeouts(s, now, &s_timeout)) {
1453 if (timeout == 0 || s_timeout < timeout)
1454 timeout = s_timeout;
1455 }
1456 }
1457#if !defined(COAP_EPOLL_SUPPORT) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
1459 if (*num_sockets < max_sockets)
1460 sockets[(*num_sockets)++] = &s->sock;
1461 }
1462#endif /* ! COAP_EPOLL_SUPPORT && ! WITH_LWIP && ! RIOT_VERSION */
1463#if COAP_Q_BLOCK_SUPPORT
1464 /*
1465 * Check if any server large transmits have hit MAX_PAYLOAD and need
1466 * restarting
1467 */
1468 if (s->lg_xmit) {
1469 s_timeout = coap_block_check_q_block2_xmit(s, now);
1470 if (timeout == 0 || s_timeout < timeout)
1471 timeout = s_timeout;
1472 }
1473#endif /* COAP_Q_BLOCK_SUPPORT */
1474release_1:
1476 }
1477 }
1478 }
1479#endif /* COAP_SERVER_SUPPORT */
1480#if COAP_CLIENT_SUPPORT
1481 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1482 if (s->type == COAP_SESSION_TYPE_CLIENT &&
1484 ctx->ping_timeout > 0) {
1485 if (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND <= now) {
1486 /* Time to send a ping */
1488 /* Some issue - not safe to continue processing */
1489 continue;
1490 if (s->last_ping > 0 && s->last_pong < s->last_ping) {
1492 }
1493 s->last_rx_tx = now;
1494 s->last_ping = now;
1495 }
1496 s_timeout = (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND) - now;
1497 if (timeout == 0 || s_timeout < timeout)
1498 timeout = s_timeout;
1499 }
1500
1501#if !COAP_DISABLE_TCP
1503 s->state == COAP_SESSION_STATE_CSM && ctx->csm_timeout_ms > 0) {
1504 if (s->csm_tx == 0) {
1505 s->csm_tx = now;
1506 s_timeout = (ctx->csm_timeout_ms * COAP_TICKS_PER_SECOND) / 1000;
1507 } else if (s->csm_tx + (ctx->csm_timeout_ms * COAP_TICKS_PER_SECOND) / 1000 <= now) {
1508 /* timed out */
1509 s_timeout = 0;
1510 } else {
1511 s_timeout = (s->csm_tx + (ctx->csm_timeout_ms * COAP_TICKS_PER_SECOND) / 1000) - now;
1512 }
1513 if ((timeout == 0 || s_timeout < timeout) && s_timeout != 0)
1514 timeout = s_timeout;
1515 }
1516#endif /* !COAP_DISABLE_TCP */
1517
1518 /* Make sure the session object is not deleted in any callbacks */
1520 /* Check any DTLS timeouts and expire if appropriate */
1522 s->proto == COAP_PROTO_DTLS && s->tls) {
1523 coap_tick_t tls_timeout = coap_dtls_get_timeout(s, now);
1524 while (tls_timeout > 0 && tls_timeout <= now) {
1525 coap_log_debug("** %s: DTLS retransmit timeout\n", coap_session_str(s));
1527 goto release_2;
1528
1529 if (s->tls)
1530 tls_timeout = coap_dtls_get_timeout(s, now);
1531 else {
1532 tls_timeout = 0;
1533 timeout = 1;
1534 }
1535 }
1536 if (tls_timeout > 0 && (timeout == 0 || tls_timeout - now < timeout))
1537 timeout = tls_timeout - now;
1538 }
1539
1540 /* Check if any client large receives are missing blocks */
1541 if (s->lg_crcv) {
1542 if (coap_block_check_lg_crcv_timeouts(s, now, &s_timeout)) {
1543 if (timeout == 0 || s_timeout < timeout)
1544 timeout = s_timeout;
1545 }
1546 }
1547 /* Check if any client large sending have timed out */
1548 if (s->lg_xmit) {
1549 if (coap_block_check_lg_xmit_timeouts(s, now, &s_timeout)) {
1550 if (timeout == 0 || s_timeout < timeout)
1551 timeout = s_timeout;
1552 }
1553 }
1554#if COAP_Q_BLOCK_SUPPORT
1555 /*
1556 * Check if any client large transmits have hit MAX_PAYLOAD and need
1557 * restarting
1558 */
1559 if (s->lg_xmit) {
1560 s_timeout = coap_block_check_q_block1_xmit(s, now);
1561 if (timeout == 0 || s_timeout < timeout)
1562 timeout = s_timeout;
1563 }
1564#endif /* COAP_Q_BLOCK_SUPPORT */
1565
1566#if !defined(COAP_EPOLL_SUPPORT) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
1567 assert(s->ref > 1);
1568 if (s->sock.flags & (COAP_SOCKET_WANT_READ |
1571 if (*num_sockets < max_sockets)
1572 sockets[(*num_sockets)++] = &s->sock;
1573 }
1574#endif /* ! COAP_EPOLL_SUPPORT && ! WITH_LWIP && ! RIOT_VERSION */
1575release_2:
1577 }
1578#endif /* COAP_CLIENT_SUPPORT */
1579
1580 return (unsigned int)((timeout * 1000 + COAP_TICKS_PER_SECOND - 1) / COAP_TICKS_PER_SECOND);
1581}
1582
1583/*
1584 * return 0 Insufficient space to hold fds, or fds not supported
1585 * 1 All fds found
1586 */
1587COAP_API unsigned int
1589 coap_fd_t read_fds[],
1590 unsigned int *have_read_fds,
1591 unsigned int max_read_fds,
1592 coap_fd_t write_fds[],
1593 unsigned int *have_write_fds,
1594 unsigned int max_write_fds,
1595 unsigned int *rem_timeout_ms) {
1596 unsigned int ret;
1597
1598 coap_lock_lock(ctx, return 0);
1599 ret = coap_io_get_fds_lkd(ctx, read_fds, have_read_fds, max_read_fds, write_fds,
1600 have_write_fds, max_write_fds, rem_timeout_ms);
1601 coap_lock_unlock(ctx);
1602 return ret;
1603}
1604
1605#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
1606static int
1607coap_add_fd(coap_fd_t fd, coap_fd_t this_fds[], unsigned int *have_this_fds,
1608 unsigned int max_this_fds) {
1609 if (*have_this_fds < max_this_fds) {
1610 this_fds[(*have_this_fds)++] = fd;
1611 return 1;
1612 }
1613 coap_log_warn("coap_io_get_fds: Insufficient space for new fd (%u >= %u)\n", *have_this_fds,
1614 max_this_fds);
1615 return 0;
1616}
1617
1618/*
1619 * return 0 Insufficient space to hold fds, or fds not supported
1620 * 1 All fds found
1621 */
1622unsigned int
1624 coap_fd_t read_fds[],
1625 unsigned int *have_read_fds,
1626 unsigned int max_read_fds,
1627 coap_fd_t write_fds[],
1628 unsigned int *have_write_fds,
1629 unsigned int max_write_fds,
1630 unsigned int *rem_timeout_ms) {
1631 *have_read_fds = 0;
1632 *have_write_fds = 0;
1633
1634#ifdef COAP_EPOLL_SUPPORT
1635 (void)write_fds;
1636 (void)max_write_fds;;
1637
1638 if (!coap_add_fd(ctx->epfd, read_fds, have_read_fds, max_read_fds))
1639 return 0;
1640 /* epoll is making use of timerfd, so no need to return any timeout */
1641 *rem_timeout_ms = 0;
1642 return 1;
1643#else /* ! COAP_EPOLL_SUPPORT */
1644 coap_session_t *s, *rtmp;
1645 coap_tick_t now;
1646 unsigned int timeout_ms;
1647#if COAP_SERVER_SUPPORT
1648 coap_endpoint_t *ep;
1649
1650 LL_FOREACH(ctx->endpoint, ep) {
1652 if (!coap_add_fd(ep->sock.fd, read_fds, have_read_fds, max_read_fds))
1653 return 0;
1654 }
1656 if (!coap_add_fd(ep->sock.fd, write_fds, have_write_fds, max_write_fds))
1657 return 0;
1658 }
1659 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1661 if (!coap_add_fd(s->sock.fd, read_fds, have_read_fds, max_read_fds))
1662 return 0;
1663 }
1665 if (!coap_add_fd(s->sock.fd, write_fds, have_write_fds, max_write_fds))
1666 return 0;
1667 }
1668 }
1669 }
1670#endif /* COAP_SERVER_SUPPORT */
1671
1672#if COAP_CLIENT_SUPPORT
1673 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1675 if (!coap_add_fd(s->sock.fd, read_fds, have_read_fds, max_read_fds))
1676 return 0;
1677 }
1679 if (!coap_add_fd(s->sock.fd, write_fds, have_write_fds, max_write_fds))
1680 return 0;
1681 }
1682 }
1683#endif /* COAP_CLIENT_SUPPORT */
1684
1685 coap_ticks(&now);
1686 timeout_ms = (unsigned int)(ctx->next_timeout ? ctx->next_timeout > now ?
1687 ctx->next_timeout - now : 0 : 0) *
1688 1000 / COAP_TICKS_PER_SECOND;
1689 *rem_timeout_ms = timeout_ms;
1690 return 1;
1691#endif /* ! COAP_EPOLL_SUPPORT */
1692}
1693
1694#else /* WITH_LWIP || WITH_CONTIKI */
1695
1696/*
1697 * return 0 Insufficient space to hold fds, or fds not supported
1698 * 1 All fds found
1699 */
1700unsigned int
1702 coap_fd_t read_fds[],
1703 unsigned int *have_read_fds,
1704 unsigned int max_read_fds,
1705 coap_fd_t write_fds[],
1706 unsigned int *have_write_fds,
1707 unsigned int max_write_fds,
1708 unsigned int *rem_timeout_ms) {
1709 (void)ctx;
1710 (void)read_fds;
1711 (void)max_read_fds;
1712 (void)write_fds;
1713 (void)max_write_fds;
1714
1715 *have_read_fds = 0;
1716 *have_write_fds = 0;
1717 *rem_timeout_ms = 0;
1718
1719 coap_log_warn("coap_io_get_fds: Not supported\n");
1720 return 0;
1721}
1722#endif /* WITH_LWIP || WITH_CONTIKI */
1723
1724#if !defined(WITH_LWIP) && !defined(CONTIKI) && !defined(RIOT_VERSION)
1725COAP_API int
1726coap_io_process(coap_context_t *ctx, uint32_t timeout_ms) {
1727 int ret;
1728
1729 coap_lock_lock(ctx, return 0);
1730 ret = coap_io_process_lkd(ctx, timeout_ms);
1731 coap_lock_unlock(ctx);
1732 return ret;
1733}
1734
1735int
1736coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms) {
1737 return coap_io_process_with_fds_lkd(ctx, timeout_ms, 0, NULL, NULL, NULL);
1738}
1739
1740COAP_API int
1742 int enfds, fd_set *ereadfds, fd_set *ewritefds,
1743 fd_set *eexceptfds) {
1744 int ret;
1745
1746 coap_lock_lock(ctx, return 0);
1747 ret = coap_io_process_with_fds_lkd(ctx, timeout_ms, enfds, ereadfds, ewritefds,
1748 eexceptfds);
1749 coap_lock_unlock(ctx);
1750 return ret;
1751}
1752
1753int
1755 int enfds, fd_set *ereadfds, fd_set *ewritefds,
1756 fd_set *eexceptfds) {
1757 coap_fd_t nfds = 0;
1758 coap_tick_t before, now;
1759 unsigned int timeout;
1760#ifndef COAP_EPOLL_SUPPORT
1761 struct timeval tv;
1762 int result;
1763 unsigned int i;
1764#endif /* ! COAP_EPOLL_SUPPORT */
1765
1767 coap_ticks(&before);
1768
1769#ifndef COAP_EPOLL_SUPPORT
1770
1771 timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets,
1772 (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])),
1773 &ctx->num_sockets, before);
1774 ctx->next_timeout = timeout ? timeout + before : 0;
1775
1776 if (ereadfds) {
1777 ctx->readfds = *ereadfds;
1778 nfds = enfds;
1779 } else {
1780 FD_ZERO(&ctx->readfds);
1781 }
1782 if (ewritefds) {
1783 ctx->writefds = *ewritefds;
1784 nfds = enfds;
1785 } else {
1786 FD_ZERO(&ctx->writefds);
1787 }
1788 if (eexceptfds) {
1789 ctx->exceptfds = *eexceptfds;
1790 nfds = enfds;
1791 } else {
1792 FD_ZERO(&ctx->exceptfds);
1793 }
1794 for (i = 0; i < ctx->num_sockets; i++) {
1795 if (ctx->sockets[i]->fd + 1 > nfds)
1796 nfds = ctx->sockets[i]->fd + 1;
1797 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ)
1798 FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
1799 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE)
1800 FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
1801#if !COAP_DISABLE_TCP
1802 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT)
1803 FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
1804 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) {
1805 FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
1806 FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds);
1807 }
1808#endif /* !COAP_DISABLE_TCP */
1809 }
1810
1811 if (timeout_ms == COAP_IO_NO_WAIT) {
1812 tv.tv_usec = 0;
1813 tv.tv_sec = 0;
1814 timeout = 1;
1815 } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) {
1816 ;
1817 } else {
1818 if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout))
1819 timeout = timeout_ms;
1820 tv.tv_usec = (timeout % 1000) * 1000;
1821 tv.tv_sec = (long)(timeout / 1000);
1822 }
1823
1824 /* Unlock so that other threads can lock/update ctx */
1825 coap_lock_unlock(ctx);
1826
1827 result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds,
1828 timeout > 0 ? &tv : NULL);
1829
1830 coap_lock_lock(ctx, return -1);
1831
1832 if (result < 0) { /* error */
1833#ifdef _WIN32
1834 coap_win_error_to_errno();
1835#endif
1836 if (errno != EINTR) {
1838 return -1;
1839 }
1840 }
1841 if (ereadfds) {
1842 *ereadfds = ctx->readfds;
1843 }
1844 if (ewritefds) {
1845 *ewritefds = ctx->writefds;
1846 }
1847 if (eexceptfds) {
1848 *eexceptfds = ctx->exceptfds;
1849 }
1850
1851 if (result > 0) {
1852#if COAP_THREAD_SAFE
1853 /* Need to refresh what is available to read / write etc. */
1854 tv.tv_usec = 0;
1855 tv.tv_sec = 0;
1856 select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, &tv);
1857#endif /* COAP_THREAD_SAFE */
1858 for (i = 0; i < ctx->num_sockets; i++) {
1859 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) &&
1860 FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds))
1862#if !COAP_DISABLE_TCP
1863 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) &&
1864 FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds))
1866 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) &&
1867 FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds))
1869 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) &&
1870 (FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds) ||
1871 FD_ISSET(ctx->sockets[i]->fd, &ctx->exceptfds)))
1873#endif /* !COAP_DISABLE_TCP */
1874 }
1875 }
1876
1877 coap_ticks(&now);
1878 coap_io_do_io_lkd(ctx, now);
1879 coap_ticks(&now);
1880 timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets,
1881 (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])),
1882 &ctx->num_sockets, now);
1883 ctx->next_timeout = timeout ? timeout + now : 0;
1884
1885#else /* COAP_EPOLL_SUPPORT */
1886 (void)ereadfds;
1887 (void)ewritefds;
1888 (void)eexceptfds;
1889 (void)enfds;
1890
1891 timeout = coap_io_prepare_epoll_lkd(ctx, before);
1892
1893 do {
1894 struct epoll_event events[COAP_MAX_EPOLL_EVENTS];
1895 int etimeout;
1896
1897 /* Potentially adjust based on what the caller wants */
1898 if (timeout_ms == COAP_IO_NO_WAIT) {
1899 /* Need to return immediately from epoll_wait() */
1900 etimeout = 0;
1901 } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) {
1902 /*
1903 * Nothing found in coap_io_prepare_epoll_lkd() and COAP_IO_WAIT set,
1904 * so wait forever in epoll_wait().
1905 */
1906 etimeout = -1;
1907 } else {
1908 etimeout = timeout;
1909 if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout))
1910 etimeout = timeout_ms;
1911 if (etimeout < 0) {
1912 /*
1913 * If timeout > INT_MAX, epoll_wait() cannot wait longer than this as
1914 * it has int timeout parameter
1915 */
1916 etimeout = INT_MAX;
1917 }
1918 }
1919
1920 /* Unlock so that other threads can lock/update ctx */
1921 coap_lock_unlock(ctx);
1922
1923 nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, etimeout);
1924 if (nfds < 0) {
1925 if (errno != EINTR) {
1926 coap_log_err("epoll_wait: unexpected error: %s (%d)\n",
1927 coap_socket_strerror(), nfds);
1928 }
1929 coap_lock_lock(ctx, return -1);
1930 break;
1931 }
1932
1933#if COAP_THREAD_SAFE
1934 /* Need to refresh what is available to read / write etc. */
1935 nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, 0);
1936 if (nfds < 0) {
1937 if (errno != EINTR) {
1938 coap_log_err("epoll_wait: unexpected error: %s (%d)\n",
1939 coap_socket_strerror(), nfds);
1940 }
1941 coap_lock_lock(ctx, return -1);
1942 break;
1943 }
1944#endif /* COAP_THREAD_SAFE */
1945 coap_lock_lock(ctx, return -1);
1946
1947 coap_io_do_epoll_lkd(ctx, events, nfds);
1948
1949 /*
1950 * reset to COAP_IO_NO_WAIT (which causes etimeout to become 0)
1951 * incase we have to do another iteration
1952 * (COAP_MAX_EPOLL_EVENTS insufficient)
1953 */
1954 timeout_ms = COAP_IO_NO_WAIT;
1955
1956 /* Keep retrying until less than COAP_MAX_EPOLL_EVENTS are returned */
1957 } while (nfds == COAP_MAX_EPOLL_EVENTS);
1958
1959#endif /* COAP_EPOLL_SUPPORT */
1960#if COAP_SERVER_SUPPORT
1962#endif /* COAP_SERVER_SUPPORT */
1963 coap_ticks(&now);
1964#if COAP_ASYNC_SUPPORT
1965 /* Check to see if we need to send off any Async requests as delay might
1966 have been updated */
1967 coap_check_async(ctx, now);
1968 coap_ticks(&now);
1969#endif /* COAP_ASYNC_SUPPORT */
1970
1971 return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND);
1972}
1973#endif /* ! WITH_LWIP && ! WITH_CONTIKI && ! RIOT_VERSION*/
1974
1975COAP_API int
1977 int ret;
1978
1979 coap_lock_lock(context, return 0);
1980 ret = coap_io_pending_lkd(context);
1981 coap_lock_unlock(context);
1982 return ret;
1983}
1984
1985/*
1986 * return 1 I/O pending
1987 * 0 No I/O pending
1988 */
1989int
1991 coap_session_t *s, *rtmp;
1992#if COAP_SERVER_SUPPORT
1993 coap_endpoint_t *ep;
1994#endif /* COAP_SERVER_SUPPORT */
1995
1996 if (!context)
1997 return 0;
1998 coap_lock_check_locked(context);
1999 if (coap_io_process_lkd(context, COAP_IO_NO_WAIT) < 0)
2000 return 0;
2001
2002 if (context->sendqueue)
2003 return 1;
2004#if COAP_SERVER_SUPPORT
2005 LL_FOREACH(context->endpoint, ep) {
2006 SESSIONS_ITER(ep->sessions, s, rtmp) {
2007 if (s->delayqueue)
2008 return 1;
2009 if (s->lg_xmit)
2010 return 1;
2011 if (s->lg_srcv)
2012 return 1;
2013 }
2014 }
2015#endif /* COAP_SERVER_SUPPORT */
2016#if COAP_CLIENT_SUPPORT
2017 SESSIONS_ITER(context->sessions, s, rtmp) {
2018 if (s->delayqueue)
2019 return 1;
2020 if (s->lg_xmit)
2021 return 1;
2022 if (s->lg_crcv)
2023 return 1;
2024 }
2025#endif /* COAP_CLIENT_SUPPORT */
2026 return 0;
2027}
2028
2029const char *
2031 return strerror(error);
2032}
2033#ifdef _WIN32
2034const char *
2036 return coap_socket_format_errno(WSAGetLastError());
2037}
2038#else /* _WIN32 */
2039const char *
2041 return coap_socket_format_errno(errno);
2042}
2043#endif /* _WIN32 */
2044
2047#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
2048 return socket->fd;
2049#else
2050 (void)(socket);
2051 return COAP_INVALID_SOCKET;
2052#endif
2053}
2054
2057 return socket->flags;
2058}
2059
2060COAP_API void
2062 socket->flags = flags;
2063}
2064
2065#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:2030
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:681
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:1607
void coap_socket_close(coap_socket_t *sock)
Function interface to close off a socket.
Definition coap_io.c:375
const char * coap_socket_strerror(void)
Definition coap_io.c:2040
ssize_t coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet)
Function interface for reading data.
Definition coap_io.c:1025
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:828
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:1012
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:622
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:504
#define MSG_NOSIGNAL
#define iov_len_t
Definition coap_io.c:775
#define COAP_SOL_IP
Definition coap_io.c:746
#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:224
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition coap_notls.c:219
int coap_dtls_handle_timeout(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:233
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
#define COAP_DEFAULT_SESSION_TIMEOUT
int coap_proxy_check_timeouts(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem)
Idle timeout inactive proxy sessions as well as return in tim_rem the time to remaining to timeout th...
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:2528
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:1990
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:2463
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:1623
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1736
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:1754
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:1325
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:1256
COAP_API int coap_io_process(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1726
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:1976
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:1588
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:1307
#define COAP_IO_NO_WAIT
Definition coap_net.h:663
COAP_API void coap_socket_set_flags(coap_socket_t *socket, coap_socket_flags_t flags)
Set the libcoap internal flags for a socket.
Definition coap_io.c:2061
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:1246
COAP_API coap_fd_t coap_socket_get_fd(coap_socket_t *socket)
Get the libcoap internal file descriptor for a socket.
Definition coap_io.c:2046
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:1741
#define COAP_IO_WAIT
Definition coap_net.h:662
COAP_API coap_socket_flags_t coap_socket_get_flags(coap_socket_t *socket)
Get the libcoap internal flags for a socket.
Definition coap_io.c:2056
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
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:4496
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition coap_net.c:270
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:278
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2055
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:214
@ 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(c)
Dummy for no thread-safe code.
#define coap_lock_lock(c, failed)
Dummy for no thread-safe code.
#define coap_lock_check_locked(c)
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
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:266
@ COAP_PROTO_DTLS
Definition coap_pdu.h:315
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 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
coap_socket_t sock
socket object for the session, if any
coap_session_state_t state
current state of relationship with peer
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
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
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:726
unsigned int ipi6_ifindex
Definition coap_io.c:727
struct in_addr ipi_spec_dst
Definition coap_io.c:732
struct in_addr ipi_addr
Definition coap_io.c:733
int ipi_ifindex
Definition coap_io.c:731