Commit graph

554 commits

Author SHA1 Message Date
Daniel Leung d47b1c05f3 kernel: userspace: add k_object_is_valid()
This adds a function k_object_is_valid() to check if a kernel
object exists, of certain type, and has been initialized.
This replaces the same (or very similar) code that has been
copied from kernel into the network subsystem.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-09-28 17:28:43 -04:00
Anas Nashif 6d23a960db lib: os: build fdtable conditionally
Stop building fdtable by default, make it conditional and build it only
when needed.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-09-28 06:25:16 -04:00
Flavio Ceolin 5d505c7b28 random: Fix feature dependency usage
Code using sys_csrand_get should depend on CONFIG_CSPRNG_ENABLED symbol
and not in ENTROPY_HAS_DRIVER since they are not using the entropy
device directly.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-09-27 11:55:10 -05:00
Tobias Frauenschläger dcc63120cf net: sockets: add support for SO_REUSEPORT
This commits adds support for the SO_REUSEPORT socket option.

The implementation follows the behavior of BSD and tries to also follow
the specific additional features of linux with the following
limitations:
* SO_REUSEADDR and SO_REUSEPORT are not "the same" for client sockets,
  as we do not have a trivial way so identify a socket as "client"
  during binding. To get the Linux behavior, one has to use SO_REUSEPORT
  with Zephyr
* No prevention of "port hijacking"
* No support for the load balancing stuff for incoming
  packets/connections

There is also a new Kconfig option to control this feature, which is
enabled by default if TCP or UDP is enabled.

Signed-off-by: Tobias Frauenschläger <t.frauenschlaeger@me.com>
2023-09-20 08:56:31 +02:00
Tobias Frauenschläger 3d3a221b1e net: sockets: add support for SO_REUSEADDR
This commit adds support for the SO_REUSEADDR option to be enabled for
a socket using setsockopt(). With this option, it is possible to bind
multiple sockets to the same local IP address / port combination, when
one of the IP address is unspecified (ANY_ADDR).

The implementation strictly follows the BSD implementation and tries to
follow the Linux implementation as close as possible. However, there is
one limitation: for client sockets, the Linux implementation of
SO_REUSEADDR behaves exactly like the one for SO_REUSEPORT and enables
multiple sockets to have exactly the same specific IP address / port
combination. This behavior is not possible with this implementation, as
there is no trivial way to identify a socket to be a client socket
during the bind() call. For this behavior, one has to use the
SO_REUSEPORT option in Zephyr.

There is also a new Kconfig to control this feature similar to other
socket options: CONFIG_NET_CONTEXT_REUSEADDR. This option is enabled by
default if TCP or UDP are enabled. However, it can still be disabled
explicitly.

Signed-off-by: Tobias Frauenschläger <t.frauenschlaeger@me.com>
2023-09-20 08:56:31 +02:00
Ambroise Vincent bb450eb26f net: sockets: Keep lock when notifying condvar
Releasing the lock before notifying condvar led to a race condition
between a thread calling k_condvar_wait to wait for a condition variable
and another thread signalling for this same condition variable. This
resulted in the waiting thread to stay pending and the handle to it
getting removed from the notifyq, meaning it couldn't get woken up
again.

Signed-off-by: Ambroise Vincent <ambroise.vincent@arm.com>
2023-09-18 15:41:23 -04:00
Chaitanya Tata 40ee8791f2 net: socketpair: Fix use after free
In low memory conditions, its possible for socketpair memory allocation
to fail and then the socketpair is freed but after that the remote
semaphore is released causing a crash.

Fix this by freeing the socketpair after releasing the semaphore. Add a
test case to induce low memory conditions (low HEAP and high socketpair
buffer size), with the fix issue is not seen.

Signed-off-by: Chaitanya Tata <Chaitanya.Tata@nordicsemi.no>
2023-09-18 20:34:12 +02:00
Martin Jäger eae44a55d8 net: lib: sockets: sockets_tls: prefix mbedtls error with 0x
The errors are printed in hex, but no prefix was used. This could be
confused with usual errno return values. The 0x prefix makes clear
that it's a hex value.

Also a missing minus sign is added to one log message.

Signed-off-by: Martin Jäger <martin@libre.solar>
2023-09-18 10:38:44 +01:00
Carles Cufi 8c748fd005 kernel: Modify the signature of k_mem_slab_free()
Modify the signature of the k_mem_slab_free() function with a new one,
replacing the old void **mem with void *mem as a parameter.

The following function:
void k_mem_slab_free(struct k_mem_slab *slab, void **mem);

has the wrong signature. mem is only used as a regular pointer, so there
is no need to use a double-pointer. The correct signature should be:
void k_mem_slab_free(struct k_mem_slab *slab, void *mem);

The issue with the current signature, although functional, is that it is
extremely confusing. I myself, a veteran Zephyr developer, was confused
by this parameter when looking at it recently.

All in-tree uses of the function have been adapted.

Fixes #61888.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2023-09-03 18:20:59 -04:00
Jukka Rissanen 7aa4904b5a net: socket: Change SO_BINDTODEVICE to use interface name
Make sure we use the network interface name (if configured)
instead of device name when binding to certain network
interface.

Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2023-08-31 14:43:36 +02:00
Robert Lubos d8a96b1be0 net: sockets: tls: Implement TLS_DTLS_CID option
Add TLS_DTLS_CID socket option, which enables to use the Connection ID
extension for the DTLS session.

The option provides control of the use of CID with the `setsockopt()`
function. The value provided can disable, enable, and control whether to
provide a CID to the peer. It uses a random self CID (if told to provide
one to the peer) unless TLS_DTLS_CID_VALUE set previously.

Add TLS_DTLS_CID_VALUE to get or set the CID sent to the peer, if any.

Add TLS_DTLS_PEER_CID_VALUE to get the CID value provided by the peer,
if any.

Add TLS_DTLS_CID_STATUS to determine if CID used, and whether
bidirectional or one way.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Signed-off-by: Pete Skeggs <peter.skeggs@nordicsemi.no>
2023-08-30 11:36:51 +02:00
Robert Lubos d5252cb5de net: sockets: Fix getsockname()
getsockname() did not work properly on bound sockets, as it verified
whether the socket has an active connection before retuning result. This
is not correct, as socket after bound may not have a connection yet.

Fix this, by verifying that local_addr on an underlying net_context is
set, to determine whether socket has a local address assigned, before
returning result.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-08-27 07:35:34 -04:00
Robert Lubos 6e1a205819 net: sockets: Fix connected datagram socket packet filtering
The previous patch to address race condition on STREAM sockets had a
side effect on DGRAM socket, where net_context_recv() is not only
installing recv callback, but also registering a connection at net_conn
level. Doing so before setting remote address first (which is done in
net_context_connect()) had an impact on the connected DGRAM socket
operation, which now accepted packets from any remote peer, and not only
the one socket was connected to.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-08-25 10:31:19 +02:00
Christopher Friedt 4a095bb34b net: sockets: support fionbio and fionread
The `ioctl()` interface is already supported by the network
subsystem but there was no `zsock_` interface available for it.

Add the `zsock_ioctl()` syscall.

Implement two somewhat commont ioctl requests for socket
file descriptors; namely

- `FIONBIO` set non-blocking I/O mode
- `FIONREAD` get the number of available bytes

In the process, added `net_pkt_ip_proto_hdr_len()`

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2023-08-22 09:59:44 +02:00
Christopher Friedt 501c56cce7 net: socketpair: support for fionbio
Support for setting non-blocking mode via `ZFD_IOCTL_FIONBIO`.

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2023-08-22 09:59:44 +02:00
Christopher Friedt e0ac4eb5cd net: sockets: socketpair: support querying bytes available
In order to get a semi-accurate assessment of how many
bytes are available on a socket prior to performing a read,
BSD and POSIX systems have typically used

`ioctl(fd, FIONREAD, &avail)`

We can support this in Zephyr as well with little effort, so
add support for `socketpair()` sockets as an example.

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2023-08-22 09:59:44 +02:00
Christopher Friedt 1fa2ea1c82 net: sockets: tcp: split recv_stream into immediate and timed
Previously, if a net_context had multiple packets already in
the receive queue, and a call to zsock_recvfrom() was made with
a buffer large enough to receive content from multiple packets,
only the content from a single receive buffer would be received.

Since zsock_recvfrom() is a system call, which has a
non-negligible overhead, it makes sense to receive as many bytes
as possible per system call.

Add zsock_recv_stream_immediate() as a shorthand for
"fill this receive buffer with as many bytes as possible without
blocking". Allow nullable buffer parameters so that we can also
have a shorthand for "count how many bytes are immediately
available".

