Commit graph

554 commits

Author SHA1 Message Date
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
Emil Lindqvist 3115610558 net: socket: dtls: add sockopt to set & get dtls handshake timeout
An option has been added which can be passed to setsockopt
which allows the user to set & get the dtls handshake timeout,
either before first handshake or online.

Signed-off-by: Emil Lindqvist <emil@lindq.gr>
2021-04-01 20:02:59 +03:00
Jani Hirsimäki bd40cb48d9 net: socket: packet: using pckt sckt for passing the PPP dialup data
With these changes, dial up Zephyr application/driver can use
socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW) for creating
a socket for sending/receiving data to/from ppp net link, i.e.
packet is going to/from PPP L2.

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2021-04-01 09:43:56 +03:00
Robert Lubos bed1dc26f1 net: sockets: tls: Fix poll() handling during the handshake
Current implementation of poll prepare/update could end up busy looping
if `poll()` function was called before/during DTLS client handshake
(i. e. `poll()` called before an initial `send()`).

Fix this, by monitoring the handshake semaphore, already available in
the tls_context structure for DTLS client instead of underlying socket.
After the handshake is complete, switch to monitoring the underlying
socket instead.

For DTLS server this is not needed, since the handshake is initiated in
the `recv()` function, therefore any incoming data should trigger the
handshake.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-31 08:06:30 -04:00
Robert Lubos 02a1168475 net: sockets: tls: Implement MSG_TRUNC flag
Add implementation of MSG_TRUNC `recv()` flag for DTLS sockets.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-23 13:16:30 +02:00
Robert Lubos 833517f994 net: sockets: Implement MSG_TRUNC flag
Add implementation of MSG_TRUNC `recv()` flag for UDP sockets.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-23 13:16:30 +02:00
Anas Nashif a518f48796 clock: renmae z_timeout_end_calc -> sys_clock_timeout_end_calc
Do not use z_ for internal APIs, z_ is for private APIs within one
subsystem only.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-19 11:22:17 -04:00
Anas Nashif fe0872c0ab clocks: rename z_tick_get -> sys_clock_tick_get
Do not use z_ for internal APIs, z_ is for private APIs within one
subsystem only.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-19 11:22:17 -04:00
Marcin Niestroj 9f12dbba5d net: sockets: improve DGRAM recvfrom() on NET_OFFLOAD iface
When recvfrom() was called with src_addr != NULL, then source address
was fetched from beginning of net_pkt. This works with native IP stack
obviously. However with offloaded IP stack there is no IP header, so
trying to parse missing IP header results in undefined behavior.

Check if network interface has offloaded IP stack. If positive, then
figure out if there is assigned remote address to network context on
which packet was received. Return this remote address, which SHOULD be
the source address of received packet. Otherwise, return an error.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2021-03-17 20:00:42 +02:00
Jukka Rissanen ee2e3dd9fc net: sockets: Provide close method for packet sockets
There was no close method implemented for AF_PACKET type
sockets. This meant that calling close() on packet socket
caused NULL pointer access.

This will allow #32949 issue to work properly.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-15 15:17:52 +02:00
Robert Lubos a670c84530 net: sockets: tls: Implement MSG_WAITALL flag
Add MSG_WAITALL flag implmentation for secure sockets.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-12 13:57:11 -05:00
Robert Lubos d47e803976 net: sockets: Implement MSG_WAITALL recv flag
Implement MSG_WAITALL flag for stream sockets. Setting this flag on
`recv()` call will make it wait until the requested amount of data is
received.

In case both, MSG_WAITALL all is set and SO_RCVTIMEO option configured
on a socket, follow the Linux behavior, i. e. when the requested amount
of data is not received until the timeout expires, return the data
received so far w/o an error.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-12 13:57:11 -05:00
James Harris b10428163a kernel: sem: add K_SEM_MAX_LIMIT
Currently there is no way to distinguish between a caller
explicitly asking for a semaphore with a limit that
happens to be `UINT_MAX` and a semaphore that just
has a limit "as large as possible".

Add `K_SEM_MAX_LIMIT`, currently defined to `UINT_MAX`, and akin
to `K_FOREVER` versus just passing some very large wait time.

In addition, the `k_sem_*` APIs were type-confused, where
the internal data structure was `uint32_t`, but the APIs took
and returned `unsigned int`. This changes the underlying data
structure to also use `unsigned int`, as changing the APIs
would be a (potentially) breaking change.

