libcoap  4.3.0beta
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-2019 Olaf Bergmann <bergmann@tzi.org> and others
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8 
9 #include "coap_internal.h"
10 
11 #ifdef HAVE_STDIO_H
12 # include <stdio.h>
13 #endif
14 
15 #ifdef HAVE_SYS_SELECT_H
16 # include <sys/select.h>
17 #endif
18 #ifdef HAVE_SYS_SOCKET_H
19 # include <sys/socket.h>
20 # define OPTVAL_T(t) (t)
21 # define OPTVAL_GT(t) (t)
22 #endif
23 #ifdef HAVE_SYS_IOCTL_H
24  #include <sys/ioctl.h>
25 #endif
26 #ifdef HAVE_NETINET_IN_H
27 # include <netinet/in.h>
28 #endif
29 #ifdef HAVE_WS2TCPIP_H
30 #include <ws2tcpip.h>
31 # define OPTVAL_T(t) (const char*)(t)
32 # define OPTVAL_GT(t) (char*)(t)
33 # undef CMSG_DATA
34 # define CMSG_DATA WSA_CMSG_DATA
35 #endif
36 #ifdef HAVE_SYS_UIO_H
37 # include <sys/uio.h>
38 #endif
39 #ifdef HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif
42 #include <errno.h>
43 #ifdef COAP_EPOLL_SUPPORT
44 #include <sys/epoll.h>
45 #include <sys/timerfd.h>
46 #ifdef HAVE_LIMITS_H
47 #include <limits.h>
48 #endif
49 #endif /* COAP_EPOLL_SUPPORT */
50 
51 #ifdef WITH_CONTIKI
52 # include "uip.h"
53 #endif
54 
55 #if !defined(WITH_CONTIKI) && !defined(RIOT_VERSION)
56  /* define generic PKTINFO for IPv4 */
57 #if defined(IP_PKTINFO)
58 # define GEN_IP_PKTINFO IP_PKTINFO
59 #elif defined(IP_RECVDSTADDR)
60 # define GEN_IP_PKTINFO IP_RECVDSTADDR
61 #else
62 # error "Need IP_PKTINFO or IP_RECVDSTADDR to request ancillary data from OS."
63 #endif /* IP_PKTINFO */
64 
65 /* define generic KTINFO for IPv6 */
66 #ifdef IPV6_RECVPKTINFO
67 # define GEN_IPV6_PKTINFO IPV6_RECVPKTINFO
68 #elif defined(IPV6_PKTINFO)
69 # define GEN_IPV6_PKTINFO IPV6_PKTINFO
70 #else
71 # error "Need IPV6_PKTINFO or IPV6_RECVPKTINFO to request ancillary data from OS."
72 #endif /* IPV6_RECVPKTINFO */
73 #endif /* !(WITH_CONTIKI || RIOT_VERSION) */
74 
75 #ifdef WITH_CONTIKI
76 static int ep_initialized = 0;
77 
80  static coap_endpoint_t ep;
81 
82  if (ep_initialized) {
83  return NULL;
84  } else {
85  ep_initialized = 1;
86  return &ep;
87  }
88 }
89 
90 void
92  ep_initialized = 0;
93 }
94 
95 int
97  const coap_address_t *listen_addr,
98  coap_address_t *bound_addr) {
99  sock->conn = udp_new(NULL, 0, NULL);
100 
101  if (!sock->conn) {
102  coap_log(LOG_WARNING, "coap_socket_bind_udp");
103  return 0;
104  }
105 
106  coap_address_init(bound_addr);
107  uip_ipaddr_copy(&bound_addr->addr, &listen_addr->addr);
108  bound_addr->port = listen_addr->port;
109  udp_bind((struct uip_udp_conn *)sock->conn, bound_addr->port);
110  return 1;
111 }
112 
113 int
115  const coap_address_t *local_if,
116  const coap_address_t *server,
117  int default_port,
118  coap_address_t *local_addr,
119  coap_address_t *remote_addr) {
120  return 0;
121 }
122 
123 ssize_t
124 coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) {
125  return -1;
126 }
127 
128 ssize_t
129 coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) {
130  return -1;
131 }
132 
133 void coap_socket_close(coap_socket_t *sock) {
134  if (sock->conn)
135  uip_udp_remove((struct uip_udp_conn *)sock->conn);
136  sock->flags = COAP_SOCKET_EMPTY;
137 }
138 
139 #else
140 
144 }
145 
146 void
149 }
150 
151 int
153  const coap_address_t *listen_addr,
154  coap_address_t *bound_addr) {
155 #ifndef RIOT_VERSION
156  int on = 1, off = 0;
157 #endif /* RIOT_VERSION */
158 #ifdef _WIN32
159  u_long u_on = 1;
160 #endif
161 
162  sock->fd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
163 
164  if (sock->fd == COAP_INVALID_SOCKET) {
166  "coap_socket_bind_udp: socket: %s\n", coap_socket_strerror());
167  goto error;
168  }
169 #ifndef RIOT_VERSION
170 #ifdef _WIN32
171  if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) {
172 #else
173  if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) {
174 #endif
176  "coap_socket_bind_udp: ioctl FIONBIO: %s\n", coap_socket_strerror());
177  }
178 
179 #ifndef RIOT_VERSION
180  if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
182  "coap_socket_bind_udp: setsockopt SO_REUSEADDR: %s\n",
184 #endif /* RIOT_VERSION */
185 
186  switch (listen_addr->addr.sa.sa_family) {
187  case AF_INET:
188  if (setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
190  "coap_socket_bind_udp: setsockopt IP_PKTINFO: %s\n",
192  break;
193  case AF_INET6:
194  /* Configure the socket as dual-stacked */
195  if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), sizeof(off)) == COAP_SOCKET_ERROR)
197  "coap_socket_bind_udp: setsockopt IPV6_V6ONLY: %s\n",
199  if (setsockopt(sock->fd, IPPROTO_IPV6, GEN_IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
201  "coap_socket_bind_udp: setsockopt IPV6_PKTINFO: %s\n",
203  setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on)); /* ignore error, because the likely cause is that IPv4 is disabled at the os level */
204  break;
205  default:
206  coap_log(LOG_ALERT, "coap_socket_bind_udp: unsupported sa_family\n");
207  break;
208  }
209 #endif /* RIOT_VERSION */
210 
211  if (bind(sock->fd, &listen_addr->addr.sa,
212  listen_addr->addr.sa.sa_family == AF_INET ?
213  (socklen_t)sizeof(struct sockaddr_in) :
214  (socklen_t)listen_addr->size) == COAP_SOCKET_ERROR) {
215  coap_log(LOG_WARNING, "coap_socket_bind_udp: bind: %s\n",
217  goto error;
218  }
219 
220  bound_addr->size = (socklen_t)sizeof(*bound_addr);
221  if (getsockname(sock->fd, &bound_addr->addr.sa, &bound_addr->size) < 0) {
223  "coap_socket_bind_udp: getsockname: %s\n",
225  goto error;
226  }
227 
228  return 1;
229 
230 error:
231  coap_socket_close(sock);
232  return 0;
233 }
234 
235 int
237  const coap_address_t *local_if,
238  const coap_address_t *server,
239  int default_port,
240  coap_address_t *local_addr,
241  coap_address_t *remote_addr) {
242 #ifndef RIOT_VERSION
243  int on = 1;
244  int off = 0;
245 #endif /* RIOT_VERSION */
246 #ifdef _WIN32
247  u_long u_on = 1;
248 #endif
249  coap_address_t connect_addr;
250  int is_mcast = coap_is_mcast(server);
251  coap_address_copy(&connect_addr, server);
252 
254  sock->fd = socket(connect_addr.addr.sa.sa_family, SOCK_DGRAM, 0);
255 
256  if (sock->fd == COAP_INVALID_SOCKET) {
257  coap_log(LOG_WARNING, "coap_socket_connect_udp: socket: %s\n",
259  goto error;
260  }
261 
262 #ifndef RIOT_VERSION
263 #ifdef _WIN32
264  if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) {
265 #else
266  if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) {
267 #endif
268  coap_log(LOG_WARNING, "coap_socket_connect_udp: ioctl FIONBIO: %s\n",
270  }
271 #endif /* RIOT_VERSION */
272 
273  switch (connect_addr.addr.sa.sa_family) {
274  case AF_INET:
275  if (connect_addr.addr.sin.sin_port == 0)
276  connect_addr.addr.sin.sin_port = htons(default_port);
277  break;
278  case AF_INET6:
279  if (connect_addr.addr.sin6.sin6_port == 0)
280  connect_addr.addr.sin6.sin6_port = htons(default_port);
281 #ifndef RIOT_VERSION
282  /* Configure the socket as dual-stacked */
283  if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), sizeof(off)) == COAP_SOCKET_ERROR)
285  "coap_socket_connect_udp: setsockopt IPV6_V6ONLY: %s\n",
287 #endif /* RIOT_VERSION */
288  break;
289  default:
290  coap_log(LOG_ALERT, "coap_socket_connect_udp: unsupported sa_family\n");
291  break;
292  }
293 
294  if (local_if && local_if->addr.sa.sa_family) {
295 #ifndef RIOT_VERSION
296  if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
298  "coap_socket_connect_udp: setsockopt SO_REUSEADDR: %s\n",
300 #endif /* RIOT_VERSION */
301  if (bind(sock->fd, &local_if->addr.sa,
302  local_if->addr.sa.sa_family == AF_INET ?
303  (socklen_t)sizeof(struct sockaddr_in) :
304  (socklen_t)local_if->size) == COAP_SOCKET_ERROR) {
305  coap_log(LOG_WARNING, "coap_socket_connect_udp: bind: %s\n",
307  goto error;
308  }
309  }
310 
311  /* special treatment for sockets that are used for multicast communication */
312  if (is_mcast) {
313  if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) {
315  "coap_socket_connect_udp: getsockname for multicast socket: %s\n",
317  }
318  coap_address_copy(remote_addr, &connect_addr);
319  sock->flags |= COAP_SOCKET_MULTICAST;
320  return 1;
321  }
322 
323  if (connect(sock->fd, &connect_addr.addr.sa, connect_addr.size) == COAP_SOCKET_ERROR) {
324  coap_log(LOG_WARNING, "coap_socket_connect_udp: connect: %s\n",
326  goto error;
327  }
328 
329  if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) {
330  coap_log(LOG_WARNING, "coap_socket_connect_udp: getsockname: %s\n",
332  }
333 
334  if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) {
335  coap_log(LOG_WARNING, "coap_socket_connect_udp: getpeername: %s\n",
337  }
338 
339  sock->flags |= COAP_SOCKET_CONNECTED;
340  return 1;
341 
342 error:
343  coap_socket_close(sock);
344  return 0;
345 }
346 
348  if (sock->fd != COAP_INVALID_SOCKET) {
349 #ifdef COAP_EPOLL_SUPPORT
350  coap_context_t *context = sock->session ? sock->session->context :
351  sock->endpoint ? sock->endpoint->context : NULL;
352  if (context != NULL) {
353  int ret;
354  struct epoll_event event;
355 
356  /* Kernels prior to 2.6.9 expect non NULL event parameter */
357  ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, sock->fd, &event);
358  if (ret == -1) {
360  "%s: epoll_ctl DEL failed: %s (%d)\n",
361  "coap_socket_close",
362  coap_socket_strerror(), errno);
363  }
364  }
365 #endif /* COAP_EPOLL_SUPPORT */
366  sock->endpoint = NULL;
367  sock->session = NULL;
368  coap_closesocket(sock->fd);
369  sock->fd = COAP_INVALID_SOCKET;
370  }
371  sock->flags = COAP_SOCKET_EMPTY;
372 }
373 
374 #ifdef COAP_EPOLL_SUPPORT
375 void
377  uint32_t events,
378  const char *func
379 ) {
380  int ret;
381  struct epoll_event event;
382  coap_context_t *context;
383 
384  if (sock == NULL)
385  return;
386 
387  context = sock->session ? sock->session->context :
388  sock->endpoint ? sock->endpoint->context : NULL;
389  if (context == NULL)
390  return;
391 
392  event.events = events;
393  event.data.ptr = sock;
394 
395  ret = epoll_ctl(context->epfd, EPOLL_CTL_MOD, sock->fd, &event);
396  if (ret == -1) {
398  "%s: epoll_ctl MOD failed: %s (%d)\n",
399  func,
400  coap_socket_strerror(), errno);
401  }
402 }
403 #endif /* COAP_EPOLL_SUPPORT */
404 
405 ssize_t
406 coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) {
407  ssize_t r;
408 
410 #ifdef _WIN32
411  r = send(sock->fd, (const char *)data, (int)data_len, 0);
412 #else
413  r = send(sock->fd, data, data_len, 0);
414 #endif
415  if (r == COAP_SOCKET_ERROR) {
416 #ifdef _WIN32
417  if (WSAGetLastError() == WSAEWOULDBLOCK) {
418 #elif EAGAIN != EWOULDBLOCK
419  if (errno==EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
420 #else
421  if (errno==EAGAIN || errno == EINTR) {
422 #endif
423  sock->flags |= COAP_SOCKET_WANT_WRITE;
424 #ifdef COAP_EPOLL_SUPPORT
425  coap_epoll_ctl_mod(sock,
426  EPOLLOUT |
427  ((sock->flags & COAP_SOCKET_WANT_READ) ?
428  EPOLLIN : 0),
429  __func__);
430 #endif /* COAP_EPOLL_SUPPORT */
431  return 0;
432  }
433  if (errno == EPIPE || errno == ECONNRESET) {
434  coap_log(LOG_INFO, "coap_socket_write: send: %s\n",
436  }
437  else {
438  coap_log(LOG_WARNING, "coap_socket_write: send: %s\n",
440  }
441  return -1;
442  }
443  if (r < (ssize_t)data_len) {
444  sock->flags |= COAP_SOCKET_WANT_WRITE;
445 #ifdef COAP_EPOLL_SUPPORT
446  coap_epoll_ctl_mod(sock,
447  EPOLLOUT |
448  ((sock->flags & COAP_SOCKET_WANT_READ) ?
449  EPOLLIN : 0),
450  __func__);
451 #endif /* COAP_EPOLL_SUPPORT */
452  }
453  return r;
454 }
455 
456 ssize_t
457 coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) {
458  ssize_t r;
459 #ifdef _WIN32
460  int error;
461 #endif
462 
463 #ifdef _WIN32
464  r = recv(sock->fd, (char *)data, (int)data_len, 0);
465 #else
466  r = recv(sock->fd, data, data_len, 0);
467 #endif
468  if (r == 0) {
469  /* graceful shutdown */
470  sock->flags &= ~COAP_SOCKET_CAN_READ;
471  return -1;
472  } else if (r == COAP_SOCKET_ERROR) {
473  sock->flags &= ~COAP_SOCKET_CAN_READ;
474 #ifdef _WIN32
475  error = WSAGetLastError();
476  if (error == WSAEWOULDBLOCK) {
477 #elif EAGAIN != EWOULDBLOCK
478  if (errno==EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
479 #else
480  if (errno==EAGAIN || errno == EINTR) {
481 #endif
482  return 0;
483  }
484 #ifdef _WIN32
485  if (error != WSAECONNRESET)
486 #else
487  if (errno != ECONNRESET)
488 #endif
489  coap_log(LOG_WARNING, "coap_socket_read: recv: %s\n",
491  return -1;
492  }
493  if (r < (ssize_t)data_len)
494  sock->flags &= ~COAP_SOCKET_CAN_READ;
495  return r;
496 }
497 
498 #endif /* WITH_CONTIKI */
499 
500 #if (!defined(WITH_CONTIKI)) != ( defined(HAVE_NETINET_IN_H) || defined(HAVE_WS2TCPIP_H) )
501 /* define struct in6_pktinfo and struct in_pktinfo if not available
502  FIXME: check with configure
503 */
504 struct in6_pktinfo {
505  struct in6_addr ipi6_addr; /* src/dst IPv6 address */
506  unsigned int ipi6_ifindex; /* send/recv interface index */
507 };
508 
509 struct in_pktinfo {
511  struct in_addr ipi_spec_dst;
512  struct in_addr ipi_addr;
513 };
514 #endif
515 
516 #if !defined(WITH_CONTIKI) && !defined(SOL_IP)
517 /* Solaris expects level IPPROTO_IP for ancillary data. */
518 #define SOL_IP IPPROTO_IP
519 #endif
520 
521 #ifdef __GNUC__
522 #define UNUSED_PARAM __attribute__ ((unused))
523 #else /* not a GCC */
524 #define UNUSED_PARAM
525 #endif /* GCC */
526 
527 #if defined(_WIN32)
528 #include <mswsock.h>
529 static __declspec(thread) LPFN_WSARECVMSG lpWSARecvMsg = NULL;
530 /* Map struct WSABUF fields to their posix counterpart */
531 #define msghdr _WSAMSG
532 #define msg_name name
533 #define msg_namelen namelen
534 #define msg_iov lpBuffers
535 #define msg_iovlen dwBufferCount
536 #define msg_control Control.buf
537 #define msg_controllen Control.len
538 #define iovec _WSABUF
539 #define iov_base buf
540 #define iov_len len
541 #define iov_len_t u_long
542 #undef CMSG_DATA
543 #define CMSG_DATA WSA_CMSG_DATA
544 #define ipi_spec_dst ipi_addr
545 #else
546 #define iov_len_t size_t
547 #endif
548 
549 #if defined(_CYGWIN_ENV)
550 #define ipi_spec_dst ipi_addr
551 #endif
552 
553 #ifndef RIOT_VERSION
554 ssize_t
555 coap_network_send(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen) {
556  ssize_t bytes_written = 0;
557 
558  if (!coap_debug_send_packet()) {
559  bytes_written = (ssize_t)datalen;
560 #ifndef WITH_CONTIKI
561  } else if (sock->flags & COAP_SOCKET_CONNECTED) {
562 #ifdef _WIN32
563  bytes_written = send(sock->fd, (const char *)data, (int)datalen, 0);
564 #else
565  bytes_written = send(sock->fd, data, datalen, 0);
566 #endif
567 #endif
568  } else {
569 #ifdef _WIN32
570  DWORD dwNumberOfBytesSent = 0;
571  int r;
572 #endif
573 #ifdef HAVE_STRUCT_CMSGHDR
574  /* a buffer large enough to hold all packet info types, ipv6 is the largest */
575  char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
576  struct msghdr mhdr;
577  struct iovec iov[1];
578  const void *addr = &session->addr_info.remote.addr;
579 
580  assert(session);
581 
582  memcpy (&iov[0].iov_base, &data, sizeof (iov[0].iov_base));
583  iov[0].iov_len = (iov_len_t)datalen;
584 
585  memset(buf, 0, sizeof (buf));
586 
587  memset(&mhdr, 0, sizeof(struct msghdr));
588  memcpy (&mhdr.msg_name, &addr, sizeof (mhdr.msg_name));
589  mhdr.msg_namelen = session->addr_info.remote.size;
590 
591  mhdr.msg_iov = iov;
592  mhdr.msg_iovlen = 1;
593 
594  if (!coap_address_isany(&session->addr_info.local) &&
595  !coap_is_mcast(&session->addr_info.local))
596  switch (session->addr_info.local.addr.sa.sa_family) {
597  case AF_INET6:
598  {
599  struct cmsghdr *cmsg;
600 
601  if (IN6_IS_ADDR_V4MAPPED(&session->addr_info.local.addr.sin6.sin6_addr)) {
602 #if defined(IP_PKTINFO)
603  struct in_pktinfo *pktinfo;
604  mhdr.msg_control = buf;
605  mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
606 
607  cmsg = CMSG_FIRSTHDR(&mhdr);
608  cmsg->cmsg_level = SOL_IP;
609  cmsg->cmsg_type = IP_PKTINFO;
610  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
611 
612  pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
613 
614  pktinfo->ipi_ifindex = session->ifindex;
615  memcpy(&pktinfo->ipi_spec_dst,
616  session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
617  sizeof(pktinfo->ipi_spec_dst));
618 #elif defined(IP_SENDSRCADDR)
619  mhdr.msg_control = buf;
620  mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
621 
622  cmsg = CMSG_FIRSTHDR(&mhdr);
623  cmsg->cmsg_level = IPPROTO_IP;
624  cmsg->cmsg_type = IP_SENDSRCADDR;
625  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
626 
627  memcpy(CMSG_DATA(cmsg),
628  session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
629  sizeof(struct in_addr));
630 #endif /* IP_PKTINFO */
631  } else {
632  struct in6_pktinfo *pktinfo;
633  mhdr.msg_control = buf;
634  mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
635 
636  cmsg = CMSG_FIRSTHDR(&mhdr);
637  cmsg->cmsg_level = IPPROTO_IPV6;
638  cmsg->cmsg_type = IPV6_PKTINFO;
639  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
640 
641  pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
642 
643  pktinfo->ipi6_ifindex = session->ifindex;
644  memcpy(&pktinfo->ipi6_addr,
645  &session->addr_info.local.addr.sin6.sin6_addr,
646  sizeof(pktinfo->ipi6_addr));
647  }
648  break;
649  }
650  case AF_INET:
651  {
652 #if defined(IP_PKTINFO)
653  struct cmsghdr *cmsg;
654  struct in_pktinfo *pktinfo;
655 
656  mhdr.msg_control = buf;
657  mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
658 
659  cmsg = CMSG_FIRSTHDR(&mhdr);
660  cmsg->cmsg_level = SOL_IP;
661  cmsg->cmsg_type = IP_PKTINFO;
662  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
663 
664  pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
665 
666  pktinfo->ipi_ifindex = session->ifindex;
667  memcpy(&pktinfo->ipi_spec_dst,
668  &session->addr_info.local.addr.sin.sin_addr,
669  sizeof(pktinfo->ipi_spec_dst));
670 #elif defined(IP_SENDSRCADDR)
671  struct cmsghdr *cmsg;
672  mhdr.msg_control = buf;
673  mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
674 
675  cmsg = CMSG_FIRSTHDR(&mhdr);
676  cmsg->cmsg_level = IPPROTO_IP;
677  cmsg->cmsg_type = IP_SENDSRCADDR;
678  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
679 
680  memcpy(CMSG_DATA(cmsg),
681  &session->addr_info.local.addr.sin.sin_addr,
682  sizeof(struct in_addr));
683 #endif /* IP_PKTINFO */
684  break;
685  }
686  default:
687  /* error */
688  coap_log(LOG_WARNING, "protocol not supported\n");
689  bytes_written = -1;
690  }
691 #endif /* HAVE_STRUCT_CMSGHDR */
692 
693 #ifdef _WIN32
694  r = WSASendMsg(sock->fd, &mhdr, 0 /*dwFlags*/, &dwNumberOfBytesSent, NULL /*lpOverlapped*/, NULL /*lpCompletionRoutine*/);
695  if (r == 0)
696  bytes_written = (ssize_t)dwNumberOfBytesSent;
697  else
698  bytes_written = -1;
699 #else
700 #ifdef HAVE_STRUCT_CMSGHDR
701  bytes_written = sendmsg(sock->fd, &mhdr, 0);
702 #elif !defined(CONTIKI) /* ! HAVE_STRUCT_CMSGHDR */
703  bytes_written = sendto(sock->fd, data, datalen, 0,
704  &session->addr_info.remote.addr.sa,
705  session->addr_info.remote.size);
706 #endif /* ! HAVE_STRUCT_CMSGHDR */
707 #endif
708 #if defined(WITH_CONTIKI)
709  /* FIXME: untested */
710  /* FIXME: is there a way to check if send was successful? */
711  (void)datalen;
712  (void)data;
713  uip_udp_packet_sendto((struct uip_udp_conn *)sock->conn, data, datalen,
714  &session->addr_info.remote.addr, session->addr_info.remote.port);
715  bytes_written = datalen;
716 #endif /* WITH_CONTIKI */
717  }
718 
719  if (bytes_written < 0)
720  coap_log(LOG_CRIT, "coap_network_send: %s\n", coap_socket_strerror());
721 
722  return bytes_written;
723 }
724 #endif /* RIOT_VERSION */
725 
726 #define SIN6(A) ((struct sockaddr_in6 *)(A))
727 
728 void
729 coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length) {
730  *address = packet->payload;
731  *length = packet->length;
732 }
733 
734 #ifndef RIOT_VERSION
735 ssize_t
737  ssize_t len = -1;
738 
739  assert(sock);
740  assert(packet);
741 
742  if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) {
743  return -1;
744  } else {
745  /* clear has-data flag */
746  sock->flags &= ~COAP_SOCKET_CAN_READ;
747  }
748 
749 #if !defined(WITH_CONTIKI) && !defined(RIOT_VERSION)
750  if (sock->flags & COAP_SOCKET_CONNECTED) {
751 #ifdef _WIN32
752  len = recv(sock->fd, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0);
753 #else
754  len = recv(sock->fd, packet->payload, COAP_RXBUFFER_SIZE, 0);
755 #endif
756  if (len < 0) {
757 #ifdef _WIN32
758  if (WSAGetLastError() == WSAECONNRESET) {
759 #else
760  if (errno == ECONNREFUSED) {
761 #endif
762  /* client-side ICMP destination unreachable, ignore it */
763  coap_log(LOG_WARNING, "coap_network_read: unreachable\n");
764  return -2;
765  }
766  coap_log(LOG_WARNING, "coap_network_read: %s\n", coap_socket_strerror());
767  goto error;
768  } else if (len > 0) {
769  packet->length = (size_t)len;
770  }
771  } else {
772 #endif /* !(WITH_CONTIKI || RIOT_VERSION) */
773 #if defined(_WIN32)
774  DWORD dwNumberOfBytesRecvd = 0;
775  int r;
776 #endif
777 #if !defined(WITH_CONTIKI)
778 #ifdef HAVE_STRUCT_CMSGHDR
779  /* a buffer large enough to hold all packet info types, ipv6 is the largest */
780  char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
781  struct cmsghdr *cmsg;
782  struct msghdr mhdr;
783  struct iovec iov[1];
784 
785  iov[0].iov_base = packet->payload;
786  iov[0].iov_len = (iov_len_t)COAP_RXBUFFER_SIZE;
787 
788  memset(&mhdr, 0, sizeof(struct msghdr));
789 
790  mhdr.msg_name = (struct sockaddr*)&packet->addr_info.remote.addr;
791  mhdr.msg_namelen = sizeof(packet->addr_info.remote.addr);
792 
793  mhdr.msg_iov = iov;
794  mhdr.msg_iovlen = 1;
795 
796  mhdr.msg_control = buf;
797  mhdr.msg_controllen = sizeof(buf);
798  /* set a big first length incase recvmsg() does not implement updating
799  msg_control as well as preset the first cmsg with bad data */
800  cmsg = (struct cmsghdr *)buf;
801  cmsg->cmsg_len = CMSG_LEN(sizeof(buf));
802  cmsg->cmsg_level = -1;
803  cmsg->cmsg_type = -1;
804 
805 #if defined(_WIN32)
806  if (!lpWSARecvMsg) {
807  GUID wsaid = WSAID_WSARECVMSG;
808  DWORD cbBytesReturned = 0;
809  if (WSAIoctl(sock->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &wsaid, sizeof(wsaid), &lpWSARecvMsg, sizeof(lpWSARecvMsg), &cbBytesReturned, NULL, NULL) != 0) {
810  coap_log(LOG_WARNING, "coap_network_read: no WSARecvMsg\n");
811  return -1;
812  }
813  }
814  r = lpWSARecvMsg(sock->fd, &mhdr, &dwNumberOfBytesRecvd, NULL /* LPWSAOVERLAPPED */, NULL /* LPWSAOVERLAPPED_COMPLETION_ROUTINE */);
815  if (r == 0)
816  len = (ssize_t)dwNumberOfBytesRecvd;
817 #else
818  len = recvmsg(sock->fd, &mhdr, 0);
819 #endif
820 
821 #else /* ! HAVE_STRUCT_CMSGHDR */
822  len = recvfrom(sock->fd, packet->payload, COAP_RXBUFFER_SIZE, 0,
823  &packet->addr_info.remote.addr.sa,
824  &packet->addr_info.remote.size);
825 #endif /* ! HAVE_STRUCT_CMSGHDR */
826 
827  if (len < 0) {
828 #ifdef _WIN32
829  if (WSAGetLastError() == WSAECONNRESET) {
830 #else
831  if (errno == ECONNREFUSED) {
832 #endif
833  /* server-side ICMP destination unreachable, ignore it. The destination address is in msg_name. */
834  return 0;
835  }
836  coap_log(LOG_WARNING, "coap_network_read: %s\n", coap_socket_strerror());
837  goto error;
838  } else {
839 #ifdef HAVE_STRUCT_CMSGHDR
840  int dst_found = 0;
841 
842  packet->addr_info.remote.size = mhdr.msg_namelen;
843  packet->length = (size_t)len;
844 
845  /* Walk through ancillary data records until the local interface
846  * is found where the data was received. */
847  for (cmsg = CMSG_FIRSTHDR(&mhdr); cmsg; cmsg = CMSG_NXTHDR(&mhdr, cmsg)) {
848 
849  /* get the local interface for IPv6 */
850  if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
851  union {
852  uint8_t *c;
853  struct in6_pktinfo *p;
854  } u;
855  u.c = CMSG_DATA(cmsg);
856  packet->ifindex = (int)(u.p->ipi6_ifindex);
857  memcpy(&packet->addr_info.local.addr.sin6.sin6_addr,
858  &u.p->ipi6_addr, sizeof(struct in6_addr));
859  dst_found = 1;
860  break;
861  }
862 
863  /* local interface for IPv4 */
864 #if defined(IP_PKTINFO)
865  if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_PKTINFO) {
866  union {
867  uint8_t *c;
868  struct in_pktinfo *p;
869  } u;
870  u.c = CMSG_DATA(cmsg);
871  packet->ifindex = u.p->ipi_ifindex;
872  if (packet->addr_info.local.addr.sa.sa_family == AF_INET6) {
873  memset(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr, 0, 10);
874  packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[10] = 0xff;
875  packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[11] = 0xff;
876  memcpy(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
877  &u.p->ipi_addr, sizeof(struct in_addr));
878  } else {
879  memcpy(&packet->addr_info.local.addr.sin.sin_addr,
880  &u.p->ipi_addr, sizeof(struct in_addr));
881  }
882  dst_found = 1;
883  break;
884  }
885 #elif defined(IP_RECVDSTADDR)
886  if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR) {
887  packet->ifindex = sock->fd;
888  memcpy(&packet->addr_info.local.addr.sin.sin_addr,
889  CMSG_DATA(cmsg), sizeof(struct in_addr));
890  dst_found = 1;
891  break;
892  }
893 #endif /* IP_PKTINFO */
894  if (!dst_found) {
895  /* cmsg_level / cmsg_type combination we do not understand
896  (ignore preset case for bad recvmsg() not updating cmsg) */
897  if (cmsg->cmsg_level != -1 && cmsg->cmsg_type != -1) {
899  "cmsg_level = %d and cmsg_type = %d not supported - fix\n",
900  cmsg->cmsg_level, cmsg->cmsg_type);
901  }
902  }
903  }
904  if (!dst_found) {
905  /* Not expected, but cmsg_level and cmsg_type don't match above and
906  may need a new case */
907  packet->ifindex = (int)sock->fd;
908  if (getsockname(sock->fd, &packet->addr_info.local.addr.sa,
909  &packet->addr_info.local.size) < 0) {
910  coap_log(LOG_DEBUG, "Cannot determine local port\n");
911  }
912  }
913 #else /* ! HAVE_STRUCT_CMSGHDR */
914  packet->length = (size_t)len;
915  packet->ifindex = 0;
916  if (getsockname(sock->fd, &packet->addr_info.local.addr.sa,
917  &packet->addr_info.local.size) < 0) {
918  coap_log(LOG_DEBUG, "Cannot determine local port\n");
919  goto error;
920  }
921 #endif /* ! HAVE_STRUCT_CMSGHDR */
922  }
923 #endif /* !defined(WITH_CONTIKI) && !defined(RIOT_VERSION) */
924 #ifdef WITH_CONTIKI
925  /* FIXME: untested, make this work */
926 #define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
927 #define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
928 
929  if (uip_newdata()) {
930  uip_ipaddr_copy(&packet->addr_info.remote.addr, &UIP_IP_BUF->srcipaddr);
931  packet->addr_info.remote.port = UIP_UDP_BUF->srcport;
932  uip_ipaddr_copy(&(packet)->addr_info.local.addr, &UIP_IP_BUF->destipaddr);
933  packet->addr_info.local.port = UIP_UDP_BUF->destport;
934 
935  len = uip_datalen();
936 
937  if (len > COAP_RXBUFFER_SIZE) {
938  /* FIXME: we might want to send back a response */
939  coap_log(LOG_WARNING, "discarded oversized packet\n");
940  return -1;
941  }
942 
943  ((char *)uip_appdata)[len] = 0;
944  if (LOG_DEBUG <= coap_get_log_level()) {
945 #ifndef INET6_ADDRSTRLEN
946 #define INET6_ADDRSTRLEN 40
947 #endif
948  unsigned char addr_str[INET6_ADDRSTRLEN + 8];
949 
950  if (coap_print_addr(&packet->addr_info.remote, addr_str,
951  INET6_ADDRSTRLEN + 8)) {
952  coap_log(LOG_DEBUG, "received %zd bytes from %s\n", len, addr_str);
953  }
954  }
955 
956  packet->length = len;
957  memcpy(&packet->payload, uip_appdata, len);
958  }
959 
960 #undef UIP_IP_BUF
961 #undef UIP_UDP_BUF
962 #endif /* WITH_CONTIKI */
963 #ifdef RIOT_VERSION
964  packet->src.size = sizeof(packet->src.addr);
965  len = recvfrom (sock->fd, packet->payload, COAP_RXBUFFER_SIZE,
966  0, &packet->src.addr.sa, &packet->src.size);
967  if (LOG_DEBUG <= coap_get_log_level()) {
968  unsigned char addr_str[INET6_ADDRSTRLEN + 8];
969 
970  if (coap_print_addr(&packet->src, addr_str, INET6_ADDRSTRLEN + 8)) {
971  coap_log(LOG_DEBUG, "received %zd bytes from %s\n", len, addr_str);
972  }
973  }
974 #endif /* RIOT_VERSION */
975 #if !defined(WITH_CONTIKI) && !defined(RIOT_VERSION)
976  }
977 #endif /* !(WITH_CONTIKI || RIOT_VERSION) */
978 
979  if (len >= 0)
980  return len;
981 #if !defined(WITH_CONTIKI) && !defined(RIOT_VERSION)
982 error:
983 #endif
984  return -1;
985 }
986 #endif /* RIOT_VERSION */
987 
988 #if !defined(WITH_CONTIKI)
989 
990 unsigned int
992 #ifndef COAP_EPOLL_SUPPORT
993  (void)ctx;
994  (void)now;
996  "coap_io_prepare_epoll() requires libcoap compiled for using epoll\n");
997  return 0;
998 #else /* COAP_EPOLL_SUPPORT */
999  coap_socket_t *sockets[1];
1000  unsigned int max_sockets = sizeof(sockets)/sizeof(sockets[0]);
1001  unsigned int num_sockets;
1002  unsigned int timeout;
1003 
1004  /* Use the common logic */
1005  timeout = coap_io_prepare_io(ctx, sockets, max_sockets, &num_sockets, now);
1006  /* Save when the next expected I/O is to take place */
1007  ctx->next_timeout = timeout ? now + timeout : 0;
1008  if (ctx->eptimerfd != -1) {
1009  struct itimerspec new_value;
1010  int ret;
1011 
1012  memset(&new_value, 0, sizeof(new_value));
1013  coap_ticks(&now);
1014  if (ctx->next_timeout != 0 && ctx->next_timeout > now) {
1015  coap_tick_t rem_timeout = ctx->next_timeout - now;
1016  /* Need to trigger an event on ctx->epfd in the future */
1017  new_value.it_value.tv_sec = rem_timeout / COAP_TICKS_PER_SECOND;
1018  new_value.it_value.tv_nsec = (rem_timeout % COAP_TICKS_PER_SECOND) *
1019  1000000;
1020  }
1021  /* reset, or specify a future time for eptimerfd to trigger */
1022  ret = timerfd_settime(ctx->eptimerfd, 0, &new_value, NULL);
1023  if (ret == -1) {
1024  coap_log(LOG_ERR,
1025  "%s: timerfd_settime failed: %s (%d)\n",
1026  "coap_io_prepare_epoll",
1027  coap_socket_strerror(), errno);
1028  }
1029  }
1030  return timeout;
1031 #endif /* COAP_EPOLL_SUPPORT */
1032 }
1033 
1034 /*
1035  * return 0 No i/o pending
1036  * +ve millisecs to next i/o activity
1037  */
1038 unsigned int
1040  coap_socket_t *sockets[],
1041  unsigned int max_sockets,
1042  unsigned int *num_sockets,
1043  coap_tick_t now)
1044 {
1045  coap_queue_t *nextpdu;
1046  coap_endpoint_t *ep;
1047  coap_session_t *s, *rtmp;
1048  coap_tick_t session_timeout;
1049  coap_tick_t timeout = 0;
1050 #ifdef COAP_EPOLL_SUPPORT
1051  (void)sockets;
1052  (void)max_sockets;
1053 #endif /* COAP_EPOLL_SUPPORT */
1054 
1055  *num_sockets = 0;
1056 
1057  /* Check to see if we need to send off any Observe requests */
1058  coap_check_notify(ctx);
1059 
1060  if (ctx->session_timeout > 0)
1061  session_timeout = ctx->session_timeout * COAP_TICKS_PER_SECOND;
1062  else
1064 
1065  LL_FOREACH(ctx->endpoint, ep) {
1066 #ifndef COAP_EPOLL_SUPPORT
1068  if (*num_sockets < max_sockets)
1069  sockets[(*num_sockets)++] = &ep->sock;
1070  }
1071 #endif /* ! COAP_EPOLL_SUPPORT */
1072  SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1073  if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 &&
1074  s->delayqueue == NULL &&
1075  (s->last_rx_tx + session_timeout <= now ||
1076  s->state == COAP_SESSION_STATE_NONE)) {
1077  coap_session_free(s);
1078  } else {
1079  if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 && s->delayqueue == NULL) {
1080  coap_tick_t s_timeout = (s->last_rx_tx + session_timeout) - now;
1081  if (timeout == 0 || s_timeout < timeout)
1082  timeout = s_timeout;
1083  }
1084 #ifndef COAP_EPOLL_SUPPORT
1086  if (*num_sockets < max_sockets)
1087  sockets[(*num_sockets)++] = &s->sock;
1088  }
1089 #endif /* ! COAP_EPOLL_SUPPORT */
1090  }
1091  }
1092  }
1093  SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1094  if (!COAP_DISABLE_TCP
1097  && ctx->ping_timeout > 0
1098  ) {
1099  coap_tick_t s_timeout;
1100  if (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND <= now) {
1101  if ((s->last_ping > 0 && s->last_pong < s->last_ping)
1103  {
1104  /* Make sure the session object is not deleted in the callback */
1108  continue;
1109  }
1110  s->last_rx_tx = now;
1111  s->last_ping = now;
1112  }
1113  s_timeout = (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND) - now;
1114  if (timeout == 0 || s_timeout < timeout)
1115  timeout = s_timeout;
1116  }
1117 
1118  if (!COAP_DISABLE_TCP
1120  && COAP_PROTO_RELIABLE(s->proto)
1121  && s->state == COAP_SESSION_STATE_CSM
1122  && ctx->csm_timeout > 0
1123  ) {
1124  coap_tick_t s_timeout;
1125  if (s->csm_tx == 0) {
1126  s->csm_tx = now;
1127  } else if (s->csm_tx + ctx->csm_timeout * COAP_TICKS_PER_SECOND <= now) {
1128  /* Make sure the session object is not deleted in the callback */
1132  continue;
1133  }
1134  s_timeout = (s->csm_tx + ctx->csm_timeout * COAP_TICKS_PER_SECOND) - now;
1135  if (timeout == 0 || s_timeout < timeout)
1136  timeout = s_timeout;
1137  }
1138 
1139 #ifndef COAP_EPOLL_SUPPORT
1141  if (*num_sockets < max_sockets)
1142  sockets[(*num_sockets)++] = &s->sock;
1143  }
1144 #endif /* ! COAP_EPOLL_SUPPORT */
1145  }
1146 
1147  nextpdu = coap_peek_next(ctx);
1148 
1149  while (nextpdu && now >= ctx->sendqueue_basetime && nextpdu->t <= now - ctx->sendqueue_basetime) {
1150  coap_retransmit(ctx, coap_pop_next(ctx));
1151  nextpdu = coap_peek_next(ctx);
1152  }
1153 
1154  if (nextpdu && (timeout == 0 || nextpdu->t - ( now - ctx->sendqueue_basetime ) < timeout))
1155  timeout = nextpdu->t - (now - ctx->sendqueue_basetime);
1156 
1157  if (ctx->dtls_context) {
1160  if (tls_timeout > 0) {
1161  if (tls_timeout < now + COAP_TICKS_PER_SECOND / 10)
1162  tls_timeout = now + COAP_TICKS_PER_SECOND / 10;
1163  coap_log(LOG_DEBUG, "** DTLS global timeout set to %dms\n",
1164  (int)((tls_timeout - now) * 1000 / COAP_TICKS_PER_SECOND));
1165  if (timeout == 0 || tls_timeout - now < timeout)
1166  timeout = tls_timeout - now;
1167  }
1168  } else {
1169  LL_FOREACH(ctx->endpoint, ep) {
1170  if (ep->proto == COAP_PROTO_DTLS) {
1171  SESSIONS_ITER(ep->sessions, s, rtmp) {
1172  if (s->state == COAP_SESSION_STATE_HANDSHAKE &&
1173  s->proto == COAP_PROTO_DTLS && s->tls) {
1174  coap_tick_t tls_timeout = coap_dtls_get_timeout(s, now);
1175  while (tls_timeout > 0 && tls_timeout <= now) {
1176  coap_log(LOG_DEBUG, "** %s: DTLS retransmit timeout\n",
1177  coap_session_str(s));
1178  /* Make sure the session object is not deleted in any callbacks */
1181  if (s->tls)
1182  tls_timeout = coap_dtls_get_timeout(s, now);
1183  else {
1184  tls_timeout = 0;
1185  timeout = 1;
1186  }
1188  }
1189  if (tls_timeout > 0 && (timeout == 0 || tls_timeout - now < timeout))
1190  timeout = tls_timeout - now;
1191  }
1192  }
1193  }
1194  }
1195  SESSIONS_ITER(ctx->sessions, s, rtmp) {
1196  if (s->state == COAP_SESSION_STATE_HANDSHAKE &&
1197  s->proto == COAP_PROTO_DTLS && s->tls) {
1198  coap_tick_t tls_timeout = coap_dtls_get_timeout(s, now);
1199  while (tls_timeout > 0 && tls_timeout <= now) {
1200  coap_log(LOG_DEBUG, "** %s: DTLS retransmit timeout\n", coap_session_str(s));
1201  /* Make sure the session object is not deleted in any callbacks */
1204  if (s->tls)
1205  tls_timeout = coap_dtls_get_timeout(s, now);
1206  else {
1207  tls_timeout = 0;
1208  timeout = 1;
1209  }
1211  }
1212  if (tls_timeout > 0 && (timeout == 0 || tls_timeout - now < timeout))
1213  timeout = tls_timeout - now;
1214  }
1215  }
1216  }
1217  }
1218 
1219  return (unsigned int)((timeout * 1000 + COAP_TICKS_PER_SECOND - 1) / COAP_TICKS_PER_SECOND);
1220 }
1221 
1222 #ifndef RIOT_VERSION
1223 int
1225  return coap_io_process_with_fds(ctx, timeout_ms, 0, NULL, NULL, NULL);
1226 }
1227 
1228 int
1230  int enfds, fd_set *ereadfds, fd_set *ewritefds,
1231  fd_set *eexceptfds) {
1232 #if COAP_CONSTRAINED_STACK
1233  static coap_mutex_t static_mutex = COAP_MUTEX_INITIALIZER;
1234 # ifndef COAP_EPOLL_SUPPORT
1235  static fd_set readfds, writefds, exceptfds;
1236  static coap_socket_t *sockets[64];
1237  unsigned int num_sockets = 0;
1238 # endif /* ! COAP_EPOLL_SUPPORT */
1239 #else /* ! COAP_CONSTRAINED_STACK */
1240 # ifndef COAP_EPOLL_SUPPORT
1241  fd_set readfds, writefds, exceptfds;
1242  coap_socket_t *sockets[64];
1243  unsigned int num_sockets = 0;
1244 # endif /* ! COAP_EPOLL_SUPPORT */
1245 #endif /* ! COAP_CONSTRAINED_STACK */
1246  coap_fd_t nfds = 0;
1247  coap_tick_t before, now;
1248  unsigned int timeout;
1249 #ifndef COAP_EPOLL_SUPPORT
1250  struct timeval tv;
1251  int result;
1252  unsigned int i;
1253 #endif /* ! COAP_EPOLL_SUPPORT */
1254 
1255 #if COAP_CONSTRAINED_STACK
1256  coap_mutex_lock(&static_mutex);
1257 #endif /* COAP_CONSTRAINED_STACK */
1258 
1259  coap_ticks(&before);
1260 
1261 #ifndef COAP_EPOLL_SUPPORT
1262  timeout = coap_io_prepare_io(ctx, sockets,
1263  (sizeof(sockets) / sizeof(sockets[0])),
1264  &num_sockets, before);
1265  if (timeout == 0 || timeout_ms < timeout)
1266  timeout = timeout_ms;
1267 
1268  if (ereadfds) {
1269  readfds = *ereadfds;
1270  nfds = enfds;
1271  }
1272  else {
1273  FD_ZERO(&readfds);
1274  }
1275  if (ewritefds) {
1276  writefds = *ewritefds;
1277  nfds = enfds;
1278  }
1279  else {
1280  FD_ZERO(&writefds);
1281  }
1282  if (eexceptfds) {
1283  exceptfds = *eexceptfds;
1284  nfds = enfds;
1285  }
1286  else {
1287  FD_ZERO(&exceptfds);
1288  }
1289  for (i = 0; i < num_sockets; i++) {
1290  if (sockets[i]->fd + 1 > nfds)
1291  nfds = sockets[i]->fd + 1;
1292  if (sockets[i]->flags & COAP_SOCKET_WANT_READ)
1293  FD_SET(sockets[i]->fd, &readfds);
1294  if (sockets[i]->flags & COAP_SOCKET_WANT_WRITE)
1295  FD_SET(sockets[i]->fd, &writefds);
1296 #if !COAP_DISABLE_TCP
1297  if (sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT)
1298  FD_SET(sockets[i]->fd, &readfds);
1299  if (sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) {
1300  FD_SET(sockets[i]->fd, &writefds);
1301  FD_SET(sockets[i]->fd, &exceptfds);
1302  }
1303 #endif /* !COAP_DISABLE_TCP */
1304  }
1305 
1306  if (timeout_ms == COAP_IO_NO_WAIT) {
1307  tv.tv_usec = 0;
1308  tv.tv_sec = 0;
1309  timeout = 1;
1310  }
1311  else if (timeout > 0) {
1312  tv.tv_usec = (timeout % 1000) * 1000;
1313  tv.tv_sec = (long)(timeout / 1000);
1314  }
1315 
1316  result = select((int)nfds, &readfds, &writefds, &exceptfds, timeout > 0 ? &tv : NULL);
1317 
1318  if (result < 0) { /* error */
1319 #ifdef _WIN32
1320  if (WSAGetLastError() != WSAEINVAL) { /* May happen because of ICMP */
1321 #else
1322  if (errno != EINTR) {
1323 #endif
1325 #if COAP_CONSTRAINED_STACK
1326  coap_mutex_unlock(&static_mutex);
1327 #endif /* COAP_CONSTRAINED_STACK */
1328  return -1;
1329  }
1330  }
1331 
1332  if (result > 0) {
1333  for (i = 0; i < num_sockets; i++) {
1334  if ((sockets[i]->flags & COAP_SOCKET_WANT_READ) && FD_ISSET(sockets[i]->fd, &readfds))
1335  sockets[i]->flags |= COAP_SOCKET_CAN_READ;
1336 #if !COAP_DISABLE_TCP
1337  if ((sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) && FD_ISSET(sockets[i]->fd, &readfds))
1338  sockets[i]->flags |= COAP_SOCKET_CAN_ACCEPT;
1339  if ((sockets[i]->flags & COAP_SOCKET_WANT_WRITE) && FD_ISSET(sockets[i]->fd, &writefds))
1340  sockets[i]->flags |= COAP_SOCKET_CAN_WRITE;
1341  if ((sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) && (FD_ISSET(sockets[i]->fd, &writefds) || FD_ISSET(sockets[i]->fd, &exceptfds)))
1342  sockets[i]->flags |= COAP_SOCKET_CAN_CONNECT;
1343 #endif /* !COAP_DISABLE_TCP */
1344  }
1345  }
1346 
1347  coap_ticks(&now);
1348  coap_io_do_io(ctx, now);
1349  if (ereadfds) {
1350  *ereadfds = readfds;
1351  }
1352  if (ewritefds) {
1353  *ewritefds = writefds;
1354  }
1355  if (eexceptfds) {
1356  *eexceptfds = exceptfds;
1357  }
1358 
1359 #else /* COAP_EPOLL_SUPPORT */
1360  (void)ereadfds;
1361  (void)ewritefds;
1362  (void)eexceptfds;
1363  (void)enfds;
1364 
1365  timeout = coap_io_prepare_epoll(ctx, before);
1366 
1367  if (timeout == 0 || timeout_ms < timeout)
1368  timeout = timeout_ms;
1369 
1370  do {
1371  struct epoll_event events[COAP_MAX_EPOLL_EVENTS];
1372  int etimeout = timeout;
1373 
1374  /* Potentially adjust based on what the caller wants */
1375  if (timeout_ms == COAP_IO_NO_WAIT) {
1376  etimeout = 0;
1377  }
1378  else if (timeout == COAP_IO_WAIT) {
1379  /* coap_io_prepare_epoll() returned 0 and timeout_ms COAP_IO_WAIT (0) */
1380  etimeout = -1;
1381  }
1382  else if (etimeout < 0) {
1383  /* epoll_wait cannot wait longer than this as int timeout parameter */
1384  etimeout = INT_MAX;
1385  }
1386 
1387  nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, etimeout);
1388  if (nfds < 0) {
1389  if (errno != EINTR) {
1390  coap_log (LOG_ERR, "epoll_wait: unexpected error: %s (%d)\n",
1391  coap_socket_strerror(), nfds);
1392  }
1393  break;
1394  }
1395 
1396  coap_io_do_epoll(ctx, events, nfds);
1397 
1398  /*
1399  * reset to COAP_IO_NO_WAIT (which causes etimeout to become 0)
1400  * incase we have to do another iteration
1401  * (COAP_MAX_EPOLL_EVENTS insufficient)
1402  */
1403  timeout_ms = COAP_IO_NO_WAIT;
1404 
1405  /* Keep retrying until less than COAP_MAX_EPOLL_EVENTS are returned */
1406  } while (nfds == COAP_MAX_EPOLL_EVENTS);
1407 
1409  coap_ticks(&now);
1410 #endif /* COAP_EPOLL_SUPPORT */
1411 
1412 #if COAP_CONSTRAINED_STACK
1413  coap_mutex_unlock(&static_mutex);
1414 #endif /* COAP_CONSTRAINED_STACK */
1415 
1416  return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND);
1417 }
1418 #endif /* RIOT_VERSION */
1419 
1420 #else /* WITH_CONTIKI */
1421 int coap_io_process(coap_context_t *ctx, uint32_t timeout_ms) {
1422  coap_tick_t now;
1423 
1424  coap_ticks(&now);
1425  /* There is something to read on the endpoint */
1427  /* read in, and send off any responses */
1428  coap_io_do_io(ctx, now); /* read received data */
1429  return -1;
1430 }
1431 
1432 unsigned int
1433 coap_io_prepare(coap_context_t *ctx,
1434  coap_socket_t *sockets[],
1435  unsigned int max_sockets,
1436  unsigned int *num_sockets,
1437  coap_tick_t now)
1438 {
1439  *num_sockets = 0;
1440  return 0;
1441 }
1442 #endif /* WITH_CONTIKI */
1443 
1444 #ifdef _WIN32
1445 const char *coap_socket_format_errno(int error) {
1446  static char szError[256];
1447  if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)szError, (DWORD)sizeof(szError), NULL) == 0)
1448  strcpy(szError, "Unknown error");
1449  return szError;
1450 }
1451 
1452 const char *coap_socket_strerror(void) {
1453  return coap_socket_format_errno(WSAGetLastError());
1454 }
1455 #else /* _WIN32 */
1456 const char *coap_socket_format_errno(int error) {
1457  return strerror(error);
1458 }
1459 const char *coap_socket_strerror(void) {
1460  return coap_socket_format_errno(errno);
1461 }
1462 #endif /* _WIN32 */
1463 
1464 ssize_t
1466  const uint8_t *data, size_t data_len) {
1467  return session->context->network_send(sock, session, data, data_len);
1468 }
1469 
1470 #undef SIN6
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
Definition: address.c:98
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
Definition: address.c:81
COAP_STATIC_INLINE int coap_address_isany(const coap_address_t *a)
Checks if given address object a denotes the wildcard address.
Definition: address.h:188
COAP_STATIC_INLINE void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
Definition: address.h:150
int coap_debug_send_packet(void)
Check to see whether a packet should be sent or not.
Definition: coap_debug.c:906
Pulls together all the internal only header files.
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)
Definition: coap_io.c:236
ssize_t coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len)
Definition: coap_io.c:457
void coap_socket_close(coap_socket_t *sock)
Definition: coap_io.c:347
ssize_t coap_socket_send(coap_socket_t *sock, coap_session_t *session, const uint8_t *data, size_t data_len)
Definition: coap_io.c:1465
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:729
ssize_t coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len)
Definition: coap_io.c:406
#define SOL_IP
Definition: coap_io.c:518
ssize_t coap_network_read(coap_socket_t *sock, coap_packet_t *packet)
Function interface for reading data.
Definition: coap_io.c:736
int coap_socket_bind_udp(coap_socket_t *sock, const coap_address_t *listen_addr, coap_address_t *bound_addr)
Definition: coap_io.c:152
ssize_t coap_network_send(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen)
Definition: coap_io.c:555
#define iov_len_t
Definition: coap_io.c:546
const char * coap_socket_strerror(void)
Definition: coap_io.c:1459
const char * coap_socket_format_errno(int error)
Definition: coap_io.c:1456
void coap_mfree_endpoint(coap_endpoint_t *ep)
Definition: coap_io.c:147
coap_endpoint_t * coap_malloc_endpoint(void)
Definition: coap_io.c:142
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
Definition: coap_io.h:91
#define COAP_SOCKET_WANT_ACCEPT
non blocking server socket is waiting for accept
Definition: coap_io.h:85
#define coap_closesocket
Definition: coap_io.h:41
#define COAP_MAX_EPOLL_EVENTS
Definition: coap_io.h:31
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
Definition: coap_io.h:88
#define COAP_RXBUFFER_SIZE
Definition: coap_io.h:22
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
Definition: coap_io.h:83
#define COAP_SOCKET_ERROR
Definition: coap_io.h:42
@ COAP_NACK_NOT_DELIVERABLE
Definition: coap_io.h:216
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
Definition: coap_io.h:89
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
Definition: coap_io.h:84
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
Definition: coap_io.h:90
int coap_fd_t
Definition: coap_io.h:40
void coap_epoll_ctl_mod(coap_socket_t *sock, uint32_t events, const char *func)
#define COAP_SOCKET_WANT_CONNECT
non blocking client socket is waiting for connect
Definition: coap_io.h:86
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
Definition: coap_io.h:87
#define COAP_SOCKET_CONNECTED
the socket is connected
Definition: coap_io.h:82
#define COAP_SOCKET_EMPTY
coap_socket_flags_t values
Definition: coap_io.h:79
#define COAP_INVALID_SOCKET
Definition: coap_io.h:43
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context UNUSED)
Definition: coap_notls.c:127
coap_tick_t coap_dtls_get_timeout(coap_session_t *session UNUSED, coap_tick_t now UNUSED)
Definition: coap_notls.c:132
void coap_dtls_handle_timeout(coap_session_t *session UNUSED)
Definition: coap_notls.c:136
coap_session_t * coap_session_reference(coap_session_t *session)
Increment reference counter on a session.
Definition: coap_session.c:68
void coap_session_release(coap_session_t *session)
Decrement reference counter on a session.
Definition: coap_session.c:74
void coap_session_free(coap_session_t *session)
Definition: coap_session.c:190
coap_tid_t coap_session_send_ping(coap_session_t *session)
Send a ping message for the session.
Definition: coap_session.c:345
void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:420
#define INET6_ADDRSTRLEN
#define SESSIONS_ITER_SAFE(e, el, rtmp)
Definition: coap_session.h:640
#define COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:56
#define COAP_SESSION_STATE_CSM
Definition: coap_session.h:57
#define COAP_SESSION_TYPE_CLIENT
coap_session_type_t values
Definition: coap_session.h:46
#define COAP_PROTO_RELIABLE(p)
Definition: coap_session.h:40
#define COAP_SESSION_STATE_NONE
coap_session_state_t values
Definition: coap_session.h:54
#define COAP_SESSION_STATE_ESTABLISHED
Definition: coap_session.h:58
#define SESSIONS_ITER(e, el, rtmp)
Definition: coap_session.h:637
#define COAP_SESSION_TYPE_SERVER
server-side
Definition: coap_session.h:47
#define COAP_DEFAULT_SESSION_TIMEOUT
Definition: coap_session.h:35
void coap_io_do_io(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: net.c:1589
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:991
void coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition: net.c:1650
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:1039
int coap_io_process(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition: coap_io.c:1224
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:1229
#define COAP_IO_NO_WAIT
Definition: net.h:734
#define COAP_IO_WAIT
Definition: net.h:733
void coap_expire_cache_entries(coap_context_t *ctx)
Expire coap_cache_entry_t entries.
Definition: coap_cache.c:239
void coap_ticks(coap_tick_t *t)
Sets t to the internal time with COAP_TICKS_PER_SECOND resolution.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition: coap_time.h:120
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition: coap_time.h:135
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition: coap_notls.c:123
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition: coap_debug.c:61
size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len)
Print the address into the defined buffer.
Definition: coap_debug.c:167
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log(level,...)
Logging function.
Definition: coap_debug.h:150
@ LOG_ERR
Error.
Definition: coap_debug.h:53
@ LOG_CRIT
Critical.
Definition: coap_debug.h:52
@ LOG_INFO
Information.
Definition: coap_debug.h:56
@ LOG_ALERT
Alert.
Definition: coap_debug.h:51
@ LOG_WARNING
Warning.
Definition: coap_debug.h:54
@ LOG_DEBUG
Debug.
Definition: coap_debug.h:57
@ LOG_EMERG
Emergency.
Definition: coap_debug.h:50
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.
@ COAP_ENDPOINT
Definition: mem.h:36
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition: net.c:266
coap_queue_t * coap_pop_next(coap_context_t *context)
Returns the next pdu to send and removes it from the sendqeue.
Definition: net.c:274
coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition: net.c:1191
#define COAP_PROTO_DTLS
Definition: pdu.h:345
#define COAP_INVALID_TID
Indicates an invalid transaction id.
Definition: pdu.h:247
void coap_check_notify(coap_context_t *context)
Checks for all known resources, if they are dirty and notifies subscribed observers.
Definition: resource.c:999
coap_address_t remote
remote address and port
Definition: coap_io.h:49
coap_address_t local
local address and port
Definition: coap_io.h:50
multi-purpose address abstraction
Definition: address.h:94
socklen_t size
size of addr
Definition: address.h:95
struct sockaddr_in sin
Definition: address.h:98
struct sockaddr_in6 sin6
Definition: address.h:99
struct sockaddr sa
Definition: address.h:97
union coap_address_t::@0 addr
The CoAP stack's global state is stored in a coap_context_t object.
Definition: net.h:141
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
Definition: net.h:159
unsigned int csm_timeout
Timeout for waiting for a CSM from the remote side.
Definition: net.h:203
coap_session_t * sessions
client sessions
Definition: net.h:162
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
Definition: net.h:202
ssize_t(* network_send)(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen)
Definition: net.h:187
void * dtls_context
Definition: net.h:195
coap_endpoint_t * endpoint
the endpoints used for listening
Definition: net.h:161
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
Definition: net.h:199
Abstraction of virtual endpoint that can be attached to coap_context_t.
struct coap_context_t * context
endpoint's context
struct coap_session_t * sessions
hash table or list of active sessions
coap_socket_t sock
socket object for the interface, if any
coap_proto_t proto
protocol used on this interface
size_t length
length of payload
Definition: coap_io.h:208
coap_addr_tuple_t addr_info
local and remote addresses
Definition: coap_io.h:206
unsigned char payload[COAP_RXBUFFER_SIZE]
payload
Definition: coap_io.h:209
int ifindex
the interface index
Definition: coap_io.h:207
Queue entry.
Definition: net.h:36
coap_tick_t t
when to send PDU for the next time
Definition: net.h:38
coap_tick_t last_pong
Definition: coap_session.h:87
coap_tick_t last_rx_tx
Definition: coap_session.h:84
coap_socket_t sock
socket object for the session, if any
Definition: coap_session.h:71
coap_session_state_t state
current state of relationaship with peer
Definition: coap_session.h:63
coap_addr_tuple_t addr_info
key: remote/local address info
Definition: coap_session.h:69
coap_proto_t proto
protocol used
Definition: coap_session.h:61
struct coap_queue_t * delayqueue
list of delayed messages waiting to be sent
Definition: coap_session.h:79
struct coap_context_t * context
session's context
Definition: coap_session.h:73
void * tls
security parameters
Definition: coap_session.h:74
coap_tick_t last_ping
Definition: coap_session.h:86
coap_session_type_t type
client or server side socket
Definition: coap_session.h:62
coap_tid_t last_ping_mid
the last keepalive message id that was used in this session
Definition: coap_session.h:78
coap_tick_t csm_tx
Definition: coap_session.h:88
int ifindex
interface index
Definition: coap_session.h:70
coap_endpoint_t * endpoint
Definition: coap_io.h:69
coap_fd_t fd
Definition: coap_io.h:59
struct coap_session_t * session
Definition: coap_io.h:65
coap_socket_flags_t flags
Definition: coap_io.h:64
struct in6_addr ipi6_addr
Definition: coap_io.c:505
unsigned int ipi6_ifindex
Definition: coap_io.c:506
struct in_addr ipi_spec_dst
Definition: coap_io.c:511
struct in_addr ipi_addr
Definition: coap_io.c:512
int ipi_ifindex
Definition: coap_io.c:510
unsigned int uint32_t
Definition: uthash.h:78
unsigned char uint8_t
Definition: uthash.h:79
#define LL_FOREACH(head, el)
Definition: utlist.h:413