With minor refactoring, zsock_recv_stream_timed() is a simple
wrapper around zsock_recv_stream_immediate() that handles timing
and error conditions.

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2023-08-22 09:59:44 +02:00
Sjors Hettinga 81650746f7 net: socket: Make the send timeout configurable
When the protocol layer like TCP is blocking transmission, the socket
layer will attempt and wait for a maximum amount of time before returning
with an ENOBUFS error.
This change allows to set the maximum waiting time from the configuration
file instead of using a fixed 10 second value.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2023-08-16 10:30:33 +02:00
Daniel Leung 5bc08ae3c6 net: rename shadow variables
Renames shadow variables found by -Wshadow.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-08-10 08:14:43 +00:00
Daniel Mangum 775a8e8c8d net: sockets: use DTLS in NET_SOCKETS_TLS_MAX_APP_PROTOCOLS
Updates NET_SOCKETS_TLS_MAX_APP_PROTOCOLS Kconfig option description to use
DTLS instead of DTL.

Signed-off-by: Daniel Mangum <georgedanielmangum@gmail.com>
2023-08-07 11:27:33 +02:00
Seppo Takalo c8ac3070cc net: sockets: socketpair: Allow statically allocated socketpairs
When the target board does not have heap by default, allows
statically reserving the space for required socketpairs.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2023-07-31 14:49:05 +02:00
Nicolas Pitre 603cdaa032 subsys/net/lib/socket: move to timepoint API
Remove sys_clock_timeout_end_calc() usage and custom timeout_recalc().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-07-25 09:12:26 +02:00
Daniel Leung 1e1ab38bf0 net: syscalls: use zephyr_syscall_header
This adds a few line use zephyr_syscall_header() to include
headers containing syscall function prototypes.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-06-17 07:57:45 -04:00
Robert Lubos e6fc53b399 net: sockets: tls: Allow to interrupt blocking accept() call
In order to allow the TLS accept() call to be interrupted, it should
release the top-level TLS socket mutex before blocking. As the
underlying TCP accept() makes no use of TLS resources, and has its own
mutex protection, it should be safe to do so.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-05-29 14:34:03 -04:00
Robert Lubos 76b74f007f net: sockets: Fix accept() not being interrupted on close()
The accept() so far would block with mutex held, making it impossible to
interrupt it from another thread when the socket was closed.

Fix this, by reusing the condvar mechanism used for receiving. It's OK
to use the same routine, as underneath accept() is monitoring the same
FIFO as recv().

Additionally, simplify k_fifo_get() handling in accept() - as the
waiting now takes place on condvar, it can be used in a non-blocking
manner. Blocking accept() call should not reach this place if there's no
new incoming connection waiting on the FIFO.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-05-29 14:34:03 -04:00
Robert Lubos 2c75070360 net: sockets: tcp: Fix possible race between connect/recv
Installing recv callback with net_context_recv() after
net_context_connect() left an opening for a possible race - in case the
server send some data immediately after establishing TCP connection, and
Zephyr did not manage to install the callback on time, the data would be
lost, corrupting the stream.