These changes are backwards-compatible, but it is strongly suggested
to take a quick scan for `k_sem_init` and `K_SEM_DEFINE` calls with
`UINT_MAX` (or `UINT32_MAX`) and replace them with `K_SEM_MAX_LIMIT`
where appropriate.

Signed-off-by: James Harris <james.harris@intel.com>
2021-03-05 08:13:53 -06:00
Hubert Miś dd319c2d4c net: socket send timeout option
This patch adds SO_SNDTIMEO option used to time out socket sending
operations.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-02-24 14:16:33 +02:00
Hubert Miś ce3dcf2394 net: socket: getsockopt SO_PROTOCOL implementation
This patch adds implementation of socket option used to get
protocol used for given socket (e.g. IPPROTO_TCP). This option
is not defined in POSIX, but it is Linux extension.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-02-17 10:36:58 +02:00
Hubert Miś f6263c8143 net: socket: getsockopt SO_TYPE implementation
This patch adds implementation of socket option used to get
type of given socket (e.g. SOCK_STREAM).

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-02-17 10:36:58 +02:00
Jukka Rissanen 1364a9c52e net: tls: Allow access to TLS socket in userspace
If userspace is enabled, then the TLS context needs to be
made a NET_SOCKET kernel object. Without this the userspace
cannot access TLS sockets.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-15 10:56:44 -05:00
Hubert Miś 2dd611c9d0 net: socket: Implement SO_RCVTIMEO timeout option
This patch adds SO_RCVTIMEO option used to time out socket receiving
operations.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-01-19 17:11:25 -05:00
Hubert Miś ade40136ea net: resolve literal IP addresses even when DNS is disabled
With this patch the resolver module can resolve literal IPv6
and IPv4 addresses even when DNS client is not presnet in
the system.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2020-12-22 15:44:00 +02:00
Seppo Takalo f684b7c6cd net: getaddrinfo: Fix getaddrinfo() to respect socket type hints
If getaddrinfo() was called with AI_PASSIVE flag in hints,
returned address defaulted to SOCK_STREAM and IPPROTO_TCP.
Fixed so that SOCK_DGRAM leads to correct address type
that can be fed to bind() directly.

Same hard coding was visible when numerical IPv4 address string
was converted to binary. That is also fixed to respect hints now.

Also, added functionality to get IPv6 address, when hints contained
AF_INET6.

Fixes #30686

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2020-12-15 19:22:50 +02:00
Paul Sokolovsky d29fcb8187 net: sockets: recv() on unconnected stream socket should lead to ENOTCONN
Because unoconnected stream socket doesn't have any chance to receive
any data, so a blocking recv() would hang forever on it (and does
without this change).

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2020-11-19 16:58:37 -05:00
Marcin Niestroj fbc487cce3 net: tls: use Maximum Fragment Length (MFL) extension by default
Call mbedtls_ssl_conf_max_frag_len() on created TLS context
configuration, so that Maximum Fragment Length (MFL) will be sent to
peer using RFC 6066 max_fragment_length extension. MFL value is
automatically chosen based on MBEDTLS_SSL_OUT_CONTENT_LEN and
MBEDTLS_SSL_IN_CONTENT_LEN mbed TLS macros.

This extension is mostly useful for TLS client side to tell TLS server
what is the maximum supported receive record length.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-11-05 14:47:24 +02:00
Marcin Niestroj 761f1c4bed net: tls: fix tls_context leak in ztls_socket() error path
If there are enough tls_context objects in the system (configured by
CONFIG_NET_SOCKETS_TLS_MAX_CONTEXTS), but there are not enough file
descriptors (configured by CONFIG_POSIX_MAX_FDS) to create underneath
TCP/UDP socket, then TLS socket creation fails with leaked tls_context.

Call tls_release() in ztls_socket() error path whenever underneath
TCP/UDP socket creation fails.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-11-03 19:25:48 +02:00
Emil Hammarstrom ec00feef35 net: lib: sockets: added ALPN extension option to TLS
Adds the socket option TLS_ALPN_LIST for SOL_TLS sockets

Passes the configured alpn list to the mbedtls config
on mbedtls init

Signed-off-by: Emil Hammarstrom <emil.hammarstrom@assaabloy.com>
2020-10-22 11:35:43 +03:00
Jan Pohanka 91adf41dd4 net: sockets: tls: fix using of zsock_ functions
Use zsock_ variants of socket functions to be independent on
NET_SOCKETS_POSIX_NAMES config.

