1 /**
2 * @file
3 * @brief BSD Sockets compatible API definitions
4 *
5 * An API for applications to use BSD Sockets like API.
6 */
7
8 /*
9 * Copyright (c) 2017-2018 Linaro Limited
10 * Copyright (c) 2021 Nordic Semiconductor
11 *
12 * SPDX-License-Identifier: Apache-2.0
13 */
14
15 #ifndef ZEPHYR_INCLUDE_NET_SOCKET_H_
16 #define ZEPHYR_INCLUDE_NET_SOCKET_H_
17
18 /**
19 * @brief BSD Sockets compatible API
20 * @defgroup bsd_sockets BSD Sockets compatible API
21 * @since 1.9
22 * @version 1.0.0
23 * @ingroup networking
24 * @{
25 */
26
27 #include <zephyr/kernel.h>
28 #include <sys/types.h>
29 #include <zephyr/types.h>
30 #include <zephyr/device.h>
31 #include <zephyr/net/net_ip.h>
32 #include <zephyr/net/socket_select.h>
33 #include <zephyr/net/socket_poll.h>
34 #include <zephyr/sys/iterable_sections.h>
35 #include <zephyr/sys/fdtable.h>
36 #include <zephyr/net/dns_resolve.h>
37 #include <stdlib.h>
38
39 #ifdef __cplusplus
40 extern "C" {
41 #endif
42
43 /**
44 * @name Options for poll()
45 * @{
46 */
47 /* ZSOCK_POLL* values are compatible with Linux */
48 /** zsock_poll: Poll for readability */
49 #define ZSOCK_POLLIN 1
50 /** zsock_poll: Poll for exceptional condition */
51 #define ZSOCK_POLLPRI 2
52 /** zsock_poll: Poll for writability */
53 #define ZSOCK_POLLOUT 4
54 /** zsock_poll: Poll results in error condition (output value only) */
55 #define ZSOCK_POLLERR 8
56 /** zsock_poll: Poll detected closed connection (output value only) */
57 #define ZSOCK_POLLHUP 0x10
58 /** zsock_poll: Invalid socket (output value only) */
59 #define ZSOCK_POLLNVAL 0x20
60 /** @} */
61
62 /**
63 * @name Options for sending and receiving data
64 * @{
65 */
66 /** zsock_recv: Read data without removing it from socket input queue */
67 #define ZSOCK_MSG_PEEK 0x02
68 /** zsock_recvmsg: Control data buffer too small.
69 */
70 #define ZSOCK_MSG_CTRUNC 0x08
71 /** zsock_recv: return the real length of the datagram, even when it was longer
72 * than the passed buffer
73 */
74 #define ZSOCK_MSG_TRUNC 0x20
75 /** zsock_recv/zsock_send: Override operation to non-blocking */
76 #define ZSOCK_MSG_DONTWAIT 0x40
77 /** zsock_recv: block until the full amount of data can be returned */
78 #define ZSOCK_MSG_WAITALL 0x100
79 /** @} */
80
81 /**
82 * @name Options for shutdown() function
83 * @{
84 */
85 /* Well-known values, e.g. from Linux man 2 shutdown:
86 * "The constants SHUT_RD, SHUT_WR, SHUT_RDWR have the value 0, 1, 2,
87 * respectively". Some software uses numeric values.
88 */
89 /** zsock_shutdown: Shut down for reading */
90 #define ZSOCK_SHUT_RD 0
91 /** zsock_shutdown: Shut down for writing */
92 #define ZSOCK_SHUT_WR 1
93 /** zsock_shutdown: Shut down for both reading and writing */
94 #define ZSOCK_SHUT_RDWR 2
95 /** @} */
96
97 /**
98 * @defgroup secure_sockets_options Socket options for TLS
99 * @since 1.13
100 * @version 0.8.0
101 * @{
102 */
103 /**
104 * @name Socket options for TLS
105 * @{
106 */
107
108 /** Protocol level for TLS.
109 * Here, the same socket protocol level for TLS as in Linux was used.
110 */
111 #define SOL_TLS 282
112
113 /** Socket option to select TLS credentials to use. It accepts and returns an
114 * array of sec_tag_t that indicate which TLS credentials should be used with
115 * specific socket.
116 */
117 #define TLS_SEC_TAG_LIST 1
118 /** Write-only socket option to set hostname. It accepts a string containing
119 * the hostname (may be NULL to disable hostname verification). By default,
120 * hostname check is enforced for TLS clients.
121 */
122 #define TLS_HOSTNAME 2
123 /** Socket option to select ciphersuites to use. It accepts and returns an array
124 * of integers with IANA assigned ciphersuite identifiers.
125 * If not set, socket will allow all ciphersuites available in the system
126 * (mbedTLS default behavior).
127 */
128 #define TLS_CIPHERSUITE_LIST 3
129 /** Read-only socket option to read a ciphersuite chosen during TLS handshake.
130 * It returns an integer containing an IANA assigned ciphersuite identifier
131 * of chosen ciphersuite.
132 */
133 #define TLS_CIPHERSUITE_USED 4
134 /** Write-only socket option to set peer verification level for TLS connection.
135 * This option accepts an integer with a peer verification level, compatible
136 * with mbedTLS values:
137 * - 0 - none
138 * - 1 - optional
139 * - 2 - required
140 *
141 * If not set, socket will use mbedTLS defaults (none for servers, required
142 * for clients).
143 */
144 #define TLS_PEER_VERIFY 5
145 /** Write-only socket option to set role for DTLS connection. This option
146 * is irrelevant for TLS connections, as for them role is selected based on
147 * connect()/listen() usage. By default, DTLS will assume client role.
148 * This option accepts an integer with a TLS role, compatible with
149 * mbedTLS values:
150 * - 0 - client
151 * - 1 - server
152 */
153 #define TLS_DTLS_ROLE 6
154 /** Socket option for setting the supported Application Layer Protocols.
155 * It accepts and returns a const char array of NULL terminated strings
156 * representing the supported application layer protocols listed during
157 * the TLS handshake.
158 */
159 #define TLS_ALPN_LIST 7
160 /** Socket option to set DTLS min handshake timeout. The timeout starts at min,
161 * and upon retransmission the timeout is doubled util max is reached.
162 * Min and max arguments are separate options. The time unit is ms.
163 */
164 #define TLS_DTLS_HANDSHAKE_TIMEOUT_MIN 8
165
166 /** Socket option to set DTLS max handshake timeout. The timeout starts at min,
167 * and upon retransmission the timeout is doubled util max is reached.
168 * Min and max arguments are separate options. The time unit is ms.
169 */
170 #define TLS_DTLS_HANDSHAKE_TIMEOUT_MAX 9
171
172 /** Socket option for preventing certificates from being copied to the mbedTLS
173 * heap if possible. The option is only effective for DER certificates and is
174 * ignored for PEM certificates.
175 */
176 #define TLS_CERT_NOCOPY 10
177 /** TLS socket option to use with offloading. The option instructs the network
178 * stack only to offload underlying TCP/UDP communication. The TLS/DTLS
179 * operation is handled by a native TLS/DTLS socket implementation from Zephyr.
180 *
181 * Note, that this option is only applicable if socket dispatcher is used
182 * (CONFIG_NET_SOCKETS_OFFLOAD_DISPATCHER is enabled).
183 * In such case, it should be the first socket option set on a newly created
184 * socket. After that, the application may use SO_BINDTODEVICE to choose the
185 * dedicated network interface for the underlying TCP/UDP socket.
186 */
187 #define TLS_NATIVE 11
188 /** Socket option to control TLS session caching on a socket. Accepted values:
189 * - 0 - Disabled.
190 * - 1 - Enabled.
191 */
192 #define TLS_SESSION_CACHE 12
193 /** Write-only socket option to purge session cache immediately.
194 * This option accepts any value.
195 */
196 #define TLS_SESSION_CACHE_PURGE 13
197 /** Write-only socket option to control DTLS CID.
198 * The option accepts an integer, indicating the setting.
199 * Accepted values for the option are: 0, 1 and 2.
200 * Effective when set before connecting to the socket.
201 * - 0 - DTLS CID will be disabled.
202 * - 1 - DTLS CID will be enabled, and a 0 length CID value to be sent to the
203 * peer.
204 * - 2 - DTLS CID will be enabled, and the most recent value set with
205 * TLS_DTLS_CID_VALUE will be sent to the peer. Otherwise, a random value
206 * will be used.
207 */
208 #define TLS_DTLS_CID 14
209 /** Read-only socket option to get DTLS CID status.
210 * The option accepts a pointer to an integer, indicating the setting upon
211 * return.
212 * Returned values for the option are:
213 * - 0 - DTLS CID is disabled.
214 * - 1 - DTLS CID is received on the downlink.
215 * - 2 - DTLS CID is sent to the uplink.
216 * - 3 - DTLS CID is used in both directions.
217 */
218 #define TLS_DTLS_CID_STATUS 15
219 /** Socket option to set or get the value of the DTLS connection ID to be
220 * used for the DTLS session.
221 * The option accepts a byte array, holding the CID value.
222 */
223 #define TLS_DTLS_CID_VALUE 16
224 /** Read-only socket option to get the value of the DTLS connection ID
225 * received from the peer.
226 * The option accepts a pointer to a byte array, holding the CID value upon
227 * return. The optlen returned will be 0 if the peer did not provide a
228 * connection ID, otherwise will contain the length of the CID value.
229 */
230 #define TLS_DTLS_PEER_CID_VALUE 17
231 /** Socket option to configure DTLS socket behavior on connect().
232 * If set, DTLS connect() will execute the handshake with the configured peer.
233 * This is the default behavior.
234 * Otherwise, DTLS connect() will only configure peer address (as with regular
235 * UDP socket) and will not attempt to execute DTLS handshake. The handshake
236 * will take place in consecutive send()/recv() call.
237 */
238 #define TLS_DTLS_HANDSHAKE_ON_CONNECT 18
239
240 /* Valid values for @ref TLS_PEER_VERIFY option */
241 #define TLS_PEER_VERIFY_NONE 0 /**< Peer verification disabled. */
242 #define TLS_PEER_VERIFY_OPTIONAL 1 /**< Peer verification optional. */
243 #define TLS_PEER_VERIFY_REQUIRED 2 /**< Peer verification required. */
244
245 /* Valid values for @ref TLS_DTLS_ROLE option */
246 #define TLS_DTLS_ROLE_CLIENT 0 /**< Client role in a DTLS session. */
247 #define TLS_DTLS_ROLE_SERVER 1 /**< Server role in a DTLS session. */
248
249 /* Valid values for @ref TLS_CERT_NOCOPY option */
250 #define TLS_CERT_NOCOPY_NONE 0 /**< Cert duplicated in heap */
251 #define TLS_CERT_NOCOPY_OPTIONAL 1 /**< Cert not copied in heap if DER */
252
253 /* Valid values for @ref TLS_SESSION_CACHE option */
254 #define TLS_SESSION_CACHE_DISABLED 0 /**< Disable TLS session caching. */
255 #define TLS_SESSION_CACHE_ENABLED 1 /**< Enable TLS session caching. */
256
257 /* Valid values for @ref TLS_DTLS_CID (Connection ID) option */
258 #define TLS_DTLS_CID_DISABLED 0 /**< CID is disabled */
259 #define TLS_DTLS_CID_SUPPORTED 1 /**< CID is supported */
260 #define TLS_DTLS_CID_ENABLED 2 /**< CID is enabled */
261
262 /* Valid values for @ref TLS_DTLS_CID_STATUS option */
263 #define TLS_DTLS_CID_STATUS_DISABLED 0 /**< CID is disabled */
264 #define TLS_DTLS_CID_STATUS_DOWNLINK 1 /**< CID is in use by us */
265 #define TLS_DTLS_CID_STATUS_UPLINK 2 /**< CID is in use by peer */
266 #define TLS_DTLS_CID_STATUS_BIDIRECTIONAL 3 /**< CID is in use by us and peer */
267 /** @} */ /* for @name */
268 /** @} */ /* for @defgroup */
269
270 /**
271 * @brief Definition used when querying address information.
272 *
273 * A linked list of these descriptors is returned by getaddrinfo(). The struct
274 * is also passed as hints when calling the getaddrinfo() function.
275 */
276 struct zsock_addrinfo {
277 struct zsock_addrinfo *ai_next; /**< Pointer to next address entry */
278 int ai_flags; /**< Additional options */
279 int ai_family; /**< Address family of the returned addresses */
280 int ai_socktype; /**< Socket type, for example SOCK_STREAM or SOCK_DGRAM */
281 int ai_protocol; /**< Protocol for addresses, 0 means any protocol */
282 int ai_eflags; /**< Extended flags for special usage */
283 socklen_t ai_addrlen; /**< Length of the socket address */
284 struct sockaddr *ai_addr; /**< Pointer to the address */
285 char *ai_canonname; /**< Optional official name of the host */
286
287 /** @cond INTERNAL_HIDDEN */
288 struct sockaddr _ai_addr;
289 char _ai_canonname[DNS_MAX_NAME_SIZE + 1];
290 /** @endcond */
291 };
292
293 /**
294 * @brief Obtain a file descriptor's associated net context
295 *
296 * With CONFIG_USERSPACE enabled, the kernel's object permission system
297 * must apply to socket file descriptors. When a socket is opened, by default
298 * only the caller has permission, access by other threads will fail unless
299 * they have been specifically granted permission.
300 *
301 * This is achieved by tagging data structure definitions that implement the
302 * underlying object associated with a network socket file descriptor with
303 * '__net_socket`. All pointers to instances of these will be known to the
304 * kernel as kernel objects with type K_OBJ_NET_SOCKET.
305 *
306 * This API is intended for threads that need to grant access to the object
307 * associated with a particular file descriptor to another thread. The
308 * returned pointer represents the underlying K_OBJ_NET_SOCKET and
309 * may be passed to APIs like k_object_access_grant().
310 *
311 * In a system like Linux which has the notion of threads running in processes
312 * in a shared virtual address space, this sort of management is unnecessary as
313 * the scope of file descriptors is implemented at the process level.
314 *
315 * However in Zephyr the file descriptor scope is global, and MPU-based systems
316 * are not able to implement a process-like model due to the lack of memory
317 * virtualization hardware. They use discrete object permissions and memory
318 * domains instead to define thread access scope.
319 *
320 * User threads will have no direct access to the returned object
321 * and will fault if they try to access its memory; the pointer can only be
322 * used to make permission assignment calls, which follow exactly the rules
323 * for other kernel objects like device drivers and IPC.
324 *
325 * @param sock file descriptor
326 * @return pointer to associated network socket object, or NULL if the
327 * file descriptor wasn't valid or the caller had no access permission
328 */
329 __syscall void *zsock_get_context_object(int sock);
330
331 /**
332 * @brief Create a network socket
333 *
334 * @details
335 * See POSIX.1-2017 article
336 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/socket.html
337 * for normative description.
338 * This function is also exposed as `socket()`
339 * if @kconfig{CONFIG_POSIX_API} is defined.
340 *
341 * If CONFIG_USERSPACE is enabled, the caller will be granted access to the
342 * context object associated with the returned file descriptor.
343 * @see zsock_get_context_object()
344 *
345 */
346 __syscall int zsock_socket(int family, int type, int proto);
347
348 /**
349 * @brief Create an unnamed pair of connected sockets
350 *
351 * @details
352 * See POSIX.1-2017 article
353 * https://pubs.opengroup.org/onlinepubs/009695399/functions/socketpair.html
354 * for normative description.
355 * This function is also exposed as `socketpair()`
356 * if @kconfig{CONFIG_POSIX_API} is defined.
357 */
358 __syscall int zsock_socketpair(int family, int type, int proto, int *sv);
359
360 /**
361 * @brief Close a network socket
362 *
363 * @details
364 * Close a network socket.
365 * This function is also exposed as `close()`
366 * if @kconfig{CONFIG_POSIX_API} is defined (in which case it
367 * may conflict with generic POSIX `close()` function).
368 */
369 __syscall int zsock_close(int sock);
370
371 /**
372 * @brief Shutdown socket send/receive operations
373 *
374 * @details
375 * See POSIX.1-2017 article
376 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/shutdown.html
377 * for normative description, but currently this function has no effect in
378 * Zephyr and provided solely for compatibility with existing code.
379 * This function is also exposed as `shutdown()`
380 * if @kconfig{CONFIG_POSIX_API} is defined.
381 */
382 __syscall int zsock_shutdown(int sock, int how);
383
384 /**
385 * @brief Bind a socket to a local network address
386 *
387 * @details
388 * See POSIX.1-2017 article
389 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html
390 * for normative description.
391 * This function is also exposed as `bind()`
392 * if @kconfig{CONFIG_POSIX_API} is defined.
393 */
394 __syscall int zsock_bind(int sock, const struct sockaddr *addr,
395 socklen_t addrlen);
396
397 /**
398 * @brief Connect a socket to a peer network address
399 *
400 * @details
401 * See POSIX.1-2017 article
402 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/connect.html
403 * for normative description.
404 * This function is also exposed as `connect()`
405 * if @kconfig{CONFIG_POSIX_API} is defined.
406 */
407 __syscall int zsock_connect(int sock, const struct sockaddr *addr,
408 socklen_t addrlen);
409
410 /**
411 * @brief Set up a STREAM socket to accept peer connections
412 *
413 * @details
414 * See POSIX.1-2017 article
415 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html
416 * for normative description.
417 * This function is also exposed as `listen()`
418 * if @kconfig{CONFIG_POSIX_API} is defined.
419 */
420 __syscall int zsock_listen(int sock, int backlog);
421
422 /**
423 * @brief Accept a connection on listening socket
424 *
425 * @details
426 * See POSIX.1-2017 article
427 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/accept.html
428 * for normative description.
429 * This function is also exposed as `accept()`
430 * if @kconfig{CONFIG_POSIX_API} is defined.
431 */
432 __syscall int zsock_accept(int sock, struct sockaddr *addr, socklen_t *addrlen);
433
434 /**
435 * @brief Send data to an arbitrary network address
436 *
437 * @details
438 * See POSIX.1-2017 article
439 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/sendto.html
440 * for normative description.
441 * This function is also exposed as `sendto()`
442 * if @kconfig{CONFIG_POSIX_API} is defined.
443 */
444 __syscall ssize_t zsock_sendto(int sock, const void *buf, size_t len,
445 int flags, const struct sockaddr *dest_addr,
446 socklen_t addrlen);
447
448 /**
449 * @brief Send data to a connected peer
450 *
451 * @details
452 * See POSIX.1-2017 article
453 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/send.html
454 * for normative description.
455 * This function is also exposed as `send()`
456 * if @kconfig{CONFIG_POSIX_API} is defined.
457 */
zsock_send(int sock,const void * buf,size_t len,int flags)458 static inline ssize_t zsock_send(int sock, const void *buf, size_t len,
459 int flags)
460 {
461 return zsock_sendto(sock, buf, len, flags, NULL, 0);
462 }
463
464 /**
465 * @brief Send data to an arbitrary network address
466 *
467 * @details
468 * See POSIX.1-2017 article
469 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html
470 * for normative description.
471 * This function is also exposed as `sendmsg()`
472 * if @kconfig{CONFIG_POSIX_API} is defined.
473 */
474 __syscall ssize_t zsock_sendmsg(int sock, const struct msghdr *msg,
475 int flags);
476
477 /**
478 * @brief Receive data from an arbitrary network address
479 *
480 * @details
481 * See POSIX.1-2017 article
482 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/recvfrom.html
483 * for normative description.
484 * This function is also exposed as `recvfrom()`
485 * if @kconfig{CONFIG_POSIX_API} is defined.
486 */
487 __syscall ssize_t zsock_recvfrom(int sock, void *buf, size_t max_len,
488 int flags, struct sockaddr *src_addr,
489 socklen_t *addrlen);
490
491 /**
492 * @brief Receive a message from an arbitrary network address
493 *
494 * @details
495 * See POSIX.1-2017 article
496 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html
497 * for normative description.
498 * This function is also exposed as `recvmsg()`
499 * if @kconfig{CONFIG_POSIX_API} is defined.
500 */
501 __syscall ssize_t zsock_recvmsg(int sock, struct msghdr *msg, int flags);
502
503 /**
504 * @brief Receive data from a connected peer
505 *
506 * @details
507 * See POSIX.1-2017 article
508 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/recv.html
509 * for normative description.
510 * This function is also exposed as `recv()`
511 * if @kconfig{CONFIG_POSIX_API} is defined.
512 */
zsock_recv(int sock,void * buf,size_t max_len,int flags)513 static inline ssize_t zsock_recv(int sock, void *buf, size_t max_len,
514 int flags)
515 {
516 return zsock_recvfrom(sock, buf, max_len, flags, NULL, NULL);
517 }
518
519 /**
520 * @brief Control blocking/non-blocking mode of a socket
521 *
522 * @details
523 * This functions allow to (only) configure a socket for blocking or
524 * non-blocking operation (O_NONBLOCK).
525 * This function is also exposed as `fcntl()`
526 * if @kconfig{CONFIG_POSIX_API} is defined (in which case
527 * it may conflict with generic POSIX `fcntl()` function).
528 */
529 __syscall int zsock_fcntl_impl(int sock, int cmd, int flags);
530
531 /** @cond INTERNAL_HIDDEN */
532
533 /*
534 * Need this wrapper because newer GCC versions got too smart and "typecheck"
535 * even macros.
536 */
zsock_fcntl_wrapper(int sock,int cmd,...)537 static inline int zsock_fcntl_wrapper(int sock, int cmd, ...)
538 {
539 va_list args;
540 int flags;
541
542 va_start(args, cmd);
543 flags = va_arg(args, int);
544 va_end(args);
545 return zsock_fcntl_impl(sock, cmd, flags);
546 }
547
548 #define zsock_fcntl zsock_fcntl_wrapper
549
550 /** @endcond */
551
552 /**
553 * @brief Control underlying socket parameters
554 *
555 * @details
556 * See POSIX.1-2017 article
557 * https://pubs.opengroup.org/onlinepubs/9699919799/functions/ioctl.html
558 * for normative description.
559 * This function enables querying or manipulating underlying socket parameters.
560 * Currently supported @p request values include `ZFD_IOCTL_FIONBIO`, and
561 * `ZFD_IOCTL_FIONREAD`, to set non-blocking mode, and query the number of
562 * bytes available to read, respectively.
563 * This function is also exposed as `ioctl()`
564 * if @kconfig{CONFIG_POSIX_API} is defined (in which case
565 * it may conflict with generic POSIX `ioctl()` function).
566 */
567 __syscall int zsock_ioctl_impl(int sock, unsigned long request, va_list ap);
568
569 /** @cond INTERNAL_HIDDEN */
570
zsock_ioctl_wrapper(int sock,unsigned long request,...)571 static inline int zsock_ioctl_wrapper(int sock, unsigned long request, ...)
572 {
573 int ret;
574 va_list args;
575
576 va_start(args, request);
577 ret = zsock_ioctl_impl(sock, request, args);
578 va_end(args);
579
580 return ret;
581 }
582
583 #define zsock_ioctl zsock_ioctl_wrapper
584
585 /** @endcond */
586
587 /**
588 * @brief Efficiently poll multiple sockets for events
589 *
590 * @details
591 * See POSIX.1-2017 article
592 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html
593 * for normative description.
594 * This function is also exposed as `poll()`
595 * if @kconfig{CONFIG_POSIX_API} is defined (in which case
596 * it may conflict with generic POSIX `poll()` function).
597 */
zsock_poll(struct zsock_pollfd * fds,int nfds,int timeout)598 static inline int zsock_poll(struct zsock_pollfd *fds, int nfds, int timeout)
599 {
600 return zvfs_poll(fds, nfds, timeout);
601 }
602
603 /**
604 * @brief Get various socket options
605 *
606 * @details
607 * See POSIX.1-2017 article
608 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockopt.html
609 * for normative description. In Zephyr this function supports a subset of
610 * socket options described by POSIX, but also some additional options
611 * available in Linux (some options are dummy and provided to ease porting
612 * of existing code).
613 * This function is also exposed as `getsockopt()`
614 * if @kconfig{CONFIG_POSIX_API} is defined.
615 */
616 __syscall int zsock_getsockopt(int sock, int level, int optname,
617 void *optval, socklen_t *optlen);
618
619 /**
620 * @brief Set various socket options
621 *
622 * @details
623 * See POSIX.1-2017 article
624 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/setsockopt.html
625 * for normative description. In Zephyr this function supports a subset of
626 * socket options described by POSIX, but also some additional options
627 * available in Linux (some options are dummy and provided to ease porting
628 * of existing code).
629 * This function is also exposed as `setsockopt()`
630 * if @kconfig{CONFIG_POSIX_API} is defined.
631 */
632 __syscall int zsock_setsockopt(int sock, int level, int optname,
633 const void *optval, socklen_t optlen);
634
635 /**
636 * @brief Get peer name
637 *
638 * @details
639 * See POSIX.1-2017 article
640 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/getpeername.html
641 * for normative description.
642 * This function is also exposed as `getpeername()`
643 * if @kconfig{CONFIG_POSIX_API} is defined.
644 */
645 __syscall int zsock_getpeername(int sock, struct sockaddr *addr,
646 socklen_t *addrlen);
647
648 /**
649 * @brief Get socket name
650 *
651 * @details
652 * See POSIX.1-2017 article
653 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockname.html
654 * for normative description.
655 * This function is also exposed as `getsockname()`
656 * if @kconfig{CONFIG_POSIX_API} is defined.
657 */
658 __syscall int zsock_getsockname(int sock, struct sockaddr *addr,
659 socklen_t *addrlen);
660
661 /**
662 * @brief Get local host name
663 *
664 * @details
665 * See POSIX.1-2017 article
666 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/gethostname.html
667 * for normative description.
668 * This function is also exposed as `gethostname()`
669 * if @kconfig{CONFIG_POSIX_API} is defined.
670 */
671 __syscall int zsock_gethostname(char *buf, size_t len);
672
673 /**
674 * @brief Convert network address from internal to numeric ASCII form
675 *
676 * @details
677 * See POSIX.1-2017 article
678 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/inet_ntop.html
679 * for normative description.
680 * This function is also exposed as `inet_ntop()`
681 * if @kconfig{CONFIG_POSIX_API} is defined.
682 */
zsock_inet_ntop(sa_family_t family,const void * src,char * dst,size_t size)683 static inline char *zsock_inet_ntop(sa_family_t family, const void *src,
684 char *dst, size_t size)
685 {
686 return net_addr_ntop(family, src, dst, size);
687 }
688
689 /**
690 * @brief Convert network address from numeric ASCII form to internal representation
691 *
692 * @details
693 * See POSIX.1-2017 article
694 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/inet_pton.html
695 * for normative description.
696 * This function is also exposed as `inet_pton()`
697 * if @kconfig{CONFIG_POSIX_API} is defined.
698 */
699 __syscall int zsock_inet_pton(sa_family_t family, const char *src, void *dst);
700
701 /** @cond INTERNAL_HIDDEN */
702 __syscall int z_zsock_getaddrinfo_internal(const char *host,
703 const char *service,
704 const struct zsock_addrinfo *hints,
705 struct zsock_addrinfo *res);
706 /** @endcond */
707
708 /* Flags for getaddrinfo() hints. */
709
710 /**
711 * @name Flags for getaddrinfo() hints
712 * @{
713 */
714 /** Address for bind() (vs for connect()) */
715 #define AI_PASSIVE 0x1
716 /** Fill in ai_canonname */
717 #define AI_CANONNAME 0x2
718 /** Assume host address is in numeric notation, don't DNS lookup */
719 #define AI_NUMERICHOST 0x4
720 /** May return IPv4 mapped address for IPv6 */
721 #define AI_V4MAPPED 0x8
722 /** May return both native IPv6 and mapped IPv4 address for IPv6 */
723 #define AI_ALL 0x10
724 /** IPv4/IPv6 support depends on local system config */
725 #define AI_ADDRCONFIG 0x20
726 /** Assume service (port) is numeric */
727 #define AI_NUMERICSERV 0x400
728 /** Extra flags present (see RFC 5014) */
729 #define AI_EXTFLAGS 0x800
730 /** @} */
731
732 /**
733 * @brief Resolve a domain name to one or more network addresses
734 *
735 * @details
736 * See POSIX.1-2017 article
737 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/getaddrinfo.html
738 * for normative description.
739 * This function is also exposed as `getaddrinfo()`
740 * if @kconfig{CONFIG_POSIX_API} is defined.
741 */
742 int zsock_getaddrinfo(const char *host, const char *service,
743 const struct zsock_addrinfo *hints,
744 struct zsock_addrinfo **res);
745
746 /**
747 * @brief Free results returned by zsock_getaddrinfo()
748 *
749 * @details
750 * See POSIX.1-2017 article
751 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
752 * for normative description.
753 * This function is also exposed as `freeaddrinfo()`
754 * if @kconfig{CONFIG_POSIX_API} is defined.
755 */
756 void zsock_freeaddrinfo(struct zsock_addrinfo *ai);
757
758 /**
759 * @brief Convert zsock_getaddrinfo() error code to textual message
760 *
761 * @details
762 * See POSIX.1-2017 article
763 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/gai_strerror.html
764 * for normative description.
765 * This function is also exposed as `gai_strerror()`
766 * if @kconfig{CONFIG_POSIX_API} is defined.
767 */
768 const char *zsock_gai_strerror(int errcode);
769
770 /**
771 * @name Flags for getnameinfo()
772 * @{
773 */
774 /** zsock_getnameinfo(): Resolve to numeric address. */
775 #define NI_NUMERICHOST 1
776 /** zsock_getnameinfo(): Resolve to numeric port number. */
777 #define NI_NUMERICSERV 2
778 /** zsock_getnameinfo(): Return only hostname instead of FQDN */
779 #define NI_NOFQDN 4
780 /** zsock_getnameinfo(): Dummy option for compatibility */
781 #define NI_NAMEREQD 8
782 /** zsock_getnameinfo(): Dummy option for compatibility */
783 #define NI_DGRAM 16
784
785 /* POSIX extensions */
786
787 /** zsock_getnameinfo(): Max supported hostname length */
788 #ifndef NI_MAXHOST
789 #define NI_MAXHOST 64
790 #endif
791 /** @} */
792
793 /**
794 * @brief Resolve a network address to a domain name or ASCII address
795 *
796 * @details
797 * See POSIX.1-2017 article
798 * http://pubs.opengroup.org/onlinepubs/9699919799/functions/getnameinfo.html
799 * for normative description.
800 * This function is also exposed as `getnameinfo()`
801 * if @kconfig{CONFIG_POSIX_API} is defined.
802 */
803 int zsock_getnameinfo(const struct sockaddr *addr, socklen_t addrlen,
804 char *host, socklen_t hostlen,
805 char *serv, socklen_t servlen, int flags);
806
807 /**
808 * @name Network interface name description
809 * @{
810 */
811 /** Network interface name length */
812 #if defined(CONFIG_NET_INTERFACE_NAME)
813 #define IFNAMSIZ CONFIG_NET_INTERFACE_NAME_LEN
814 #else
815 #define IFNAMSIZ Z_DEVICE_MAX_NAME_LEN
816 #endif
817
818 /** Interface description structure */
819 struct ifreq {
820 char ifr_name[IFNAMSIZ]; /**< Network interface name */
821 };
822 /** @} */
823
824 /**
825 * @name Socket level options (SOL_SOCKET)
826 * @{
827 */
828 /** Socket-level option */
829 #define SOL_SOCKET 1
830
831 /* Socket options for SOL_SOCKET level */
832
833 /** Recording debugging information (ignored, for compatibility) */
834 #define SO_DEBUG 1
835 /** address reuse */
836 #define SO_REUSEADDR 2
837 /** Type of the socket */
838 #define SO_TYPE 3
839 /** Async error */
840 #define SO_ERROR 4
841 /** Bypass normal routing and send directly to host (ignored, for compatibility) */
842 #define SO_DONTROUTE 5
843 /** Transmission of broadcast messages is supported (ignored, for compatibility) */
844 #define SO_BROADCAST 6
845
846 /** Size of socket send buffer */
847 #define SO_SNDBUF 7
848 /** Size of socket recv buffer */
849 #define SO_RCVBUF 8
850
851 /** Enable sending keep-alive messages on connections */
852 #define SO_KEEPALIVE 9
853 /** Place out-of-band data into receive stream (ignored, for compatibility) */
854 #define SO_OOBINLINE 10
855 /** Socket priority */
856 #define SO_PRIORITY 12
857 /** Socket lingers on close (ignored, for compatibility) */
858 #define SO_LINGER 13
859 /** Allow multiple sockets to reuse a single port */
860 #define SO_REUSEPORT 15
861
862 /** Receive low watermark (ignored, for compatibility) */
863 #define SO_RCVLOWAT 18
864 /** Send low watermark (ignored, for compatibility) */
865 #define SO_SNDLOWAT 19
866
867 /**
868 * Receive timeout
869 * Applies to receive functions like recv(), but not to connect()
870 */
871 #define SO_RCVTIMEO 20
872 /** Send timeout */
873 #define SO_SNDTIMEO 21
874
875 /** Bind a socket to an interface */
876 #define SO_BINDTODEVICE 25
877
878 /** Socket accepts incoming connections (ignored, for compatibility) */
879 #define SO_ACCEPTCONN 30
880
881 /** Timestamp TX RX or both packets. Supports multiple timestamp sources. */
882 #define SO_TIMESTAMPING 37
883
884 /** Protocol used with the socket */
885 #define SO_PROTOCOL 38
886
887 /** Domain used with SOCKET */
888 #define SO_DOMAIN 39
889
890 /** Enable SOCKS5 for Socket */
891 #define SO_SOCKS5 60
892
893 /** Socket TX time (when the data should be sent) */
894 #define SO_TXTIME 61
895 /** Socket TX time (same as SO_TXTIME) */
896 #define SCM_TXTIME SO_TXTIME
897
898 /** Timestamp generation flags */
899
900 /** Request RX timestamps generated by network adapter. */
901 #define SOF_TIMESTAMPING_RX_HARDWARE BIT(0)
902 /**
903 * Request TX timestamps generated by network adapter.
904 * This can be enabled via socket option or control messages.
905 */
906 #define SOF_TIMESTAMPING_TX_HARDWARE BIT(1)
907
908 /** */
909
910 /** @} */
911
912 /**
913 * @name TCP level options (IPPROTO_TCP)
914 * @{
915 */
916 /* Socket options for IPPROTO_TCP level */
917 /** Disable TCP buffering (ignored, for compatibility) */
918 #define TCP_NODELAY 1
919 /** Start keepalives after this period (seconds) */
920 #define TCP_KEEPIDLE 2
921 /** Interval between keepalives (seconds) */
922 #define TCP_KEEPINTVL 3
923 /** Number of keepalives before dropping connection */
924 #define TCP_KEEPCNT 4
925
926 /** @} */
927
928 /**
929 * @name IPv4 level options (IPPROTO_IP)
930 * @{
931 */
932 /* Socket options for IPPROTO_IP level */
933 /** Set or receive the Type-Of-Service value for an outgoing packet. */
934 #define IP_TOS 1
935
936 /** Set or receive the Time-To-Live value for an outgoing packet. */
937 #define IP_TTL 2
938
939 /** Pass an IP_PKTINFO ancillary message that contains a
940 * pktinfo structure that supplies some information about the
941 * incoming packet.
942 */
943 #define IP_PKTINFO 8
944
945 /**
946 * @brief Incoming IPv4 packet information.
947 *
948 * Used as ancillary data when calling recvmsg() and IP_PKTINFO socket
949 * option is set.
950 */
951 struct in_pktinfo {
952 unsigned int ipi_ifindex; /**< Network interface index */
953 struct in_addr ipi_spec_dst; /**< Local address */
954 struct in_addr ipi_addr; /**< Header Destination address */
955 };
956
957 /** Retrieve the current known path MTU of the current socket. Returns an
958 * integer. IP_MTU is valid only for getsockopt and can be employed only when
959 * the socket has been connected.
960 */
961 #define IP_MTU 14
962
963 /** Set IPv4 multicast datagram network interface. */
964 #define IP_MULTICAST_IF 32
965 /** Set IPv4 multicast TTL value. */
966 #define IP_MULTICAST_TTL 33
967 /** Join IPv4 multicast group. */
968 #define IP_ADD_MEMBERSHIP 35
969 /** Leave IPv4 multicast group. */
970 #define IP_DROP_MEMBERSHIP 36
971
972 /**
973 * @brief Struct used when joining or leaving a IPv4 multicast group.
974 */
975 struct ip_mreqn {
976 struct in_addr imr_multiaddr; /**< IP multicast group address */
977 struct in_addr imr_address; /**< IP address of local interface */
978 int imr_ifindex; /**< Network interface index */
979 };
980
981 /**
982 * @brief Struct used when setting a IPv4 multicast network interface.
983 */
984 struct ip_mreq {
985 struct in_addr imr_multiaddr; /**< IP multicast group address */
986 struct in_addr imr_interface; /**< IP address of local interface */
987 };
988
989 /** Clamp down the global port range for a given socket */
990 #define IP_LOCAL_PORT_RANGE 51
991
992 /** @} */
993
994 /**
995 * @name IPv6 level options (IPPROTO_IPV6)
996 * @{
997 */
998 /* Socket options for IPPROTO_IPV6 level */
999 /** Set the unicast hop limit for the socket. */
1000 #define IPV6_UNICAST_HOPS 16
1001
1002 /** Set multicast output network interface index for the socket. */
1003 #define IPV6_MULTICAST_IF 17
1004
1005 /** Set the multicast hop limit for the socket. */
1006 #define IPV6_MULTICAST_HOPS 18
1007
1008 /** Join IPv6 multicast group. */
1009 #define IPV6_ADD_MEMBERSHIP 20
1010
1011 /** Leave IPv6 multicast group. */
1012 #define IPV6_DROP_MEMBERSHIP 21
1013
1014 /** Join IPv6 multicast group. */
1015 #define IPV6_JOIN_GROUP IPV6_ADD_MEMBERSHIP
1016
1017 /** Leave IPv6 multicast group. */
1018 #define IPV6_LEAVE_GROUP IPV6_DROP_MEMBERSHIP
1019
1020 /**
1021 * @brief Struct used when joining or leaving a IPv6 multicast group.
1022 */
1023 struct ipv6_mreq {
1024 /** IPv6 multicast address of group */
1025 struct in6_addr ipv6mr_multiaddr;
1026
1027 /** Network interface index of the local IPv6 address */
1028 int ipv6mr_ifindex;
1029 };
1030
1031 /** For getsockopt(), retrieve the current known IPv6 path MTU of the given socket.
1032 * Valid only when the socket has been connected.
1033 * For setsockopt(), set the MTU to be used for the socket. The MTU is limited by
1034 * the device MTU or the path MTU when path MTU discovery is enabled.
1035 */
1036 #define IPV6_MTU 24
1037
1038 /** Don't support IPv4 access */
1039 #define IPV6_V6ONLY 26
1040
1041 /** Pass an IPV6_RECVPKTINFO ancillary message that contains a
1042 * in6_pktinfo structure that supplies some information about the
1043 * incoming packet. See RFC 3542.
1044 */
1045 #define IPV6_RECVPKTINFO 49
1046
1047 /** RFC5014: Source address selection. */
1048 #define IPV6_ADDR_PREFERENCES 72
1049
1050 /** Prefer temporary address as source. */
1051 #define IPV6_PREFER_SRC_TMP 0x0001
1052 /** Prefer public address as source. */
1053 #define IPV6_PREFER_SRC_PUBLIC 0x0002
1054 /** Either public or temporary address is selected as a default source
1055 * depending on the output interface configuration (this is the default value).
1056 * This is Linux specific option not found in the RFC.
1057 */
1058 #define IPV6_PREFER_SRC_PUBTMP_DEFAULT 0x0100
1059 /** Prefer Care-of address as source. Ignored in Zephyr. */
1060 #define IPV6_PREFER_SRC_COA 0x0004
1061 /** Prefer Home address as source. Ignored in Zephyr. */
1062 #define IPV6_PREFER_SRC_HOME 0x0400
1063 /** Prefer CGA (Cryptographically Generated Address) address as source. Ignored in Zephyr. */
1064 #define IPV6_PREFER_SRC_CGA 0x0008
1065 /** Prefer non-CGA address as source. Ignored in Zephyr. */
1066 #define IPV6_PREFER_SRC_NONCGA 0x0800
1067
1068 /**
1069 * @brief Incoming IPv6 packet information.
1070 *
1071 * Used as ancillary data when calling recvmsg() and IPV6_RECVPKTINFO socket
1072 * option is set.
1073 */
1074 struct in6_pktinfo {
1075 struct in6_addr ipi6_addr; /**< Destination IPv6 address */
1076 unsigned int ipi6_ifindex; /**< Receive interface index */
1077 };
1078
1079 /** Set or receive the traffic class value for an outgoing packet. */
1080 #define IPV6_TCLASS 67
1081 /** @} */
1082
1083 /**
1084 * @name Backlog size for listen()
1085 * @{
1086 */
1087 /** listen: The maximum backlog queue length */
1088 #define SOMAXCONN 128
1089 /** @} */
1090
1091 /**
1092 * @name Macros for checking special IPv6 addresses.
1093 * @{
1094 */
1095 /** Check unspecified IPv6 address. */
1096 #define IN6_IS_ADDR_UNSPECIFIED(addr) \
1097 net_ipv6_addr_cmp(net_ipv6_unspecified_address(), addr)
1098
1099 /** Check loopback IPv6 address. */
1100 #define IN6_IS_ADDR_LOOPBACK(addr) net_ipv6_is_addr_loopback(addr)
1101
1102 /** Check IPv6 multicast address */
1103 #define IN6_IS_ADDR_MULTICAST(addr) net_ipv6_is_addr_mcast(addr)
1104
1105 /** Check IPv6 link local address */
1106 #define IN6_IS_ADDR_LINKLOCAL(addr) net_ipv6_is_ll_addr(addr)
1107
1108 /** Check IPv6 site local address */
1109 #define IN6_IS_ADDR_SITELOCAL(addr) net_ipv6_is_sl_addr(addr)
1110
1111 /** Check IPv6 v4 mapped address */
1112 #define IN6_IS_ADDR_V4MAPPED(addr) net_ipv6_addr_is_v4_mapped(addr)
1113
1114 /** Check IPv6 multicast global address */
1115 #define IN6_IS_ADDR_MC_GLOBAL(addr) net_ipv6_is_addr_mcast_global(addr)
1116
1117 /** Check IPv6 multicast node local address */
1118 #define IN6_IS_ADDR_MC_NODELOCAL(addr) net_ipv6_is_addr_mcast_iface(addr)
1119
1120 /** Check IPv6 multicast link local address */
1121 #define IN6_IS_ADDR_MC_LINKLOCAL(addr) net_ipv6_is_addr_mcast_link(addr)
1122
1123 /** Check IPv6 multicast site local address */
1124 #define IN6_IS_ADDR_MC_SITELOCAL(addr) net_ipv6_is_addr_mcast_site(addr)
1125
1126 /** Check IPv6 multicast organization local address */
1127 #define IN6_IS_ADDR_MC_ORGLOCAL(addr) net_ipv6_is_addr_mcast_org(addr)
1128
1129 /** @} */
1130
1131 /** @cond INTERNAL_HIDDEN */
1132 /**
1133 * @brief Registration information for a given BSD socket family.
1134 */
1135 struct net_socket_register {
1136 int family;
1137 bool is_offloaded;
1138 bool (*is_supported)(int family, int type, int proto);
1139 int (*handler)(int family, int type, int proto);
1140 #if defined(CONFIG_NET_SOCKETS_OBJ_CORE)
1141 /* Store also the name of the socket type in order to be able to
1142 * print it later.
1143 */
1144 const char * const name;
1145 #endif
1146 };
1147
1148 #define NET_SOCKET_DEFAULT_PRIO CONFIG_NET_SOCKETS_PRIORITY_DEFAULT
1149
1150 #define NET_SOCKET_GET_NAME(socket_name, prio) \
1151 __net_socket_register_##prio##_##socket_name
1152
1153 #if defined(CONFIG_NET_SOCKETS_OBJ_CORE)
1154 #define K_OBJ_TYPE_SOCK K_OBJ_TYPE_ID_GEN("SOCK")
1155
1156 #define NET_SOCKET_REGISTER_NAME(_name) \
1157 .name = STRINGIFY(_name),
1158 #else
1159 #define NET_SOCKET_REGISTER_NAME(_name)
1160 #endif
1161
1162 #define _NET_SOCKET_REGISTER(socket_name, prio, _family, _is_supported, _handler, _is_offloaded) \
1163 static const STRUCT_SECTION_ITERABLE(net_socket_register, \
1164 NET_SOCKET_GET_NAME(socket_name, prio)) = { \
1165 .family = _family, \
1166 .is_offloaded = _is_offloaded, \
1167 .is_supported = _is_supported, \
1168 .handler = _handler, \
1169 NET_SOCKET_REGISTER_NAME(socket_name) \
1170 }
1171
1172 #define NET_SOCKET_REGISTER(socket_name, prio, _family, _is_supported, _handler) \
1173 _NET_SOCKET_REGISTER(socket_name, prio, _family, _is_supported, _handler, false)
1174
1175 #define NET_SOCKET_OFFLOAD_REGISTER(socket_name, prio, _family, _is_supported, _handler) \
1176 _NET_SOCKET_REGISTER(socket_name, prio, _family, _is_supported, _handler, true)
1177
1178 /** @endcond */
1179
1180 #ifdef __cplusplus
1181 }
1182 #endif
1183
1184 #include <zephyr/syscalls/socket.h>
1185
1186 /**
1187 * @}
1188 */
1189
1190 /* Avoid circular loops with POSIX socket headers.
1191 * We have these includes here so that we do not need
1192 * to change the applications that were only including
1193 * zephyr/net/socket.h header file.
1194 *
1195 * Additionally, if non-zephyr-prefixed headers are used here,
1196 * native_sim pulls in those from the host rather than Zephyr's.
1197 */
1198 #if defined(CONFIG_POSIX_API)
1199 #if !defined(ZEPHYR_INCLUDE_POSIX_ARPA_INET_H_)
1200 #include <zephyr/posix/arpa/inet.h>
1201 #endif
1202 #if !defined(ZEPHYR_INCLUDE_POSIX_NETDB_H_)
1203 #include <zephyr/posix/netdb.h>
1204 #endif
1205 #if !defined(ZEPHYR_INCLUDE_POSIX_UNISTD_H_)
1206 #include <zephyr/posix/unistd.h>
1207 #endif
1208 #if !defined(ZEPHYR_INCLUDE_POSIX_POLL_H_)
1209 #include <zephyr/posix/poll.h>
1210 #endif
1211 #if !defined(ZEPHYR_INCLUDE_POSIX_SYS_SOCKET_H_)
1212 #include <zephyr/posix/sys/socket.h>
1213 #endif
1214 #endif /* CONFIG_POSIX_API */
1215
1216 #endif /* ZEPHYR_INCLUDE_NET_SOCKET_H_ */
1217