This can be avoided, by installing the recv callback before the
connection is triggered. As net_context_recv() called w/o timeout only
registers the callback function, it should have no negative impact. The
only change on the TCP side is when the connection is closed - in case
TCP is in connect stage, do not call the recv callback (before this
change it'd be NULL at that point).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-05-26 09:55:13 -04:00
Robert Lubos 966eff642f net: sockets: Fix recv() not being interrupted on close()
In case recv() call was waiting for data, and the socket was closed from
another thread, the recv() call would not be interrupted, causing the
receiving thread to be blocked indefinitely.

Fix this, by signalling the condvar the recv() call is waiting on
close(). Additionally, close will now set the socket into error mode,
with EINTR as the error condition, allowing the blocked calls to
recognise that the call was interrupted, and return a proper error code
on the event.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-05-26 09:05:12 -04:00
Gerard Marull-Paretas dacb3dbfeb iterable_sections: move to specific header
Until now iterable sections APIs have been part of the toolchain
(common) headers. They are not strictly related to a toolchain, they
just rely on linker providing support for sections. Most files relied on
indirect includes to access the API, now, it is included as needed.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-05-22 10:42:30 +02:00
Wojciech Slenska c3575fbd2e net: sockets: fix POLLOUT for offloaded iface
For offloaded iface net_tcp_get is never called, so context->tcp
is always NULL. In that case net_tcp_tx_sem_get will return wrong pointer.
For pollout k_poll will be called with NULL semph,
which cause HardFault.

Signed-off-by: Wojciech Slenska <wsl@trackunit.com>
2023-04-19 17:15:12 +02:00
Daniel Nejezchleb 663b684fea net: socket: fix hanging net contexts
Calls put instead of unref on net contexts
in the socket accept function.
Mere unref didn't subtract the reference
count of net context which leaves
it in used state. This situation happens
in case of accepting already
closed connection.

Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
2023-04-17 15:12:41 +02:00
Daniel Nejezchleb ee720b5412 net: socket: asynchronous connect
Added a feature of socket connect
being asynchronous. If socket is set
to nonblock with O_NONBLOCK flag,
then connect() is non-blocking aswell.
App can normally poll the socket to
test when the connection is established.

Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
2023-04-17 11:35:20 +02:00
Gerard Marull-Paretas a5fd0d184a init: remove the need for a dummy device pointer in SYS_INIT functions
The init infrastructure, found in `init.h`, is currently used by:

- `SYS_INIT`: to call functions before `main`
- `DEVICE_*`: to initialize devices

They are all sorted according to an initialization level + a priority.
`SYS_INIT` calls are really orthogonal to devices, however, the required
function signature requires a `const struct device *dev` as a first
argument. The only reason for that is because the same init machinery is
used by devices, so we have something like:

```c
struct init_entry {
	int (*init)(const struct device *dev);
	/* only set by DEVICE_*, otherwise NULL */
	const struct device *dev;
}
```

As a result, we end up with such weird/ugly pattern:

```c
static int my_init(const struct device *dev)
{
	/* always NULL! add ARG_UNUSED to avoid compiler warning */
	ARG_UNUSED(dev);
	...
}
```

This is really a result of poor internals isolation. This patch proposes
a to make init entries more flexible so that they can accept sytem
initialization calls like this:

```c
static int my_init(void)
{
	...
}
```

This is achieved using a union:

```c
union init_function {
	/* for SYS_INIT, used when init_entry.dev == NULL */
	int (*sys)(void);
	/* for DEVICE*, used when init_entry.dev != NULL */
	int (*dev)(const struct device *dev);
};

struct init_entry {
	/* stores init function (either for SYS_INIT or DEVICE*)
	union init_function init_fn;
	/* stores device pointer for DEVICE*, NULL for SYS_INIT. Allows
	 * to know which union entry to call.
	 */
	const struct device *dev;
}
```

This solution **does not increase ROM usage**, and allows to offer clean
public APIs for both SYS_INIT and DEVICE*. Note that however, init
machinery keeps a coupling with devices.

**NOTE**: This is a breaking change! All `SYS_INIT` functions will need
to be converted to the new signature. See the script offered in the
following commit.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

init: convert SYS_INIT functions to the new signature

Conversion scripted using scripts/utils/migrate_sys_init.py.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

manifest: update projects for SYS_INIT changes

Update modules with updated SYS_INIT calls:

- hal_ti
- lvgl
- sof
- TraceRecorderSource

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

tests: devicetree: devices: adjust test

Adjust test according to the recently introduced SYS_INIT
infrastructure.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

tests: kernel: threads: adjust SYS_INIT call

Adjust to the new signature: int (*init_fn)(void);

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-04-12 14:28:07 +00:00
Robert Lubos afaf4cddd2 net: sockets: tls: Implement handshake timeout
Currently, the handshake operation could only be fully blocking or
non-blocking. This did not play well if SO_RCVTIMEO was set for DTLS
server, as the recv() call where the blocking handshake was used, could
block indefinitely, ignoring the timeout parameter. Fix this, by
allowing for the handshake operation to timeout.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-04-12 11:09:58 +02:00
Robert Lubos 9082d4b98e net: sockets: tls: Implement TLS/DTLS socket TX/RX timeout
As the underlying socket operations for TLS/DTLS are now non-blocking,
it's no longer possible to rely on the underlying socket timeout
handling. Instead, implement SO_RCVTIMEO/SO_SNDTIMEO at the TLS socket
layer.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-04-12 11:09:58 +02:00
Robert Lubos 81be0f6d73 net: sockets: tls: Switch DTLS to use non-blocking socket operations
As for TLS, switch to use non-blocking operations on underlying socket.
This is a bit tricker for DTLS, as there were not truly blocking bio
(binary input/output) function for DTLS, as timeout had to been
implemented. It is possible though to implement non-blocking mbedTLS bio
function instead, and handle timeout outside of mbedTLS context, which
has been done in this commit.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-04-12 11:09:58 +02:00
Robert Lubos ee48ddc205 net: sockets: tls: Switch TLS to use non-blocking socket operations
Switch TLS sockets to use non-blocking socket operations underneath.
This allows to implement the socket blocking outside of the mbedTLS
context (using poll()), and therefore release the mutex for the time the
underlying socket is waiting for data. In result, it's now possible to
do blocking TLS RX/TX operations simultaneously from separate threads.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-04-12 11:09:58 +02:00
Robert Lubos 96e14ba91f net: sockets: tls: Implement ZFD_IOCTL_SET_LOCK handling
Implement ZFD_IOCTL_SET_LOCK so that TLS socket layer gets access to the
mutex protecting socket calls.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-04-12 11:09:58 +02:00
Chris Friedt ff2efd7ae5 net: socket: socketpair: remove experimental status
Socketpair functionality has matured enough to be used in a
consistent way now regardless of architecture or platform,
even on `native_posix`.

Remove the experimental status to reflect that.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2023-03-25 07:05:53 -04:00
Robert Lubos 66ae9153a6 net: sockets: Fix SO_SNDTIMEO handling
The TX timeout configured with SO_SNDTIMEO on a socket did not work
properly. If the timeout was set on a socket, the TX would work as if
the socket was put into non-blocking mode. This commit fixes this.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-03-20 16:54:41 +01:00
Robert Lubos 616797c429 net: sockets: Add helper function for recalculating remaining timeout
The timeout recalculation logic was duplicated across several routines,
therefore it makes sense to make a helper function out of it,
especially, that the same functionality would be needed for the send
routines.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-03-20 16:54:41 +01:00
Vidar Lillebø ca3d0c8ee9 mbedtls: Remove dependency on MBEDTLS_BUILTIN for MBEDTLS_DEBUG
Allows using MBEDTLS_DEBUG functionality when not using MBEDTLS_BUILTIN.

Signed-off-by: Vidar Lillebø <vidar.lillebo@nordicsemi.no>
2023-03-10 09:30:32 +01:00
Stig Bjørlykke 0f71a130ef net: sockets: getaddrinfo: Minor refactoring
Minor refactoring in getaddrinfo() to make the code easier to
read and to make handling IPv4 and IPv6 support more equal.

- Move common wait and error handling code to exec_query()
- Use the same check for CONFIG_NET_IPV4 and CONFIG_NET_IPV6
- Add extra sanity check for family before exec_query()
- Do not set errno when return DNS_EAI_ADDRFAMILY

Fix issue with setting port number for all DNS servers.

Signed-off-by: Stig Bjørlykke <stig.bjorlykke@nordicsemi.no>
2023-02-21 15:02:35 +01:00
Chris Friedt c093678784 net: sockets: fix fcntl.h usage
If we are using `CONFIG_ARCH_POSIX`, then include
`<fcntl.h>`. Otherwise, include `<zephyr/posix/fcntl.h>`
since there are no requirements to use `CONFIG_POSIX_API`
internally.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2023-02-08 19:04:25 +09:00
Chris Friedt ac3efe70cd net: sockets: socketpair: header fixups
* include `<zephyr/posix/fcntl.h>` instead of `<fcntl.h>`
* drop unused logging header and module declaration
* reorder headers alphabetically

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2023-02-08 19:04:25 +09:00
Jared Baumann 5a62f2592f net: lib: Fix build warning for sockets_tls
Fixes issue where a build warning would be emmited for sockets_tls.c due
to usage of the deprecated fcntl.h header file.

Signed-off-by: Jared Baumann <jared.baumann8@t-mobile.com>
2023-01-28 08:01:03 -05:00
Chris Friedt c2a62f4ad7 net: sockets: conditionally include zephyr/posix/fcntl.h
Only include `<fcntl.h>` for `CONFIG_ARCH_POSIX`. Otherwise,
include `<zephyr/posix/fcntl.h>`.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2023-01-23 09:57:31 -08:00
Chris Friedt 6ac402bb3a net: socket: additional POSIX constants
The POSIX spec requires that `SO_LINGER`, `SO_RCVLOWAT`,
and `SO_SNDLOWAT`, and `SOMAXCONN` are defined in
`<sys/socket.h>`. However, most of the existing socket
options and related constants are defined in
`<zephyr/net/socket.h>`.

For now, we'll co-locate them. It would be
good to properly namespace things.

Additionally, a no-op for setsockopt for `SO_LINGER` to
make things Just Work (TM) for now.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2023-01-23 09:57:31 -08:00
Marco Argiolas d51182d57d net: lib: sockets: support IPv6-only use case with AF_UNSPEC
Setting `hints.ai_family` to `AF_UNSPEC` was causing
`net_getaddrinfo_addr_str()` and in turn `getaddrinfo()` to resolve the
literal SNTP SERVER first into IPv4 and then (if supported) IPv6 addresses.
 This was causing useless waste of time and memory in case IPv4 was not
supported. In addition, in case IPv4 addresses were not supported, other
system components (eg. SNTP) could fail due to the DNS returning IP
addresses with unsupported family type (ie. IPv4).
Now, if address family is not explicitly set to `AF_INET` (ie. IPv4), then
 no attempt is made to resolve SNTP server address into an IPv4 address.

Signed-off-by: Marco Argiolas <marco.argiolas@ftpsolutions.com.au>
2023-01-03 11:03:25 +01:00
Markus Fuchs ea17d5152d net: sockets_tls: Fix memory leak in socket
Fix file descriptor leak on unsupported socket protocols.

Signed-off-by: Markus Fuchs <markus.fuchs@ch.sauter-bc.com>
2022-11-09 10:44:44 +01:00
Christoph Schnetzler c364721796 net: sockets: Prevent compiler error if warnings being treated as errors
If gcc compiler option -Werror is used the warning,

declared inside parameter list will not be visible outside of this
definition or declaration [-Werror]

is treated as error, for

sockets_internal.h:18:28: ‘struct net_context’
sockets_internal.h:19:32: ‘struct zsock_pollfd’
fdtable.h:108:17: ‘struct k_mutex’

Signed-off-by: Christoph Schnetzler <christoph.schnetzler@husqvarnagroup.com>
2022-11-09 09:15:32 +00:00
Chris Friedt d832b04e96 net: sockets: socketpair: do not allow blocking IO in ISR context
Using a socketpair for communication in an ISR is not a great
solution, but the implementation should be robust in that case
as well.

It is not acceptible to block in ISR context, so robustness here
means to return -1 to indicate an error, setting errno to `EAGAIN`
(which is synonymous with `EWOULDBLOCK`).

Fixes #25417

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-10-22 02:30:04 -07:00
Robert Lubos 618fa8d665 net: sockets: Add options to control DSCP/ECN value
Add new socket options IP_TOS and IPV6_TCLASS which allows to set
DSCP/ECN values on a socket for an outgoing packet IPv4/IPv6 headers.

The options are compatible with Linux behaviour, where both DSCP and ECN
are set with a single socket option.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos d28a72ed9e net: sockets: Add missing break statement in setsockopt
SOL_SOCKET and IPPROTO_TCP levels were missing the break statement at
the end of their processing logic, which could cause unexpected
fallthrough on unhandled optname value.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Andrzej Głąbek 916e04e0ef net: lib: sockets_tls: Include zephyr_mbedtls_priv.h conditionally
This is a follow-up to commit a418ad4bb4.

Since the path to zephyr_mbedtls_priv.h is added to include directories
only when CONFIG_MBEDTLS_BUILTIN is enabled, the inclusion of the file
needs to be done under the same condition. Otherwise, an error occurs
when socket_tls.c is compiled without CONFIG_MBEDTLS_BUILTIN.

Signed-off-by: Andrzej Głąbek <andrzej.glabek@nordicsemi.no>
2022-10-07 13:23:18 +02:00
Florian Grandel c57650c403 net: context: clean up net_context_get()
* reduced cyclomatic complexity
* group validation by family to make the validation easier to understand
and extend
* change preprocessor markup where possible to allow for complete code
elimination when features (esp. IP) are disabled
* renamed net_context_get/set_ip_proto() to net_context_get_proto()

While the latter is formally part of the public API and might therefore
have to be deprecated rather than renamed, it is considered internal API
by the net developers, see
https://github.com/zephyrproject-rtos/zephyr/pull/48751#discussion_r942402612

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-09-05 14:35:17 +00:00
Florian Grandel 9695a022f4 net: core: clean up inbound packet handling
The net_core:process_data() and connection:net_conn_input() methods are
the central network packet reception pipeline which:

1) guide network packets through all network layers,
2) decode, validate and filter packages along the way and
3) distribute packages to connections/sockets on all layers.