Signed-off-by: Jan Pohanka <xhpohanka@gmail.com>
2020-10-01 17:35:45 +03:00
Jukka Rissanen 9cccf0ea55 net: tcp2: If the send window is full, do not try to send
If there is no space in the sending window, then return -EAGAIN
so that the caller may try later.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen 69d9eb6c94 net: socket: Wait new buffers when sending
If we run out of network buffers and cannot send data, and if
we have a blocking socket, then wait until new buffers are
available before returning. As this might lead to deadlock,
wait only max 10 seconds and return ENOMEM if we cannot get
buffers in a reasonable amount of time.

Fixes #28216

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Robert Lubos 7242a80036 net: sockets: tls: Fix invalid variable initialization
The timeout variable in `dtls_rx()` was initialized improperly.

Coverity ID: 214219

Fixes #28161

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-09-09 14:10:29 +03:00
Robert Lubos b79f538adc net: sockets: tls: Add Kconfig option to disable offloaded TLS
This new option allows to include `sockets_tls.c` into the build when
socket offloading is enabled.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-09-03 11:00:01 +03:00
Robert Lubos 968a3101a2 net: sockets: tls: Add support for offloaded poll
Given that the offloaded poll handling differs from the poll handling of
native sockets (entire poll function call is offloaded), some
adjustements were needed to make TLS socket work with offloaded poll
calls.

To achieve this, in case socket offloading is used, instead of jumping
directly to the offloaded poll call, a TLS wrapper for the offloaded
poll will be called. This wrapper will do additional checks at the
mbedtls level, to verify that the event is only notified to the caller
when the application data is available (i. e. not to report events
during handshake or when partial data is received, not ready to
decrypt).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-09-03 11:00:01 +03:00
Robert Lubos 27211cf112 net: sockets: tls: Decouple TLS sockets from net_context
Separate TLS sockets implementation from net_context layer. Instead of
calling net_context functions directly, create an underlying TCP/UDP
socket, and call socket functions on it instead. This results in a
simpler design, where we don't need to duplicate specific parts of code
from the native socket implementation. Additionally, this allows to use
a different TCP/UDP stack underneath (i. e. when sockets offloading is
used).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-09-03 11:00:01 +03:00
Robert Lubos 7d77307c5c net: sockets: tls: Add helper function to verify protocol
This commit adds helper function to verify protocol, which was done in
two different places in the code. The function returns the underlying
protocol information on success.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-09-03 11:00:01 +03:00
Tomasz Bursztyka 38809a44a8 subsys: net: Fix device instance const qualifier loss in socket tls
Entropy device, as being unique here, does not need to be passed through
mbedtls and can instead set static locally.

Fixes #27399

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-09-02 13:48:13 +02:00
Tomasz Bursztyka e18fcbba5a device: Const-ify all device driver instance pointers
Now that device_api attribute is unmodified at runtime, as well as all
the other attributes, it is possible to switch all device driver
instance to be constant.

A coccinelle rule is used for this:

@r_const_dev_1
  disable optional_qualifier
@
@@
-struct device *
+const struct device *

@r_const_dev_2
 disable optional_qualifier
@
@@
-struct device * const
+const struct device *

Fixes #27399

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-09-02 13:48:13 +02:00
Jukka Rissanen 2ba4d5c2f0 net: socket: packet: Add support to SOCK_DGRAM packet sockets
Allow user to create SOCK_DGRAM type AF_PACKET socket. This
allows user to send raw IP packets without specifying
L2 (like Ethernet) headers.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-08-27 10:56:06 +03:00
Flavio Ceolin 0aaae4a039 guideline: Make explicit fallthrough cases
-Wimplicit-fallthrough=2 requires a fallthrough comment or a compiler
to tells gcc that this happens intentionally.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-08-24 20:28:47 -04:00
Jukka Rissanen 13c8b110e5 net: socketpair: Check NULL value
When verifying the parameters check NULL value separately.
This will avoid nasty warning message to be printed.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-08-14 09:47:51 -07:00
Jukka Rissanen d0d041d833 net: getsockname: Call via vtable instead of ioctl
Add function pointer to vtable and use that directly instead of
routing via ioctl() call. This is done as we are trying to get
rid of ioctl() calls in the system.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-08-14 09:47:51 -07:00
Jukka Rissanen 2ed6b6a8ed lib: fdtable: Add callback for close() calls
Do not route close() calls via ioctl() as that is error prone
and quite pointless. Instead create a callback for close() in
fdtable and use it directly.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-08-14 09:47:51 -07:00
Tomasz Bursztyka 98d9b01322 device: Apply driver_api/data attributes rename everywhere
Via coccinelle:

@r_device_driver_api_and_data_1@
struct device *D;
@@
(
D->
-	driver_api
+	api
|
D->
-	driver_data
+	data
)

@r_device_driver_api_and_data_2@
expression E;
@@
(
net_if_get_device(E)->
-	driver_api
+	api
|
net_if_get_device(E)->
-	driver_data
+	data
)

And grep/sed rules for macros:

git grep -rlz 'dev)->driver_data' |
	xargs -0 sed -i 's/dev)->driver_data/dev)->data/g'

git grep -rlz 'dev->driver_data' |
	xargs -0 sed -i 's/dev->driver_data/dev->data/g'

git grep -rlz 'device->driver_data' |
	xargs -0 sed -i 's/device->driver_data/device->data/g'

Fixes #27397

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-08-11 19:30:53 +02:00
Jukka Rissanen 4dfc589904 net: Collect net_pkt RX detailed timing stats when passing IP stack
This adds RX support to get detailed net_pkt timing statistics.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-08-07 10:12:51 +03:00
Vincent Wan 34db96404b net: sockets: add support for select() when using socket offloading
When socket offloading is used, we should build the implementation of
select().

Fixes #12705

Signed-off-by: Vincent Wan <vwan@ti.com>
2020-07-27 13:28:06 +02:00
Flavio Ceolin c4f7faea10 random: Include header where it is used
Unit tests were failing to build because random header was included by
kernel_includes.h. The problem is that rand32.h includes a generated
file that is either not generated or not included when building unit
tests. Also, it is better to limit the scope of this file to where it is
used.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-07-08 21:05:36 -04:00
Adam Porter f09b8681f6 net: sockets: remove POSIX_NAMES dependency on SOCKETS_OFFLOAD
This is no longer required since drivers implementing the sockets
offload interface were migrated to use pure zsock_ instead of
raw POSIX types and functions.

Signed-off-by: Adam Porter <porter.adam@gmail.com>
2020-06-17 08:55:17 +03:00
Christian Taedcke 8ac2f96ca6 net: sockets: fix conn_handler check in zsock_getsockname_ctx
The check was inverted, so a bound socket was detected as not bound.

Signed-off-by: Christian Taedcke <christian.taedcke@lemonbeat.com>
2020-06-16 14:57:16 +03:00
Léonard Bise 8e4faab30a net: sockets: Return EINVAL when an accept call is unblocked
Under Linux when you shutdown a socket which is blocked on
an accept call the error code returned by accept is EINVAL.
Modify the socket code to be inline with this behaviour.

Signed-off-by: Léonard Bise <leonard.bise@gmail.com>
2020-06-15 22:15:07 +03:00
Léonard Bise 5cedb73555 net: sockets: tls: Check accepted context is not NULL
When closing a listening socket the functions waiting on the
FIFO will be unblocked this will result in receiving a NULL child
context. If that is the case return an error instead of carrying on.
Return the same error code (EINVAL) that is returned on Linux when
calling shutdown on a blocked accept call.

Signed-off-by: Léonard Bise <leonard.bise@gmail.com>
2020-06-15 22:15:07 +03:00
Andrew Boie 5d1ce47ef6 net: sockets: fix zsock_gethostname_ctx()
The SET_ERRNO() macro does nothing if a positive value is provided
to it, and the functions were not returning -1 or setting errno
as expected.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-09 10:58:02 +03:00
Andrew Boie 71d4aeb1c2 net: sockets: set errno EBADF on bad fd
APIs were returning -1 without setting errno if the file
descriptor looked up a null object or there was no function
installed in the vtable. Set to EBADF for this case.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-09 10:58:02 +03:00
Jukka Rissanen 43287d2323 net: socket: Add sendmsg() support to AF_PACKET
The AF_PACKET was missing support for sendmsg() socket call.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-06-08 21:34:35 +03:00
Kumar Gala a1b77fd589 zephyr: replace zephyr integer types with C99 types
git grep -l 'u\(8\|16\|32\|64\)_t' | \
		xargs sed -i "s/u\(8\|16\|32\|64\)_t/uint\1_t/g"
	git grep -l 's\(8\|16\|32\|64\)_t' | \
		xargs sed -i "s/s\(8\|16\|32\|64\)_t/int\1_t/g"

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-06-08 08:23:57 -05:00
Robert Lubos 370dfe088f net: sockets: Fix socket ctx check in usermode
When `z_get_fd_obj_and_vtable()` function returns NULL (no valid entry
in the FD table for the socket), there is no need for further usermode
checks on the `ctx` pointer, as there is nothing to invalidate in that
case.

Fixes #25990
Fixes #25991

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-06-05 18:34:25 +02:00
Andrew Boie c951d71eba net: check permissions on net contexts
The original sockets system calls used file descriptors which
were actually net_context pointers. For all socket system calls,
any calls from user mode would check if the caller had permission
to use the net context.

This was later changed to not stuff net_context pointers into file
descriptors, but all the permission checking was unintentionally
lost, allowing all threads on the system to
read/write all socket file descriptors in the system at will, with
no way to isolate applications running on the same microcontroller
from each other's network activity.

This patch restores the permission checks on network context objects
for socket system calls that originated from user mode.

The call to z_object_recycle() was never removed from
zsock_socket_internal(); this is again leveraged to grant the
caller who opened the socket permission on the net_context
associated with the returned file descriptor.

To ensure that all socket calls do this checking, all uses of
z_get_fd_obj_and_vtable() have been routed through get_sock_vtable().

Objects have initialization state set and thread permissions
reset to just the caller in common zsock_socket() code.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Andrew Boie 8ea273b44a net: socketpair: fix user mode access
The socketpair file descriptor context objects are heap allocated
and not drawn from a static pool. Register these as kernel objects
when we create them if user mode is enabled.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Andrew Boie 9f63a0a0a0 net: lib: remove socket-specific recycle calls
This is just done in common code now.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Andrew Boie 04bba6772b net: sockets: add API to fetch an fd's ctx object
Zephyr running on MPU devices have a different memory model than
process-oriented OSes like Linux and require a method to set
kernel object permissions on a file descriptor's underlying
context object. Add this, and a test to show that it is working.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Andrew Boie fed960b94a net: tag net socket objects
Used for permission validation when accessing the associated file
descriptors from user mode.

There often get defined in implementation code, expand the search
to look in drivers/ and subsys/net/.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Jukka Rissanen a2f0a9effe net: sockets: Fix sendmsg() user mode param checks for aux data
If we are calling sendmsg() without any aux data, then msg_controllen
is 0 and msg_control is NULL. Check these allowed values properly.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-06-03 18:33:59 +02:00
Jukka Rissanen d3dde1ad1c net: sockets: Fix sendmsg() user mode param checks for dst address
If we are calling sendmsg() for a connected socket, then msg_namelen
is 0 and msg_name is NULL. Check these allowed values properly.

Also modify unit tests so that we test this scenario.

Fixes #25925

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-06-03 18:33:59 +02:00
Christopher Friedt 2715357e63 net: socket: socketpair: initialize after NULL check
Fixes #25788
Coverity-CID: 210581

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-06-03 18:33:19 +02:00
Christopher Friedt 195a536073 net: socket: socketpair: remove dead code
In this, case is_nonblock is false and will_block is true.
Therefore, we *may* block, and furthermore we *expect* to
block. Checking is_nonblock is, in fact, redundant, and
passing K_FOREVER to k_sem_take() is justified.

Fixes #25727
Coverity-CID: 210611

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-06-03 18:33:19 +02:00
Jukka Rissanen 35f4ffb186 net: sockets: Add sendmsg() parameter verification
If run in usermode, the sendmsg() parameters were not verified.

Fixes #25702

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-06-02 15:22:47 +02:00
Christopher Friedt 6161ea2542 net: socket: socketpair: mitigate possible race condition
There was a possible race condition between sock_is_nonblock()
and k_sem_take() in spair_read() and spair_write() that was
mitigated.

Also clarified some of the conditional branching in those
functions.

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-05-20 10:34:07 +02:00
Christopher Friedt 3bfc765aad tests: socket: socketpair: tests for socketpair(2) syscall
Tests for issue #24366

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-05-10 17:46:43 +02:00
Christopher Friedt 09f957c47a net: socket: syscall for socketpair(2)
Working:

* non-blocking reads / writes
* blocking reads / writes
* send(2) / recv(2) / sendto(2) / recvfrom(2) / sendmsg(2)
* select(2)
* poll(2)