This code seems to have grown complex and rather cluttered over time as
all protocols, layers and socket implementations meet there in one single
place.

The code also reveals its origin as a pure IP stack which makes it hard
to introduce non-IP protocols and their supporting socket infrastructure
in a modularized way.

For an outside contributor it seems almost impossible to add another
protocol, protocol layer, filter rule or socket implementation without
breaking things.

This change doesn't try to solve all issues at once. It focuses
exclusively on aspects that maintain backwards compatibility:

* Improve modularization and encapsulation on implementation level by
disentangling code that mixes up layers, protocols and socket
implementations.

* Make IP just one protocol among others by removing assymmetry in
protocol handling logic and introduce preprocessor markup so that
IP-specific code can be eliminated by the preprocessor if not needed.

* Use preprocessor markup to delineate hook points for future
modularization or expansion without introducing structural changes (as
this would almost certainly break the API).

* Reduce cyclomatic complexity, use positive rather than negative logic,
improve variable naming, replace if/elseif/else blocks with switches,
reduce variable span, introduce inline comments where code does not
speak for itself, etc. as much as possible to make the code overall
more human-friendly.

Background: These are preparative steps for the introduction of IEEE
802.15.RAW sockets, DGRAM sockets and sockets bound to PAN IDs and device
addresses similar to what the Linux kernel does.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-09-05 14:35:17 +00:00
Florian Grandel 228526e0db net: lib: sockets: improve scalability through a hidden var
Introducing additional socket implementations is rather involved right
now due to some more or less convoluted code that had grown over time.

This change introduces an additional configuration variable in preparation
for additional socket API drivers. The idea is to reduce redundant code
and make existing code more readable by better exposing its actual intent.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-09-05 14:35:17 +00:00
Florian Grandel e9a433cd8f net: introduce NET_IP config to efficiently mark conditional code
The code contained several repeated composite IPv4/v6 and UDP/TCP
preprocessor statements that can be simplified by introducing a hidden
NET_IP preprocessor constant that captures what probably is actually
"meant" by this code.

While we were on it we also used the new constant to further isolate
IP-specific code from non-IP specific generics.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-09-05 14:35:17 +00:00
Florian Grandel e608e92112 net: context: properly namespace can-related methods
The net_context_set/get_filter_id() methods are CAN specific and should
say so.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-09-05 14:35:17 +00:00
Florian Grandel ed0060f5a0 net: l2: ieee802154: AF_PACKET support for IEEE 802.15.4
This change makes the packet socket and ieee802154 l2 drivers aware of
AF_PACKET sockets, see https://github.com/linux-wpan/wpan-tools/tree/master/examples
for examples which inspired this change.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-31 21:52:37 +00:00
Henrik Brix Andersen 27eb12ed48 net: socketcan: decouple SocketCAN and CAN controller headers
Decouple the zephyr/net/socketcan.h and zephyr/drivers/can.h header files
by moving the SocketCAN utilities to their own header.

This is preparation for including the SocketCAN types defined in
socketcan.h in a native posix (Linux) SocketCAN driver context without name
clashes.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-08-18 10:19:29 +02:00
Henrik Brix Andersen d1d48e8304 net: socketcan: rename SocketCAN header from socket_can.h to socketcan.h
Rename the SocketCAN header from socket_can.h to socketcan.h to better
match the naming of the functionality.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-08-18 10:19:29 +02:00
Henrik Brix Andersen b40a8cb9fd net: socket: can: rename utility functions
Rename the SocketCAN utility functions to reflect the new naming of the CAN
controller API and SocketCAN API data types.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-08-18 10:19:29 +02:00
Henrik Brix Andersen 13c75417ba drivers: can: remove z prefix from public CAN API types
Remove the "z" prefix from the public CAN controller API types as this
makes them appear as internal APIs.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-08-18 10:19:29 +02:00
Henrik Brix Andersen d159947443 net: socket: can: prepend SocketCAN data types with socketcan
Rename the SocketCAN data types to "socketcan_*" in preparation of renaming
the low-level CAN controller API data types.

This breaks the naming compatibility with the similar SocketCAN data types
from the Linux kernel, but Zephyr and Linux SocketCAN are not 100%
compatible anyways (only the structure fields are compatible, extended
functionality such filtering, error reporting etc. are not).

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-08-18 10:19:29 +02:00
Peter Mitsis f86027ffb7 kernel: pipes: rewrite pipes implementation
This new implementation of pipes has a number of advantages over the
previous.
  1. The schedule locking is eliminated both making it safer for SMP
     and allowing for pipes to be used from ISR context.
  2. The code used to be structured to have separate code for copying
     to/from a wating thread's buffer and the pipe buffer. This had
     unnecessary duplication that has been replaced with a simpler
     scatter-gather copy model.
  3. The manner in which the "working list" is generated has also been
     simplified. It no longer tries to use the thread's queuing node.
     Instead, the k_pipe_desc structure (whose instances are on the
     part of the k_thread structure) has been extended to contain
     additional fields including a node for use with a linked list. As
     this impacts the k_thread structure, pipes are now configurable
     in the kernel via CONFIG_PIPES.

Fixes #47061

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-08-17 19:31:25 +02:00
Marcin Niestroj 6653fd945f modules: mbedtls: set mbedTLS debug threshold during module initialization
mbedTLS library threshold initialization was done in native TLS socket
implementation (which tends to use mbedTLS now) and inside mbedTLS
benchmark test. Move that to mbedTLS module initialization, as this is a
global setting.

Update description of CONFIG_MBEDTLS_DEBUG_LEVEL to clarify when
mbedtls_debug_set_threshold() is called.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2022-08-17 12:03:52 +02:00
Marcin Niestroj a418ad4bb4 modules: mbedtls: move debug log hook implementation to modules/mbedtls/
So far there was a debug log hook installed in TLS socket implementation.
However, mbedTLS (with debug enabled) might be used outside from TLS socket
and even outside from networking context.

Add new module, which implements debug log hook and makes it available
whenever CONFIG_MBEDTLS_DEBUG is enabled.

Note that debug hook needs to be installed for each mbedTLS context
separately, which means that this requires action from mbedTLS users, such
as TLS sockets implementation.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2022-08-17 12:03:52 +02:00
Robert Lubos bead038ba2 net: sockets: Fill the address structure provided in recvfrom()
The packet socket implementation did not fill the address structure
provided by the application. This commit fixes this.

Note, that the implementation needs to cover two cases: SOCK_RAW and
SOCK_DGRAM. In the first case, the information is extracted directly
from the L2 header (curently only Ethernet supported). In latter case,
the header is already removed from the packet as the L2 has already
processed the packet, so the information is obtained from the net_pkt
structure.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-01 18:02:20 +02:00
Robert Lubos 78c871ab86 net: sockets: Fix potential deadlock during TCP send
There is a potential, corner case scenario, where a deadlock can occur
between TCP and socket layers, when both ends of the connection transmit
data.

The scenario is as follows:
 * Both ends of the connection transmit data,
 * Zephyr side send() call gets blocked due to filing the TX window
 * The next incoming packet is data packet, not updating the RX window
   on the peer side or acknowledging new data. The TCP layer will
   attepmt to notify the new data to the socket layer, by calling the
   registered callback. This will block the RX thread processing the TCP
   layer, as the socket mutex is already acquired by the blocked send()
   call.
 * No further packets are processed until the socket mutex is freed,
   which does not happen as the only way to unblock send() is process
   a new ACK, either updating window size or a acknowledging data.
   The connection stalls until send() times out.

The deadlock is not permament, as both threads get unlocked once send()
times out. It effectively breaks the active connection though.

Fix this, by unlocking the socket mutex for the time the send() call is
idle. Once the TCP layer notifies that the window is available again,
the mutex is acquired back.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-07-18 08:36:09 -07:00
Henrik Brix Andersen d22a9909a1 drivers: net: canbus: move CAN bus network driver to drivers/net
Move the CAN bus network driver from drivers/can to drivers/net as it
implements a network driver, not a CAN controller driver.