Fixes #24366

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-05-10 17:46:43 +02:00
Xavier Chapron e5aaf21a73 subsys: Replace printf by printk when applicable
Signed-off-by: Xavier Chapron <xavier.chapron@stimio.fr>
2020-05-09 21:25:33 +02:00
Jukka Rissanen 65a1bebe85 net: Replace NET_WAIT_FOREVER by SYS_FOREVER_MS
As we now have SYS_FOREVER_MS, use that instead of network
specific NET_WAIT_FOREVER.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-05-05 16:29:23 +03:00
Kumar Gala 43a7d26603 drivers: entropy: replace CONFIG_ENTROPY_NAME with DT macro
Replace CONFIG_ENTROPY_NAME with DT_CHOSEN_ZEPHYR_ENTROPY_LABEL.  We now
set zephyr,entropy in the chosen node of the device tree to the entropy
device.

This allows us to remove CONFIG_ENTROPY_NAME from dts_fixup.h.  Also
remove any other stale ENTROPY related defines in dts_fixup.h files.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-04-13 09:14:21 -05:00
Jukka Rissanen 66d394d97a net: getaddrinfo: Fix timeout data type
Convert to use k_timeout_t

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-04-09 16:07:03 +03:00
Jukka Rissanen 9f17c33b60 net: sockets: Refactor because of timeout overhaul
Use k_timeout_t internally, no change to user API.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-04-09 16:07:03 +03:00
Jukka Rissanen 0a47dc5918 net: sockets: Release net_pkt if error during UDP recv()
If we are receiving UDP packet and if there is some error happening
inside zsock_recv_dgram(), then make sure that the net_pkt received
from recv_q is freed.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-03-17 13:13:58 +02:00
Robert Lubos 56566ad497 net: sockets: tls: Fix net_context referencing
TLS sockets did not increase refcount of a net_context running TCP,
which could lead to a crash upon TCP disconnection.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-03-10 14:08:20 +02:00
Jukka Rissanen ba3c5deea9 net: stats: Add RX time statistics for packet sockets
If CONFIG_NET_PKT_RXTIME_STATS is set, then update the received
packet RX time for packet sockets (SOCK_RAW). This was already
working for normal sockets but the statistics update was missing
from SOCK_RAW.

Fixes #22489

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-02-12 17:33:54 +02:00
Inbar Anson Bratspiess 827f6f1714 net: socket: Release fd on failure in accept()
The zsock_accept_ctx() calls z_reserve_fd() on entry but fails
to call z_free_fd() on failure. This will leak the allocated
socket descriptor.

Fixes #22366

Signed-off-by: Inbar Anson Bratspiess <inbar.anson.bratspiess@330plus.net>
2020-02-10 12:33:22 +02:00
Vincent Wan 115949a97f sockets: tls: set TLS_CREDENTIALS when using non-native stack
When is NET_SOCKETS_SOCKOPT_TLS set, it should set TLS_CREDENTIALS
even when NET_NATIVE=n, so that platforms that use socket offloading
can continue to set TLS credentials.

We are now setting this via 'imply' instead of 'select', so that
prj.conf can opt out if necessary.

Fixes #22390

Signed-off-by: Vincent Wan <vincent.wan@linaro.org>
2020-02-05 18:47:54 -05:00
Robert Lubos bea1093e62 net: sockets: Remove socket offloading interface
Instead of using a custom offloading interface, users can use
`NET_SOCKET_REGISTER` macro to register custom socket API provider. This
solution removes a limitation, that only one offloaded interface can be
registered and that it cannot be used together with native IP stack.

The only exception remainig are DNS releated operations -
`getaddrinfo`/`freeaddrinfo`, which, when offloaded, have to be
registered specifically.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-01-31 11:36:02 -05:00
Robert Lubos 561973060e net: sockets: Extend ioctl poll protocol with offloading feature
Allow to use offloaded `poll` implementation via the existing ioctl poll
control mechanism.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-01-31 11:36:02 -05:00
Robert Lubos 41cfe0b31a sockets: tls: Fix Kconfig mbedTLS dependencies
Sort out mbedTLS dependencies in sockets Kconfig. mbedTLS will now
be enabled when TLS sockets and native network stack are enabled.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-01-31 09:52:21 +02:00
Robert Lubos 9b2fa8a5a7 net: sockets: Rework ioctl poll helpers error handling
Make ioctl handlers of `ZFD_IOCTL_POLL_PREPARE` and
`ZFD_IOCTL_POLL_UPDATE` return an error code instead of setting errno
variable.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-01-22 22:43:54 -05:00
Jukka Rissanen 61249021c0 net: socket: poll() with POLLOUT can return immediately
If we can write to the socket in POLLOUT, then there is no need to
wait.

Note that this is not a full POLLOUT implementation but prevents
the code from waiting even if we could send data out.

Fixes #18867

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-01-03 11:26:46 -08:00
Ravi kumar Veeramally cf9ad748ba net: ipv4: Add IPv4 options length to net pkt
IPv4 header options length will be stored in ipv4_opts_len
in net_pkt structure. Now IPv4 header length will be in
net_pkt ip_hdr_len + ipv4_opts_len. So modified relevant
places of ip header length calculation for IPv4.

Signed-off-by: Ravi kumar Veeramally <ravikumar.veeramally@linux.intel.com>
2019-12-16 11:35:24 +02:00
Jukka Rissanen b92a4c5cff net: sockets: tls: Mark accepted socket correctly in accept()
The TCP code expects that we know when the socket has called accept()
in order to continue connection attempt.

Fixes #21335

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-12-16 11:07:06 +02:00
Markus Fuchs 2f982b3bc2 net: tls: Add SSL/TLS secure renegotiation support
Allow enabling SSL/TLS secure renegotiation support when initiated by
peer.

Signed-off-by: Markus Fuchs <markus.fuchs@de.sauter-bc.com>
2019-12-13 13:26:45 +02:00
Kumar Gala 24ae1b1aa7 include: Fix use of <misc/FOO.h> -> <sys/FOO.h>
Fix #include <misc/FOO.h> as misc/FOO.h has been deprecated and
should be #include <sys/FOO.h>.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-12-10 08:39:37 -05:00
Markus Fuchs 1f2727c5fa net: tls: Add sendmsg
Add an implementation for `sendmsg`, so secure sockets can be used
together with the WebSocket module to implement secure WebSockets
("wss").

Fixes #20431

Signed-off-by: Markus Fuchs <markus.fuchs@de.sauter-bc.com>
2019-11-27 12:16:07 -05:00
Ulf Magnusson bd6e04411e kconfig: Clean up header comments and make them consistent
Use this short header style in all Kconfig files:

    # <description>

    # <copyright>
    # <license>

    ...

Also change all <description>s from

    # Kconfig[.extension] - Foo-related options

to just

    # Foo-related options

It's clear enough that it's about Kconfig.

The <description> cleanup was done with this command, along with some
manual cleanup (big letter at the start, etc.)

    git ls-files '*Kconfig*' | \
        xargs sed -i -E '1 s/#\s*Kconfig[\w.-]*\s*-\s*/# /'

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-04 17:31:27 -05:00
Ulf Magnusson 975de21858 kconfig: Global whitespace/consistency cleanup
Clean up space errors and use a consistent style throughout the Kconfig
files. This makes reading the Kconfig files more distraction-free, helps
with grepping, and encourages the same style getting copied around
everywhere (meaning another pass hopefully won't be needed).

Go for the most common style:

 - Indent properties with a single tab, including for choices.

   Properties on choices work exactly the same syntactically as
   properties on symbols, so not sure how the no-indentation thing
   happened.

 - Indent help texts with a tab followed by two spaces

 - Put a space between 'config' and the symbol name, not a tab. This
   also helps when grepping for definitions.

 - Do '# A comment' instead of '#A comment'

I tweaked Kconfiglib a bit to find most of the stuff.

Some help texts were reflowed to 79 columns with 'gq' in Vim as well,
though not all, because I was afraid I'd accidentally mess up
formatting.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-01 15:53:23 +01:00
David B. Kinder 241044f178 doc: fix misspellings in Kconfig files
Fix misspellings in Kconfig files missed during regular reviews.

Signed-off-by: David B. Kinder <david.b.kinder@intel.com>
2019-10-30 10:24:30 +01:00
Jukka Rissanen d88f25bd76 net: tcp: Handle special case where accepted socket is closed
Handle this corner case with TCP connection closing:

1) Client A connects, it is accepted and can send data to us
2) Client B connects, the application needs to call accept()
   before we will receive any data from client A to the application.
   The app has not yet called accept() at this point (for
   whatever reason).
3) Client B then disconnects and we receive FIN. The connection
   cleanup is a bit tricky as the client is in half-connected state
   meaning that the connection is in established state but the
   accept_q in socket queue contains still data which needs to be
   cleared.
4) Client A then disconnects, all data is sent etc

The above was not working correctly as the system did not handle the
step 3) properly. The client B was accepted in the application even
if the connection was closing.

After this commit, the commit called "net: tcp: Accept connections
only in LISTENING state" and related other commits are no longer
needed and are reverted.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-10-28 13:58:59 +02:00
Jukka Rissanen c3f0c32304 Revert "net: tls: Set accepting socket to LISTENING state"
This reverts commit d70a854904.