Use a separate Kconfig for enabling the CAN bus network driver instead of
piggybacking on the SocketCAN Kconfig. This allows for other
(e.g. out-of-tree) SocketCAN transports.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-07-13 10:34:51 +02:00
Sjors Hettinga 3bcd8d1ee1 net: socket: Use exponential backoff in case of polling errors
Some errors can occur in the sending process that have to be handled
in a polling fasion instead of blocking using semaphores. In this case
apply an exponentially growing backoff time. This will allow for fast
reactions in most situations and prevents high system loads in case
resolving the situation takes a little longer.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-29 10:28:11 +02:00
Ulf Lilleengen 61f4513750 net: improve error message on not supported op
When an operation on the socket is not supported by the implementation,
which is the case for some drivers, set errno to a value that reflects
this situation rather than signalling an error with the file descriptor.

Signed-off-by: Ulf Lilleengen <lulf@redhat.com>
2022-06-27 14:14:53 +02:00
Krzysztof Chruscinski 041f0e5379 all: logging: Remove log_strdup function
Logging v1 has been removed and log_strdup wrapper function is no
longer needed. Removing the function and its use in the tree.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-06-23 13:42:23 +02:00
Robert Lubos 41bbb51412 net: sockets: Fix uninitialized variable use in accept userspace check
Prevent local "addrlen_copy" variable from being used uninitialized in
accept() userspace verification function.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-06-23 09:11:29 +02:00
Sjors Hettinga e097d95c66 net: tcp: Implement Nagle's algorithm
To improve the performance with small chunks send, implement Nagle's
algorithm. Provide the option TCP_NODELAY to disable the algorithm.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-09 11:32:50 +02:00
Marcin Niestroj 900137ef32 net: sockets: tls: prevent sending fragmented datagrams with sendmsg()
Fragmented data passed to sendmsg() should be sent as a single datagram in
case of datagram sockets (i.e. DTLS connection). Right now that is not
happening now, as each fragment is sent separately, which works fine only
for stream sockets.

There is no mbedTLS API for 'gather' write at this moment. This means that
implementing sendmsg() would require allocating contiguous memory area at
Zephyr TLS socket level and copying all data fragments before passing to
mbedTLS library. While this might be a good option for future, let's just
check if data passed to sendmsg() API consists of a single memory region
and can be sent using single send request. Return EMSGSIZE error if there
are more then one data fragments.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2022-05-25 14:20:09 +02:00
Robert Lubos 8ba5990766 net: sockets: Implement POLLOUT for stream sockets
Implement POLLOUT for stream sockets, based on newly introduced tx_sem
functionality of the TCP stack.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-18 11:09:17 +02:00
Robert Lubos 86105fb795 net: sockets: Monitor TCP transmit state with semaphore
Utilize the TCP semaphore monitoring transmit status at the socket
layer. This allows to resume transfer as soon as possible instead of
waiting blindly.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-18 11:09:17 +02:00
Robert Lubos 78e8e0da42 net: sockets: Make use of the status field reported by TCP
Make use of the status field, reported by TCP, in the socket receive
callback. This allows to differentiate a graceful connection shutdown
from actual errors at TCP level (transmission timeout or RST received).
In case of error reported from TCP layer, set a new SOCK_ERROR flag on
the socket, and store the error code in the net_context user_data.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-13 15:42:01 +02:00
Gerard Marull-Paretas 5113c1418d subsystems: migrate includes to <zephyr/...>
In order to bring consistency in-tree, migrate all subsystems code to
the new prefix <zephyr/...>. Note that the conversion has been scripted,
refer to zephyrproject-rtos#45388 for more details.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-05-09 12:07:35 +02:00
Robert Lubos 5cefcf80e9 net: sockets: Move offloading out of experimental
Socket offloading has been in the tree for a while and improved a lot
over time (from a simple define-based API override to a complex
vtable-based solution, supporting mutliple offloaded interfaces). As the
feature is heavily used by certain vendors (Nordic and its nRF Connect
SDK), I propose to move it out of experimental phase.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-06 11:30:22 +02:00
Robert Lubos 7ad2e604bb net: sockets: tls: Add options to control session caching on a socket
Introduce TLS socket options, which allow to configure session caching
on a socket.

The cache can be enabled on a socket with TLS_SESSION_CACHE option.
Once cache is enabled on a socket, the session will be stored for re-use
after a sucessfull handshake. If a socket is attempting to connect to a
host for which session is stored, the session will be resumed and mbed
TLS will attempt to use a simplified handshake procedure.
The server-side management of sessions is fully controlled by mbed TLS
after session caching is enabled on a socket.

The other TLS_SESSION_CACHE_PURGE option allows to clear all of the
cache entries, releasing the memory allocated for sessions.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-04-28 11:31:07 +02:00
Pete Skeggs fb2a966128 net: sockets: tls: use cipherlist set by user
The function setsockopt() option TLS_CIPHERSUITE_LIST
allows the user to set a specific list of ciphersuites
when using the Zephyr native + Mbed TLS stack.  However, the
list provided was not actually being used later for
handshaking.

This adds the missing calls to mbedtls_ssl_conf_ciphersuites()
to use the list provided.  If none was provided, fall back
to the default list as determined by Mbed TLS from Kconfig
values.

Signed-off-by: Pete Skeggs <peter.skeggs@nordicsemi.no>
2022-04-26 15:54:32 -04:00
Robert Lubos e2fe8e7307 net: socket: Add option to create native TLS sock with offloaded TCP
In some cases (for examples when offloaded socket implementation does
not implement TLS functionality) it could be desired to create a native
TLS socket with an underlying offloaded socket.

This cannot be achieved with SO_BINDTODEVICE option only, as TLS socket
type is not really associated with a particular interface - it either
has to be offloaded, or a fully native socket is created (native TLS on
a native interface).

In order to address the problem, introduce TLS_NATIVE socket option.
This option instructs the socket dispatcher layer to create a native TLS
socket. As with the socket dispatcher the underlying socket
implementation is not decided during TLS socket creation, therefore it's
possible to use SO_BINDTODEVICE to choose either native or offloaded
interface for the underlying socket.

Additionally remove NET_SOCKETS_OFFLOAD_TLS Kconfig option, as it's no
longer needed with an runtime option to select whether to offload TLS or
not.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-04-20 11:27:05 +02:00
Robert Lubos 641b2a0d93 net: sockets: Add socket dispatcher
Add an intermediate socket implementation called socket dispatcher. This
layer can be used along with the socket offloading, to postpone the
actual socket creation until a first operation on a socket is executed.

This approach leaves an opening to bind a socket to a particular
offloaded network interface, and thus offloaded socket implementation,
using SO_BINDTODEVICE socket option. Thanks to this, it is now possible
to use multiple offloaded sockets implementations along with native
sockets, and easily select which socket should use with network
interface (even if it's an offloaded interface).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-04-20 11:27:05 +02:00
Mohan Kumar Kumar f105ea6ef5 net: add sndbuf socket option
Introduce set/get SO_SNDBUF option using the setsockopt
function. In addition, for TCP, check the sndbuf value
before queuing data.

Signed-off-by: Mohan Kumar Kumar <mohankm@fb.com>
2022-04-11 10:23:31 +02:00
Marcin Niestroj 5d07c53118 net: sockets: do not unconstify 'optval' in setsockopt()
'optval' in setsockopt(..., SO_BINDTODEVICE, ...) was casted explicitly
from 'const void *' to 'struct ifreq *'. Rely on C implicit casting from
'const void *' to 'const struct ifreq *' and simply update variable
type. This prevents unwanted modification of ifreq value in the future.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2022-04-08 15:51:38 -07:00
Marcin Niestroj cf75f01a71 net: sockets: introduce NET_SOCKETS_OFFLOAD_PRIORITY option
This option will be used as default socket priority by offloaded socket
drivers.

Describe how to prioritize native TLS over offloaded TLS (and vice
versa) using sockets priorities.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2022-04-08 15:50:11 -07:00
Mohan Kumar Kumar 5d37de8551 net: add rcvbuf socket option
Introduce set/get SO_RCVBUF option using the setsockopt
function. In addition, use the rcvbuf value to set the
tcp recv window.

Signed-off-by: Mohan Kumar Kumar <mohankm@fb.com>
2022-04-01 13:30:09 +02:00
Emil Gydesen ae55dae454 sys: util: Change return type of ARRAY_SIZE to size_t
The ARRAY_SIZE macro uses sizeof and thus the return
type should be an unsigned value. size_t is typically
the type used for sizeof and fits well for the
ARRAY_SIZE macro as well.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2022-03-23 14:09:23 +01:00
Nazar Kazakov f483b1bc4c everywhere: fix typos
Fix a lot of typos

Signed-off-by: Nazar Kazakov <nazar.kazakov.work@gmail.com>
2022-03-18 13:24:08 -04:00
Robert Lubos 08752aed0f net: sockets: Fix userspace accept() verification
The verification function for accept() did not take into account that
addr and addrlen pointers provided could be NULL.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-16 16:23:16 +01:00
Robert Lubos 546267ab3b net: sockets: Implement getpeername() function
Implement getpeername() function.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-16 16:23:16 +01:00
Robert Lubos 6a0df63ea0 net: sockets: Retry net_context_sendmsg if EAGAIN is reported
TCP module can report EAGAIN in case TX window is full. This should not
be forwarded to the application, as blocking socket is not supposed to
return EAGAIN.

Fix this for sendmsg by implementing the same mechanism for handling TX
errors as for regular send/sendto operations.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-15 09:50:21 -07:00
Gerard Marull-Paretas 95fb0ded6b kconfig: remove Enable from boolean prompts
According to Kconfig guidelines, boolean prompts must not start with
"Enable...". The following command has been used to automate the changes
in this patch:

sed -i "s/bool \"[Ee]nables\? \(\w\)/bool \"\U\1/g" **/Kconfig*

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-03-09 15:35:54 +01:00
Marcin Niestroj 084ca91a73 net: sockets: tls: implement shutdown() method for TLS sockets
Add basic shutdown() implementation of TLS sockets, which basically
calls shutdown() on underlying wrapped sockets.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2022-03-02 10:05:09 -08:00
Marcin Niestroj f54dee6531 net: sockets: implement shutdown() method for net_context sockets
Add basic shutdown() implementation for net_context sockets, which
handles only SHUT_RD as 'how' parameter and returns -ENOTSUP for SHUT_WR
and SHUT_RDWR. The main use case to cover is to allow race-free wakeup
of threads calling recv() on the same socket.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2022-03-02 10:05:09 -08:00
Marcin Niestroj 8eb2565dbf net: sockets: add shutdown() support in vtable
So far shutdown() implementation was a noop and just resulted in warning
logs. Add shutdown() method into socket vtable. Call it if provided and
fallback into returning -ENOTSUP if not.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2022-03-02 10:05:09 -08:00
Robert Lubos 74bc876bf5 net: tcp: Implement receive window handling
Add implementation of net_tcp_update_recv_wnd() function.

Move the window deacreasing code to the tcp module - receive window
has to be decreased before sending ACK, which was not possible when
window was decreased in the receive callback function.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-22 10:09:45 -08:00
Robert Lubos 3ebd581467 net: sockets: Allow to build CAN sockets with offloading enabled
There is no releavnce between CAN sockets and offloading that would
prevent one from working with another, therefore it's not right to
allow CAN sockets to be build only if offloading is disabled. Fix the
wrong dependency in socket CMakeLists.txt file.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-21 20:52:38 -05:00
Daniel Nejezchleb d3a9e7c29a net: sockets: Fixes net_pkt leak in accept
Fix net_pkt leak by increasing net_context the reference count earlier
in the zsock_accepted_cb() with instalment of the
zsock_received_cb() callback.

And consequently flushing recv_q and decrement net_context
reference count if zsock_accept_ctx() fails.

Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
2022-02-01 14:22:37 -06:00
Robert Lubos 0755a7f057 net: sockets: getaddrinfo: Fix possible crash when callback is delayed
In case system workqueue processing is delayed for any reason, and
resolver callback is executed after getaddrinfo() call already timed
out, the system would crash as the callback makes use of the user data
allocated on the stack within getaddrinfo() function.

Prevent that, by cancelling the DNS request explicitly from the
getaddrinfo() context, therefore preventing the resolver callback
from being executed after the getaddrinfo() call ends.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-01 14:18:33 -06:00
Robert Lubos f4a18e471b net: sockets: tls: Fix ZSOCK_POLLHUP detection
The previous approach to detect if the underlying transport was closed
(by checking the return value of `mbedtls_ssl_read()` was not right,
since the function call does not request any data - therefore 0 as a
return value is perfectly fine.

Instead, rely on the underlying transport ZSOCK_POLLHUP event - if it
reports that the connection ended, forward the event to the application.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-01-31 17:20:55 +01:00
Robert Lubos f8751629c7 net: sockets: Report ZSOCK_POLLHUP when socket is in EOF state
Report ZSOCK_POLLHUP event if peer closed the connection, and thus the
socket is in EOF state.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-01-31 17:20:55 +01:00
Ramiro Merello 4d5eee05f1 net: sockets_tls: Reset mbedtls session on handshake errors
According to MbedTLS API documentation, its session must be reset if
mbedtls_ssl_handshake returns something other than:
 - 0
 - MBEDTLS_ERR_SSL_WANT_READ
 - MBEDTLS_ERR_SSL_WANT_WRITE
 - MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS
 - MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS

In MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS and
MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS cases the function must be called
again when operation is ready. These cases now return -EAGIN or
continue to retry if it's a blocking call.

Signed-off-by: Ramiro Merello <rmerello@itba.edu.ar>
2022-01-04 09:07:21 -05:00
Hou Zhiqiang 2fafd8559f net: socket: packet: Add EtherCAT protocol support
Add EtherCAT protocol support, now applications can
transmit/receive EtherCAT packets via RAW socket.

Signed-off-by: Hou Zhiqiang <Zhiqiang.Hou@nxp.com>
2021-12-20 17:49:10 +01:00
Robert Lubos a0c669e7e6 net: sockets: Simplify common getsockname() implementation
Simplify common `getsockname()` implementation by using VTABLE_CALL()
macro, in the same way as other socket calls do. This additionally
allows to cover the case, when `getsockname()` is not implemnented by
particular socket implementation, preventing the crash.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-29 16:30:29 +01:00
Robert Lubos 666e9f80d6 net: ipv6: Remove in6_addr from packed net_ipv6_hdr struct
Replace unpacked in6_addr structures with raw buffers in net_ipv6_hdr
struct, to prevent compiler warnings about unaligned access.

Remove __packed parameter from `struct net_6lo_context` since the
structure isn't really serialized.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-25 10:46:35 -05:00
Robert Lubos 064200b420 net: ipv4: Remove in_addr from packed net_ipv4_hdr struct
Replace unpacked in_addr structures with raw buffers in net_ipv4_hdr
struct, to prevent compiler warnings about unaligned access.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-25 10:46:35 -05:00
Lucas Dietrich 4e103bcb20 net: sockets: tls: Support for DER cert chain and NOCOPY optimisation
Add TLS socket option "TLS_CERT_NOCOPY" to prevent the copy of
certificates to mbedTLS heap if possible.

Add support to provide a chain of DER certificates by registering
them with multiple tags.

Signed-off-by: Lucas Dietrich <ld.adecy@gmail.com>
2021-11-25 10:44:17 -05:00
David Brown 28d2ee6af7 net: sockets: tls: Clarify missing entropy warning
Change the wording of the warning printed when there is no entropy to
hopefully remove any doubt that there might be security in TLS without
an entropy source.  TLS connections with insufficient entropy are
trivially decodable, and should not be relied on for any type of
security.

Signed-off-by: David Brown <david.brown@linaro.org>
2021-11-08 10:56:04 -05:00
Robert Lubos e8f09b471e net: sockets: tls: Fix TCP disconnect detection in poll()
`ztls_socket_data_check()` function ignored a fact when
`mbedtls_ssl_read()` indicated that the underlying TCP connection was
closed. Fix this by returning `-ENOTCONN` in such case, allowing
`poll()` to detect such event.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-02 13:26:25 +01:00
Torsten Rasmussen 36f5600387 kconfig: net: experimental settings now uses select EXPERIMENTAL
With the introduction of `EXPERIMENTAL` and `WARN_EXPERIMENTAL` in
Zephyr all subsys/net and drivers/ethernet/Kconfig.e1000 settings
having `[EXPERIMENTAL]` in their prompt has has been updated to include
`select EXPERIMENTAL` so that developers can enable warnings when
experimental features are enabled.

The following settings has EXPERIMENTAL removed as they are considered
mature:
- NET_OFFLOAD
- NET_PROMISCUOUS_MODE

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2021-10-25 10:46:48 +02:00
Nicolas Pitre cf49699b0d net: sockets: socketpair: fix locking
The irq_lock() usage here is incompatible with SMP systems, and one's
first reaction might be to convert it to a spinlock.

But are those irq_lock() instances really necessary?

Commit 6161ea2542 ("net: socket: socketpair: mitigate possible race
condition") doesn't say much:

> There was a possible race condition between sock_is_nonblock()
> and k_sem_take() in spair_read() and spair_write() that was
> mitigated.

A possible race without the irq_lock would be:

thread A                thread B
|                       |
+ spair_write():        |
+   is_nonblock = sock_is_nonblock(spair); [false]
*   [preemption here]   |
|                       + spair_ioctl():
|                       +   res = k_sem_take(&spair->sem, K_FOREVER);
|                       +   [...]
|                       +   spair->flags |= SPAIR_FLAG_NONBLOCK;
|                       *   [preemption here]
+   res = k_sem_take(&spair->sem, K_NO_WAIT); [-1]
+   if (res < 0) {      |
+     if (is_nonblock) { [skipped] }
*     res = k_sem_take(&spair->sem, K_FOREVER); [blocks here]
|                       +   [...]

But the version with irq_lock() isn't much better:

thread A                thread B
|                       |
|                       + spair_ioctl():
|                       +   res = k_sem_take(&spair->sem, K_FOREVER);
|                       +   [...]
|                       *   [preemption here]
+ spair_write():        |
+   irq_lock();         |
+   is_nonblock = sock_is_nonblock(spair); [false]
+   res = k_sem_take(&spair->sem, K_NO_WAIT); [-1]
+   irq_unlock();       |
*   [preemption here]   |
|                       +   spair->flags |= SPAIR_FLAG_NONBLOCK;
|                       +   [...]
|                       +   k_sem_give(&spair->sem);
|                       + spair_read():
|                       +   res = k_sem_take(&spair->sem, K_NO_WAIT);
|                       *   [preemption here]
+   if (res < 0) {      |
+     if (is_nonblock) { [skipped] }
*     res = k_sem_take(&spair->sem, K_FOREVER); [blocks here]

In both cases the last k_sem_take(K_FOREVER) will block despite
SPAIR_FLAG_NONBLOCK being set at that moment. Other race scenarios
exist too, and on SMP they are even more likely.

The only guarantee provided by the irq_lock() is to make sure that
whenever the semaphore is acquired then the is_nonblock value is always
current. A better way to achieve that and be SMP compatible is to simply
move the initial sock_is_nonblock() *after* the k_sem_take() and remove
those irq_locks().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-10-11 21:00:41 -04:00
David Brown fc3f4a627e net: sockets: tls: Use better error code
Mbed TLS 3.0 removes the definition for MBED_ERR_SSL_PEER_VERIFY_FAILED,
since non of its code ever returns that value.  Since there isn't really
a perfect response, instead return a somewhat generic response
indicating this was unexpected.

Signed-off-by: David Brown <david.brown@linaro.org>
2021-10-07 14:02:40 -05:00
Flavio Ceolin 1cdc5034e1 net: sockets_tls: Fix mbedTLS usage
mbedtls_pk_parse_key signature has changed and requires an entropy
source.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-10-07 14:02:40 -05:00
Flavio Ceolin 4edcf48e05 sockets: tls: Enable access to mbedtls private fields
Several fields of structures in mbedTLS 3.0 are now private. To access
them directly is necessary to define MBEDTLS_ALLOW_PRIVATE_ACCESS.

That is a temporary fix, the proper solution is not access directly
but using proper API.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-10-07 14:02:40 -05:00
Mateusz Karlic 3844b79e96 net: sockets: sockets_can: Allow parallel receive/send
Implements mechanism similar to the one available in net/lib/sockets.c
(since the merge of #27054) in sockets_can to enable parallel rx/tx.

Fixes #38698

Signed-off-by: Mateusz Karlic <mkarlic@internships.antmicro.com>
2021-10-06 22:22:43 -04:00
Robert Lubos 45e07dbbb3 net: sockets: tls: Ignore empty iovec entries in sendmsg
According to `sendmsg()` man pages, the `struct msghdr` can contain
empty records (iov_len equal to 0). Ignore them in TLS `sendmsg()`
implementation to avoid unnecessary calls to mbed TLS.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-29 11:08:40 +02:00
Robert Lubos 0dbdcc770d net: sockets: Add socket processing priority
When creating a socket, all of the registered socket implementation are
processed in a sequence, allowing to find appropriate socket
implementation for specified family/type/protocol. So far however,
the order of processing was not clearly defined, leaving ambiguity if
multiple implmentations supported the same set of parameters.

Fix this, by registering socket priority along with implementation. This
makes the processing order of particular socket implementations
explicit, giving more flexibility to the user, for example when it's
neeed to prioritze one implementation over another if they support the
same set of parameters.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-28 20:11:26 -04:00
Robert Lubos 8b851af02a net: sockets: Register native TCP/UDP like any other socket type
This will allow to assing priority to a native TCP/UDP socket
implementation as well.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-28 20:11:26 -04:00
Robert Lubos 9cdc1bb944 net: sockets: tls: Fix TLS POLLHUP notification
The `poll()` function did not report POLLHUP if the peer ended the DTLS
session, making it impossible to detect such event on the application
side.

On the other hand, TLS erroneusely reported POLLHUP along with each
POLLIN event, as the 0 returned by the `recv()` socket call was
wrongly interpreted (it was expected to get 0 in return as 0 bytes were
requested).

Fix this by introducing a helper function to process the mbedtls context
and verify if new application data is pendingi or session has ended.
Use this new function in the poll handler, instead of a socket `recv()`
call, to remove any ambiguity in the usage, for both TLS and DTLS.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 18:14:33 -04:00
Robert Lubos d0affeff69 net: sockets: tls: Return ENOTCONN when DTLS client session ends
Notify the application when DTLS client session ends by returning
ENOTCONN on such event. Additionally, reset the mbed TLS session
structures, allowing to reinstante the session on the next send() call.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 18:14:33 -04:00
Robert Lubos b999c47424 net: sockets: tls: Fix incorrectly used errno codes
ECONNABORTED was returned in case tls_mbedtls_reset() function for
resetting session failed, which can be caused by memory shortage. Return
ENOMEM instead.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 18:14:33 -04:00
Pavlo Hamov 6975d92324 net: socket: fix significant buffer tls send
Sending of > 2k buffers leads to split socket writes.
Current implementation is not checking for full buffer size.
ztls_sendmsg_ctx proceeds to next iov on sucessful write.

Solution: Add loop into ztls_sendmsg_ctx to process whole buffer
before proceeding to next iov.

Signed-off-by: Pavlo Hamov <pasha.gamov@gmail.com>
2021-09-02 19:35:50 -04:00
Fabio Baltieri f88a420d69 toolchain: migrate iterable sections calls to the external API
This migrates all the current iterable section usages to the external
API, dropping the "Z_" prefix:

Z_ITERABLE_SECTION_ROM
Z_ITERABLE_SECTION_ROM_GC_ALLOWED
Z_ITERABLE_SECTION_RAM
Z_ITERABLE_SECTION_RAM_GC_ALLOWED
Z_STRUCT_SECTION_ITERABLE
Z_STRUCT_SECTION_ITERABLE_ALTERNATE
Z_STRUCT_SECTION_FOREACH

Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
2021-08-12 17:47:04 -04:00
Emil Lindqvist dab4616e45 net: socket: fix regression causing corrupted poll timeout
k_timeout_t was converted to ticks using a nonsense function
causing poll timeout corruption for offloaded sockets; this
commit uses ticks directly from the struct instead.

Fixes #37472

Signed-off-by: Emil Lindqvist <emil@lindq.gr>
2021-08-06 19:20:48 -04:00
Emil Lindqvist f9023d2c41 net: sockets: dtls: reset mbedtls session on timed out handshake
According to MbedTLS API documentation, its session must be
reset if mbedtls_ssl_handshake returns timeout error. This
commit resets the session for said return value, and that
allows us to call send() multiple times even if handshake
times out for previous calls.

Fixes #35711

Signed-off-by: Emil Lindqvist <emil@lindq.gr>
2021-08-06 19:19:26 -04:00
Robert Lubos 8a4e489739 net: sockets: dtls: Fix handshake with socket offloading
Fix `poll()` handling for DTLS clients when the underlying socket is an
offloaded socket. As in this case no `k_poll()` is used underneath, it's
not possible to monitor the handhshake status with `tls_established`
semaphore. Instead, do the following:

1. If no handhshake is in progress yet, just drop the incoming data -
   it's the client who should initiate the handshake, any data incoming
   before that should not be processed.
2. If handshake is currently in progress, lift the `POLLIN` flag and add
   small delay to allow the other thread to proceed with the handshake.
3. Otherwise, just proceed as usual.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-16 22:09:58 -04:00
Robert Lubos b4366a8732 net: sockets: tls: Fix handshake on non blocking sockets
The TLS/DTLS handshake in most cases is a blocking process, therefore
the underlying socket should be in a blocking mode to prevent busy
looping in the handshake thread. Fix this by clearing the O_NONBLOCK
flag on the underlying socket before the handshake, and restoring it
afterards.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-16 22:09:04 -04:00
Chih Hung Yu a927ae39ed net: lib: sockets: Fix assertion failure when zsock_close()
When zsock_close() is called, socket is freed before the mutex for the
socket is unlocked. If the freed socket is given to another thread
immediately, the mutex for the socket will be initialized by the new
socket owner, while the mutex is still locked by the thread calling
zosck_close().

Fixes #36568

Signed-off-by: Chih Hung Yu <chyu313@gmail.com>
2021-07-12 20:16:37 -04:00
Robert Lubos 6d366093c8 net: sockets: socketpair: Rename read/write signals
Rename `write_signal` to `readable` and `read_signal` to `writeable`
which are more meaningful to the actual states they represent, and make
the code analysis easier.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-02 22:22:42 -04:00
Robert Lubos e415518f5f net: sockets: socketpair: Fix poll signalling
In case read or write were called before the actual poll() call, the
poll() function was not signalled correctly about such events, which in
order could lead to a deadlock if the poll() was called with infinite
timeout.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-02 22:22:42 -04:00
Jukka Rissanen 703233e115 net: socket: Allow microsecond accuracy in zsock_select()
Allow caller to specify microsecond accuracy and not convert
to milliseconds.

Fixes #36072

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-06-17 15:23:13 +03:00
Jukka Rissanen 1b025c8d64 net: socket: Make zsock_select() a syscall
Make zsock_select() a syscall so that the following commit
can call the internal poll implementation directly. This is
needed as zsock_select() will not call zsock_poll() directly
in order to allow select to use microsecond timeout accuracy.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-06-17 15:23:13 +03:00
Ievgen Glinchuk 1ce8d6fae4 net: dns: Fix multiple IP DNS resolution
Fixed mutli-IP DNS resolution as previously the same IP address was
used to populate all AI entries and added DNS_RESOLVER_AI_MAX_ENTRIES
config entry to define max number of IP addresses per DNS name to be
handled.

Signed-off-by: Ievgen Glinchuk <john.iceblink@gmail.com>
2021-06-07 23:54:55 -04:00
Robert Lubos 34fb892fb5 net: sockets: tls: Use secure random generator from Zephyr
Zephyr has introduced secure random generator API after the TLS sockets
were implemented. Use this new API in TLS sockets implementation,
instead of implementing secure RNG with mbedTLS in the module itself.
This facilitates integration of the HW RNG accelerators with the TLS
sockets module.

Signed-off-by: Frank Audun Kvamtrø <frank.kvamtro@nordicsemi.no>
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-06-04 16:27:17 -05:00
Emil Lindqvist 91177eebc1 net: sockets: tls: check return code from fcntl
Not checking return code in fcntl can result in interpreting -1 as
flags, and cause unexpected behaviour.

Fixes #35541

Signed-off-by: Emil Lindqvist <emil@lindq.gr>
2021-05-27 15:44:03 +02:00
Jukka Rissanen c53d483b6d net: sockets: Do not hijack k_fifo API name
The k_fifo_ prefix is meant for kernel API functions, and
not to our socket helper. So remove the k_ prefix in order
to avoid confusion.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-24 23:30:18 -04:00
Jukka Rissanen 20a51b49a0 net: sockets: Release the socket lock if needed
If we are waiting all the data i.e., the MSG_WAITALL flag is set,
then if we have not yet received all the data at the end of the
receive loop. We must use the condition variable to get the signal
when the data is ready to be received. Otherwise the receive loop
will not release the socket lock and receive_cb will not be able
to indicate that data is received.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-24 23:30:18 -04:00
Jukka Rissanen 1184089d54 net: sockets: Add locking to receive callback
Fix a regression when application is waiting data but does
not notice that because socket layer is not woken up.

This could happen because application was waiting condition
variable but the signal to wake the condvar came before the
wait started. Normally if there is constant flow of incoming
data to the socket, the signal would be given later. But if
the peer is waiting that Zephyr replies, there might be a
timeout at peer.

The solution is to add locking in socket receive callback so
that we only signal the condition variable after we have made
sure that the condition variable is actually waiting the data.

Fixes #34964

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-24 23:30:18 -04:00
David Brown aa5187ecde tls: Change some external symbols from Mbed TLS
In Mbed TLS:
    commit eccd88871767e2fba5f3a079cfdfcb77c376cf20
    Author: Gilles Peskine <Gilles.Peskine@arm.com>
    Date:   Tue Mar 10 12:19:08 2020 +0100

        Rename identifiers containing double-underscore

changes the name of a symbol we use.  As part of upgrading to newer
versions of Mbed TLS, change the name of the symbol we use.

A better fix would be to not use this symbol at all, and perhaps define
our own symbol the same way this internal symbol is defined within the
library.

Signed-off-by: David Brown <david.brown@linaro.org>
2021-05-09 09:59:22 -05:00
Chih Hung Yu 5cebdf5fd3 net: lib: sockets: Fix zsock_select
zsock_select() cannot poll file descriptors with number >= 32.

When a whole word in FD_SET was skipped due to being empty,
corresponding fd number was not updated, leading to wrong
fd's being passed to poll().

Fixes #34563

Signed-off-by: Chih Hung Yu <chyu313@gmail.com>
2021-04-28 20:01:31 +03:00
Jukka Rissanen bd03493fdc net: pkt: Have separate create time for net_pkt
This value is used to measure the RX/TX statistics. The previous
use of the timestamp field did not work in RX path as the timestamp
value could be overwritten by the driver if gPTP timestamping
is enabled. So to fix the RX statistics, use a separate field
for the create time.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-27 12:02:19 +03:00
Jukka Rissanen 9f2fa87e05 net: Remove support for CONFIG_NET_CONTEXT_TIMESTAMP option
This option was only able to collect statistics of transmitted
data. The same functionality is available if one sets the
CONFIG_NET_PKT_RXTIME_STATS and/or CONFIG_NET_PKT_TXTIME_STATS
options.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-26 10:46:43 +03:00
Jukka Rissanen a7f1c2821a net: sockets: RX statistics were not properly compiled in
The RX statistics might not get updated properly because the used
ifdef was referring the TX options.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-26 10:46:43 +03:00
Jukka Rissanen dde03c6770 net: socket: Add locking to prevent concurrent access
The BSD API calls were not thread safe. Add locking to fix this.

Fixes #27032

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-15 07:16:51 -05:00
Paul Sokolovsky 471afe5ddc net: sockets: Make NET_SOCKETS_POSIX_NAMES be on by default
Zephyr socket subsystem has come a long way since initial experimental
alternative to internal Zephyr networking API. Its configuration also
mirrors the usual conservative approach, where a user needs to
explicitly enable options to get "more" features. And as an
experimental API, socket subsystem was initially developed as
namespaced API, where all functions/structures are prefixed with
"zsock_", and to get standard names, CONFIG_NET_SOCKETS_POSIX_NAMES
needs to be set (or alternatively, CONFIG_POSIX_API needs to be, which
enabled full POSIX subsys overall).

However, a few years later, sockets are the standard networking API,
and in majority of cases its used under the standard POSIX names.
Necessity to explicitly set an option to achieve this effects, and
confusion which results from it - are just unneeded chores for users.

So, switch CONFIG_NET_SOCKETS_POSIX_NAMES to be on by default (unless
CONFIG_POSIX_API is already defined). It still can be explicitly
disabled if needed (but usecases for that would be peculiar and rare).

Addresses #34165

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2021-04-13 13:00:53 -04:00
Robert Lubos 814fb71bf3 net: socket: Implement SO_BINDTODEVICE socket option
Implement SO_BINDTODEVICE socket option which allows to bind an open
socket to a particular network interface. Once bound, the socket will
only send and receive packets through that interface.

For the TX path, simply avoid overwriting the interface pointer by
net_context_bind() in case it's already bound to an interface with an
option. For the RX path, drop the packet in case the connection handler
detects that the net_context associated with that connection is bound to
a different interface that the packet origin interface.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-02 07:23:17 -04:00