The next commit fixes the original issue so this commit is no
longer needed.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-10-28 13:58:59 +02:00
Jukka Rissanen e73d5a6479 Revert "net: tcp: Accept connections only in LISTENING state"
This reverts commit 1a6f4a6368.

Let's try to fix the backlog handling instead of this.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-10-28 13:58:59 +02:00
Jukka Rissanen f6f4467098 net: socks: Prefer setsockopt() API instead of legacy proxy api
Applications should use setsockopt() to setup the SOCKS5 proxy,
so the old API file, which is using net_context directly, is
moved SOCKS5 directory.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-10-25 13:56:01 +03:00
Jukka Rissanen d70a854904 net: tls: Set accepting socket to LISTENING state
This is related to commit 1a6f4a6368 ("net: tcp: Accept
connections only in LISTENING state") which made the system
to only accept new connections if the application had called
accept(). Unfortunately the TLS accept was not fixed by that
commit so we were in wrong state when accepting TLS sockets.
This commit fixes that issue.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-10-15 23:30:34 +03:00
Jukka Rissanen 8d3b74ab61 net: Add statistics how long packets have spent in RX path
Calculate how long on average net_pkt has spent on its way from
network device driver to the application. The data is only
calculated for UDP and TCP network packets.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-10-14 16:34:48 +03:00
Jukka Rissanen e98f5d37f5 net: sockets: Store socket private data into its own variable
Do not try to re-use net_context.user_data field as in many places
(like in accept) it is expected to contain pointer to net_context.
Storing the socket flags will corrupt the value. To simplify and
make things less error prone, use socket specific field in net_context
to store the socket flags.

Fixes #19191

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-09-18 23:47:36 +03:00
Jukka Rissanen c755be0ee7 net: socket: The socket flags need to use uintptr_t
The socket flags are stored in void* so we need to use uintptr_t
instead of u32_t when manipulating the flag variable.

Fixes #19181

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-09-16 14:41:18 -05:00
Jukka Rissanen 0b1034aee2 net: socket: Support non-blocking accept()
If socket is marked non-blocking, then accept() will return immediately
if there is no one connecting.

Fixes #19103

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-09-13 10:41:33 +03:00
Jukka Rissanen 2f8f5fdd33 net: socket: Set default protocol if proto == 0
If proto field in socket() call is set to 0, then we should have
a sane default for it that depends on the type of the socket.

Fixes #18873

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-09-12 11:22:45 +03:00
Andy Ross 643701aaf8 kernel: syscalls: Whitespace fixups
The semi-automated API changes weren't checkpatch aware.  Fix up
whitespace warnings that snuck into the previous patches.  Really this
should be squashed, but that's somewhat difficult given the structure
of the series.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Andy Ross 346cce31d8 kernel: Port remaining buildable syscalls to new API
These calls are buildable on common sanitycheck platforms, but are not
invoked at runtime in any tests accessible to CI.  The changes are
mostly mechanical, so the risk is low, but this commit is separated
from the main API change to allow for more careful review.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Andy Ross 6564974bae userspace: Support for split 64 bit arguments
System call arguments, at the arch layer, are single words.  So
passing wider values requires splitting them into two registers at
call time.  This gets even more complicated for values (e.g
k_timeout_t) that may have different sizes depending on configuration.
This patch adds a feature to gen_syscalls.py to detect functions with
wide arguments and automatically generates code to split/unsplit them.

Unfortunately the current scheme of Z_SYSCALL_DECLARE_* macros won't
work with functions like this, because for N arguments (our current
maximum N is 10) there are 2^N possible configurations of argument
widths.  So this generates the complete functions for each handler and
wrapper, effectively doing in python what was originally done in the
preprocessor.

Another complexity is that traditional the z_hdlr_*() function for a
system call has taken the raw list of word arguments, which does not
work when some of those arguments must be 64 bit types.  So instead of
using a single Z_SYSCALL_HANDLER macro, this splits the job of
z_hdlr_*() into two steps: An automatically-generated unmarshalling
function, z_mrsh_*(), which then calls a user-supplied verification
function z_vrfy_*().  The verification function is typesafe, and is a
simple C function with exactly the same argument and return signature
as the syscall impl function.  It is also not responsible for
validating the pointers to the extra parameter array or a wide return
value, that code gets automatically generated.

This commit includes new vrfy/msrh handling for all syscalls invoked
during CI runs.  Future commits will port the less testable code.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00