Commit graph

5663 commits

Author SHA1 Message Date
Ajay Parida
c69731a281 net: wifi_mgmt: Display TWT setup response status
Display the TWT setup response status.

Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
2023-02-21 10:58:40 +01:00
Jeroen van Dooren
d20cceb48e net: ip: net_mgmt: Increase default queue size
There is no reason why the default size should be 2,
because an event is only a combination of

{uint32_t + void*} + info

Using 2 as default causes a high risk of loosing events,
setting the default to a more sensible value of 5 still
restricts memory usage but keeps it more safe.

Signed-off-by: Jeroen van Dooren <jeroen.van.dooren@nobleo.nl>
2023-02-21 10:58:10 +01:00
Jeroen van Dooren
a63fcb67b6 net: ip: net_mgmt: Prevent loss of event
The current implementation doesn't handle
re-entrant calls correctly, causing events
to get lost.

Under specific conditions, re-entrancy happens
from event callback done by net_mgmt.c back into
'net_mgmt_event_notify_with_info' causing circular
buffer administration corruption.

These conditions are:

- llmnr_iface_event_handler
- mdns_iface_event_handler
- wifi_mgmt_raise_connect_result_event
- dhcpv4_immediate_timeout uses a workaround

Validated the fix on a Nucleo_H743ZI, using an
sample app.

Signed-off-by: Jeroen van Dooren <jeroen.van.dooren@nobleo.nl>
2023-02-21 10:58:10 +01:00
Krishna T
55802e5e86 net: l2: ethernet: Fix double free
In the case of no ARP entry, the incoming packet is added to the ARP's
pending queue, while ARP is being resolved. Here a reference is taken
by the ARP layer to the packet to avoid it being freed, but the Ethernet
immediately puts down the reference and send the ARP packet to the
driver.

If the ARP request fails for some reason, L2 returns failure to net_if
which then puts down the reference and the packet will be freed as the
reference count is now zero.

But the packet is still in the ARP's pending queue and after timeout
ARP will put down the reference causing double free bus fault (double
free message is only seen if the CONFIG_NET_PKT_LOG_LEVEL_DBG is
enabled, so, a bit hard to debug.

Fix this by clearing the ARP entry and pending queue after taking a
reference and then free ARP packet, IP packets are either freed by ARP
pending queue drain or net_if layer.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-02-20 19:45:28 +01:00
Robert Lubos
243af28a2f net: ipv4: Implement fallback to LL address
According to RFC3927, hosts with only IPv4 LL address should still be
able to send packets to destination w/o IPv4 LL address:

   A host with an IPv4 Link-Local address may send to a destination
   which does not have an IPv4 Link-Local address.  If the host is not
   multi-homed, the procedure is simple and unambiguous: Using ARP and
   forwarding directly to on-link destinations is the default route

This behaviour however was not possible with Zephyr, which only allowed
to use IPv4 LL source address for IPv4 LL destinations.

Fix this, by introducing a final fallback (only if IPv4 autoconf is
enabled), to select IPv4 LL address as a source address if no other
address is available.

Additionally, modify the ARP routine a bit if IPv4 LL address is in use.
There's no really point to forward the packet to gateway if IPv4 LL
address is used, as such addresses are not routable. Instead, try to
find the peer in local network in such case.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-20 11:19:14 +01:00
Jonathan Rico
3a9c825bab Net: Bluetooth: add enough room to user data
We need to make sure the user_data of the network buffer has enough room to
store the L2CAP metadata.

Signed-off-by: Jonathan Rico <jonathan.rico@nordicsemi.no>
2023-02-20 09:53:51 +01:00
Krishna T
b136676772 net: lib: zperf: Add support to disable Nagle's algorithm
This helps in benchmarking smaller packets, esp. as this is the default
behaviour of iperf.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-02-20 09:53:43 +01:00
Jani Hirsimäki
f21051b728 net: iface: bypassing IP stack with SOCK_RAW sockets
Bypass the IP stack and go directly to L2 with
SOCK_RAW/IPPROTO_RAW sockets in net_if_send_data().

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2023-02-20 09:52:39 +01:00
Krishna T
92aa0e8ab6 net: shell: Log missing Ethernet errors
These error counters are helpful for data path debugging.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-02-20 09:51:23 +01:00
Jun Qing Zou
cd79b81d4d lib: tftp_client: Add TFTP PUT function
Add tftp_put() API to support TFTP WRITE request.

Signed-off-by: Jun Qing Zou <jun.qing.zou@nordicsemi.no>
2023-02-20 09:50:23 +01:00
Jun Qing Zou
f7b0ccba0c lib: tftp_client: Receive file with arbitrary size
Add a callback for READ request to download files with arbitrary length.
Define TFTP_BLOCK_SIZE in API header for application to allocate buffer.

Signed-off-by: Jun Qing Zou <jun.qing.zou@nordicsemi.no>
2023-02-20 09:50:23 +01:00
Ravi Dondaputi
1c547580e4 wifi: shell: Print beacon interval and DTIM period
Print beacon interval and DTIM period as part of Wi-Fi
status output.

Signed-off-by: Ravi Dondaputi <ravi.dondaputi@nordicsemi.no>
2023-02-20 09:46:34 +01:00
Juha Ylinen
fdffdedc41 net: lwm2m: Add event LWM2M_RD_CLIENT_EVENT_REG_UPDATE
New event LWM2M_RD_CLIENT_EVENT_REG_UPDATE to indicate
application that engine starts registration update.

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2023-02-19 20:44:02 -05:00
Robert Lubos
a28dba2503 net: ip: 6lo: Fix corner case with packet format after IPHC
IEEE802154 drivers expect, that a complete 802.15.4 frame fits into a
single net_buf provided in a net_pkt.

There is a corner case with header compression when this could not be
the case. If the IPv6 packet before IPHC exceeded 802.15.4 MTU, it'd
consist of several net_buf's. This was not an issue, if the IPv6 packet
after header compression still required fragmentation, as the
fragmentation module took care of formatting individual net_buf's
properly.

For short range of packet sizes however this was no the case. The IPv6
packet, after header compression, might not require fragmentation any
more. As the IPHC logic only modified the IPv6 header part, by trimming
the buffer in front of the net_buf, such a packet would still consist of
two net_bufs, even though it should fit into a single 15.4 frame. Such
packet was passed to the driver, causing the driver to send only part of
the packet, from the first net_buf.

Fix this, by using net_pkt functions to manipulate the packet, instead
of operating on net_buf directly. net_pkt_pull() will not trim the
buffer in front, but rather move the entire packet content to the front.
On the other hand, net_pkt_compact() will assure that there's no gaps in
the net_bufs. In result, packets that do not require fragmentation,
should be placed into a single net_buf, as expected by drivers.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-19 20:33:36 -05:00
Robert Lubos
05ca67c9ba net: ipv6: mld: Don't attempt to send a MLD query if iface is down
Simply return early returning respective error.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-08 11:26:42 +01:00
Robert Lubos
e8803ddaae net: dhcpv4: Do not proceed with DHCPv4 when interface is down
It should be possible to configure/initialize the DHCPv4 for an
interface when the interface is down, the DHCPv4 however should not
proceed with the procedure in such case.

Add a simple check to prevent DHCPv4 from sending packets when interface
is down. As the module registers to the NET_IF_UP event, the procedure
will be restarted when the interface goes up.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-08 11:26:42 +01:00
Robert Lubos
004955f715 net: config: Unify the init behaviour when timeout is enabled and not
Currently, if timeout is not configured for the network initialization in
the config module, the initialization function will configure IPv4/IPv6/
DHCPv4 regardless of the interface status. This is not the case when the
timeout is set, and the interface was not brought up during the timeout
period. This lead to ambiguity in terms of interface initialization.

This commits unifies the behaviour between these two cases. The
aforementioned initializations will always take place, regardless of the
interface status. The IPv4/IPv6 and DHCPv4 routines should be prepared
to deal with interfaces that are not brought up. The only difference
now, between timeout and no timeout scenario, is that the former will
report an error in case the timeout occurs wile waiting for the expected
events.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-08 11:26:42 +01:00
Seppo Takalo
437bfc58d9 net: lwm2m: Fix deregistration timeout state handling
Socket faults or timeouts in CoAP deregistration messages
caused RD client state machine to restart registration.

Fixes #54136

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2023-02-08 11:20:00 +01:00
Ryan Erickson
d19e99b6d7 net: DHCPv4: Filter NAK during requesting state
During the requesting state, ignore NAKs from any
non-requesting server.  This gives the requesting
server a chance to ACK the request.

Signed-off-by: Ryan Erickson <ryan.erickson@lairdconnect.com>
2023-02-08 19:05:13 +09: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
Robert Lubos
f39ba57474 net: ipv4: Fix subnet mask setting when autoconf is used
When IPv4 autoconf is enabled and IPv4 LL address is configured on an
interface, the subnet mask should be updated accordingly, otherwise it
can lead to unexpected behaviour (like for example not identifying peer
LL address as a part of the same subnet).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-06 10:10:54 +01:00
Krishna T
8069d47c5e net: pkt: Allow zero payload for non-IPv4/v6 frames
For socket families that are niether INET/INET6 e.g., PACKET, we cannot
estimate header length, so, if the payload is zero as well, networking
stack drop the packet.

Instead, allow for zero header + payload packets and let L2 take care of
handling them, for some L2's this is still a valid frame.

E..g, In case of Wi-Fi this is sent as 802.11 Header + LLC Header
(no payload).

Add unittests for both AF_INET + Zero payload and AF_PACKET + Zero
payload.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-02-06 10:04:03 +01:00
Lukas Woodtli
6a5260394b net: coap: Allow insertion of an option at arbitrary position
The insertion moves the data in the message buffer to make space for
the new option.

Signed-off-by: Lukas Woodtli <lukas.woodtli@husqvarnagroup.com>
2023-02-06 10:02:19 +01:00
Robert Lubos
432ff20a72 net: websockets: Fix websocket close procedure
The websocket implementation did not comply with the RFC 6455 when it
comes to connection close. The websocket should send in such case Close
control frame. This commit fixes this behaviour.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-03 10:37:57 -08:00
Robert Lubos
7f0219985d net: websockets: Fix ZFD_IOCTL_SET_LOCK handling
The websocket "socket" layer did not handle ZFD_IOCTL_SET_LOCK command,
and just forwarded it to the underlying socket. This overwritten the
mutex pointer used by the underlying socket, resulting in erroneous
behaviour in certain cases.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-03 10:37:57 -08:00
Armin Brauns
22430ef8c4 net: ipv6_nbr: count outgoing ND packets as sent ICMP packets
This mirrors the behaviour of MLD packets, the only other ICMPv6 subtype
that is tracked separately.

Inbound ND packets are already counted as received ICMP packets by way of
going through the ICMP receive path.

Signed-off-by: Armin Brauns <armin.brauns@embedded-solutions.at>
2023-02-03 02:25:14 +09:00
Armin Brauns
abd4dd4cc5 net: ipv6_nbr: don't count incoming Neighbour Advertisements in sent stats
This caused outgoing MAC address lookups to count as one received and two
sent Neighbour Discovery packets, when it's really one sent Neighbour
Solicitation and one received Neighbour Advertisement.

Signed-off-by: Armin Brauns <armin.brauns@embedded-solutions.at>
2023-02-03 02:25:14 +09:00
Robert Lubos
e540a98331 net: shell: Validate pointer provided with net pkt command
The net_pkt pointer provided to net pkt commands was not validated in
any way. Therefore it was fairly easy to crash an application by
providing invalid address.

This commit adds the pointer validation. It's checked whether the
pointer provided belongs to any net_pkt pools known to the net stack,
and if the pointer offset within the slab actually points to the
beginning of the net_pkt structure.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-02-03 02:14:32 +09:00
Seppo Takalo
d0dc67a72d net: lwm2m: Fix native_posix fcntl() calls
Native POSIX target still needs to use the <fcntl.h> header
instead of <zephyr/posix/fcntl.h>

Also removed the include from various files that did not use it.

Also changed fcntl() calls to zsock_fcntl() because we directly
use zsock_* calls elsewhere.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2023-02-02 20:05:08 +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
Seppo Takalo
ec8884d58f net: lwm2m: lwm2m_client: Fix fcntl header path
We don't default to POSIX_API so use Zephyr's
path for fcntl.h

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2023-01-27 10:41:19 -06:00
Andrei Emeltchenko
8e72f117e3 net: ieee802154: Remove unneeded check
Fixes dead code warning. At this point we have already checked for
broadcast and it is set to false.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2023-01-27 10:38:49 -06:00
Andrei Emeltchenko
3c8c903a2d net: ieee802154: Fix dereference before NULL check
Fixes dereference of sec_ctx->level before checking sec_ctx for NULL.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2023-01-27 10:38:49 -06:00
Robert Lubos
4234e801b5 net: sockets: Fix TLS_HOSTNAME option length inconsistency
The TLS_HOSTNAME socket option expects a NULL terminated string and
doesn't really care about the optlen provided. However, as the option
expects that the string is NULL terminated, the optlen value should take
NULL character into account, for consistency across the codebase.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-01-27 19:23:36 +09:00
Robert Lubos
9fef0c521d net: tcp: Remove net_tcp_unref()
There is a pending TODO regarding unifying net_tcp_unref() and
net_tcp_put(). Given that net_tcp_unref() is no longer used by the upper
layer (it should only use get/put APIs), the function can be removed
from external TCP API, as referencing/dereferencing is now only used
internally by the TCP stack.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-01-26 12:34:04 +00:00
Robert Lubos
79461a378c net: tcp: Fix TCP connection ref counting
The net_context/TCP connection context ref counting needed to be fixed,
to avoid situation where TCP connection context could be released
before net_context is released.

Generally, this commit modifies the ref counting of the above as
follows:
* net_context is referenced both by the application and TCP stack, when
  created.
* TCP context is referenced by the application when created. The TCP
  stack adds ref to the TCP context only after connection has been
  established.
* TCP stack needs to call the final upper layer callback when connection
  is closed, but before the TCP context is released (i. e. to give upper
  layer chance to dereference the context on its side). For this,
  tcp_conn_close() was introduced which is called from within TCP stack
  instead of directly dereferencing the TCP context.
* TCP stack dereferences the net_context only after the TCP context has
  been released (i. e. upper layer has dereferenced TCP context on it's
  side and connection has been tear down, if established).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-01-26 12:34:04 +00:00
Juha Heiskanen
1f84409b48 net: lwm2m: Trace clean
Cleaned Trace message print.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2023-01-25 15:08:07 +00:00
Chamira Perera
ce49beb297 net: ethernet: Fixes for ethernet stats reporting.
The following fixes were applied:
 - Multicast Rx packets stats were not recorded due not parsing the
ethernet header. The function that tried to parse the ethernet header
was parsing the ethernet packet beyond the ethernet header.
 - Added a new stats for unknown protocol which gets updated when the
ethernet layer encounters an unknown ethernet packet type.

Fixes #53994

Signed-off-by: Chamira Perera <chamira.perera@audinate.com>
2023-01-25 15:01:14 +00:00
Andreas Chmielewski
022ff636da net: lwm2m: rd_client: added init function
To write tests it is necessary to offer init function for the RDClient
to define custom fakes before.

Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
2023-01-25 14:55:02 +00:00
Wouter Cappelle
aaefd3db7e net: http: Use poll for http timeout instead of shutdown
Change the http timeout mechanism to use poll instead of shutdown.
This should fix a problem where the shutdown will be called in a
different thread context which can lead to deadlocks on certain
driver implementations like offloaded modem drivers.
Fixes #53967

Signed-off-by: Wouter Cappelle <wouter.cappelle@crodeon.com>
2023-01-24 14:50:11 +01: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
Ajay Parida
ba39235275 net: wifi_mgmt: Add support for power save timeout configuration
Add support for configuring power save timeout in Wi-Fi chipsets.
Changes to configure power save inactivity timer.

Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
2023-01-23 10:08:01 +00:00
Ajay Parida
057e2fc59c net: wifi_shell: Display correct power save status
Display power save status correctly.

Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
2023-01-19 13:48:24 +01:00
Veijo Pesonen
f0258dbe4d net: lwm2m: Sufficient memory for resource names
Full resource names aren't as long as combined basename- and name-buffer
sizes but the compiler doesn't know it. Increasing the buffer size to
avoid the compiler warning.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2023-01-19 12:03:27 +01:00
Chamira Perera
1c51f7cbbf net: ipv4: Using a different API to ensure that IPv4 is enabled
When init_igmp is called the ipv4 pointer was not initialised.
Therefore, a different API needs to be used to ensure that IPv4
is enabled when calling init_igmp.

Fixes #53913

Signed-off-by: Chamira Perera <chamira.perera@audinate.com>
2023-01-19 10:35:44 +01:00
Jarno Lämsä
abafd7e810 net: lib: lwm2m: Replace deprecated function calls
Replace calls to deprecated functions with new ones.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Jarno Lämsä
3b3463ecba net: lib: lwm2m: Deprecate string based enable cache
Deprecate the old API and replace with new one which uses
the lwm2m_obj_path struct instead of a string.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Jarno Lämsä
460dd6530f net: lib: lwm2m: Deprecate string based send
Deprecate send API using the string references as paths.
Replace it with one using path structs.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Jarno Lämsä
49cf96858f net: lib: lwm2m: Deprecate buffer set get API
Deprecate old API and make new API using path structs
instead of using old string reference based paths.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Jarno Lämsä
bca0550413 net: lib: lwm2m: Deprecate callback registration API
Deprecate old API and create new API using path structs
instead of string references to paths.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Jarno Lämsä
a2e52c5607 net: lib: lwm2m: Deprecate observation API
Add new APIs using the lwm2m path structs instead of
string references to paths.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Jarno Lämsä
5c80be9379 net: lib: lwm2m: Deprecate object and resource API
Deprecate old API and offer a new API for object and resource
creation and deletion. The new API uses path struct instead
of using a string as a reference to a path.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Jarno Lämsä
15d81a8914 net: lib: lwm2m: Deprecate string based set get API
Use the lwm2m_obj_path struct instead and deprecate old.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2023-01-19 10:16:22 +01:00
Robert Lubos
6425f0be0a net: ppp: Fix PPP connection with host
A follow up to commit 1d7a077e11 - apparently the PPP interface should
not be brought entirely down internally, as this can break further
communication with the host. Because of that, reintroduce functionality
that used to be covered by net_if_carrier_down() (which basically
skips the L2 enable(false) call), but limited to PPP scope only.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-01-17 11:28:10 +01:00
Stephanos Ioannidis
4a64bfe351 treewide: Use CONFIG_CPP instead of CONFIG_CPLUSPLUS
This commit updates all in-tree code to use `CONFIG_CPP` instead of
`CONFIG_CPLUSPLUS`, which is now deprecated.

Signed-off-by: Stephanos Ioannidis <stephanos.ioannidis@nordicsemi.no>
2023-01-13 17:42:55 -05:00
Krishna T
fadb1fd168 net: wifi: Add support for regulatory domain configuration
Wi-Fi bands are regulated by a governing body depending on operating
country, add support for the user to provide a country of operation as a
hint to the Wi-Fi chipset.

Ideally if the chipset supports this is all handled internally, in that
case "get" is useful but for testing and other usecases add a "set" as
well, similar to "iw reg set" or "country_code=" configuration in
hostapd/wpa_supplicant in Linux world.

This add a new offload API operation "reg_domain" that can be used to
either get or set the regulatory information.

The validation is left to the underlying chipset, shell only does basic
validation, (XY/00).

This is just a regulatory hint to the chipset, there could be other
regulatory hints e.g., beacon that can override this configuration, so,
an additional option to force this setting despite other hints is also
given for testing purposes.

FYI, the standard database used is [1].

[1] - https://git.kernel.org/pub/scm/linux/kernel/git/sforshee/wireless-regdb.git/tree/db.txt

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-13 13:37:14 +00:00
Krishna T
324a45568a net: wifi: Fix unnecessary intermediate variable
Directly return the function return value.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-13 13:37:14 +00:00
Pascal Brogle
6ac281887c net: lwm2m: fix observation path list ordering
under certain conditions the current implementation did not maintain
the desired sort order.

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2023-01-13 13:47:27 +01:00
Pascal Brogle
cc40bc33ba net: lwm2m: fix senml max name size
base name or name can contain up to two shorts.
(object id & object intstance or resource id & resource instance id)

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2023-01-13 12:02:07 +00:00
Pascal Brogle
b6bc324a1d net: lwm2m: rename path size define
Rename max path constant to prevent string length vs data size confusion

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2023-01-13 12:02:07 +00:00
Pascal Brogle
b178ff5246 net: lwm2m: fix senml cbor compiler warning
use size_t instead of assuming uint32_t

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2023-01-13 12:00:13 +00:00
Chamira Perera
b71b514e93 net: ipv4: Added mechanism to add 224.0.0.1 address to a multicast filter
The purpose of the change was to have the Zephyr network stack
internally add the IGMP all systems 224.0.0.1 multicast address to a
multicast membership list so that multicast hash filter implementations
can add this address to the hash filter.

Fixes #53548

Signed-off-by: Chamira Perera <chamira.perera@audinate.com>
2023-01-13 09:44:10 +01:00
Ravi Dondaputi
551f8c40b2 net: shell: Support IPv6 address and route config
Add and delete options to configure IPv6 address
 and route from shell.

Signed-off-by: Ravi Dondaputi <ravi.dondaputi@nordicsemi.no>
2023-01-12 19:08:14 +01:00
Ravi Dondaputi
d11ae3a4c8 net: shell: Add support to configure IP address
Add support to configure IP address using net shell.

Signed-off-by: Ravi Dondaputi <ravi.dondaputi@nordicsemi.no>
2023-01-12 19:08:14 +01:00
Krishna T
bc80b0a232 net: shell: Use net management API for MAC address configuration
Fix a bug in setting MAC address using net_if API, the API doesn't do a
memcpy but just stores the pointer and shell was passing stack pointer.

We can use dynamic allocation but freeing the memory for the MAC address
would be trickier, so, use the net management API and let the underlying
drivers figure out the MAC address memory management.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-12 19:07:44 +01:00
Krishna T
7952197a89 net: shell: Add MAC address validation
Validate MAC address before setting, add new helper APIs to cover all
cases.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-12 19:07:44 +01:00
Florian Grandel
e854314928 net: l2: ieee802154: fix double address swap
As we have to provide LL addresses in big endian to userspace to be
POSIX compliant and we also do not want to reserve extra space for
such addresses, bff6a5cce5 introduced
a change that swaps address bytes in place in the packet before
returning the packet with LL address pointers to userspace.

Unfortunately a regression sneaked into the code base while doing
so: The byte swapping was duplicated when using 6LoWPAN compression
and the byte swapping caused decryption to fail in some cases,
see #53630. This commit fixes the problem.

Fixes: #53630

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2023-01-12 12:46:18 +01:00
Krishna T
02ab878704 net: ethernet: Check return value for start/stop
The L2 networking layer checks for return value from enable, but
Ethernet is not checking and always returns 0, so, relay the return
value from the Ethernet driver to networking stack.

This fixes the issue of interface start failing but interface still
being up.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-12 12:14:55 +01:00
Robert Lubos
a64be51391 net: stats: Fix UDP packet counter for DHCPv4 TX
Fix UDP TX packet count when DHCPv4 is used. Currently UDP TX counter
is only updated when net context is in use. DHCPv4 however does not use
net_context underneath, therefore it needs to update UDP TX stats on its
own.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-01-11 11:26:08 +01:00
Robert Lubos
76dd77df7e net: zperf: Fix potential build warning
A variable was defined directly after a label in two case statements,
resulting in build warning with certain compilers.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-01-10 14:07:21 +00:00
Krishna T
b59c89123c net: shell: Add support to set Ethernet MAC address
Add a shell command to set Ethernet MAC address, useful in configuring
custom/local MAC addresses.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-10 13:29:22 +01:00
Krishna T
6e3e10e6cd net: shell: Fix duplicate tag
Recently introduced MISRA-C CI check complains about use of a duplicte
tag, so, shorten the variable from shell->sh to avoid same name as the
structure.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-10 13:29:22 +01:00
Nick Ward
583545b662 net: openthread: Add state change callback list
Add a new callback list structure for state change information.

These APIs are meant to eventually replace the single callback API
provided by openthread_set_state_changed_cb().

This will allow multiple users to gain information about
OpenThread stage changes.

Note CONFIG_OPENTHREAD_MAX_STATECHANGE_HANDLERS
with OpenThread's otSetStateChangedCallback() API can also be
used to enable registration of multiple callbacks of this type but this
cannot be modified if a certified OpenThread binary is used in the
build.

Signed-off-by: Nick Ward <nick.ward@ftpsolutions.com.au>
2023-01-10 13:29:15 +01:00
Krishna T
d796f23e0e net: wifi_mgmt: Add support for power save configuration
Add support for configuring power-save in Wi-Fi chipsets, supports
Legacy, WMM and TWT.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-10 09:52:11 +01:00
Krishna T
3f4597d0c9 net: l2: wifi: Arrange commands in alphabetical order
This helps find the command needed easily.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-10 09:52:11 +01:00
Sjors Hettinga
1be1b472cd net: tcp: Extend TCP receive queue timeout
After several fixes of the re-ordering logic in TCP, the receive queue
works as intended and cleans itself up properly. Previously the default
timeout was 100 ms, which pretty much disables it for real applications.

Increase the timeout to 2 seconds to actually enable it for in practice.
This should help pass much more of the Maxwell Pro tests.

This is the first step before removing the timeout completely.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2023-01-10 09:26:28 +01:00
Jani Hirsimäki
e92b067b7f net: ip: net_context: AF_PACKET/SOCK_RAW/IPPROTO_RAW: set pkt family
Setting a detected packet family (ipv4 or ipv6) in net_context level
instead in lower layers for AF_PACKET/SOCK_RAW/IPPROTO_RAW type sockets
when sending data.

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2023-01-09 19:21:18 +01:00
Robert Lubos
3fd0801a49 net: ipv4: Fix packet leak with IPv4 autoconf
The IPv4 autoconfiguration feature relies on the fact, that autoconf
ARP packets are always prepared by the ARP module. After recent ARP
refactoring though that could no longer be the case due to packet
queueing mechanism. This could lead to net pkt leaks in the autoconf
module.

Fix this by skipping the pending packet queue for autoconf packets.
Since for autoconf ARP requests there's no really a pending packet
to queue, it can be safely avoided. This results in the ARP request
being always sent for the autoconf case, preventing the packet leak.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2023-01-05 14:39:17 +00:00
Juha Ylinen
5e4eeb104d net: lwm2m: Verify data buffer size in lwm2m_engine_set()
Check data buffer size and return error if
     * buffer size is too small for opaque or string data type
     * buffer size is not equal to res data length when data type
       is fixed size

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2023-01-05 14:39:01 +00:00
Pascal Brogle
60bf310aae net: lwm2m: fix senml cbor object link encoding
use text format instead of tlv format

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2023-01-05 12:43:24 +01:00
Juha Heiskanen
a70f420b2b net: lib: Patch file for generated code fix
Patch for generated lwm2m senml-cbor.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2023-01-05 12:43:24 +01:00
Juha Heiskanen
d939c79af1 net: lib: LwM2M SenML-Cbor regenrated files update
Patched and fixed regenerated code.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2023-01-05 12:43:24 +01:00
Juha Heiskanen
637c9bbf95 net: lib: regenerate cbor code using zcbor
with the updated cddl for object links.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2023-01-05 12:43:24 +01:00
Pascal Brogle
547c3063b9 net: lwm2m: support senml cbor object link
use "vlo" map key

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2023-01-05 12:43:24 +01:00
Juha Ylinen
eb914f45d1 net: lwm2m: Check return value from lwm2m_rd_client_pause/resume
Check return values from lwm2m_rd_client_pause() and
lwm2m_rd_client_resume() when engine thread suspend is requested.

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2023-01-05 12:43:00 +01:00
Juha Ylinen
c7a5f7fda7 net: lwm2m: Deprecate Kconfig for LwM2M RD Client
RD-Client is essential part of LwM2M specification and it can't
be disabled from LwM2M engine. This commit deprecates Kconfig
variable CONFIG_LWM2M_RD_CLIENT_SUPPORT and removes
all usages if it.

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2023-01-03 13:23:46 +01:00
Marco Argiolas
2527320848 net: lib: sntp: add support for unspecified IP-family type
`sntp_simple()` was forcing to resolve SNTP-server's URL into IPv4 address
addresses. This was not allowing sntp_init() to succeed in case the system
 did not support IPv4 addresses (returning EPFNOSUPPORT, ie. Protocol
Family error).
Now by default SNTP has unspecified family type and it relies on
`net_getaddrinfo_addr_str()` to be able to resolve literal server URLs
into the supported IP family type.

Signed-off-by: Marco Argiolas <marco.argiolas@ftpsolutions.com.au>
2023-01-03 11:03:25 +01: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
Juha Ylinen
7dfa2c8a2b net: lwm2m: Add shell commands
Add shell commands to read and write native time_t value.

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2023-01-03 11:03:16 +01:00
Seppo Takalo
a33f3b6abb net: lwm2m: Add shell command to enable timeseries cache
Add shell command

  cache   :Enable data cache for resource
           cache PATH NUM
           PATH is LwM2M path
           NUM how many elements to cache

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2023-01-03 11:02:54 +01:00
Juha Heiskanen
1800e629e6 net: lwm2m: LwM2M times series data update
Fixed problem for matching path url with or without '/'
by change time series data structure to use struct lwm2m_obj_path.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2023-01-03 11:02:54 +01:00
Juha Heiskanen
3abd9c364a net: lwm2m: LwM2M Object path equal API
Added new API for check is 2 object path equal.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2023-01-03 11:02:54 +01:00
Juha Ylinen
16b6892294 net: lwm2m: Refactor lwm2m_information_interface_send()
Call lwm2m_send_message_async() from function
lwm2m_information_interface_send() and remove duplicate code.

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2023-01-03 11:02:44 +01:00
Juha Ylinen
1111184b74 net: lwm2m: Remove lwm2m_send_message() from public API
lwm2m_send_message() sends a message directly to the socket. Remove
the function from public API and combine the code with
socket_send_message().

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2023-01-03 11:02:44 +01:00
romain pelletant
5c14c56f2c net: lwm2m: add binaryappdatacontainer obj support
OMA LwM2M object 19 support for application specific binary data
Related issue #53340

Signed-off-by: romain pelletant <romainp@kickmaker.net>
2023-01-03 11:02:09 +01:00
Krishna T
59842531d1 net: zperf: Make shell dependency optional
Now that we a proper API, shell is just optional, so, make the
dependency optional by refactoring the code.

Also, add a build test combination in twister.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2023-01-03 11:02:01 +01:00
Miquel Raynal
9ce8c26d34 net: l2: ieee802154: Add missing scan callback registration
Initializing an event callback with net_mgmt_init_event_callback() just
sets some of the callback fields but do not propagate those masks in the
core. If we want to use the callback, it is necessary to also call
net_mgmt_add_event_callback().

Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
2023-01-02 10:54:46 +01:00
Miquel Raynal
6a11e79b4b net: l2: ieee802154: Fix a wrong channel change during association
The current association logic starts by changing the channel. The way it
is done is wrong because it dereferences req->channel which is simply
not initialized by the caller. But anyway, the command itself does not
support providing a channel so we must already be on the right one when
trying to associate. Hence, drop this channel change call.

Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
2023-01-02 10:54:46 +01:00
Miquel Raynal
31b35973e3 net: l2: ieee802154: Change the hardware filters while associating
During an association, the peer we are trying to connect to will send us
an association response frame with the destination PAN ID set to the PAN
ID we try to join. If we do not update the hardware address filters
beforehands, it is likely that the hardware will just discard the
response and the association will fail.

Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
2023-01-02 10:54:46 +01:00
Miquel Raynal
19e67800f9 net: l2: ieee802154: Avoid dangling MAC command bits
While the packet structures seem to always be reset when they are
allocated, it's apparently not the case of the data buffers. Indeed,
these are allocated differently and just attached to the packet
structure through a frag/buffer member.

Experience shows that we may get uninitialized buffers so let's set
all MAC parameter bits one by one, even the reserved ones.

Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
2023-01-02 10:54:46 +01:00
Miquel Raynal
2fd336c5d2 net: l2: ieee802154: AR shall be provided in association requests
The spec clearly states: "association requests shall set the AR bit".

Even though Zephyr can currently only implement RFD devices which are
not expected to support incoming association requests, because this MAC
command is actually processed until being voluntarily ignored, let's
ensure the expected "ar" value is right to avoid failing because of a
wrong reason.

Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
2023-01-02 10:54:46 +01:00
Miquel Raynal
fa05c60674 net: l2: ieee802154: Fix logic with address types
When validating a MAC command, the "src" and "dst" fields may be set to:
- IEEE802154_ADDR_MODE_SHORT (0x2)
- IEEE802154_ADDR_MODE_EXTENDED (0x3)
- IEEE802154_ADDR_MODE_SHORT | IEEE802154_ADDR_MODE_EXTENDED (0x3)
Hence when the mode check happens, any times the mode is set to SHORT
the check will fail while in practice it was meant to be valid because
the check is:

    if (src_mode == src || dst_mod == dst)

Use bitfields when relevant so that when checking capabilities we use
the bit offsets rather than the plain numbers.

Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
2023-01-02 10:54:46 +01:00
Miquel Raynal
b86b7d3a41 net: l2: ieee802154: Fix address length macros
When validating a MAC command, there is sometimes a misunderstanding of
what "src" and "dst" length mean.

There are actually two fields in the MHR:
- One giving the type of address, if it is short or extended, it is the
  value provided by the macros IEEE802154_ADDR_MODE_{SHORT,EXTENDED} and
  their respective decimal values are 2 and 3.
- One giving the size of the address field, this is
  IEEE802154_{SHORT,EXT}_ADDR_LENGTH and their value is actually 2 and 8
  (bytes).

The function validate_mac_command() provides inputs to
validate_mac_command_cfi_to_mhr() which expects the former information.

Signed-off-by: Miquel Raynal <miquel.raynal@bootlin.com>
2023-01-02 10:54:46 +01:00
Andrei Emeltchenko
d320100df4 net: ip: Fix dereference before NULL check
Fix warnings like "Dereference before NULL check". Also make check
readable.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-12-30 11:11:06 +00:00
Juha Heiskanen
4a50f9362f net: lib: LwM2M rd client fix
Fix LwM2M rd client stop call hang when Queue client is at
RX_ON_IDLE_STATE. Added miossing connection resume for
de-register functionality.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-12-22 15:50:31 +00:00
Juha Ylinen
1827636ab6 net: lwm2m: Verify receiving buffer size in lwm2m_engine_get()
Check receiving buffer size and return error if
 * buffer size is too small for opaque or string data type
 * buffer size is not equal to data lenght when data type is
   fixed size

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2022-12-22 13:44:27 +01:00
Robert Lubos
d27ace4012 net: zperf: Simplify shell initialization
Instead of calling zperf shell initialization routine on the first
command execution, initialize it during system boot, along with other
zperf submodules.

Remove redundant IP address configuration on an interface. The default
configuration relies on NET_CONFIG module, so there's no need to set the
address manually in zperf.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Robert Lubos
7a2c8d2ab8 net: zperf: Shell cleanup
Zperf shell functionality is now encapsuled within a single file,
therefore it no longer makes sense to have a separate shell_utils
file.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Robert Lubos
dd3fb692fe net: zperf: Add shell command to stop TCP/UDP server
Add zperf shell command to stop TCP/UDP server.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Robert Lubos
87ca1c3329 net: zperf: Make UDP/TCP servers restartable
Make the TCP/UDP server functionality restartable. Provide a public API
to stop the TCP/UDP server.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Robert Lubos
cd4f7cbc61 net: zperf: Add public API to start TCP/UDP server
Add public API for zperf download functionality. The TCP/UDP server
modules are decoupled from shell, allowing to trigger download directly
from the application code. The shell submodule makes use of this new
public API.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Robert Lubos
722ed07287 net: zperf: Add shell option for asynchronous upload
Add shell option to the UDP/TCP upload command, which allows to execute
the upload asynchronously. This allows to unblock the shell for other
commands during the upload.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Robert Lubos
fde9577e24 net: zperf: Implement asynchronous upload API
Add an API which allows to perform UDP/TCP upload operations
asychronously.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Robert Lubos
812a1bc152 net: zperf: Define a public upload API for the library
This commit defines a public API for zperf upload functionality. The
UDP/TCP uploader modules are decoupled from shell, allowing to perform
uploads directly from the application code. The shell submodule makes
use of this new public API.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-22 11:05:11 +01:00
Erwan Gouriou
66d4c64966 all: Fix "#if IS_ENABLED(CONFIG_FOO)" occurrences
Clean up occurrences of "#if IS_ENABLED(CONFIG_FOO)" an replace
with classical "#if defined(CONFIG_FOO)".

Signed-off-by: Erwan Gouriou <erwan.gouriou@linaro.org>
2022-12-21 10:09:23 +01:00
Grixa Yrev
2a992c65c0 net: websocket: new receiving algorithm
websocket_recv_msg() is reworked with using fsm. Now the function
return 0 when payload is empty, -ENOTCONN if socket close. Receiving
empty ping and sending empty pong were added in tests.
Fixes #52327

Signed-off-by: Grixa Yrev <grixayrev@yandex.ru>
2022-12-20 17:05:12 +00:00
Robert Lubos
a60f32549e net: l2: ieee802154: Align LL address update routine
IEEE802154 L2 may modify the LL address during interface operation (when
processing MAC command). So far the L2 workaround the LL address update
protection by clearing the NET_IF_UP flag temporarily, but due to recent
changes it no longer works. Update this workaround to verify
NET_IF_RUNNING flag instead.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-19 18:18:03 +01:00
Robert Lubos
129f34fd0b net: if: Allow to set LL address after interface was brough admin UP
Bluetooth IPSP L2 sets the LL address only after establishing Bluetooth
connection. As this can take place after the interface was brough UP by
the application, the network interface API should not block such
attempt. Instead, verify the NET_IF_RUNNING flag.

For the same reason, move the assert verifying that LL address is set
from net_if_up() (which only puts the interface in the admin UP state)
into the function that transitions the interface into operational UP
state.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-19 18:18:03 +01:00
Robert Lubos
f38d5f440f net: l2: bluetooth: Remove invalid check
After network interfaces state handling rework, it's no longer correct
to verify the connection status on `net_if_up()`, as this only changes
the administrative state of the interface. The interface won't be put in
operational UP state until it's connected.

This check prevented the interface from being brought up during system
boot.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-19 18:18:03 +01:00
Robert Lubos
1448923be3 net: shell: Make it possible to abort ping command
Rewrite the "net ping" command handling, to allow the command to be
aborted during execution. This includes:

* Using shell bypass mode to capture input whilst the ping is active.
* Using system workqueue to send individual ping requestes, instead of
  sending ping requests directly from shell thread, in a blocking
  manner. This is needed because in order to receive input in the
  registered bypass handler, the shell thread must be unblocked to
  process the input.
* The bypass mode is left after receiveing `CTRL-C` character (which
  cancels the ping), after receiving all expected Ping replies or after
  the timeout occurs.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-12-19 09:46:53 +00:00
Reto Schneider
c646a5576a net: zperf: Fix SO_RCVTIMEO dependency
Since 6c30c9ac47 (samples: net: zperf:
Rewrite upload part to use sockets), zperf uses SO_RCVTIMEO in UDP mode,
hence must depend on/enable support for it.

Without SO_RCVTIMEO support, zperf fails like this:
> nb_packets=47   delay=188964    adjust=-13
> setsockopt error (109)
> setsockopt error (109)
> -
> Upload completed!
> LAST PACKET NOT RECEIVED!!!
> Statistics:             server  (client)
> Duration:               0 us    (10.19 s)
> Num packets:            0       (50)
> Num packets out order:  0
> Num packets lost:       0
> Jitter:                 0 us
> Rate:                   0 Kbps  (9 Kbps)

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2022-12-15 17:14:26 +01:00
Marco Argiolas
f8f3629efd net: lib: lwm2m: add uCIFI LPWAN object
Add support for Low Power Wide Area Network (LPWAN) Object (ID 3412)

Signed-off-by: Marco Argiolas <marco.argiolas@ftpsolutions.com.au>
2022-12-14 09:51:38 +01:00
Jani Hirsimäki
5a93a25158 net: l2: ethernet: ethernet support for AF_PACKET/SOCK_RAW/IPPROTO_RAW
Setting the protocol type for raw IP packets to be sent so that they
can be passed to Ethernet.

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2022-12-12 14:56:07 +01:00
Yanqin Wei
00cdb7afa2 net: zperf: fix incorrect statistics of zperf
The sequence id from iperf starts with 1. The commit changes the
initial value of "next_id" in zperf from 0 to 1. In addition, the
error output of "error" and "out of order" packets is corrected.

Signed-off-by: Yanqin Wei <Yanqin.Wei@arm.com>
2022-12-09 11:18:25 +01:00
Carles Cufi
3d306c181f net: buf: Simplify fragment handling
This patch reworks how fragments are handled in the net_buf
infrastructure.

In particular, it removes the union around the node and frags members in
the main net_buf structure. This is done so that both can be used at the
same time, at a cost of 4 bytes per net_buf instance.
This implies that the layout of net_buf instances changes whenever being
inserted into a queue (fifo or lifo) or a linked list (slist).

Until now, this is what happened when enqueueing a net_buf with frags in
a queue or linked list:

1.1 Before enqueueing:

 +--------+      +--------+      +--------+
 |#1  node|\     |#2  node|\     |#3  node|\
 |        | \    |        | \    |        | \
 | frags  |------| frags  |------| frags  |------NULL
 +--------+      +--------+      +--------+

net_buf #1 has 2 fragments, net_bufs #2 and #3. Both the node and frags
pointers (they are the same, since they are unioned) point to the next
fragment.

1.2 After enqueueing:

 +--------+      +--------+      +--------+      +--------+      +--------+
 |q/slist |------|#1  node|------|#2  node|------|#3  node|------|q/slist |
 |node    |      | *flag  | /    | *flag  | /    |        | /    |node    |
 |        |      | frags  |/     | frags  |/     | frags  |/     |        |
 +--------+      +--------+      +--------+      +--------+      +--------+

When enqueing a net_buf (in this case #1) that contains fragments, the
current net_buf implementation actually enqueues all the fragments (in
this case #2 and #3) as actual queue/slist items, since node and frags
are one and the same in memory. This makes the enqueuing operation
expensive and it makes it impossible to atomically dequeue. The `*flag`
notation here means that the `flags` member has been set to
`NET_BUF_FRAGS` in order to be able to reconstruct the frags pointers
when dequeuing.

After this patch, the layout changes considerably:

2.1 Before enqueueing:

 +--------+       +--------+       +--------+
 |#1  node|--NULL |#2  node|--NULL |#3  node|--NULL
 |        |       |        |       |        |
 | frags  |-------| frags  |-------| frags  |------NULL
 +--------+       +--------+       +--------+

This is very similar to 1.1, except that now node and frags are
different pointers, so node is just set to NULL.

2.2 After enqueueing:

 +--------+       +--------+       +--------+
 |q/slist |-------|#1  node|-------|q/slist |
 |node    |       |        |       |node    |
 |        |       | frags  |       |        |
 +--------+       +--------+       +--------+
                      |            +--------+       +--------+
                      |            |#2  node|--NULL |#3  node|--NULL
                      |            |        |       |        |
                      +------------| frags  |-------| frags  |------NULL
                                   +--------+       +--------+

When enqueuing net_buf #1, now we only enqueue that very item, instead
of enqueing the frags as well, since now node and frags are separate
pointers. This simplifies the operation and makes it atomic.

Resolves #52718.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2022-12-06 11:06:43 +02:00
Christian Taedcke
12f2258305 net: Make user_data size in rx and tx buffers configurable
Introduce the Kconfig symbol `NET_PKT_BUF_USER_DATA_SIZE`. It is used to
set the user data size in the buffers used in the rx and tx network buffer
pools.

Signed-off-by: Christian Taedcke <christian.taedcke@lemonbeat.com>
2022-12-01 15:50:35 +01:00
Christian Taedcke
5bd3beff14 Kconfig: net: Remove deprecated NET_BUF_USER_DATA_LEN
This Kconfig setting was deprecated since
commit 8e99db5801 ("Kconfig: net: deprecate `NET_BUF_USER_DATA_LEN`")
and zephyr release 3.0.0.

This commit removes this deprecated and unused setting.

Signed-off-by: Christian Taedcke <christian.taedcke@lemonbeat.com>
2022-12-01 15:50:35 +01:00
Manuel Arguelles
d17caaacc5 net: icmpv6: fix if need calc tx checksum
Fix regression from 0a3bf289b6.

Signed-off-by: Manuel Arguelles <manuel.arguelles@nxp.com>
2022-11-28 10:47:20 +01:00
Andrei Emeltchenko
a5400407fc net: conn: Fix issues with SMP in connection code
When testing on qemu_x86_64 with e1000 Ethernet driver, there are
several crashes due to list management simultaneously executing on
different cores. Add mutexes similar to other parts on networking
stack, for example tcp_lock.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-11-24 15:23:11 +01:00
Chamira Perera
67db7d07f2 net: ip: Fixed IGMP V2 membership report destination address.
As per RFC 2236 Section 9, the IGMP V2 membership reports should be sent
to the group multicast address being reported. Without this fix, when
IGMP snooping is enabled on a network a device is not able to receive
multicast from certain multicast addresses e.g. 239.255.x.x.

Fixes #52449

Signed-off-by: Chamira Perera <chamira.perera@audinate.com>
2022-11-24 15:22:38 +01:00
Johann Fischer
b70f92e570 net: buf: keep memory alignment provided by k_heap_alloc and k_malloc
Allocation callback in net_buf_heap_cb and net_buf_var_cb
used for net_bufs with variable size payloads, defined by
NET_BUF_POOL_HEAP_DEFINE or NET_BUF_POOL_VAR_DEFINE,
allocate one more octet for internal variable ref_count,
used in function generic_data_ref(), which in turn is needed
for net_buf_clone()).
The user gets a buffer which is shifted by one octet in memory
block. This breaks alignment provided k_heap_alloc and k_malloc.

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
2022-11-24 09:35:13 +01:00
Anas Nashif
cffe98d9de crc: Make the build of crc function dependent on a Kconfig
Add CONFIG_CRC for building CRC related routines.
CRC routines are now being built for each application, whether used or
not and are add in the build system unconditionally.

Keep CONFIG_CRC enabled by default for now and until all users have
converted to use the new option.

Partial fix for #50654

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-11-23 13:30:00 +01:00
Reto Schneider
b51218a110 net: net_pkt: Fix conditional compilation
This aligns the conditional compilation logic with the one used for the
prototype in net_pkt.h, avoids build errors due to a undefined reference
to net_pkt_print_frags.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2022-11-22 09:30:26 +00:00
Reto Schneider
a66935aea7 net: net_pkt: Embrace NET_PKT_DEBUG_ENABLED
This deduplicates the logic a tiny bit.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2022-11-22 09:30:26 +00:00
Reto Schneider
217d9ac113 net: net_pkt: Simplify conditional compilation
The #if has the same conditions as the one closed the previous #endif.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2022-11-22 09:30:26 +00:00
Martin Fletzer
144d30eb47 net: gptp_md: Consider different resolutions regarding correction field
From https://www.ieee802.org/1/files/public/docs2007/as-garner-protocol-state-machines-frame-formats-0307.pdf:
  The correctionField is the value of the correction
  measured in nanoseconds and multiplied by 2^16.

Zephyr uses nanoseconds for follow_up_correction_field.
Therefore, the value must be shifted by 2^16.

Signed-off-by: Martin Fletzer <martin.fletzer@kftec.at>
2022-11-21 10:14:48 +01:00
Robert Lubos
387a66131e net: pkt: Introduce minimum length requirement to net_pkt_get_frag()
net_pkt_get_frag() and a few other functions did not specify the
allocated fragment length, incorrectly assuming that fixed-sized
buffers are always used.

In order to make the function work properly also with variable-sized
buffers, extend the function argument list with minimum expected
fragment length parameter. This allows to use net_buf_alloc_len()
allocator in variable buffer length configuration, as well as verify if
the fixed-sized buffer is large enough to satisfy the requirements
otherwise.

Update the existing codebase to provide the expected fragment length,
based on the context.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-19 07:39:32 -05:00
Robert Lubos
98608b3c30 net: shell: Fix build with CONFIG_NET_BUF_VARIABLE_DATA_SIZE
The "net mem" command handler did not take the variable buffer length
configuration, and failed to build in such case.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-19 07:39:32 -05:00
Robert Lubos
521341813e net: pkt: Fix build with CONFIG_NET_BUF_VARIABLE_DATA_SIZE
In case variable buffer length feature was enabled, net_pkt code did
not build due to unconditional references to CONFIG_NET_BUF_DATA_SIZE,
which is not avaialable in this configuration.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-19 07:39:32 -05:00
Robert Lubos
00269af3e6 net: tcp: Fix build with CONFIG_NET_BUF_VARIABLE_DATA_SIZE
In case variable buffer length feature was enabled, the TCP stack did
not build due to unconditional references to CONFIG_NET_BUF_DATA_SIZE,
which is not avaialable in this configuration.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-19 07:39:32 -05:00
Robert Lubos
0e388e64fd net: shell: Process Echo Replies without a timestamp
In case Echo Request did not carry timestamp (i. e. requested payload
size was smaller than 4), there won't be a timestamp in the reply
either. Such replies should not be ignored. Instead, simply skip the
turnround time calculation if timestamp is missing.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-19 07:34:45 -05:00
Robert Lubos
2b67e421a0 net: shell: Allow to specify ping payload size
Add -s parameter to the net ping command, allowing to specify the
payload size for the Echo Request.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-19 07:34:45 -05:00
Robert Lubos
967a91dce5 net: icmp: Allow to autogenerate Echo Request payload
Let net_icmpv4_send_echo_request() and net_icmpv6_send_echo_request()
autogenerate Echo Request payload, in case data length is specified but
no data pointer provided. The autogenerated payload includes timestamp
(if payload size permits) so that the turnround time can be calculated.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-19 07:34:45 -05:00
Robert Lubos
1d7a077e11 net: ppp: Revert interface management changes
This reverts changes introduced in commit
dd535f611d, as they broke the gsm_ppp
driver integration with PPP L2. Apparently, a more thorough
refactoring is needed to use the new interface management scheme with
PPP.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-11-16 11:21:24 +01:00
Veijo Pesonen
f467410088 net: lwm2m: shell - allow leading slash
Paths should start from root.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-11-11 08:49:25 +00:00
Ryan Erickson
12b4187092 lwm2m: swmgmt: fix observations not working for resources
The pointers to resource values should not be used
directly to update the values.
This will break observations if the server is trying to
observe changes during a software update.

Signed-off-by: Ryan Erickson <ryan.erickson@lairdconnect.com>
2022-11-10 09:27:54 +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
René Beckmann
26758117d6 net: mqtt-sn: Add MQTT-SN library
This commit adds an implementation of MQTT-SN v1.2.
The specification is available on oasis-open.org:
https://www.oasis-open.org/committees/download.php/66091/MQTT-SN_spec_v1.2.pdf

The following things are missing in this implementation:
- Pre-defined topic IDs
- QoS -1 - it's most useful with predefined topics
- Gateway discovery using ADVERTISE, SEARCHGW and GWINFO messages.
- Setting the will topic and message after the initial connect
- Forwarder Encapsulation

Signed-off-by: René Beckmann <rene.beckmann@grandcentrix.net>
2022-11-09 10:43:00 +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
Jamie McCrae
b6cd83bf7a net: ipv4: Add fragmented packet support
Adds support for incoming and outgoing IPv4 fragmented packet support,
allowing a single packet that is too large to be sent to be split up
and sent successfully.

Signed-off-by: Jamie McCrae <spam@helper3000.net>
2022-11-05 19:58:26 +01:00
Juha Heiskanen
efa75b5a76 net: lwm2m: Send operation registry lock update
Secured Message allocation, init and rebuild process for secure
timeseries ring buffer.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-11-04 09:59:51 +01:00
Juha Heiskanen
05a92f9258 net: lwm2m: Timeseries data cache read update
Added support for handle case when all data is not possible to
add in 1 message for Send and Observed Notification.

Notification continuous pending timeseries data is triggred
by iMIN attribute.

Send Operation generate continuous message in multiple lwm2m
message.

Normal Read by server only report back latest stored data.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-11-04 09:59:51 +01:00
Tommi Kangas
75b5eaac0f net: lwm2m: fix hanging deregistration
Fixed a deadlock in deregistration by moving mutex unlocking.

Signed-off-by: Tommi Kangas <tommi.kangas@nordicsemi.no>
2022-11-04 08:56:05 +00:00
Christoph Schnetzler
0dd14404e1 net: lwm2m: Prevent wundef warnings
If -Werror is used compilation fails due to wundef warning.

Signed-off-by: Christoph Schnetzler <christoph.schnetzler@husqvarnagroup.com>
2022-10-28 22:06:09 +09:00
Carles Cufi
8e4d499fa0 treewide: Use CONFIG_*_ENDIAN instead of __BYTE_ORDER__
In order to avoid using multiple sources of truth for the platfom's
endianness, convert the in-tree code to use the (BIG|LITTLE)_ENDIAN
Kconfig variables exclusively, instead of the compiler's
__BYTE_ORDER__.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2022-10-28 19:23:46 +09:00
Krishna T
1852e33213 net: lib: zperf: Disable prints during ongoing traffic
Prints when traffic is ongoing cost a few Mbps due to writing to UART as
observed by the profiler, so, disable them by default.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-10-27 15:37:41 +02:00
Veijo Pesonen
8c68e01e55 doc: lwm2m: LwM2M Shell
Describes a possible scenario where to use the LwM2M shell
and how to enable it.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-10-27 11:05:05 +02:00
Juha Heiskanen
a66970a6b8 net: lwm2m: Fix connection resume without DTLS
LwM2M connection resume was missing socket connection when
DTLS is disabled.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-27 11:00:46 +02:00
Marc Lasch
df68307121 net: lwm2m: Rename timer object instance create function
Rename timer object instance create funciton `timer_create` to fix a
name collision regression with a POSIX function in `timer.h`. The issue
was introduced with commit 73a637eda0 when
first including`timer.h` into `lwm2ms.h`.

Signed-off-by: Marc Lasch <mlasch@mailbox.org>
2022-10-26 12:01:27 +02:00
Tommi Kangas
c3ad5efa19 net: lwm2m: use zsock_ functions
Use Zephyr internal zsock_ calls to remove dependency
to NET_SOCKETS_POSIX_NAMES.

Signed-off-by: Tommi Kangas <tommi.kangas@nordicsemi.no>
2022-10-26 12:01:14 +02:00
Robert Lubos
3bf503085f net: ip: Increase the number of IPv4/IPv6 interfaces with loopback
In case loopback interface is enabled, it's most likely there will be
more than a one network interface if running on real hardware. Therefore
increase the default IPv4/IPv6 interface count to avoid the need to
increase it manually in every test suite.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-26 12:00:22 +02:00
Krishna T
9b02f91f80 net: wifi: Fix MFP when security type is not given
When security type is not given but instead MFP is given, MFP setting
will be considered as security type, this is because both are optional
and no way to distinguish them easily.

Make security type mandatory for MFP selection, this way we either
assume defaults for both security type and MFP or explicitly ask user
for both. Reword the help text to reflect this.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-10-26 12:00:11 +02:00
Sjors Hettinga
14cb6cb419 net: ip: Speed up the IP/UDP/TCP checksum calculation
Instead of doing a 1-complement addition for every 16-bit word, process
32-bit words and handle the 1-complement addition at the end.

This work is a colaboration with Diego Pino García. The algorithm is
inspired by:
https://blogs.igalia.com/dpino/2018/06/14/fast-checksum-computation/

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-10-25 12:46:11 +02:00
Robert Lubos
caab8cb1b3 net: lwm2m: Don't assume time_t data type size
sizeof(time_t) can vary depending on architecture/libc being in use,
therefore LwM2M should not assume time_t data type size. Instead of
using magic numbers, use a proper sizeof.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-24 16:13:40 +03:00
Juha Heiskanen
4bcc880670 net: lwm2m: LwM2M engine time API update
Updated lwm2m_enigen_set/get_time API for support time_t.

Updated LwM2M engine set/get resource time to time resource support
time_t and uint32_t input.

LwM2M engine put and get time API update to use time_t.

Time series data cache entry have own type for time resource.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-24 10:39:03 +02:00
Juha Heiskanen
e1e2228e9c net: lwm2m: LwM2M object time resource update
Updated Timestamp resource default buffer type to time_t.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-24 10:39:03 +02: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
Krishna T
9d1974ea08 net: ip: mgmt: Log the event ID for dropped events
This helps debug and fix the maximum event size allocation.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-10-20 15:40:02 +02:00
Krishna T
0ac7c6a32a net: ip: mgmt: Fix the maximum event size calculation
Use a union to capture all big NET event structures with a default size
of 32bytes, this makes maintenance easier.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-10-20 15:40:02 +02:00
Robert Lubos
6851a33a64 net: dhcpv4: Fix NAK processing in RENEWING state
NAK message should be processed in the RENEWING state just like in
REBINDING, not ignored.

Additinonally, NAK processing should include the rejected IP address
removal from the nework interface, otherwise the IP address will remain
on the interface indefinitely (i. e. until removed manually), which
might disturb further operation.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:01:13 +02:00
Robert Lubos
80f71ff2d2 net: dhcpv4: Fix requested IP address overwrite
It could happen, that the requested IP address, stored in the dhcpv4
config structure in the network interface, could get overwritten with an
unexpected message, for example NAK from the DHCP server. In result, the
DHCPv4 module was no longer able to remove the requested address from
the network interface, as it simply no longer remembered what the
address was.

Fix this, by setting the requested address only when it's actually
provided by the DHCP server, i. e. when handling the OFFER message from
the server. Accordingly, the requested address will be cleared when the
SELECTING stage is entered, where all of the cleanups should've already
be done.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:01:13 +02:00
Robert Lubos
43b057a7b2 net: if: Remove net_if_carrier_down function
The function is no longer used, as its functionality has been replaced
with net_if_carrier_off().

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
0ac6fe913e net: virtual: Align virtual L2 with iface status upgrade
Align virtual L2 with interface state handling update. Introduce
net_virtual_enable() function, which gets called whenever a network
interface is brought up (operational). This, combined with already
existing net_virtual_disable() function, can be used to update the
carrier state on the virtual interface, based on the underlying
interface status.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
dd535f611d net: ppp: Align PPP driver/L2 with iface state upgrade
Align PPP drivers/L2 with interface state handling update. Use the
carrier on/off notification instead of bringing the interface up/down to
update the interface state.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
65db65a6be net: openthread: Align OpenThread L2 with iface state upgrade
Align OpenThread L2 with interface state handling update. Use the
dormant flag to indicate whether an interface joined a Thread network.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
ec243e2553 net: bluetooth: Align Bluetooth L2 with iface state upgrade
Align Bluetooth L2 with interface state handling update. Use the dormant
flag to indicate whether interface has a Bluetooth connection or not.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
b279bfd2dd net: ethernet: Align Ethernet drivers/L2 with iface state upgrade
Align Ethernet/Wi-Fi drivers/L2 with interface state handling update.

For drivers, that did not support carrier detection, no changes are
needed.

Driver that did support carrier detection, are updated to set the
carrier state to OFF by default, instead of setting the
NET_IF_NO_AUTO_START flag. This allows to postopne the actual
NET_EVENT_IF_UP notification until driver detects that carrier is ready.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
89b32a0f5d net: if: Verify actual interface state instead of admin state on TX
When packet is passed to transmit at the net_if level, verify the
carrier state (NET_IF_LOWER_UP) instead of administrative state
(NET_IF_UP).

The administrative state is checked anyway at higher level (net_context)
so no need to verify it again. This will allow to still transmit control
packets for example when interface is in a dormant state.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
efd03a86d7 net: if: Introduce carrier and dormant management on a network iface
Introduce a new interface state management scheme, according to
RFC 2863. This includes the following changes:

* Introduce a new interface flag: NET_IF_LOWER_UP, along with
  corresponding helper functions. The flag should be set/cleared on an
  interface by a network driver/L2 to signalize physical readiness of an
  interface to transmit data (for example cable plugged in).

* Introduce a new interface flag: NET_IF_DORMANT, along with
  corresponding helper functions. The flag should be set on an
  iterface when the interface is not ready to transmit application data,
  for example still not joined a Wi-Fi network.

* Introduce a new interface flag: NET_IF_RUNNING, indicating that
  interface is ready to transmit application data.

* Update the meaning of the NET_IF_UP flag - it now singnalizes whether
  an interface has been brought up/down by the application (admin
  up/down).

* Introduce operational state of an interface, derived from above. It
  reflects the internal interface state.

The meaning of net_if_is_up() function and NET_EVENT_IF_UP/DOWN events
remains unchanged to retain backward compability - they reflect the
interface readiness to transmit application data.

To verify the administrative up/down state, a new function
net_if_is_admin_up() has been introduced, along with
NET_EVENT_IF_ADMIN_UP/DOWN events.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
04fce39e03 net: if: Fix if down handling for all offloaded interfaces
Socket offloading was not taken into consideration when network
interface was put down. Fix this by introducing a helper function, to
verify whether an interface is offloaded or not.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-20 10:00:31 +02:00
Robert Lubos
c27a6af712 net: zperf: Add QoS support
Improve the zperf upload/upload2 commands, by allowing to specify
DSCP/ECP fields for outgoing packets. The introduced -S option is
compatible with Linux iperf3 utility.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos
d437f950db net: shell: Allow for ping arguments to be specified in hex
Improve the parse_arg() helper function used with shell ping command,
by allowing to parse arguments provided in hex.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos
9e38a3ec48 net: shell: Add support for ping -Q parameter (Quality of Service)
Add new option to the net shell ping command, which allows to specify
the DSCP/ECN values for an outgoing ping request. The option is
compatible with Linux ping command.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos
45ce047605 net: icmpv6: Allow to specify DSCP and ECN values in ping
Add support for setting DSCP/ECN values for an outgoing ping request.
Additionally, copy DSCP/ECN values from an incoming ping request into
the ping response, like Linux does.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos
38aff54961 net: icmpv4: Allow to specify DSCP and ECN values in ping
Add support for setting DSCP/ECN values for an outgoing ping request.
Additionally, copy DSCP/ECN values from an incoming ping request into
the ping response, like Linux does.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02: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
Robert Lubos
c868018c3c net: context: Add DSCP/ECN support
Add a new net_context option, which allows to set DSCP/ECN values on a
net context. Those values are then encoded into outgoing packet
IPv4/IPv6 header.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos
c7af28b9af net: ipv6: Add support for setting/reading DSCP/ECN fields (TC)
Encode/decode recently added DSCP/ECN fields into/from IPv6 header.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos
5c10f6f9d6 net: ipv4: Add support for setting/reading DSCP/ECN fields (ToS)
Encode/decode recently added DSCP/ECN values into/from IPv4 header.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Robert Lubos
c5096f4ca1 net: pkt: Add IP DSCP/ECN information to a packet structure
Add new fields to the net_pkt structure, representing IP-specific
Differentiated services code point (DSCP) and Explicit Congestion
Notification (ECN) values. Those values are encoded in legacy
Type of Service (IPv4) and Trafic Class (IPv6) header fields.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-19 19:03:48 +02:00
Øyvind Rønningstad
1e88e7cc9b lwm2m_senml_cbor.patch: Update patch file to match current changes
File created by commiting changes and running

  git diff HEAD~1.. > lwm2m_senml_cbor.patch

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
2022-10-19 16:04:56 +02:00
Øyvind Rønningstad
8b295bc58c lwm2m_senml: Regenerate cbor code using zcbor
Also do clang-format and apply patch.

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
2022-10-19 16:04:56 +02:00
Øyvind Rønningstad
7b05569d49 lwm2m_senml_cbor_regenerate.sh: Fix argument order in zcbor call
zcbor 0.6.0 has changed the argument order to put code/convert/validate
first.

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
2022-10-19 16:04:56 +02:00
Øyvind Rønningstad
f8d0c8a43f lwm2m_senml_cbor_regenerate.sh: Use git am instead of git apply
Since it's better at resolving conflicts.
Commit regenerated files before applying patch.

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
2022-10-19 16:04:56 +02:00
Veijo Pesonen
33453e1135 lwm2m: fails if incorrect registration reply
No need to proceed if registration reply parsing fails.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-10-17 20:06:32 +02:00
Florian Grandel
b674ed6b8b net: pkt: decouple from ieee802154 internals
This change implements part two of the program laid out in the TSCH RFC,
see #50336#issuecomment-1250250154 :

> Consolidate IEEE 802.15.4 options in net_pkt

This change improves decoupling of generic net core code from
IEEE 802.15.4 internals. It also simplifies IEEE 802.15.4
attribute cloning and thereby makes it easier to maintain and less
error prone (and probably even faster as individual bits are no longer
copied over separately).

This enables us to extend and design IEEE 802.15.4 L2 attributes inside
the package in isolation from the net core code which will no longer
have to be changed when introducing changes or additions to the flags.

This flexibility will be built upon in later change sets to model the
IEEE 802.15.4 attributes closer to the spec.

The solution is inspired by Linux's sk_buff->cb attribute which addresses
the same concern as the attribute introduced in this change set:
https://elixir.bootlin.com/linux/v6.0.1/source/include/linux/skbuff.h#L871

As the inline comment says: The cb attribute can be made a union or even a
uint8[something] in the future, if further L2s need a control block, too.
Right now such full indirection would make the code overly abstract, so
I chose to compromise with maintainability in mind.

Care has been taken to ensure that this changes does not introduce
additional padding into the net package. To maintain zero-padding, future
changes to the net packet struct will have to ensure that the
IEEE 802.15.4 struct is 4-byte aligned (iff the IEEE 802.15.4 struct
continues with max uint32_t scalar members) which is no deviation from
the previous implementation.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-17 16:54:37 +02:00
Florian Grandel
0b94947d33 net: l2: ieee802154: set ll protocol in pkt
The IEEE 802.15.4 L2 now sets the ll protocol in the packet to a
specific value. This corresponds to the respective solution in Linux and
is required to validate access to IEEE 802.15.4 specific attributes of
the packet.

Later change sets will rely on this value to ensure that IEEE 802.15.4
specific package content can only be accessed on IEEE 802.15.4 packages.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-17 16:54:37 +02:00
Florian Grandel
389bd57753 net: ip: fix and consolidate cloning of ll addr
The net packet structure contains pointers to link-layer source and
destination addresses. Usually, these structures do not point to
separately allocated memory but directly into the packet's data buffer.

In case of a deep package clone (which includes copying the buffer) the
copy of the ll addresses continued to point into the old package
(contrary to a rather misleading inline comment). This was proven by an
additional failing unit test assertion.

As the original package may be unreferenced while the cloned package is
still being accessed, the ll address pointers of the cloned package may
become invalid.

The fix consists of two parts:
 * First it is determined whether a given ll address actually points into
   the buffer and if so at which logical cursor offset it is located.
 * If the address points into the package buffer then the cursor API is
   used to determine the corresponding physical memory location in the
   cloned package. The ll address of the cloned package is then patched
   to point to the cloned buffer.

Additional assertions were introduced to the existing unit test to ensure
that the newly generated address points to the correct content of the
cloned package.

The solution is implemented in a generic way so that the previously
redundant implementations were consolidated into a single one. The code
includes a check that ensures that the ll address check and manipulation
will be skipped in case of shallow package copies.

The change also addresses problems related to the "overwrite" flag of the
package:
 * Package cloning assumes the overwrite flag to be set. Otherwise it
   will not work correctly. This was not ensured inside the clone method.
 * Package cloning manipulates the overwrite flag of the cloned package
   but does not reset it to represent the same state as the original
   package.

The change introduces a fix and unit test assertions for both problems.

Fixes: #51265

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-17 16:54:37 +02:00
Florian Grandel
f1e9dd2930 drivers: ieee802154: properly announce promisc mode
Most IEEE 802.15.4 drivers do not support promiscuous mode, some do.
There is a dedicated L2 flag to signal this capability to clients.

Unfortunately the IEEE 802.15.4 L2 stack does not announce this flag
even for drivers that correctly expose it in their HW capabilities.
Some clients (notably the OpenThread L2) even uses promiscuous mode
without checking whether the driver actually supports it.

This change lets the vanilla IEEE 802.15.4 L2 check the driver's
HW capabilities to announce promiscuous mode on its 'get_flags()'
interface if supported.

The OpenThread L2 uses a constant (potentially incorrect) response
to 'get_flags()'. Fixing the OpenThread L2 is out of scope of this
change. This change just introduces TODO messages to the OpenThread code
so that the OpenThread team may fix the issue (or delete the TODO if they
deem it irrelevant).

Fixes: #51263

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-17 16:54:37 +02:00
Andy Ross
bd063d1a9e net/ethernet/bridge: Fix k_mutex initialization
The bridge subsystem was written with a ETH_BRIDGE_INITIALIZER that
assumed it could initialize a k_mutex with a zero-filled initializer.
That never worked.  Unlike semaphores, mutexes have always required a
runtime call to k_mutex_init().  What happened instead is that
k_mutex_un/lock() returned error codes, which were ignored by the code
here.  So no locking was happening.

This was discovered while migrating to zync, where an attempt to
unlock an unlocked mutex is a panic condition (and where zero-filled
initializers are legal, but represent an unfair semaphore and not a
mutex, so deadlock correctly).

Signed-off-by: Andy Ross <andyross@google.com>
2022-10-17 10:13:56 +02:00
Andy Ross
95101e6890 net/route: Add missing lock in net_route_mcast_add()
This is a public API for the subsystem, can be called from app
context, unlocks the local k_mutex on one of its three exit paths, and
it's quite clear that nothing ever locks that mutex!

The code used to work because k_mutex simply returned an error if you
tried to unlock an unlocked object.  Now zync will panic (when
CONFIG_ZYNC_VALIDATE=y) if you try that.

Signed-off-by: Andy Ross <andyross@google.com>
2022-10-17 10:13:56 +02:00
Jukka Rissanen
cf24ebcc1f net: dns: Always init the resolver
If user has not specified any DNS servers in
CONFIG_DNS_SERVER_IP_ADDRESSES, then the DNS resolver will not be
initialized properly. So fix this by always calling dns_resolve_init()
so that DNS mutex get properly initialized.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2022-10-14 09:57:09 +02:00
Gaël PORTAY
6dedea7c16 wifi: shell: Move closing bracket after type enumeration
This fixes the output below by moving the closing bracket to "<Security
type (optional: valid only for secure SSIDs)>" after the enumeration of
security types "0:None, 1:PSK, 2:PSK-256, 3:SAE".

Fixes:

	uart:~$ wifi
	wifi - Wi-Fi commands
	Subcommands:
	  connect     :Connect to a Wi-Fi AP
	               "<SSID>"
	               <channel number (optional), 0 means all>
	               <PSK (optional: valid only for secure SSIDs)>
	               <Security type (optional: valid only for secure SSIDs)>
	                                              v----------------------^
	               0:None, 1:PSK, 2:PSK-256, 3:SAE
	               (...)

Signed-off-by: Gaël PORTAY <gael.portay@gmail.com>
2022-10-14 09:55:18 +02:00
Gaël PORTAY
f7dfae5730 wifi: shell: Indent second parameter to new line
Return to line after the first parameter to:
- have the second parameter in a single line (not splitted) and
- start every parameters from a brand new line (easier to read)

Signed-off-by: Gaël PORTAY <gael.portay@gmail.com>
2022-10-14 09:55:18 +02:00
Gaël PORTAY
ff077aafe9 wifi: shell: Add missing bracket
This fixes the output below by adding the missing closing bracket to
"<MFP (optional): 0:Disable, 1:Optional, 2:Required":

Fixes:

	uart:~$ wifi
	wifi - Wi-Fi commands
	Subcommands:
	  connect     :Connect to a Wi-Fi AP
	               "<SSID>"
	               <channel number (optional), 0 means all>
	               <PSK (optional: valid only for secure SSIDs)>
	               <Security type (optional: valid only for secure SSIDs)>
	               0:None, 1:PSK, 2:PSK-256, 3:SAE
	               <MFP (optional): 0:Disable, 1:Optional, 2:Required
	               ^-------------------------------------------------^
	               (...)

Signed-off-by: Gaël PORTAY <gael.portay@gmail.com>
2022-10-14 09:55:18 +02:00
Gaël PORTAY
b177911a4d wifi: shell: Add missing end of line
This fixes the output below by returning to line after "Connect to a
Wi-Fi AP":

Fixes:

	uart:~$ wifi
	wifi - Wi-Fi commands
	Subcommands:
	  connect     :Connect to a Wi-Fi AP"<SSID>"
	                                    ^------^
	               <channel number (optional), 0 means all>
	               (...)

Signed-off-by: Gaël PORTAY <gael.portay@gmail.com>
2022-10-14 09:55:18 +02:00
Andreas Müller
b0e76dbf35 net: shell: fix memory leak in udp_rcvd()
Without pkt_unref(), the shell command "net udp bind" will fail to
receive after a few packets ("net allocs" shows that memory is still
allocated).

Signed-off-by: Andreas Müller <andreas.mueller@husqvarnagroup.com>
2022-10-13 17:10:28 +02:00
Peter Tönz
46a59124dc net: lwm2m: Fix seg-faults if a socket was closed in the meantime
Our application (posix-naive/debug) ran into segmentaion faults,
because the socket was closed between the "wait for sockets" and the
second if in the first loop. Added the check also to line 690
and 720.
The other uses of sock_ctx[i] are already checked against NULL

Signed-off-by: Peter Tönz <peter.tonz@husqvarnagroup.com>
2022-10-12 18:42:41 +02:00
Florian Grandel
580d789cd0 net: l2: ieee802154: fix frame type field check
The LLDN frame has been obsoleted in IEEE 802.15.4-2015f. This change
removes it from the code, introduces frame types from current spec
levels and updates the frame validation rules in accordance with the
spec.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-12 18:40:59 +02:00
Florian Grandel
14c608e9c4 net: l2: ieee802154: improved context thread safety
Several attributes in the ieee802154_context struct may potentially be
accessed from different threads and/or ISR context. Only some of these
attributes were properly guarded against race conditions.

This may not have been to problematic in the past but as other changes
in this PR introduce additional attributes and mutate several attributes
in a single atomic transaction, leaving such changes unprotected seems
dangerous.

This change therefore introduces systematic locking of the
ieee802154_context structure.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-12 18:40:59 +02:00
Florian Grandel
6a6b89516d net: l2: ieee802154: improve short address support
IEEE 802.15.4 short address support is incomplete in several places.
This change improves short address support without claiming to fix
it everywhere. Future iterations will have to continue where this change
leaves off.

The purpose of this change was to:
 * use the short address returned by association responses,
 * automatically bind IEEE 802.15.4 datagram sockets to the short
   address if available,
 * use the short address in outgoing packages where applicable,
 * improve validation of association/disassociation frames,
 * model association more closely to the spec by tying it to the
   existence of a short address in the MAC PIB thereby removing
   redundancy in the PIB (which makes race conditions less probable),
 * keep both, the short and extended addresses, of the coordinator.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-12 18:40:59 +02:00
Florian Grandel
bff6a5cce5 net: l2: ieee802154: fix short/ext address endianness
This changes fixes several bugs and inconsistencies in the IEEE 802.15.4
L2 implementation. These bugs were revealed while documenting intended
endianness of driver, IP, socket and L2 attributes (see previous
changes).

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-12 18:40:59 +02:00
Florian Grandel
b951f062f5 net: l2: ieee802154: add short address to ll address
This is a preparatory change that fixes one aspect of short address
handling before fixing endianness so that the endianness fix can be
applied consistently in this method.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-12 18:40:59 +02:00
Florian Grandel
34999a8b3e net: l2: ieee802154: document endianness
The IEEE 802.15.4 L2 code stores representation of attributes like
PAN id, short address and extended address in different encodings:

* big endian for extended address and CPU byte order for everything
  else whenever such attributes enter user space (except for IP/socket
  link layer addresses which are always big endian - even in case of
  short addresses - to maintain POSIX compatibility).

* little endian for everything that is close to the radio driver as
  IEEE 802.15.4 frames are little endian encoded.

Endianness was almost nowhere documented which led to several bugs and
inconsistencies where assignments of different byte order were not
converted (or sometimes converted, sometimes not).

This change documents endianness wherever possible within the realm of
the IEEE 802.15.4 L2 code. Conversion bugs and inconsistencies that were
revealed by the improved documentation will be fixed in a separate
commit.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-12 18:40:59 +02:00
Florian Grandel
7ea6cc99ce net: ip: fix minor formatting glitch
This changes just fixes an erroneous indentation from a previous patch.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-10-12 18:40:59 +02:00
Christopher Friedt
dbe2c0d59e include: net: http: rename http_x.h http/x.h
Some minor housekeeping prior to adding an http server
implementation. There are already a number of http headers
and that number will likely increase with subsequent work.
Moving them into a common directory cleans up the
`include/net` directory a bit.

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2022-10-12 09:02:21 -04:00
Andrzej Głąbek
6ae66cc13d net: pkt: Allow compilation with custom IEEE 802.15.4 based L2
This is a follow up to commit bb86f8b967.

Also custom IEEE 802.15.4 based L2 implementations may need to use
packet handling without the IP layer. Add support for such cases.

Signed-off-by: Andrzej Głąbek <andrzej.glabek@nordicsemi.no>
2022-10-12 18:46:09 +09:00
Peter Tönz
a868da8568 net: lwm2m: Fix buffer overflow by using CONFIG_LWM2M_VERSION_1_0
By using CONFIG_LWM2M_VERSION_1_0, the function
lwm2m_engine_get_binding() returns the binding
and the queue mode bytes. Therefore the buffer
must be tree bytes long.
The issue is caused by the two inconsistent defines:

lwm2m_registry.c:
    #define BINDING_OPT_MAX_LEN 3 /* "UQ" */
lwm2m_rd_client.c:
    #define CLIENT_BINDING_LEN sizeof("U")

Signed-off-by: Peter Tönz <peter.tonz@husqvarnagroup.com>
2022-10-12 18:45:50 +09:00
Seppo Takalo
d454cc946e net: lwm2m: Add helper macro for filling lwm2m_obj_path structs
Allows filling up struct lwm2m_obj_path by a macro.
For example:
  struct lwm2m_obj_path p1 = LWM2M_OBJ(MY_OBJ);
  struct lwm2m_obj_path p2 = LWM2M_OBJ(MY_OBJ, 0, RESOURCE);

Similarly, some function calls accept the structure, so it can
be initialized from stack and given by a pointer
  lwm2m_notify_observer_path(&LWM2M_OBJ(obj_id, 0, RESOURCE_ID));

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-10-11 11:14:31 +02:00
Seppo Takalo
65c084f9e5 net: lwm2m: Don't close the socket context on callbacks
I need to register a service for the pull-context so I can
safely close the socket context. Otherwise the socket loop
would crash, because context would be closed while going through
the list where it was located.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-10-11 11:13:56 +02:00
Seppo Takalo
d49219aede net: lwm2m: Block on semaphose waiting
Minor change, the semaphore is freed by a caller so it was always
free, but just for being correct, it should be a blocking call,
so any errors would clearly block.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-10-11 11:13:56 +02:00
Seppo Takalo
b72fde1f54 net: lwm2m: Remove second layer or rettrying from pull handler
CoAP layer handles retrying so having a second layer of retry
in the pull-context does not make sense. If we need more retrying
it should be done in CoAP layer.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-10-11 11:13:56 +02:00
Seppo Takalo
4ec698004c net: lwm2m: Set FOTA state correctly on URI write
When URI is written, we must first set the state to DOWNLOADING
so when any error happens on the initialization phase, the
result written on a callbacks are correctly reflected and the state
changes correctly IDLE -> DOWNLOADING -> IDLE (result written).

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-10-11 11:13:56 +02:00
Seppo Takalo
99ebcefc71 net: lib: lwm2m: Add shell commands for lock and unlock
Allowing locking the registry from commandline allows
us to test composite observation and observation of
object instances, etc. where multiple values are changed
before the notify message triggers.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-10-11 11:12:20 +02:00
Juha Ylinen
c8a409d7d3 net: lwm2m: Use const data pointers in lwm2m_engine_set functions
lwm2m_engine_set functions use void data pointers. Change those to
to const void

Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
2022-10-07 16:43:51 +00:00
Robert Lubos
b76c35d809 modules: mbedtls: Replace select statement with depends on for EC
Instead of using "select" on certain EC configurations, which is
considered unsafe for various reasons, use a "depends on" and rely on
the user to set a proper configuration in the config file.

Update the respective project configurations to comply with the new
configuration scheme.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-10-07 15:12:42 +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
Kamil Kasperczyk
1475d20aff net: ipv6: Allowed to add route to router's link local address
Zephyr doesn't seem to allow on adding route to the device from
which it received Router Advertisement without SLLAO field set
(in particular device that doesn't include Link Layer address).

Changes done:
* Added creating new NBR without Link Layer address set on RA
reception (LL is added only if SLLAO option is set, otherwise
NBR doesn't have LL address, but exists in the table and has
valid IPv6 link local address).
* Removed two asserts preventing from adding route to the NBR
that doesn't have Link Layer address set.

Signed-off-by: Kamil Kasperczyk <kamil.kasperczyk@nordicsemi.no>
2022-10-05 16:22:40 +00:00
Juha Heiskanen
8e1ade2663 net: lwm2m: Fixed cached readtime
Added missing typecast for time read.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-05 14:23:32 +00:00
Juha Heiskanen
17b60d0fce net: lwm2m: LwM2M engine send operation update.
Added mutex lock for message build operation.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-05 14:23:32 +00:00
Juha Heiskanen
87dc170fed net: lwm2m: SenML-JSON support for Historical data
Extend SenML-JSON content format for handle cached data
timestamp API for basetime and timestamp label's.

Added support for write historical data for static resource
size's: Float (v) and Boolean (vb).

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-05 14:23:32 +00:00
Juha Heiskanen
60d9948b67 net: lwm2m: SenML-CBOR Encoder and CDDL update
Added support for historical data encode by adding base time (bt)
and time (t) label. New labels are needed for Encoder so Decoder
is not regenerated.

Added support for SenML-CBOR to write time series data.
Use "bt" base time and "t" timestamp labels for data cache.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-05 14:23:32 +00:00
Juha Heiskanen
73a637eda0 net: lwm2m: Historical data cache API update
New API for enable Historical data storage for LwM2M resource.
Data cache is only supported at resource which resource size is
static and well known.

Extend output writer for write cached data timestamp.

Enable cache support for Resource set and Read operation.

Added possibility for for drop latest or oldest data from cache.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-05 14:23:32 +00:00
Juha Heiskanen
8c2f5d3296 net: lwm2m: RD Client bootstrap trigger update
Accept now from bootstrap trigger from any state expect ongoing
bootstrap process.
Free also possible on going RD client message. There was a chance
that update message response change state and bootstrap proces
not started.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-03 10:20:13 +02:00
Juha Heiskanen
7cee4cf80c net: lwm2m: LwM2M RD client message allocate update
Updated message handler that it free possible old allocated
message. Added message free also to RD stop and idle state.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-03 10:20:13 +02:00
Juha Heiskanen
8279489aee net: lwm2m: RD Client update registration timeout
Renamed LWM2M_RD_CLIENT_EVENT_REG_UPDATE_FAILURE to
LWM2M_RD_CLIENT_EVENT_REG_TIMEOUT.

Changed reported event type for registration timeout to
LWM2M_RD_CLIENT_EVENT_REG_TIMEOUT from
LWM2M_RD_CLIENT_EVENT_REGISTRATION_FAILURE.
LWM2M_RD_CLIENT_EVENT_REGISTRATION_FAILURE should be only
reported case when server reject by response registration.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-10-03 10:20:13 +02:00
Sjors Gielen
c0bcff120e net: sntp: use zsock_ functions.
Now the library does not need to depend on NET_SOCKETS_POSIX_NAMES.

Signed-off-by: Sjors Gielen <sjors@sjorsgielen.nl>
2022-10-03 10:19:47 +02:00
Krishna T
d2b196978f net: l2: wifi: Fix channel length check
To allow 5GHz (and 6GHz) channels, use 3 digits check.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-09-26 18:41:40 +02:00
Juha Heiskanen
b559bd818c net: lwm2m: Fix LwM2M pause and resume
Fixed unstable thread state read for detetect engine thread
state.
Fixed engine missing socket conrext add.
lwm2m resume now do update also from network error state

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-09-26 15:17:37 +00:00
Juha Heiskanen
8364715998 net: lwm2m: Fix LwM2M resume from Update registration state
If LwM2M engine was paused at ENGINE_UPDATE_SENT it was not
able to resume lwm2m engine properly. There was also missing
RD client Pending message free which could also affect a issue.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-09-26 10:55:03 +00:00
Juha Heiskanen
c9c8c467b5 net: lwm2m: LwM2M rd client Update registration Timeout fix
RD client was not closing socket socket when Update registration
timeout. It fail new connection open. There is added a flag for
detect a case when Registration state need to be re-open a socket
for new connection.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-09-26 10:55:03 +00:00
Krishna T
97ee180c72 wifi: shell: Fix network switching issue
When switching from a secure network to open network, the previous
parameters are not reset which causes the open connection to fail.

Remove the unnecessary "static" storage and reset to zero for params.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-09-21 08:58:37 +00:00
Henrico Brom
bde8c6d24f net: lwm2m: Fixed missing _CONFIG prefix
Fixed missing '_CONFIG' prefix when enabling
LWM2M_FIRMWARE_UPDATE_OBJ_SUPPORT_MULTIPLE and
CONFIG_LWM2M_FIRMWARE_UPDATE_OBJ_INSTANCE_COUNT through prj.conf

Signed-off-by: Henrico Brom <henrico.brom@vention.nl>
2022-09-21 08:56:58 +00:00
Jamie McCrae
521c787e6f net: shell: Fix stray tab in "net mem" output
Fixes a stray tab in the net mem shell output which makes the TX DATA
line indented.

Signed-off-by: Jamie McCrae <spam@helper3000.net>
2022-09-21 08:54:25 +00:00
Jamie McCrae
771668cf91 net: arp: Replace pending packet pointer with fifo
This fixes a bug with ARP and multiple outgoing packets with an IP
that needs to be resolved, causing the first packet to go out and
all others to be dropped after the timeout by having a FIFO of
pending packets instead of a single packet.

Signed-off-by: Jamie McCrae <spam@helper3000.net>
2022-09-21 08:49:32 +00:00
Jarno Lämsä
05b17356e2 net: lib: lwm2m: Fix lwm2m exec
The lwm2m exec erroneously checked the previous return value
instead of checking if the resource existed. This caused exec
to try to get and execute the execute callback from NULL and caused
a reboot.

Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
2022-09-19 10:33:04 +00:00
Reto Schneider
b11ba9ddc8 net: net_pkt: Simplify net_pkt_compact() API
Since db11fcd174 [net/net_pkt: Fully
separate struct net_pkt from struct net_buf], net_pkt_compact() can not
fail anymore.

This commit acknowledges this and simplifies the API accordingly.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2022-09-15 16:35:11 +00:00
Krishna T
79f864028d net: l2: wifi: Log band from the scan result
Along with channel, also log the Wi-Fi band from the scan result.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-09-15 16:34:30 +00:00
Reto Schneider
9e1b130156 net: zperf: Configurable packet size limit
Allow user to adjust (artificial) size limitation of 1024 bytes.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2022-09-15 16:34:13 +00:00
Reto Schneider
6de54e0d03 net: context: Fix memory leak
Allocated, but undersized packets must not just be logged, but also
unreferenced before returning an error.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2022-09-14 14:38:34 +01:00
Sjors Hettinga
452592fc9a net: websockets: Fix websocket_send_msg return code
When the websocket_prepare_and_send is called from websocket_send_msg,
the header length is subtracted to retrieve the transmitted payload length.
Make an exclutsion to prevent the return code of
websocket_prepare_and_send being modified in case of 0 or a negative
return code.
This avoid confusion with modificated error codes

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-13 08:49:24 +00:00
Sagar Shah
dfd897096d net: lib: coap: method_from_code() API change to return errors.
method_from_code() signature has changed to return error and
the method. In case of an invalid code it returns -EINVAL and
causes coap_handle_request() to return -ENOTSUP.

Fixes: #49498

Signed-off-by: Sagar Shah <sagar.shah@legrand.us>
2022-09-12 10:53:34 +00:00
Ola Tangen Kulseng
1df3de4e98 net: lwm2m: API for multiple resource writing
Used the registry lock in the functions lwm2m_registry_lock() and
lwm2m_registry_unlock() to make the registry lockable through a public
API. If writing to multiple resources that are composite-observed,
locking will halt the main thread until every resource is written to,
ensuring that only one notify message will be sent. Updated
the documentation in lwm2m to include this addition.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-09-12 10:52:18 +00:00
Christian Taedcke
6a1c2304c4 net: context: Remove redunant check of automatically selected port
In the function find_available_port() a port is randomly selected. Because
the random value is always >= 0x8000, it is redundant to check if it is
<= 1023 afterwards.

This commit removes the redundant check.

Signed-off-by: Christian Taedcke <christian.taedcke@lemonbeat.com>
2022-09-09 14:12:57 +00:00
Krishna T
25d0f87b3c net: dhcp: Add support for restarting DHCP
If a L2 link has been established, then the DHCP is taking too long as
it has to go through its capped exponential backoff timers to trigger
discover (The DHCP starts immediately during init, this is itself wrong,
it should start on a link UP notification) that delays the DHCP for
few seconds to a minute.

And if we do stop and start DHCP then also it goes through the initial
delays (though configurable), which is also not ideal.

Add support for restarting DHCP without any delay, i.e., release and
send discover immediately.

This is also useful in case L2 switches to a different subnet, in this
case Zephyr doesn't restart DHCP automatically, this API can be used by
L2 apps/drivers to restart DHCP to get new subnet IP.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-09-06 09:56:22 +02:00
Florian Grandel
51af614f88 net: ip: core: clean up check_ip_addr()
* only define function when IP stack is built
* use switch statement rather then if/else if

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-09-05 14:35:17 +00: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
Gerard Marull-Paretas
79e6b0e0f6 includes: prefer <zephyr/kernel.h> over <zephyr/zephyr.h>
As of today <zephyr/zephyr.h> is 100% equivalent to <zephyr/kernel.h>.
This patch proposes to then include <zephyr/kernel.h> instead of
<zephyr/zephyr.h> since it is more clear that you are including the
Kernel APIs and (probably) nothing else. <zephyr/zephyr.h> sounds like a
catch-all header that may be confusing. Most applications need to
include a bunch of other things to compile, e.g. driver headers or
subsystem headers like BT, logging, etc.

The idea of a catch-all header in Zephyr is probably not feasible
anyway. Reason is that Zephyr is not a library, like it could be for
example `libpython`. Zephyr provides many utilities nowadays: a kernel,
drivers, subsystems, etc and things will likely grow. A catch-all header
would be massive, difficult to keep up-to-date. It is also likely that
an application will only build a small subset. Note that subsystem-level
headers may use a catch-all approach to make things easier, though.

NOTE: This patch is **NOT** removing the header, just removing its usage
in-tree. I'd advocate for its deprecation (add a #warning on it), but I
understand many people will have concerns.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-09-05 16:31:47 +02:00
Krishna T
34db41d934 net: l2: wifi: Improve help
* Fix newlines
* Improve text

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-09-02 11:07:07 +00:00
Krishna T
d6448aeb49 net: l2: wifi: Use proper Wi-Fi terminology for MAC
MAC address is generic, in context of scan it should be called BSSID.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-09-02 11:07:07 +00:00
Krishna T
870fcb3aa4 net: l2: wifi: Fix the width for security
The longest security string is 15 (WPA2-PSK-SHA256), so, use that width
for alignment.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-09-02 11:07:07 +00:00
Sagar Shah
7973483649 net: lib: coap: coap_packet_parse() returns different error values
coap_packet_parse() returns different values depending on error.
It now returns
-EINVAL for invalid input arguments,
-EBADMSG for malformed coap header,
-EILSEQ for malformed options error.

Fixes: #48960

Signed-off-by: Sagar Shah <sagar.shah@legrand.us>
2022-09-02 11:02:38 +00:00
Christopher Friedt
c59178b695 net: ip: tcp: use zu format specifier for size_t
The `%i` format specifier is for `int` and is equivalent to
`%d` for printf formatting.

However, for `size_t`, the correct format specifier is `%zu`.

Fixes #49825

Signed-off-by: Christopher Friedt <cfriedt@fb.com>
2022-09-01 10:24:39 -04:00
Sjors Hettinga
74772abfd2 net: tcp: Add build in auto check for reordering
The reorder process in rather complicated. Add a runtime check to always
check afterwards if the reordering queue is still consistent. When this
test fails, discard the contents of the complete reorder buffer.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-01 10:38:28 +00:00
Sjors Hettinga
39328e8836 net: tcp: Discard duplicate data in reodering correctly
When all the data of the new packet is already present in the
queue_recv_data, make sure the packet is discarded.
This commit adds a test line that reproduces the issue and implements a
fix.

Also in appending the packet, call the official net_buf_frag_add function
instead of updating the last net_buf pointer, since the net_pkt_remove_tail
called in between, might have removed the last net_buf.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-01 10:38:28 +00:00
Sjors Hettinga
89860fd74e net: tcp: Correctly deal with fully duplicated buffered out of order data
TCP is a streaming protocol, this means it can set the packet boundary
at an arbitrary location. Therefor a re-transmitted packet may have the
packet boundary at a different location from the original missing segment.

The reordering logic should be able to deal with this situation and
throw away the overlapping data. This fix clears the out of order queue
when the queued data is not relevant.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-01 10:38:28 +00:00
Sjors Hettinga
515fc73b79 net: tcp: Correctly handle partial duplicate buffered out of order data
TCP is a streaming protocol, this means it can set the packet boundary
at an arbitrary location. Therefor a re-transmitted packet may have the
packet boundary at a different location from the original missing segment.

The reordering logic should be able to deal with this situation and
throw away the overlapping data. Now also for data that needs to be added
to the existing queue

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-01 10:38:28 +00:00
Sjors Hettinga
e255f1a9c7 net: tcp: Correctly handle partial duplicate out of order data
TCP is a streaming protocol, this means it can set the packet boundary
at an arbitrary location. Therefor a re-transmitted packet may have the
packet boundary at a different location from the original missing segment.

The reordering logic should be able to deal with this situation and
throw away the overlapping data.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-01 10:38:28 +00:00
Sjors Hettinga
f2d94a7f5c net: tcp: Implement a fast retransmit algorithm
Instead of waiting for the retransmit timeout, retransmit as soon as
missing data is deduced based on a triple-duplicate ACK.

Increase the number of buffers in the testcase, to allow for at least 4
packets in flight to trigger the triple-duplicate ACK.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-01 10:38:28 +00:00
Sjors Hettinga
9d772efbbc net: tcp: Send a duplicate ACK for out of order data
When out of order data is received, send out a duplicate ACK to notify
the sender that there is data received out of sequence, so it can
retransmit the missing section.

Also avoid sending acknowlegdement to acknowlegdement messages that are
having an out of order sequence number.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-09-01 10:38:28 +00:00
Florian Grandel
856c985239 net: l2: ieee802154: security: fix several bugs
The IEEE 802.15.4 security implementation had several severe bugs:
* A regression introduced by 6ea225e34a
  (net/ieee802154: Finally removing usage of ll_reserve in L2)
  introduced a buffer leak (reading/ writing beyond the end of the frame
  buffer) and led the security implementation to malfunction in all but
  the simplest cases (i.e. encryption/authentication: none).
* Encryption vs. authentication modes were not properly implemented i.e.
  encryption was always active even if not required by the chosen
  encryption level.
* Nonce endianness was not correctly handled on decryption of packets
  which led to authentication failures.
* The frame counter was not checked for overflows.
* The encryption output buffer limit (out_buf_max) was not correctly set.
* Setting an invalid key mode led to a NULL pointer deref.
* We use CCM rather than CCM* as crypto.h does not provide access to
  CCM*. CCM does not support encryption-only operation, though. This
  condition was not checked by the code.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-31 21:52:37 +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
Florian Grandel
43a7695dfe net: l2: ieee802154: publish re-usable constants
Some IEEE 802.15.4 specification constants must be made available in
userspace as they will be needed to use IEEE 802.15.4 RAW/DGRAM sockets
which will be introduced in this changeset.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-31 21:52:37 +00:00
Florian Grandel
705a8b6ea1 net: ieee802154: introduce consistent MTU definition
Zephyr IEEE 802.15.4 drivers and L2 stack use the same constant names
for different MTU definitions. The intent of this change is to introduce
a consistent MTU definition which can be used everywhere in zephyr to
avoid confusion, bugs and name conflict.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-31 21:52:37 +00:00
Krishna T
2a9b06b7c6 wifi_mgmt: Fix checkpatch warnings
Checkpatch says "else after return is not useful".

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-31 21:49:47 +00:00
Krishna T
e2db4e690e wifi_shell: Fix the duplicate tag CI warning
Newly introduced Coverity scan throws a warning about duplicate tag as
per MISRA coding standards, so, use a unique tag name in the existing
code for "shell".

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-31 21:49:47 +00:00
Krishna T
bcf7585429 wifi_shell: Rename Wifi to Wi-Fi
This is the standard.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-31 21:49:47 +00:00
Krishna T
0f126a7adb wifi_mgmt: Add new API for Wi-Fi statistics
Networking statistics framework is used to define handler and the data
structure, Wi-Fi management layer implements the handler and also adds a
new offload API to get statistics from the Wi-Fi driver.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-31 21:49:47 +00:00
Krishna T
1ecca68886 wifi_shell: Add new security methods
Add PSK_256, SAE and MFP settings.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-31 21:49:47 +00:00
Krishna T
b5b11bbff0 wifi_mgmt: Add new API for Wi-Fi status
A new net_mgmt command and event are added for interface status,
depending on the implementation the status can be returned when polled
or an unsolicited event can be send by driver whenever there is a change
in status.

This is planned to be implemented only by upcoming wpa_supplicant,
offload implementation is left for driver developers.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-31 21:49:47 +00:00
Krishna T
0e5c900400 wifi_mgmt: Implement checks for new security types
Extend checks for PSK-256 and SAE.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-31 21:49:47 +00:00
Gerard Marull-Paretas
0cd311c4a1 include: fix files using legacy include paths
Some files were still using the already deprecated include path, fix
this.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-08-31 06:49:00 -04:00
Ola Tangen Kulseng
00aa80bb8c net: lwm2m: thread safety in the rd client
Used the mutex in the client to protect the state transitions of
client.state.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-08-31 10:42:02 +02:00
Ola Tangen Kulseng
0a87c2d0d0 net: lwm2m: Thread safe lwm2m registry
Created the mutex registry_lock to:
- protect read and write operations
- protect the registry.
Only partially finished as the functions like lwm2m_engine_get_obj
warrants a larger refactoring to completely thread safe the registry.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-08-31 10:42:02 +02:00
Juha Heiskanen
534c7f2246 net: lwm2m: Fixed LwM2M message wrong error response
LwM2M was not reported properly case when message "Accept"
coap option was not not supported. In that case LwM2M transport
specification define 4.06 "Not Accepted"

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-08-31 10:41:49 +02:00
Ola Tangen Kulseng
24a84ae743 net: lwm2m: Documentation of the lwm2m engine
I've provided documentation for the API's
- lwm2m_registry.h
- lwm2m_engine.h

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-08-30 14:19:05 +00:00
Veijo Pesonen
862cabc48c net: lwm2m: Fixes FOTA update result code
The update result is supposed to indicate success only after a firmware
update has been applied. The bug here was that the success was reported
already when the update image download was done.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-08-29 11:38:53 +02:00
Gerard Marull-Paretas
a202341958 devices: constify device pointers initialized at compile time
Many device pointers are initialized at compile and never changed. This
means that the device pointer can be constified (immutable).

Automated using:

```
perl -i -pe 's/const struct device \*(?!const)(.*)= DEVICE/const struct
device *const $1= DEVICE/g' **/*.c
```

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-08-22 17:08:26 +02:00
Neil Armstrong
fe7ffcf2e8 tls_credentials: add Trusted Credential storage backend
This adds a Trusted Credential storage backend using the PSA
Protected Storage API, permitting storage of the credentials
offering a trusted long-term storage with integrity checks.

This implementation tries to fit the actual tls_credentials
implementation, with some slight differences:
- the buffer pointer returned by credetial_get & credential_next_get
  is dynamically allocated and differs from the one given to
  tls_credential_add since it's extracted from the storage at runtime.

Signed-off-by: Neil Armstrong <narmstrong@baylibre.com>
2022-08-18 12:33:07 +02: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
Juha Heiskanen
b0c794305c net: lwm2m: Fix to Queue update process triggering
Fix that broken Queue client for stop looping
"ENGINE_REGISTRATION_DONE_RX_OFF" state.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-08-18 10:19:11 +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
405e3d757f net: tcp: Add exponential backoff for ZWP probing
Persist timer should implement exponential backoff, as per RFC 1122:

    The transmitting host SHOULD send the first zero-window
    probe when a zero window has existed for the retransmission
    timeout period (see Section 4.2.2.15), and SHOULD increase
    exponentially the interval between successive probes.

Implement this, by following Linux behaviour, and simply double the
timeout or each probe transmission.

Additionally, prevent reseting the persist timer in case an
acknowledgment is received with zero window size, and the timer is
already running.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-15 08:21:29 +00:00
Robert Lubos
9a090d434c net: tcp: Use default MSS value if no MSS option is present
In case peer does not send the MSS option, the TCP stack should assume
default peer MSS value of 536, as per RFC 1122:

    If an MSS option is not received at connection setup, TCP
    MUST assume a default send MSS of 536.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-12 11:33:35 +02:00
Juha Heiskanen
cec0ea0dce net: lwm2m: Fix Update registration issue
Client Registration update process may be reject by server
and this commit fix a case that it will jump to new state
which send registration message. Earlier RD client try
allocate message before only possible one was released.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-08-11 12:16:56 +02:00
Juha Heiskanen
6bfebe5fc3 net: lwm2m: Fix Queued data buffer send at wakeup from idle
Queue mode without TLS cache was loosing buffered messages at
wake-up process from idle state. Now client context linked list
are initialized at rd client start process only 1 time.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-08-11 12:16:56 +02:00
Eduardo Montoya
ee2a8d9a64 net: openthread: allow to configure OPENTHREAD_MESSAGE_BUFFER_SIZE
Add `OPENTHREAD_CONFIG_MESSAGE_BUFFER_SIZE` to Kconfig.

Also set the number of children to minumum possible for MTD builds
in order to save some resources (~512B of RAM).

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-08-10 12:01:18 +02:00
Gerard Marull-Paretas
b74a22924e net: lib: config: remove NET_CONFIG_IEEE802154_DEV_NAME
Remove NET_CONFIG_IEEE802154_DEV_NAME in favor of DT based choice using
zephyr,ieee802154.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-08-10 11:57:34 +02:00
Gerard Marull-Paretas
e2bea3b008 net: lib: config: ieee802154: use zephyr,ieee802154
Use DT choice zephyr,ieee802154 as CONFIG_NET_CONFIG_IEEE802154_DEV_NAME
is being phased out.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-08-10 11:57:34 +02:00
Robert Lubos
d18cdad2fc net: zperf: Use zsock_* API instead of POSIX socket API
In order to make the zperf to work regardless of the POSIX configuration
in the system, convert the socket API usage into Zephyr's native
zsock_* API.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-10 11:15:21 +02:00
Robert Lubos
2091b34820 net: zperf: Extract zperf into library
Make a library out of the zperf shell sample. This makes to enable the
module in any application, not only the dedicated sample.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-10 11:15:21 +02:00
Robert Lubos
2670fc9b67 net: ppp: Fix NULL pointer dereference in FSM module
ppp_send_pkt() function can be called with NULL fsm parameter (when
PPP_PROTOCOL_REJ packet was sent), howerver this was not taken into
consideration when ppp_context was retrieved. In result, this could lead
to NULL pointer dereference an crash.

Fix this, by moving the ppp_context extraction directly where it's
actually used (PPP_CODE_REJ packet type handling). In such case, fsm
point should not be NULL.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-10 11:06:24 +02:00
Stephanos Ioannidis
8fe855f166 net: dns: Check query index in dns_read
This commit adds a check, in the `dns_read` function, before
dereferencing the query index returned by the `dns_validate_msg`
function.

This fixes the warnings generated by the GCC 12 such as:

  error: array subscript -1 is below array bounds of
  'struct dns_pending_query[5]' [-Werror=array-bounds]

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-08-09 14:20:28 +02:00
Daniel DeGrasse
0a3bf289b6 net: icmp: skip checksum calculation when possible
Skip IP header checksum calculation when the network interface reports
support for this feature.

Signed-off-by: Daniel DeGrasse <daniel.degrasse@nxp.com>
2022-08-09 12:29:18 +02:00
Krishna T
b754e63d1b net: ethernet: Add EAPoL ether type support
Wi-Fi protocol uses EAPoL ether type frames for authentication, so, add
support for that ether type so that they are not dropped.

Though we have NET_ETHERNET_FORWARD_UNRECOGNISED_ETHERTYPE to allow
unknown frames to be passed up the stack, but this might cause
performance penalty.

Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
2022-08-08 14:03:54 +02:00
Seppo Takalo
eafc4f875b net: lwm2m: Allow string and opaque data types to be empty
When string and opaque types are uninitialized, we should
allow their data length to be zero. However, most content
formatters seem to calculate the string length separately
so replace the pointer of empty data into a static string
that is guaranteed to be empty.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-08-08 11:27:16 +02:00
Andreas Chmielewski
7532a23dc9 net: lwm2m: Try to reuse registration in case of a network error
For most of the times it is not necessary to do a full registration
once a connection is established after a network error. This is in
particular not needed if lifetime is not yet expired and the server
does not refuse a registration update.

Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
2022-08-08 06:55:49 +01:00
Andreas Chmielewski
74a56b05a9 net: lwm2m: separate closing context from closing socket
Separate closing lwm2m context from closing socket. This patch is required
for the rd client to take more control over lwm2m context and the socket.
The goal is to close the socket and to keep the lwm2m context if this is
needed.

Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
2022-08-08 06:55:49 +01:00
Andreas Chmielewski
3cdff65eb0 net: lwm2m: Update registration only in good path
Registration should only be updated if update of the registration was
succesful.

Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
2022-08-08 06:55:49 +01:00
Robert Lubos
de55dbcbb1 net: tcp: Fix SYN handling after connection is established
According to RFC 793, ch 3.9 Event Processing, receving SYN flag after
the connection has been established is an error codition:

    If the SYN is in the window it is an error, send a reset, any
    outstanding RECEIVEs and SEND should receive "reset" responses,
    all segment queues should be flushed, the user should also
    receive an unsolicited general "connection reset" signal, enter
    the CLOSED state, delete the TCB, and return."

Currently TCP stack ignored such event, causing interoperability test
failures. Fix this, by verifying if the SYN flag is set in a packet in
any state other than TCP_LISTEN and TCP_SYN_SENT.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-05 15:17:09 +02:00
Florian Grandel
bb86f8b967 net: ip: build IEEE 802.15.4 L2 without IP support
While a previous change had already decoupled the IEEE 802.15.4 L2 from
IP upper layers, this only worked when at least one other interface of
the device supported IP.

This change removes this requirement and thereby fixes a build error
that occurred when disabling IP support while maintaining IEEE 802.15.4
L2 support.

Fixes: #48718

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-05 15:04:37 +02:00
Florian Grandel
a1a2107b42 net: ip: only start IP configuration on IP interfaces
net_if_up() unconditionally calls iface_ipv6_start() and
net_ipv4_autoconf_start(). This is not correct for interfaces that do
not support IPv4/v6.

This patch therefore introduces a check on the interface's flags before
proceeding.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-04 13:44:06 +02:00
Florian Grandel
6b09d0e791 net: l2: ieee802154: apply clang format
This change makes the files which are part of this changeset comply to
the project's coding style rules as defined in .clang-format.

This required addition of some forward declarations and additional
dependencies into header files as some of them depended on the order of
header inclusion which was changed due to alphabetical ordering of
includes.

Background: .clang-format states "SortIncludes:true" which will force
re-ording of include-statements which in turn might break the build if
header file inclusion is not order-independent.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-04 13:44:06 +02:00
Florian Grandel
dcb2ead52c net: l2: ieee802154: rename *fragment to *6lo_fragment
6LoWPAN fragmentation is not related to IEEE 802.15.4 proper but is just
part of its IPv6-specific L3-adaptation layer. To make this more obvious
we rename all resources related to 6LoWPAN fragmentation.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-04 13:44:06 +02:00
Florian Grandel
2e5e761074 net: l2: ieee802154: decouple L2/L3 concerns
This change decouples the IEEE 802.15.4 (L2) layer from all IPv6 (L3)
concerns.

Applications may now choose to set CONFIG_NET_6LO=n and
CONFIG_NET_L2_IEEE802154=y at the same time.

Setting CONFIG_NET_6LO=n will build a vanilla IEEE 802.15.4-2006 specs
compliant L2 layer without any reference to 6LoWPAN or IPv6. This allows
application developers to design custom non-IP protocols on top of
IEEE 802.15.4-2006 and thereby makes the L2 layer much more re-usable.

Fixes #48585.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-04 13:44:06 +02:00
Florian Grandel
59be7bfb26 net: l2: ieee802154: improve inline comments
This change contains some merely editorial changes to inline comments
plus updates references from the IEEE 802.15.4-2003 spec to
IEEE 802.15.4-2006 which corresponds to the implementation level of
the module.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-04 13:44:06 +02:00
Florian Grandel
4dbaa170cf net: l2: ieee802154: Improve TODO marker consistency
Most existing TODO markers (as well as VSCode default settings) favor
TODO over ToDo - so let's make this a little bit more consistent in the
IEEE 802.15.4 module.

Signed-off-by: Florian Grandel <jerico.dev@gmail.com>
2022-08-04 13:44:06 +02:00
Juha Heiskanen
ca20462bcc net: lwm2m: Shell helper for pause and resume
Helper commit for test pause and resume.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-08-04 13:42:55 +02:00
Juha Heiskanen
ed5f3cdf06 net: lwm2m: LwM2M Pause and resume support
New API for suspend and resume LwM2M engine.
New event LWM2M_RD_CLIENT_EVENT_ENGINE_SUSPENDED for indicate
application that engine is suspended.

Simplify stack suspend and resume state same time for queue mode.

New CONFIG_LWM2M_RD_CLIENT_SUSPEND_SOCKET_AT_IDLE for enable skip socket
close at RX_OFF_IDDLE state that socket is only suspended and close is
called only when connection is resumed.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-08-04 13:42:55 +02:00
Veijo Pesonen
0b57ba8dcb net: lwm2m: remove EXPERIMENTAL-label from v1.1
Version 1.1 support is not experimental anymore.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-08-03 11:20:50 +02:00
Robert Lubos
5b34d25b69 net: context: Unregister connection for packet socket
Network connection was not unregistered properly for packet socket,
which resulted in dangling connection when net_context was dereferenced
(i. e. when packet socket was closed). This could lead to a crash on a
consecutive incoming packet.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-03 11:11:55 +02:00
Seppo Takalo
c3302d5f41 net: lwm2m: Allow observing of object instances and objects
Code was limiting observations to resources and
resource instances without any reason.
Also if resource is written, and the whole object is observer
it should trigger. Path does not have to be matching on the
same level, if parent is observed.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-08-01 18:12:33 +01: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
b5b5c29f2d net: pkt: Add ll_proto_type field
The L2 protocol type information is not carried to the upper layers.
This is problematic for packet sockets, as the address structure in
recvfrom() is supposed to provide this information.

Fix this by adding ll_proto_type field in the net_pkt structure.
Set the protocol type in the Ethernet L2 when packet is processed.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-01 18:02:20 +02:00
Robert Lubos
0023ba45ee net: pkt: Add missing l2_processed flag cloning
l2_processed flag was not copied when a packet was cloned.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-08-01 18:02:20 +02:00
Tomislav Milkovic
12dd0290fb net: l2: ieee802154: Fix removing short src address filter
Driver function was called with wrong parameter, which resulted
in filter being added instead of removed

Signed-off-by: Tomislav Milkovic <milkovic@byte-lab.com>
2022-08-01 18:00:29 +02:00
Stephanos Ioannidis
532d2671be net: coap: Remove resource pointer NULL check
This commit removes the resource pointer NULL check inside the resource
enumeration loop of the `coap_well_known_core_get` function because the
expression `(resource + 1)` will never evaluate to NULL (aka. 0).

This fixes the "comparison will always evaluate as ‘true’ for the
pointer operand" warning generated by the GCC 12.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-08-01 10:47:23 +02:00
Sjors Hettinga
fafcbf59b9 net: tcp: Implement randomized retransmission timeouts
It can happen that two similar stacks enter a retransmission cycle
due to a packet collision. If the transmission timeout is the same
both stacks will retry at the same moment resulting in another
collision.

By introducing a randomized retry timeout, the chance of
a second collision is reduced and it reduces furter the more
retransmissions occur.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-08-01 10:33:24 +02:00
Sjors Hettinga
ea4f10fc58 net: tcp: Basic exponential backoff implementation
Apply an exponentially increasing wait time between tcp retries. This
is a good balance between reacting fast to single lost packets and reduce
the network load when an outage takes a little longer. It also allows the
connection to survive a longer interruption with less retransmissions.

Update the test to accommodate for the increased socket closure timeout

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-08-01 10:33:24 +02:00
Hristo Mitrev
fc7287166c net: net_if.c: Fix build warning
Fix compilation warning in GCC 12 when it's not obvious that we want to
compare the adresses of the first elements of two arrays

Signed-off-by: Hristo Mitrev <hr.mitrev@gmail.com>
2022-07-30 01:43:22 +09:00
Bartosz Golaszewski
7cddc5a6a3 net: ipv6: use static inlines where it makes sense for stubs
If we're disabling certain features and instead providing function stubs,
it doesn't make sense to use macros for those routines that return values
that the user may check unless we want to provide them with vague errors
like:

src/coap-server.c:101:55: error: expected expression before ';' token
  101 |  ret = net_ipv6_mld_join(iface, &mcast_addr.sin6_addr);

When a function we're mocking up returns a value, use a static inline
stub.

Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-07-27 18:44:07 +02:00
Seppo Takalo
b10f2c13ed net: lwm2m: Remove two useless macros
These two macros just change the name of function call
* NOTIFY_OBSERVER
* NOTIFY_OBSERVER_PATH

I don't see any benefit of those, so I dropped them.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-07-26 23:23:34 +00:00
Andriy Gelman
a3cdb2102c net: route: Fix pkt leak if net_send_data() fails
If the call to net_send_data() fails, for example if the forwading
interface is down, then the pkt will leak. The reference taken by
net_pkt_shallow_clone() will never be released. Fix the problem
by dropping the rerefence count in the error path.

Signed-off-by: Andriy Gelman <andriy.gelman@gmail.com>
2022-07-25 15:14:58 +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
Ola Tangen Kulseng
1563d4a0c3 net: lwm2m: Default ssid
Created the variable CONFIG_LWM2M_SERVER_DEFAULT_SSID to be
the default ssid when not using bootstrap. Needed for access control.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-07-15 10:10:16 +02:00
Ola Tangen Kulseng
e05bcefedb net: lwm2m: Access control object
Implementation of the access control object. Core object (obj_id 2).
If used without bootstrap, the default value in
CONFIG_LWM2M_SERVER_DEFAULT_SSID will be used as access control owner.
Enable/disable ac control with CONFIG_LWM2M_ACCESS_CONTROL_ENABLE.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-07-15 10:10:16 +02:00
Johann Fischer
f7c9f328a4 different subsystems: use unsigned int for irq_lock()
irq_lock() returns an unsigned integer key.
Generated by spatch using semantic patch
scripts/coccinelle/irq_lock.cocci

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
2022-07-14 14:37:13 -05:00
Eduardo Montoya
e38c518540 net: openthread: fix mbedtls config when SRP is enabled
SRP feature requires `MBEDTLS_ECP_DP_SECP256R1_ENABLED` and
`MBEDTLS_HMAC_DRBG_ENABLED`.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-07-14 10:31:56 +02: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
romain pelletant
3908b9dc74 net: lwm2m: Add Event Log object
Event Log object (ID:20) from OMA LwM2M support added

Signed-off-by: romain pelletant <romainp@kickmaker.net>
2022-07-13 10:19:26 +02:00
Kiril Petrov
a4557a46b8 net: lwm2m: Pass client_ctx to observe callback
In case LWM2M cient wants to change attrs of observed obj,
it needs pointer to client_ctx.

For example:
On observer add, wants to change pmin for some obj path to 1s:

static void observe_cb(enum lwm2m_observe_event event,
		struct lwm2m_obj_path *path, void *user_data)
{
	struct lwm2m_ctx *ctx = (struct lwm2m_ctx *) user_data;

	switch (event) {
	case LWM2M_OBSERVE_EVENT_OBSERVER_ADDED:
		lwm2m_engine_update_observer_min_period(ctx, "3347", 1);
	...
}

Signed-off-by: Kiril Petrov <retfie@gmail.com>
2022-07-11 09:32:18 +00:00
Simen S. Røstad
92eb309918 net: lib: lwm2m: Give Kconfig choices symbol names
Give Kconfig choices symbols names so that they can be redefined in
applications that wants to alter the choice's default value without
setting it in the project configuration.

Signed-off-by: Simen S. Røstad <simen.rostad@nordicsemi.no>
2022-07-11 11:03:41 +02:00
Robert Lubos
815ebc316e net: openthread: Move glue code into module directory
Move OpenThread's glue code along with the Kconfig files that configure
OpenThread stack itself into module directory.

Update the maintainers file to reflect this change.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-07-11 11:00:12 +02:00
Anas Nashif
0aefa654da net: add mising braces to single line if statements
Following zephyr's style guideline, all if statements, including single
line statements shall have braces.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-07-06 11:00:45 -04:00
Juha Heiskanen
d4bf2ad6cc net: lwm2m: Fix socket offload and native TLS conflict
Removed auto select from LWM2M_DTLS_SUPPORT
* TLS_CREDENTIALS
* NET_SOCKETS_SOCKOPT_TLS
* NET_SOCKETS_ENABLE_DTLS

LwM2M stack shouldn't enforce these options as they
are not needed with socket offloading.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-07-06 11:28:19 +02:00
Andreas Chmielewski
363e2f3014 net: coap: make coap vars configurable
COAP_DEFAULT_MAX_RETRANSMIT and COAP_DEFAULT_ACK_RANDOM_FACTOR
should be configurable to determine the max transmission
timeout of a CoAP packet.

Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
2022-07-05 21:56:34 +00:00
Eduardo Montoya
848fd44518 net: openthread: enable default software tx security in 1.3
Make sure MAC software transmission security is enabled by default
for Thread 1.3 builds as well.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-07-05 15:40:14 +00:00
Juha Heiskanen
ad5492721a net: lwm2m: Fixed crash at LwM2M registration timeout
LwM2M context close moved to thread safe place when RD client
run state machine.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-07-05 14:19:24 +02:00
Ola Tangen Kulseng
9be4fd0bbb net: lwm2m: Refactor of engine, message handling
Created the file lwm2m_message_handling.c, to include all
code pertaining to CoAP and allocation and deletion of messages
in general.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-07-05 13:50:26 +02:00
Ola Tangen Kulseng
365efa0f6a net: lwm2m: Refactoring of engine, observation
Created the file lwm2m_observation.c, to include
all code maintaining observations and parameter handling.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-07-05 13:50:26 +02:00
Ola Tangen Kulseng
02fed0b22e net: lwm2m: Refactoring of lwm2m_engine.c
Created the file lwm2m_registry.c to include the
getters and setters of values and the creation
and deletion of all lwm2m objects, resources
and instances. Refactored the registry part
of lwm2m_engine.h into lwm2m_registry.h.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-07-05 13:50:26 +02:00
Veijo Pesonen
94b81664e4 net: lwm2m: default stack size with SenML CBOR
SenML CBOR data is stored statically in RAM and does not use process
stack.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-07-04 16:20:03 +02:00
Øyvind Rønningstad
c1a9866c86 west.yml: Update zcbor to v. 0.5.1
lwm2m: Regenerate lwm2m_senml code from the CDDL description.
Reapply manual changes.
Create a sh script to perform the regeneration.

tests: zcbor_bulk: Adapt to zcbor 0.5.1
zcbor_new_decode_state() now has no return value.

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
2022-07-04 15:13:42 +02:00
Andrei Emeltchenko
8dda6b8c37 net: coap: Remove unneeded statement
Assignment is not needed.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-30 10:34:40 +02:00
Veijo Pesonen
9bf570eaba net: lwm2m: Fixes SenML CBOR composite read
Path list was replaced accidentally with free list during refactoring.
This change does fix the issue.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-06-29 10:29:27 +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
Andrei Emeltchenko
def6041fb0 net: ipip: Remove unused variable
Remove masked with ARG_UNUSED() unused variable.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-27 08:51:18 -05: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
Lukasz Maciejonczyk
80eca5f7b4 net: openthread: align otPlatSettingsSet with new interface contract
The new interface contract guarantees that OpenThread stack uses
otPlatSettingsSet only for aKey which has at most one value at time.
This implies the simplification for key name used by settings subsystem
and decreases the count of records written each time when the value
for specific key is updated. In result non-volatile memory can be used
more efficiently.

It relates to zephyrproject-rtos/openthread commit: ed665e9 .

We still need to make sure that old entries are being removed for the
case with DFU.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2022-06-27 12:47:36 +02:00
Lukasz Maciejonczyk
cc9caf4b22 net: openthread: add option for setting Thread v1.3
Make Thread v1.3 configurable.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2022-06-23 15:52:34 -05:00
Andrei Emeltchenko
ce76beecc3 net: lwm2m: Remove unused variable
Remove unused variable.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-23 15:43:59 -05: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
Andrei Emeltchenko
87d5a6b1d7 net: gptp_mi: Remove unused variables
Remove unused variables and assignments.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-23 07:18:25 -04:00
Andrei Emeltchenko
f82fb0cb55 net: gptp: Remove unneeded variables
Remove unused variable and assignments.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-23 07:18:25 -04:00
Robert Lubos
ef6770f22b net: tcp: Avoid unnecessary packet cloning on the RX path
So far, TCP cloned a packet with data on an RX path for the application,
leaving the original packet intact. This isn't really needed, as the
original packet is unconditionally freed later anyway, so the TCP can as
well simply queue the original packet for the application, while
informing the network processing core, that the packet was consumed by
the TCP layer.

This allows to improve the download throughput even further, since the
CPU don't waste time on needles packet copying.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-06-23 11:10:34 +02:00
Robert Lubos
5a05ac8fc9 net: tcp: Increase default NET_TCP_TIME_WAIT_DELAY value
The current default of 250ms appears to be too low in case connection
teardown takes place in lossy networks - in case of FIN packet
retransmission, the connection on the Zephyr side could have already
been dismissed due to low TIME_WAIT state delay, resulting in ICMP
Destination Unreachable replies.

Increase the default value to 1500ms - this is still pretty low, but at
least gives the peer some time to retransmit the FIN packet.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-06-23 11:08:36 +02:00
Robert Lubos
2bd00e65ba net: tcp: Acknowledge FIN packets in TIMED_WAIT state
In case TCP stack enters TIMED_WAIT state (after receiving FIN/ACK reply
from peer), it should stil be ready to reply with ACK for any
consecutive FIN attempts. Othewise, in case the final ACK from Zephyr
side is lost, the connection is not properly closed on the other end,
and peer keeps retransmitting the final FIN packet.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-06-23 11:08:36 +02:00
Robert Lubos
28fb1a5f39 net: tcp: Prevent Silly Window Syndrome
Implement a mechanism, according to RFC 813, which allows to prevent so
called "Silly Window Syndrome" - a scenario where the TCP receiver keeps
reporting small window sizes in the acknowledgments, effectively
limiting the connection throughput. This allows to improve performance
in low-buffer configurations, where the maximum window size is small,
and the issue was hitting quite often.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-06-23 11:08:18 +02:00
Robert Lubos
e03e4d5ad1 net: openthread: Fix build with NET_MGMT_EVENT_INFO disabled
In case NET_MGMT_EVENT module was enabled but w/o NET_MGMT_EVENT_INFO,
the OpenThread integration layer failed to build as the "info" field in
the net mgmt callback structure is not available then.

Fix this by conditionally enabling code processing the event only if
NET_MGMT_EVENT_INFO is enabled. Otherwise, print a warning, as the event
is not really useful if no address information is provided.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-06-23 11:07:46 +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
Andrei Emeltchenko
b970c4daef net: capture: Remove unneeded variable
Remove unused remote_addr_len variable.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-22 12:28:35 +02:00
Andrei Emeltchenko
3d42168c74 net: ipv4: Remove double assignment
Remove double assignment of cfg variable.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-22 12:28:35 +02:00
Andrei Emeltchenko
e0e1a12eba net: ipv6: Remove double assignment
Value of nexthdr is already assigned several lines above.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-22 12:28:35 +02:00
Andrei Emeltchenko
c27b72b331 net: ethernet: Remove double assignment
Variable type would be assigned at the block end.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-22 12:28:35 +02:00
Andrei Emeltchenko
77c694178f net: ppp: Fix stored value never read warning
Move declarations to the debug block where they are actually used.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-22 12:28:35 +02:00
Sjors Hettinga
4243e8e99c net: tcp: Do not capture tx_sem during retransmission
As the stack can safely keep allocating data during retransmission mode
there is no need to take the tx_sem during retransmission any more.

Data stored in the send_data buffer will be transmitted upon the ack of
the data for which an ack is pending. This the application being fully
stalled when the TCP connection enters retransmission mode.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-22 12:25:40 +02:00
Sjors Hettinga
17f94d3f96 net: tcp: Revert: Do not accept new data in retransmission mode
After the window_full function has been fixed by looking at the
send_data_total instead of the unacked_len. There is no risk
in sending data in transmission mode.

This reverts commit 0088aaefa0.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-22 12:25:40 +02:00
Ola Tangen Kulseng
38628f409e net: lwm2m: Add LwM2M shell commands for start&stop
Added start, stop and update to the shell.
Refactored the event_cb of the rd_client_info struct into the ctx,
as it was needed in the shell script.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-06-22 12:17:52 +02:00
Ola Tangen Kulseng
3e50624e39 net: lwm2m: Added commands to the lwm2m_client shell
Added read, write and execute commands to the shell.

Signed-off-by: Ola Tangen Kulseng <ola.kulseng@nordicsemi.no>
2022-06-22 12:17:52 +02:00
Juha Heiskanen
6d42ded565 net: lwm2m: LwM2M message allocation update
Allocated own message buffer for RD client interface.
This helps to cover if all messages are queued and need to do
registration or update.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
(cherry picked from commit 8dca91109d73a4a697e074c58ee9430d56c01a51)
2022-06-20 09:13:41 -04:00
Juha Heiskanen
ad1960625a net: lwm2m: Fix Possible Notification send blocker
If Notification build fail there was possible that Notification
are blocked after failure.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
(cherry picked from commit 6dfa242c7d891b3458ab88df46b69b3a9621ee82)
2022-06-20 09:13:41 -04:00
Juha Heiskanen
e4ce689de2 net: lwm2m: Coap Pending clear update
Fixed couple possible place for leak Coap pending entry.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
(cherry picked from commit 3c175951383be56fa9c1451845a15b66df41ff64)
2022-06-20 09:13:41 -04:00
Seppo Takalo
4a8efbb1bc net: lwm2m: Allow longer lifetimes than uint16_t
Lifetimes are really 32 bit values, so the limitation
did not make sense, and it did not allow 24 hour lifetime.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-06-20 10:25:41 +02:00
Krzysztof Chruscinski
c5f2cdef09 logging: Remove logging v1 from the logging
Remove v1 implementation from log_core and all references in the tree.
Remove modules used by v1: log_list and log_msg.
Remove Kconfig v1 specific options.
Remove Kconfig flags used for distinction between v1 and v2.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-06-16 10:51:15 -04:00
Veijo Pesonen
fbef82c9c0 net: lwm2m: SenML JSON bootstrap exceptions
In bootstrap mode write to a non-exisisting optinal resource must not
cause an error.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-06-14 09:31:23 +02:00
Veijo Pesonen
a5eae6f898 net: lwm2m: adds preferred content...
...format to bootstrap registration message with LwM2M v1.1.

SenML CBOR takes precedence, followed by SenML JSON and OMA TLV.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-06-14 09:31:23 +02:00
Veijo Pesonen
db602fd81d net: lwm2m: Missing optional resource does not ...
...trigger write to the error log

Uses debug-level instead.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-06-14 09:31:23 +02:00
Veijo Pesonen
7f54aea934 net: lwm2m: SenML CBOR opaque write fixed
Write to an opaque resource failed and it has been fixed. Support for
blockwise transfer is still missing.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-06-14 09:31:23 +02:00
Veijo Pesonen
4177aa21ec net: lwm2m: SenML CBOR bootstrap exceptions
In bootstrap mode write to a non-exisisting optinal resource must not
cause an error.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-06-14 09:31:23 +02:00
Jedrzej Ciupis
adca70c0fa net: lib: openthread: use ieee802154_txpwr property
This commit aligns openthread radio platform to use `ieee802154_txpwr`
of the packet to transmit instead of setting power through a separate
API call, if possible.

Signed-off-by: Jedrzej Ciupis <jedrzej.ciupis@nordicsemi.no>
2022-06-14 09:30:43 +02:00
Jedrzej Ciupis
644da741f4 net: pkt: add IEEE 802.15.4 TX power field
This commit extends the `struct net_pkt` structure with
`ieee802154_txpwr` field that contains signed value of the desired
transmission power of a IEEE 802.15.4 frame in dBm.

Signed-off-by: Jedrzej Ciupis <jedrzej.ciupis@nordicsemi.no>
2022-06-14 09:30:43 +02:00
Andrei Emeltchenko
a4fe0edfdc net: dns: Return error code
Return ret error code instead of always returning zero causing
warnings:

...
subsys/net/lib/dns/resolve.c:975:6: warning: variable 'ret' set but
not used [-Wunused-but-set-variable]
        int ret = 0;
            ^
...

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-13 12:11:54 +02:00
Andrei Emeltchenko
4874910465 net: dns: Remove unused variable
Fix compilation warnings:
...
subsys/net/lib/dns/dns_pack.c:548:6: warning: variable
'remaining_size' set but not used [-Wunused-but-set-variable]
        int remaining_size;
            ^
...

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-13 12:11:54 +02:00
Andrei Emeltchenko
be2340ab96 net: net_context: Remove double assignment
Remove double assignment, the value is stored in initialization.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-13 12:11:54 +02:00
Andrei Emeltchenko
766358461c net: lwm2m: Fix NULL pointer dereference
It does make sense to goto to cleanup part.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-10 09:47:05 +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
Markus Rekdal
3d8f938929 net: lwm2m: Fix range of integers in SenML CBOR
This fixes a minor bug that caused an error if one attempted to encode
or decode INT64_MIN in SenML CBOR

Signed-off-by: Markus Rekdal <markus.rekdal@nordicsemi.no>
2022-06-09 11:32:01 +02:00
Markus Rekdal
0006f2c93e net: lwm2m: Fix decoding of objlnk in SenML CBOR
This fixes a bug in the decoding of objlinks. Without this the object
instance id is not retrieved correctly as it tries to read the second id
starting from the colon.

Signed-off-by: Markus Rekdal <markus.rekdal@nordicsemi.no>
2022-06-09 11:32:01 +02:00
Seppo Takalo
e0296ca0b9 net: lwm2m: Allow initializing opaque and string data to zero length
By default, any string or opaque data that LwM2M engine initializes
sets data lenght to same value as given buffer length for that
resource.

However, on run time, engine keeps track how much data is written
to each resource, so when reading from any resource, should only
return data that has been written there. But uninitialized resources
return the content of the whole buffer.

Fixed the problem by introducing macros INIT_OBJ_RES_LEN(),
INIT_OBJ_RES_MULTI_DATA_LEN() and INIT_OBJ_RES_DATA_LEN() that
allows you to give the amount of data existing in buffer when
the resource is initialized. This sets the data_len and max_data_len
variables correctly.

Also introduced new functions lwm2m_engine_get_res_buf() and
lwm2m_engine_set_res_buf() that distinct between data size and
buffer size. Deprecated the previous functions
lwm2m_engine_get_res_data() and lwm2m_engine_set_res_data()

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-06-09 11:30:37 +02:00
Sjors Hettinga
e3b8fad9fa net: tcp: Fix accidental removal of data from send_data
In the function net_tcp_queue_data. When an -ENOBUFS by
tcp_send_queued_data is returned, it throws away the whole block of size
len from the send_data. If the len is > MSS, it could happen that the
first section is transmitted, but at the second an -ENOBUFS occurs.
In that case the data is transmitted, but later on removed from the
send_data.

To circumvent this problem, check if the len + unacked_len is smaller
then the send_data_total. If so, the data can safely be removed from
send_data. Otherwise, just pretend the transmission went OK. The
acknowledgment and retransmit path will eventually take care of it.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-07 18:55:44 +02:00
Sjors Hettinga
ebf8b6d3da net: tcp: Fix the polling implementation with corrected window filling
The window full computation was corrected to use the send_total instead
of the unacked_len. This conflicted with the new polling implementation
due to the moment when these values are changed.

Move taking the tx_sem outside of tcp_send_queued_data to handle the
-ENOBUF situation properly in case called from net_tcp_queue_data.
net_tcp_queue_data removes data from the send_data in case the
transmission failed with -ENOBUF. This cause the buffer to be not full
any more.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-07 18:55:44 +02:00
Sjors Hettinga
d49d06735a net: tcp: Explicitly notify buffer allocation failures in retransmission
Log an error to explicitly log a failed buffer allocation in TCP
retransmission. This avoids silently failing retransmissions due to
repeating buffer allocation failures.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-07 18:55:44 +02:00
Sjors Hettinga
0a9b2ed391 net: tcp: Avoid new packets from causing killing the pending send_timer
When there was no room to transmit the a next packet to be transmitted,
the -ENOBUFS could cause the retransmission to fail.

Secondly the conn->unacked_len can be set to 0 in the retransmission
process, causing the subscribtion to the transmit timer to fail. Use the
variable send_data_total instead.

Make sure that is the send_data buffer becomes empty the send_timer is
cancelled, but make sure any pending data still keeps on being transmitted.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-07 18:55:44 +02:00
Sjors Hettinga
d74bd3d7d1 net: tcp: Avoid deadlock in updating the TCP receive window
The function tcp_data_get tries to update the TCP receive window using
net_context_update_recv_wnd. This function graps the context lock while
the tcp_data_get is called from a situation where it already has tcp lock
is already. Transmission actions do first grab the the context lock and
try to grab the tcp lock afterwards. The combination of both can cause a
deadlock.

By taking the shortcut to directly update the tcp receive window without
going through the net context, the context lock is not required avoiding a
possible deadlock situation.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-07 18:55:44 +02:00
Sjors Hettinga
f5679ab73e net: tcp: Use our MTU to determine the mss for transmission
In the existing the value received from the other side by the TCP options
is used as MSS for transmission. Since the MSS options are an
announcement rather then a negotionation, it is likely the receiver will
have a different and possibly bigger MSS than allowed by our side.
This allow potentially for different a MSS in the receive and transmit
path.

Directly using the received MSS could cause problems when our MSS is only
allowed to be small. At transmission, for that reason take the minimum of
the received MSS and our desired MSS to find a value compatible to both
sides of the link.

Rename the function to net_tcp_get_recv_mss to net_tcp_get_supported_mss
to better reflect its function in the new situation.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-06-07 18:55:44 +02:00
Andrei Emeltchenko
bdafd89c12 net: 6lo: Remove dead statement
Value stored to compressed_hdr_size is never read.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-07 11:54:20 +02:00
Andrei Emeltchenko
38b40f2ed1 net: utils: Remove dead statement
Value stored to needcolon is overwritten later before loop ends.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-07 11:54:20 +02:00
Juha Heiskanen
7ffc95c430 net: lwm2m: Composite Observation refactor
Json library parser modify data so thats why we can't parse same
data again. Now Composite observation handler parse SenML Json or
CBOR resource path which is given to new API composite Read API
which not need any new data parser.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-06-06 12:06:43 +02:00
Juha Heiskanen
2da8df8b7e net: lwm2m: Integrate JSON lib to LwM2M 1.0 JSON
Integrated updated JSON library to LwM2M 1.0 JSON.
Removed Old Json format default choice.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-06-06 12:06:43 +02:00
Juha Heiskanen
a9035ebe5e net: lwm2m: Integrate JSON lib to SenML-JSON
Integrated updated JSON library to SenML-JSON.
This integrate affect that Coap Block wise transfer is not
supported.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-06-06 12:06:43 +02:00
Berend Ozceri
a9376174cd net: websocket: Allow building with POSIX API
If the POSIX API is selected via the POSIX_API option, use the POSIX
headers instead.

Signed-off-by: Berend Ozceri <berend@recogni.com>
2022-06-05 14:48:52 +02:00
Eduardo Montoya
e6f3b8a296 net: openthread: fix wrong configuration
Fix wrong OpenThread config.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-06-05 14:42:33 +02:00
Andriy Gelman
f12f9d5e95 net: pkt: Fix leak when using shallow clone
Currently a shallow clone of a packet will bump the reference count on
all the fragments. The net_pkt_unref() function, however, only drops the
reference count on the head fragment. Fix this by only bumping the ref
count on the head buf during shallow clone.

Only bumping the ref count of head is more in line with the idea that
head buf is not responsible for the fragments of its child.

Signed-off-by: Andriy Gelman <andriy.gelman@gmail.com>
2022-06-05 14:29:19 +02:00
Markus Rekdal
cf43c49b5f net: lwm2m: Fix decoding of objlnk
This fixes a bug in the decoding of objlinks. Without  this the object
instance id is not retrieved correctly as it tries to read the second id
starting from the colon.

Signed-off-by: Markus Rekdal <markus.rekdal@nordicsemi.no>
2022-06-05 14:27:39 +02:00
Marcin Niestroj
c00fdcb518 net: context: prevent truncating outgoing datagrams
Datagrams should either be fully sent or not sent at all if networking
buffers or network interface MTU does not allow that. So far the behavior
was to truncate outgoing packets, even for datagram sockets.

When there is not enough available payload buffer to fit all requested
data, fail if that happens for datagram socket.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2022-06-01 11:17:07 +02:00
Olof Winge
dea9343d61 net: ipv4: Accept unspecified src address if dst is broadcast
To be able to accept DHCP discover/request incoming packets the ip stack
neeeds to accept unspecified src addr if the destination is broadcast
address.

Signed-off-by: Olof Winge <olof@skyshaper.net>
2022-05-27 15:46:44 -07:00
Ryan Erickson
67598965fb lwm2m: software management: Fix URI value not being written
Create the URI resource when creating the object if
PULL support is enabled.

URI write callback should be post-write instead to ensure
the URI value is updated for the resource.

Signed-off-by: Ryan Erickson <ryan.erickson@lairdconnect.com>
2022-05-27 15:45:14 -07:00
Robert Lubos
0516d75d84 net: ethernet: Add Kconfig option to forward unrecognized EtherType frames
Add Kconfig option to the Ethernet L2 which allows to forward frames
with unknown EtherType further into the stack. This can be useful for
packet sockets, where further frame processing is application dependent.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-27 15:40:29 -07:00
Robert Lubos
eddb6c8111 net: sockets: packet: Remove obsolete TODO
It turns out that all of the items listed under TODO section for packet
socket implmeentation has been adressed over time, threfore remove the
obsolete TODO.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-27 15:40:29 -07:00
Robert Lubos
96cc85146d net: conn: Add proper processing of DGRAM packet sockets
Datagram AF_PACKET sockets were not processed properly by the net stack.
Instead of receving a packet already processed L2, and thus with L2
header trimmed, it was receiving a raw, unprocessed packet.

Fix this by calling net_packet_socket_input() for the second time, after
L2 has processed the packet. An updated connection handler module will
forward the packet correctly based on the corresponding socket type and
packet L2 processing status.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-27 15:40:29 -07:00
Robert Lubos
5ab0d54f79 net: context: Improve packet socket interface selection on sendto()
Currently, the packet socket implementation in net_context required that
netowrk interface to transmit the packet to was set on every sendto()
call. This spoils the whole idea of binding a socket. Fix this, by
checking first if the net_conext is already bound to a particular
interface, and if so, do not throw an error in case sll_ifindex field is
not a valid interface.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-27 15:40:29 -07: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
Marc Lasch
fa84da588d net: lib: lwm2m: Cancel firmware DOWNLOADED state with NULL byte
Allow to cancel a firmware update in DOWNLOADED state by writing a
NULL byte as described in the Firmware Update object version 1.1
(urn:oma:lwm2m:oma:5:1.1). Keep object version 1.0 mechanism with
an `empty string`.

Signed-off-by: Marc Lasch <marc.lasch@husqvarnagroup.com>
2022-05-23 10:17:52 +02:00
Sjors Hettinga
c668199b5d net: tcp: Correctly determine when the TCP transmit window is full
In the stack both unacked_len and send_data_total track the amount
of data for retransmission. send_data_total actually accounts the
total bytes in the buffer, where unacked_len is used to control the
retransmission progress.

Using unacked_len is sometimes reset to 0, this can lead to more data
being allowd in the send_data buffer. In worse case this can cause
depletion of the net buffers, causing a stall and crash of the connection.

The value send_data_total actually accounts the total amount of data in
the send_data buffer, so it is the proper value to used in the
tcp_window_full function.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-05-20 19:24:26 -07:00
Sjors Hettinga
2d824f4811 net: tcp: Removed copy of conn->unacked_len
In the function tcp_send_data, the variable conn->unacked_len in copied
into a local variable pos. This value is only used in one location and
used mixed with the original conn->unacked_len.

This fix removes pos and switches to use conn->unacked_len everywhere
to reduce the chance of confusion. This does not functionally change the
code.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-05-20 12:38:24 +02:00
Flavio Ceolin
ac2e13b9a1 net: tcp: Fix possible buffer underflow
Fix possible underflow in tcp flags parse.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2022-05-20 12:36:42 +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
d35d9a6158 net: tcp: Implement persistent timer for sending ZWP
Instead of sending ZWP from send context, when it is detected that
window is full due to zero-window, implement a proper persistent timer,
that is scheduled once zero-window is detected. The timer is responsible
for sending ZWP to the peer and is canceled once non-zero-window is
notified by the peer.

Additionally, in case peer reported zero-window, do not trigger
retransmission from net_tcp_queue_data(), as it won't be transmitted
anyway by the stack.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-18 11:09:17 +02:00
Robert Lubos
7eaacdaca6 net: tcp: Add semaphore indicating if transfer is possible
The semaphore is reset when TCP layer would normally reject transfer
request (either due to TX window being full or entering retransmission
mode). Once data is acnowledged, or the reatransmission is done, the
semaphore is set again.

Upper layers can monitor the semaphore with `k_poll()` instead of
waiting blindly before attempting to transmit again.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-18 11:09:17 +02:00
Veijo Pesonen
b18f93dbc4 net: lwm2m: Fix SenML CBOR input basename length
Server might send the whole path in the basename when doing composite
write.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-05-13 10:15:27 -05:00
Veijo Pesonen
082fe9733c net: lwm2m: Adds missing SenML CBOR range check
Adds a check that number of records to be encoded does not exceed the
maximum limit configured through Kconfig.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-05-13 10:15:27 -05: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
Robert Lubos
0b27f4b2f9 net: tcp: Report TCP errors through recv_cb()
Make use of the status argument in the recv_cb() callback function -
instead of blindly reporting ECONNRESET whenever TCP context is
dereferenced, indicate whether an actual error condition happened (by
setting respective errno value) or a graceful shutdown took place (by
setting status to 0).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-13 15:42:01 +02:00
Eduardo Montoya
78a2d237d0 net: openthread: add support for PSA MAC keys
Get actual keys from references when PSA crypto is enabled.
A more secure method should be implemented once 802.15.4 platforms
support other than clear text keys.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-05-13 13:27:04 +02:00
Eduardo Montoya
ef30cf58c1 net: openthread: implement otPlatRadioGetCslUncertainty
Implement the OpenThread API to retrieve the platforms CSL
Uncertainty.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-05-13 13:22:48 +02:00
Andrey Dodonov
bc0cf10757 net: tcp: Remove unused config NET_TCP_BACKLOG_SIZE
Remove NET_TCP_BACKLOG_SIZE from KConfig and from test,
because it's not present anymore in current version of TCP stack.

Signed-off-by: Andrey Dodonov <Andrey.Dodonov@endress.com>
2022-05-13 13:04:59 +02:00
Robert Lubos
5af3c6ca90 net: tcp: Fix possible deadlock in tcp_in()
After introducing SO_SNDBUF socket option, a possible deadlock situation
slipped into the TCP implementation. The scenario for the deadlock:

  * application thread tries to send some data, it enters
    net_context_send() which locks the context mutex,
  * internal context_sendto() blocks on a TX packet allocation, if the
    TX pool is empty rescheduling takes place,
  * now, if at the same time some incoming packet has arrived (ACK for
    example), TCP stack enters tcp_in() function from a different
    thread. The function locks the TCP connection mutex, and tries to
    obtain the SNDBUF option value. net_context_get_option() tries to
    lock the context mutex, but it is already held by the transmitting
    thread, so the receiver thread blocks
  * when TX packet is available again, the transmitting thread unblocks
    and tries to pass the packet down to TCP stack. net_tcp_queue_data()
    is called which attempts to lock the TCP connection mutex, but it is
    already held by the receiving thread. Both threads are in a deadlock
    now with no chance to recover.

Fix this, by obtaining the SNDBUF option value in tcp_in() before
locking the TCP connection mutex.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-11 11:04:22 +02:00
Robert Lubos
b8b5738809 net: openthread: Skip solicited-node mcast addresses creation
Thread network makes no use of Solicited-node multicast addresses,
thereby do no create them on the interface to save multicast address
entries for important ones.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-11 11:03:26 +02:00
Robert Lubos
7acafda858 net: openthread: Fix possible deadlock in net_mgmt handlers
There is a risk of deadlock in case net_if APIs are used from within
net_mgmt handlers as both module APIs are protected with their own
mutexes.

The scenario observed with OpenThread happend when
NET_EVENT_IPV6_ADDR_ADD/NET_EVENT_IPV6_MADDR_ADD events were processed.
The net_mgmt mutex is locked when both, an event handler is being
processed (from a separate net_mgmt thread) and when an event is raised
(for example when a new address is added on an interface). In case a
net_mgmt handler tried to use some mutex-protected net_if API, we could
end up in a deadlock situation - the net_mgmt would wait for the net_if
mutex to release, while some other thread (in this case main during
initialization) could wait within some net_if function, pending on
net_mgmt mutex to be released to notify the event.

Fix this, by preventing net_if APIs from being used from within OT
net_mgmt handlers.

Additionally, simplify the net_mgmt handlers logic, by making use of
additional info provided with an event. Instead of blindy assuming that
recently added address was the last on the list (which might not always
be the case, if addresses are added/removed dynamically), read the
actual address being added from the net_mgmt_event_callback structure.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-05-11 11:03:26 +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
Juha Heiskanen
9b7a36099f net: lwm2m: LwM2M timeout recovery
LwM2M engine is blocking new notification send.
Notification or Send timeout trig Reconnect and registration state.
Send/Notification  message is blocked if client is not connected.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-05-04 09:50:28 -05:00
Jarno Lamsa
ffa222725d net: lib: lwm2m: Don't create server object in bootstrap
When bootstrap is used, the server object shouldn't be autocreated.
Automatically creating object may cause problems after bootstrap
has been done and bootstrap server deletes and creates instances
for server object. In the next boot the auto-created server object
may have clashing server_id with the server object that the
bootstrap-server has created.
Also lifetime wasn't properly added to the registration message from
the server object.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-05-04 09:46:10 -05:00
Juha Heiskanen
3bf30ef292 net: lwm2m: LwM2M RD client start and stop update
Added return code for for lwm2m_rd_client_start() & lwm2m_rd_client_stop().

lwm2m_rd_client_start() return -EINPROGRESS when start is in progress and
0 for success.

lwm2m_rd_client_stop() return -EPERM when context is unknown and
0 for success.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-05-04 09:44:29 -05:00
Ole Morten Haaland
fc6f40964c net: if: Add method to set default interface
This complements the Kconfig possibility, and allows setting an
interface as default on runtime. Changing the default interface also
works around limitations when trying to use an offloaded interface
together with a native one.

Signed-off-by: Ole Morten Haaland <omh@icsys.no>
2022-05-02 10:57:05 +02:00
Veijo Pesonen
d8b7449b52 net: lwm2m: SenML CBOR key ordering
Keys' order - bn, n - might differ from the default due to
Length-First Map Key Ordering rules.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Veijo Pesonen
975d170792 net: lwm2m: use stack for SenML CBOR data
Formatter data are is shared between different threads.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Veijo Pesonen
a1bd90646e net: lwm2m: adds README
Includes instructions for generating the SenML CBOR encoder and
decoder.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Veijo Pesonen
98b22a1850 net: lwm2m: SenML CBOR optimisations
Regenerates the encoder and decoder. Treats integers and floating-point
values as separate entities instead of saying that those are numerical
values. Brings some memory savings.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Veijo Pesonen
b78dd2498a net: lwm2m: Sets ct to registration msg
Tells the server which content format is preferred in a registration
message.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Veijo Pesonen
4f76b194a4 net: lwm2m: empty CBOR array support
Makes possible to write an empty CBOR array if there are no SenML CBOR
records that needs to be written. This came up when trying to delete a
portfolio object instance.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Veijo Pesonen
60eaafe293 net: lwm2m: SenML CBOR gencode adaption
Generated code needs some modifications for it to work correctly.

Adds license information.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Veijo Pesonen
0562de9fbe net: lwm2m: SenML CBOR RW support
* LwM2M v1.1 SenML CBOR content format support.
* Composite operations
* SEND functionality

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-29 16:10:43 +02:00
Juha Heiskanen
1b10f8345e net: lwm2m: LwM2M RD client registration update failure fix
Client jump to full registration state if registration update fail.
Update keep already opened DTLS session.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-04-29 08:57:30 +02:00
Juha Heiskanen
f20eeebbd1 net: lwm2m: DTLS session cache enable and queue mode update
Enabled DTLS session cache for support session resume.
Fixed LwM2M queue mode for close connection and reconnect automatically.
Re-connect will do Registration update before it send queued data.
Session resume is helping a case when NAT change address and cause less
network traffic.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-04-29 08:57:30 +02:00
Juha Heiskanen
5249e43e54 net: coap: Coap pending allocation fix
When sending 2 or more confirmable message before first one is
writed to socket all messages use same coap pending structure.
Now coap_pending_init() set data pointer which lock allocation
by each call.

Using data pointer for detecting free is more stable than timeout.
Timeout is initialized only before first socket send. Queued packet
may be triggered later than other and may cause that same block is
allocated multiple time.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-04-29 08:57:30 +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
Sjors Hettinga
9392b12d4b net: tcp: Set the FIN_TIMEOUT to allow all FIN retries
Instead of using a fixed fin timeout, compute it based on the number
of retries. Fixes issue found by PR 44545.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-04-27 10:08: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
Veijo Pesonen
cfcc891d3d net: lwm2m: makes CBOR as one of the default...
...content formats

In case that SenML CBOR or SenML JSON are both disabled there is need to
use plain CBOR as backup.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-22 09:44:36 +02:00
Veijo Pesonen
11b8b4e7ba net: lwm2m: enables CBOR content format
With LwM2M v1.1 the content format is enabled by default.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-22 09:44:36 +02:00
Veijo Pesonen
8fd283a788 net: lwm2m: Single instance read&write with CBOR
Raw CBOR content format support.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-22 09:44:36 +02: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
Juha Heiskanen
53fbf40227 net: lwm2m: SenML Json fix RW Time
Added missing get_time and put_time for fixing crash.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-04-20 11:10:12 +02:00
Bartosz Bilas
f9d8f34eba net: remove superfluous default n for boolean
bool symbols implicitly default to n so
there is no need to redundant those values.

Signed-off-by: Bartosz Bilas <bartosz.bilas@hotmail.com>
2022-04-19 11:49:27 +02:00
Marin Jurjević
0ab6bc6626 net: lwm2m: update client tx timestamp before sending message
Update client tx timestamp right after message is added to list
of outgoing messages. Delay between when message is generated and
sent is negligible. This will prevents bugs that appear when using
queue mode, where internal engine logic depends on timestamp being
updated when message is generated.

Signed-off-by: Marin Jurjević <marin.jurjevic@hotmail.com>
2022-04-13 13:59:58 -07:00
Veijo Pesonen
1105017ce0 net: lwm2m: Makes OMA TLV content fmt conditional
With LwM2M v1.1 usage of the OMA TLV content format is discouraged.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-13 13:28:34 -07:00
Veijo Pesonen
d1751cafd3 net: lwm2m: adds LwM2M specific shell command
First available subcommand is for doing a send operation. Send operation
is supported by the LwM2M version 1.1.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-04-12 09:57:20 +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
Eduardo Montoya
7ab43a7cc9 net: openthread: update otPlatSettingsInit
API has been modified.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-04-08 15:50:53 -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
Eduardo Montoya
fd8d1f5fb3 net: openthread: name Kconfig version choice
Name OpenThread version selection option to `OPENTHREAD_STACK_VERSION`
to be able to superseed it somewhere else.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-04-08 12:29:45 +02:00
Jordan Yates
c910e4d931 net: context: log on net_pkt alloc fail
Log an error when allocating a network packet for transmission fails.
This is a problem which can be solved by increasing
`CONFIG_NET_PKT_TX_COUNT`, but is currently hard to diagnose.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2022-04-08 09:30:17 +02:00
Jani Hirsimäki
2d39c9f463 net: l2: ppp: config: fix for max terminate-req transmissions
CONFIG_NET_L2_PPP_MAX_TERMINATE_REQ_RETRANSMITS
was not having any impact and
CONFIG_NET_L2_PPP_MAX_CONFIGURE_REQ_RETRANSMITS
was used incorrectly instead for terminate().

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2022-04-07 09:39:09 +02:00
Lingao Meng
20ff55e234 Bluetooth: host: Optimize L2CAP resource usage
Making sure struct bt_l2cap_chan has absolutely no members related
to dynamic channels.

That way we ensure that there is no overhead for a build where only
fixed channels are used.

It's not enough that the dynamic channel-related members are put behind
ifdefs - they should be completely moved out from the struct definition.

Furthermore, the public l2cap.h header file already has a struct
that's meant to be used for dynamic channels: struct bt_l2cap_le_chan!

However, currently dynamic channel support is a mess - it's a mix
between these two structs. The bt_l2cap_le_chan struct should really
be an extension of the bt_l2cap_chan struct, i.e. the former should
contain as a member the latter.

Signed-off-by: Lingao Meng <menglingao@xiaomi.com>
2022-04-07 09:37:12 +02:00
Jordan Yates
04d29c4eb4 net: mqtt: remove custom logging macros
Remove the custom MQTT logging macros and just use the NET macros
directly. The custom macros provide no additional functionality and the
non-standard naming can cause confusion.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2022-04-06 17:41:06 +02:00
Eduardo Montoya
ed89142661 net: openthread: add Time Sync support
Implement `otPlatTimeGetXtalAccuracy` which is missing when Time
Sync is enabled.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-04-06 11:23:41 +02:00
Gerard Marull-Paretas
c925b5991a include: remove unnecessary autoconf.h includes
The autoconf.h header is not required because the definitions present in
the file are exposed using the compiler `-imacros` flag.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-04-05 11:18:20 +02:00
Seppo Takalo
43c988d43e net: lwm2m: Clean up context on stop
When lwm2m_rd_client_stop() was called and immediately
followed by lwm2m_rd_client_start() it leaked the file
handle for existing socket.

Problem can be fixed when rd_client_stop() does not
move state machine to IDLE, but instead DEREGISTER
and then allow state machine to move forward.

I added a blocking wait for rd_client_stop() because
it needs to wait for proper clean up.

I also move couple of lwm2m_engine_context_close() to
set_sm_state() event handler or similarly in lwm2m_engine.c
there was couple of places where context was not properly
cleaned.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-04-05 11:16:58 +02:00
Juha Heiskanen
ba2354a277 net: lwm2m: Support for "Mute Server" resource
Added support for server Mute send operation.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-04-04 10:29:07 -05:00
Juha Heiskanen
d75b986151 net: lwm2m: SenML Json Base compare fix
Fixed wrong initialized base name objed id.
Base name was added to every object instance.
Fix will save message size.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-04-04 10:28:01 -05:00
Juha Heiskanen
164680d696 net: lwm2m: Senml Opaque BASE64URL support and fix padding
LwM2M specification is only mentioning BASE64 encoding but SenML-JSON
specification is talking about BASE64URL encoding.
This change is silently accepting both formats and automatically pads the
data if padding is dropped.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-04-04 11:16:26 +02:00
Lukasz Maciejonczyk
5dd5128345 net: openthread: align platform time with radio time
On dual-core architecture the platform time can be not aligned with
radio time. This happens e.g. for nRF53 devices. Unaligned times imply
mulfunction in CSL windows scheduling.
This PR fixes it by adding/subtracting the time offset in functions
which return the plaform time. The changes have no impact on platforms
where the times are the same.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2022-04-01 12:41:12 -05: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
Benjamin Bigler
28e368de59 net: lwm2m: Fix missing context_close
Added missing lwm2m_context_close if set TLS_HOSTNAME failed

Signed-off-by: Benjamin Bigler <benjamin.bigler@securiton.ch>
2022-03-31 14:33:04 -05:00
Benjamin Bigler
6807d75e16 net: lwm2m: Fix TLS_HOSTNAME is always set
LWM2M Client Sample with DTLS enabled fails because TLS_HOSTNAME is set
but MBEDTLS_X509_CRT_PARSE_C is disabled which leads to error
'net_lwm2m_engine: Failed to set TLS_HOSTNAME option: 109'
Add new field hostname_verify to let the application decide if hostname
should be checked.

Signed-off-by: Benjamin Bigler <benjamin.bigler@securiton.ch>
2022-03-31 14:33:04 -05:00
Berend Ozceri
782c7b6026 net: tcp: Fix possible race condition in connection establishment
When connect() is called on a TCP socket, tcp_in() is called with a NULL
packet to start establishing a connection. That in turn leads to a SYN
packet being produced which, depending on the Ethernet driver, may
result in a synchronous transmit of that packet. After that, the
connect() implementation, which at this point is executing
net_tcp_connect() starts waiting to take a semaphore until the
connection timeout is reached. However, if the transmit of the SYN
packet results in a RST packet being returned from the connection
destination (due to there being no listening socket) very quickly on a
local network, the device driver may deliver an interrupt which can
cause the receive path of the network stack to run, resulting in the
tcp_in() of the RST packet via the network RX thread. That can cause
tcp_conn_unref() to be called before the connecting thread has gotten
to the point of acquiring (or failing to) the semaphore, which results
in a deinitialized semaphore being accessed.

This commit fixes the possible race condition by ensuring that the
connection lock mutex is held until after the connection state moves
to "in connect."

Fixes #44186

Signed-off-by: Berend Ozceri <berend@recogni.com>
2022-03-31 14:30:23 -05:00
Benjamin Bigler
493b940248 net: lwm2m: Fix address length at connect
If NET_IPV4 and NET_SOCKETS_PACKET is enabled, NET_SOCKADDR_MAX_SIZE will
be bigger than the ipv4 address length.
This is a problem when DTLS is used as the address comparison will fail
because of the different length of the received and the stored address.
This is also a problem if NET_IPV6 and NET_IPV4 is enabled and the remote
address is a ipv4 address

Signed-off-by: Benjamin Bigler <benjamin.bigler@securiton.ch>
2022-03-31 10:31:01 +02:00
Andreas Pettersson
df59335541 net: lib: lwm2m: Use defines for update state and result pathstrs
Use defines instead of hardcoded strings to avoid future errors if the
values would change.

Signed-off-by: Andreas Pettersson <andreaspettersson95@gmail.com>
2022-03-31 10:30:40 +02:00
Robert Lubos
0088aaefa0 net: tcp: Do not accept new data in retransmission mode
When TCP stack enters retransmission mode, the variable tracking the
amount of unacknowledged data is cleared. This prevents the stack from
detecting when TX window is full, which could lead to queueing unlimited
amount of data, effectively consuming all of the avaiable network
buffers.

Prevent this, by returning early from net_tcp_queue_data() in case TCP
stack is in retransmission mode. The socket layer will take care of
retrying just as in case the window is full.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-30 11:08:22 +02:00
Robert Lubos
2e9866f88f net: tcp: Retrigger the send work in case of loopback
In case a loopback or own address is used in TCP connection, the TCP
stack delegates the acatual data send to a workqueue. This is fine,
however it could lead to some aritificial delays in case a lot of data
is being sent before the workqueue has a chance to execute queued work
items. In such case, we only sent a single packet, when many could've
already been queued.

Fix this, by resubmitting the queue in case a local address is used, and
there's still more packets pending for send.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-30 11:08:22 +02:00
Robert Lubos
ce93fae60b net: tcp: Simple zero window probe implementation
When peer reports a zero length receive window, the TCP stack block any
outgoing data from being queued. In case no further ACK comes from the
peer, the whole communication could stall. Fix this by sending a simple
Zero Window Probe, when we detect a Zero Length Window.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-30 11:08:22 +02:00
Robert Lubos
22f970b97f net: pkt: Add net_pkt_rx_clone() function
Add a function which allows to clone a packet, using RX packet poll to
create the clone.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-30 11:08:22 +02:00
Kweh Hock Leong
ea43f89285 net: gptp: Fix type mismatch calculation error in gptp_mi
NSEC_PER_SEC is an unsigned integer macro. Thus, -NSEC_PER_SEC will be
treated as unsigned integer as well which lead to calculation error on
64bits integer variables. Added the correct type casting into the formula
to fix the calculation error.

Signed-off-by: Kweh Hock Leong <hock.leong.kweh@intel.com>
2022-03-28 12:47:41 +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
Marin Jurjević
683868f3d2 net: lwm2m: fix potential invalid pointer dereference in reset message
Sometimes message is being reset from multiple locations in code.
If message has already been reset, pointer to context is invalid.

Signed-off-by: Marin Jurjević <marin.jurjevic@hotmail.com>
2022-03-22 12:33:31 +01:00
Juha Heiskanen
0c6ea8eec4 net: lwm2m: Fix Read operation for /object
Read operation must return empty payload when read /object_id
if there is no created object instances.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-22 12:32:45 +01:00
Sjors Hettinga
1165bd667f net: http: Allow a content_len of 4GB
Instead of maximally 99999 bytes allow a content_len of 4GB.

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-03-21 10:16:21 +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
ffdc621f1b net: http_client: Fix http_client_req() return value
http_client_req() was supposed to return the number of bytes sent as a
HTTP request. The return value was not riht however due to some bugs in
helper functions:
* http_send_data() returned the current buffer position istead of the
  number of bytes actually sent. This could result in counting the same
  data into the total request size several times. A helper variable was
  added to track how many bytes were actually sent to the network.
* http_flush_data() forwarded the return value of sendall() helper
  function. That function however did not return number of bytes sent,
  but 0 or a negative error code.

Additionally, change the return type of sendall() function - according
to standard the ssize_t type is only capable of holding -1 negative
value, but the function could return the full range of negative errno
values. Use int instead.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-18 11:14:24 +01:00
Eduardo Montoya
3efc73f031 manifest: openthread upmerge up to commit 9f30e049
Regular OpenThread upmerge.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-03-17 16:37:03 -05:00
Juha Heiskanen
9777ba7354 net: lwm2m: SenML JSON dynamic Resource instance allocation
Integrated dynamic resouce instance allocation to SenML JSON.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-17 11:41:42 +01:00
Robert Lubos
81b92fcbb3 net: tcp: Verify accept callback before use
Closing a listening socket will set the accept callback to NULL.
This could lead to a crash, in case an already received packet,
finalizing the connection handshake, was processed after the socket was
closed. Thereby, it's needed to verify if the callback is actually set
before processing it.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-16 16:23:16 +01: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
2f2c356ca7 net: tcp: Verify if IPv4/IPv6 is enabled before processing addr family
TCP processed IPv4/IPv6 packets w/o verifying first if IPv4/IPv6 is
enabled in the system. This could lead to problems especially for IPv6,
where in case it's disabled the sockaddr structure is not large enough
to accomodate IPv6 address, leading to possible out-of-bound access on
the sockaddr structure.

Fix this by adding appropriate checks where applicable.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-16 04:21:34 -07:00
Juha Heiskanen
6cb662a495 net: lwm2m: Composite Observation update
Added support for Composite observation for LwM2M v1.1.
Updated current Observation node to support linked path list.
Rename typos lwm_ to lwm2m_.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-16 10:26:01 +01:00
Juha Heiskanen
6970addc12 net: lwm2m: Observation pmin and pmax refactor
Removed to store pmin and pmax at oberservation node structure and
use attribute list store for calculate time for next Notification.
Observation class use timestamp for triggering notification based on
resource update which use pmin and default pmax behaviour.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-16 10:26:01 +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
Marin Jurjević
2a4e47a912 net: lwm2m: fix registration update event in queue mode
When queue mode is enabled, state machine will enter state
ENGINE_REGISTRATION_DONE_RX_OFF. This state needs to be
taken into account during registration update to send
correct event.

Signed-off-by: Marin Jurjević <marin.jurjevic@hotmail.com>
2022-03-15 10:06:22 +01:00
Yong Cong Sin
ce3e1e7e29 net: http: Calculate body_frag_len
Calculate the body_frag_length if any part of the body is found
in the http response.

Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2022-03-15 10:05:21 +01:00
Yong Cong Sin
49c2d8a635 net: http: Rename body_start to body_frag_start
Following #42026, the body_start pointer now points to the
start of the body fragment in the recv_buffer as long as there
is body in it, either entirely or partially.

Rename the body_start to body_frag_start to better reflect
what it represents.

Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2022-03-15 10:05:21 +01:00
Juha Heiskanen
0b38be9d3a net: lwm2m: Inteagrate LwM2M new API's
Remove local path to string and string to path functionality
and use utility library API.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-14 22:04:32 -04:00
Juha Heiskanen
c95dd9a9c5 net: lwm2m: lwm2m utility API update
New API's
- lwm2m_string_to_path
- lwm2m_path_to_string
- lwm2m_atou16

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-14 22:04:32 -04:00
Juha Heiskanen
6d624e5e18 net: lwm2m: Senml Json Base name dynamical update
SenML Json support dynamical basename for composite operation.
Changes simplify base name generation and compres message better.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-14 11:29:13 +01:00
Gerard Marull-Paretas
7a0026a5c1 net: lib: openthread: obtain entropy device using DEVICE_DT_GET
The device can be obtained at compile time. Note that now the readiness
is checked on every call, but it's a fast operation anyway.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-03-11 15:27:05 -08:00
Lukasz Maciejonczyk
245457649b net: openthread: fix check for unsuccessful wipe
ot_setting_delete_subtree returns the information if the subtree
had been found in the persistent storage or not before removing.
This has matter for otPlatSettingsGet. In other uses cases
the return value shoud be ignored.
The right place for the check if deletion succeded is in
settings_load_subtree_direct and its callback.
Currently "ot factoryreset" causes an assert if there is no
OpenThread dataset stored in the persistent memory.
This PR fixes it.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2022-03-11 11:26:34 -08:00
Robert Lubos
3d4fe03a98 net: shell: Fix packet leak in TCP receive handler
TCP receive handler did not free the net_pkt provided, causing memory
leak.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-11 09:21:51 +01:00
Robert Lubos
bb5909f7d1 net: tcp: Update receive window in other direct net_context users
As the receive window is now decreased at the TCP module level, other
direct net_context users are also responsible for acknowledging the
received data with net_context_update_recv_wnd() - otherwise, the
communication will stall.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-03-11 09:21:51 +01:00
Benedikt Schmidt
ccd7ae2445 net: if: add default selection of first up interface
Add the default selection of the first interface which is up.

Signed-off-by: Benedikt Schmidt <benedikt.schmidt@embedded-solutions.at>
2022-03-10 13:24:03 -05:00
Henrik Brix Andersen
e9c9caa80d net: remove unmaintained 6LoCAN implementation
Remove the unmaintained, experimental 6LoCAN (IPv6 over CAN bus)
implementation.

Fixes: #42559

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-03-09 18:07:31 +01: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
Przemyslaw Bida
c9645f4d36 openthread: net: implementing of otPlatRadioSetChannelMaxTransmitPower
This commit adds implementation of otPlatRadioSetChannelMaxTransmitPower
This function is responsible for setting maximum allowed power on
IEEE 802.15.4 channels.

Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
2022-03-08 09:21:48 -06:00
Krzysztof Chruscinski
47ae656cc1 all: Deprecate UTIL_LISTIFY and replace with LISTIFY
UTIL_LISTIFY is deprecated. Replacing it with LISTIFY.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-03-08 11:03:30 +01:00
Georges Oates_Larsen
303c42e70a net: http_client: Add official null response behavior
Adds an official behavior in response to null response from HTTP
endpoint.

Fixes #42988

Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
2022-03-07 09:18:50 -06:00
Juha Heiskanen
3d44738b19 net: lwm2m: Fix SenML Json Name parser
Bug fix for case when base name is not included at message.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-03-07 10:54:57 +01:00
Lu Ding
818d90efda net: gptp: Fix sync_receipt_time calculation in gptp_mi
Fix #42800
Both pss->rate_ratio and port_ds->neighbor_rate_ratio are double type
but sync_receipt_time is uint64_t. If pss->rate_ratio is less than 1
or sync_receipt_time * port_ds->neighbor_rate_ratio is less than 1,
sync_receipt_time becomes 0 due to double to uint64_t cast.
Assign port_ds->neighbor_prop_delay to sync_receipt_time first to fix
this issue.

Signed-off-by: Lu Ding <lucasdinglu@gmail.com>
2022-03-07 10:54:49 +01:00
Eduardo Montoya
e05c966992 net: openthread: remove CONFIG_OPENTHREAD_CSL_SAMPLE_WINDOW
Remove obsolete configuration option.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-03-07 10:54:30 +01:00
Veijo Pesonen
0032f0bcff net: lwm2m: obj inst processing per formatter
It depends from a content formatter is there need to put constructs
with a path level deeper than object instance. In other words with
resource- or resource-instance-level.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-03-07 10:52:58 +01:00
Przemyslaw Bida
47557d7d9d manifest: openthread: Simplification of openthread integration.
This commit moves openthread CMakeLists.txt from openthread submodule
to zephyr/modules/openthread.

Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
2022-03-02 10:06:03 -08:00
Marcin Niestroj
ab2f616641 net: http: use shutdown(..., SHUT_RD) in receive timeout handler
So far close() was called on underlying socket when timeout has expired.
This is wrong in several ways. First of all POSIX specification of
close() does not specify what should happen on blocking recv() call and
different systems have different behaviors (e.g. Linux does not wake up
recv() caller if there was no new incoming data, while other systems
might wakeup recv() caller immediately). Another (and much more severe)
problem is that HTTP client user does not know whether underlying socket
was already closed or not after HTTP request has finished. As a result
it was not clear whether close() should be called by HTTP client user.

Use shutdown(..., SHUT_RD) in internal HTTP client implementation, so
that recv() is woken up immediately with 0 as result (which means EOF).
This will allow to gracefully handle timeouts and make it clear that it
is application responsibility to always call close() after HTTP
request (successful or not).

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2022-03-02 10:05:09 -08: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
Lu Ding
24ab659cd1 net: gptp: fix endianness of correction field in sync follow up message
correction field in sync follow up message must be converted from host
endianness to network endianness.

Signed-off-by: Lu Ding <lucasdinglu@gmail.com>
2022-03-02 09:43:35 -06:00
Flavio Ceolin
df3d1f83f7 drivers: crypto: Rename cipher file
This file defines the crypto driver API, cipher is supposed to be just
one type of capability (other can be hash) of these drivers, just
change the file name to be consistent with it.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2022-03-01 16:32:43 -05:00
Flavio Ceolin
637fd58efb drivers: crypto: Change HW capabilities query namespace
This is not cipher specific, just replace it crypto to make it clear.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2022-03-01 16:32:43 -05:00
Eduardo Montoya
166fd0dc9e net: openthread: bring back LOG_MODE_MINIMAL support
A previous commit fixed OpenThread logging when `LOG=n`, but
introduced regression when `LOG_MODE_MINIMAL=y`. This commit
fixes the latest.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-03-01 12:49:36 +01:00
Lukasz Duda
0c94817b55 openthread: platform: implement otPlatCryptoRand API
This commit utilizes psa_crypto_get function to fetch cryptographically
secure pseudorandom numbers.

Signed-off-by: Lukasz Duda <lukasz.duda@nordicsemi.no>
2022-03-01 12:49:36 +01:00
Eduardo Montoya
b588444a53 net: openthread: Align Kconfig with cmake symbols
OPENTHREAD_BORDER_ROUTING_NAT64
OPENTHREAD_DNS_DSO
OPENTHREAD_EXCLUDE_TCPLP_LIB

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-03-01 12:49:36 +01:00
Veijo Pesonen
2231287e27 net: lwm2m: Resource Instance level read access.
Makes possible to read a single resource instance at a time with
plaint text, JSON and TLV content formats.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-02-25 10:12:23 -08:00
Lukasz Maciejonczyk
c5afc2e1f2 net: openthread: add assert which checks settings wipe failure
If settings wipe fails we are not informed about this what can lead to
bugs which are hard to investigate.
This commit adds log and/or assert which is triggered by this failure.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2022-02-24 08:33:30 -06:00
Juha Heiskanen
6904915a35 net: lwm2m: LwM2M engine default content format select
LwM2M version 1.1 will select SenML Json for default content format.
Version 1.0 will use TLV format.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-23 17:25:36 +01:00
Juha Heiskanen
312dd7f887 net: lwm2m: Composite Observe operation placeholder
Added detetction for Composite Observervation request and cancel.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-23 17:25:36 +01:00
Juha Heiskanen
98cd71eef2 net: lwm2m2: LwM2M Composite-Write operation
CoAP method iPATCH enable LwM2M Composite-Write operation.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-23 17:25:36 +01:00
Juha Heiskanen
3bec5de0fb net: lwm2m: LwM2M Composite read support
Adeed enabler for composite read to LwM2M engine.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-23 17:25:36 +01:00
Juha Heiskanen
906feebb33 net: lwm2m: Added LwM2M Send operation support
LwM2M engine Send operation support /dp.
Send operation based on Composite Read functionality
which is not enabled at engine side like composite write.
Added Kconfig configurable for composite read path list size.
Created generic Read object instance which is shared between
general read and Composite Read operation.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-23 17:25:36 +01:00
Juha Heiskanen
a9c1b8d0f2 net: lwm2m: Added SenML JSON support for Read & Write
LwM2M SenML JSON contain format support for Read / Write operation.
Added Kconfig configurable for enable SenML JSON format.
LwM2m read validate read operation and report out of memory.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-23 17:25:36 +01:00
Robert Lubos
9ac83be650 net: lwm2m: Add proper resource-level discovery attribute handling
In case an individual resource is being discovered, the LwM2M client
should not only fill the attributes assinged at the resource level, but
also the ones inherited from the object and object instance levels.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-22 10:12:27 -08:00
Robert Lubos
ac8881f170 net: lwm2m: Allow to write attributes for resource instances
LwM2M 1.1 allows to write attributes for resource instances as well.

Resource instance level attributes need also to be taken into
consideration when adding/updating observers.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-22 10:12:27 -08:00
Robert Lubos
3e861c04e9 net: lwm2m: Add LwM2M 1.1 discovery support
LwM2M adds Resource Instance reporting in Discovery response, along with
attributes assinged at the Resource Instance level.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-22 10:12:27 -08:00
Robert Lubos
4f5a19482b net: tcp: Make receive window size configurable
Add Kconfig option to set the receive window size.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-22 10:09:45 -08:00
Robert Lubos
c25cd5a894 net: tcp: Allow to acknowledge zero-length packets
Peer may send a zero-length keepalive message, probing the recv window
size - TCP stack should still reply for such packets, otherwise
connection will stall.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-22 10:09:45 -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
Lukasz Maciejonczyk
c9effd0ff9 net: openthread: filter ipv6 fragments
If OPENTHREAD_IP6_FRAGM is enabled the IPv6 fragments are handled in
OpenThread stack but also forwarder unconditionally to the Zephyr
uplayers. It causes additional packets processing and leads to errors
like unrecognized next header type or duplicate ping reply. What more
these errors generate additional traffic which jam channel and decrease
latency for packets required fragmentation.
This commit add filtering IPv6 fragments when data fragmentation and
reassembling is enabled in OpenThread.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2022-02-22 10:33:47 -05:00
Eduardo Montoya
be742f925e net: openthread: fix received frame flags
Uninitialized memory would report wrong value for
`mAckedWithSecEnhAck` flag in the received frame, making the
OpenThread stack to update the frame counter for the neighbor
wrongly.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-02-22 10:33:23 -05:00
Seppo Takalo
f1e0b5413c net: lwm2m: Allow changing the protocol version to 1.1
This is a bare minimal changes to tell the server that we are using
LwM2M 1.1 version. Queue-mode parameter has changed between 1.0 and
1.1 so it must be changed in the same time.

Other 1.1 features may follow on separate commits. This is still
an experimental feature that allows developing and testing of
1.1 features.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-02-21 22:18:34 -05:00
Veijo Pesonen
37b9bb87f0 net: lwm2m: Adds semantics for handling time
This far time values have been synonymous to integer values. Content
formats like CBOR do use different representation.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-02-21 22:07:01 -05:00
Juha Heiskanen
3e04783bbb net: lwm2m: LwM2M Portfolio object id support
Added support for Portfolio object support because LwM2M v1.1 conformance
test requirement that. This object is only for conformance test purposing.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-21 22:02:44 -05:00
Andreas Chmielewski
b52f1cdb59 net: lwm2m: fixed "LwM2M message is invalid"
Do not retransmit a message that just has been send successfully.

This case can in particular happen quite frequently if the modem
connection/throughput is quite bad and so there is a high latency.

A message that has to be acknowledged is scheduled for retransmission.
Before retransmission a ack for this message is received that will
cause a reset of the original message. In this case you see a
"LwM2M message is invalid" error message.

Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
2022-02-21 21:59:59 -05:00
Björn Stenberg
b4b87ad8a4 CMake: net: pkt_filter: Only construct the library if enabled
This fixes "No SOURCES given to Zephyr library: subsys__net__pkt_filter"

Signed-off-by: Björn Stenberg <bjorn@haxx.se>
2022-02-21 21:57:19 -05:00
Juha Heiskanen
dde5c16709 net: lwm2m: JSON dynamic Resource instance allocation
Integrated dynamic resouce instance allocation to JSON.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-21 21:53:48 -05:00
Juha Heiskanen
7b3a1f31fe net: lwm2m: Plain Text dynamic Resource instance allocation
Integrated dynamic resouce instance allocation to Plain text.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-21 21:53:48 -05:00
Juha Heiskanen
fcbf84b5d7 net: lwm2m: OMA TLV dynamic Resource instance allocation
Integrated dynamic resouce instance allocation to OMA TLV.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-21 21:53:48 -05:00
Juha Heiskanen
1d2f5b471e net: lwm2m: Resource instance dynamic allocation
Added support for allocate dynamically resource instance.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-21 21:53:48 -05:00
Juha Heiskanen
60088b18d4 net: lwm2m: Fix Read operation for /object
Read operation must return empty payload when read /object_id
if there is no created object instances.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-21 21:01:23 -05:00
Juha Heiskanen
392088ea13 net: lwm2m: OMA TLV Multi Resource TLV update
Added support for handle Multi Resource TLV for Write and Create operation.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-21 21:00:36 -05: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
Henning Fleddermann
7eb25df526 net: lib: lwm2m: add lwm2m_engine_is_observed function
add helper function to check wether a specific lwm2m
path is observed

Signed-off-by: Henning Fleddermann <henning.fleddermann@grandcentrix.net>
2022-02-21 20:50:52 -05:00
Eduardo Montoya
a0093eeda0 net: openthread: fix handling tx done to report all kind of errors
Fix bug in radio implementation that reported any transmit error
as `OT_ERROR_NO_ACK` to OpenThread.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-02-21 20:49:20 -05:00
Xabier Marquiegui
e238dce6cc net: gptp: gptp port role disabled on link down
Set GPTP port role to disabled if port link is down.

Signed-off-by: Xabier Marquiegui <xmarquiegui@ainguraiiot.com>
2022-02-11 10:03:05 -06:00
Daniel Nejezchleb
1f22a2bc3c net: tcp: Fix possible deadlock in tcp_conn_unref()
This reverts commit e7489d8de7.

And fixes the deadlock by allowing only 1 thread to actualy clean up
the connection when the ref_count is 0.

Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
2022-02-10 10:59:03 +01:00
Sjors Hettinga
4855e8ded1 net: ppp: Properly terminate LCP state at modem side when closing down
Takes the modem state machine by calling lcp_close instead of lcp_down
Using this method the LCP layer sends a TERMINATE_REQ to the modem and the
network interface is only taken down when the LCP layer has properly
finished.
Moved the ppp_mgmt_raise_carrier_off_event and net_if_carrier_down
to lcp.c to avoid breaking the interface.
Tested on a real modem.

Fixes: zephyrproject-rtos#41627

Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
2022-02-09 13:56:54 +01:00
Henning Fleddermann
3018279c30 net: lib: lwm2m: make pathstr parameter const correct
many functions in the lwm2m librarys api take a pathstr argument
that is never written to, so make it const

Signed-off-by: Henning Fleddermann <henning.fleddermann@grandcentrix.net>
2022-02-08 07:27:30 -05:00
Jarno Lamsa
98f99a37a2 net: lib: lwm2m: Use snprintk instead of snprintf
Use kernel print function to reduce the memory impact.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-02-07 17:22:38 +01:00
Jarno Lamsa
c2550d56c8 net: lib: lwm2m: Correct path for update result
The path was erroneously pointing to update state
resource instead of update result causing a wrong
resource value to be updated.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-02-07 17:22:38 +01:00
Daniel Nejezchleb
e7489d8de7 net: tcp: Fix possible deadlock in tcp_conn_unref()
Unlock tcp_lock when calling the recv_cb. In case when
a connection is being closed from both the tcp stack
and the application, a race condition can happen resulting
in locking each other out on tcp_lock and socket lock.

Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
2022-02-07 09:28:25 -05:00
Marin Jurjević
2f4ab97168 net: lwm2m: add missing optional resource to firmware object
Firmware Update Protocol Support resource initialization
has been left out in #41402.
Initialise the resource in object creation function.

Signed-off-by: Marin Jurjević <marin.jurjevic@hotmail.com>
2022-02-04 11:19:07 +01:00
Daniel Nejezchleb
208927d640 net: tcp: Fixed forever loop in tcp_resend_data
Increments send retry every time
after the tcp_send_data when resending.
That way unhandled return values can time
out after set amount of tcp_retries.

Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
2022-02-04 10:56:25 +01:00
Yong Cong Sin
731241f8d0 kernel: workq: Fix type errors in delayable work handlers
A common pattern here was to take the work item as the subfield of a
containing object. But the contained field is not a k_work, it's a
k_work_delayable.

Things were working only because the work field was first, so the
pointers had the same value. Do things right and fix things to
produce correct code if/when that field ever moves within delayable.

Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2022-02-02 18:43:12 -05:00
Marin Jurjević
57a66648ae net: lwm2m: fix context close race condition
Calling lwm2m_rd_client_stop causes the client context to be closed.
Doing this from arbitrary thread other than internal lwm2m engine thread
causes racing condition on lwm2m engine context pointers.

Fixes #42358

Signed-off-by: Marin Jurjević <marin.jurjevic@hotmail.com>
2022-02-02 08:58:40 -05:00
Juha Heiskanen
a03deb8ef3 net: lwm2m: Fix Server Object SSID access
Server Object SSID should only have Read access.
LightweightM2M-1.1-int-256 confirmance test validate
that write operation to SSID should return error.
Overwrite SSID affect dead block for lwm2m engine and
only reset will heal.

Fix by adding bootstrap overwrite access for Security and
Server object when bootstrap is active.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-02-02 11:18:53 +01:00
Robert Lubos
9c8d30f099 net: lwm2m: Prevent snprintk warnings on different platforms
Use explicit casting to long long within `snprintk()` and logger
functions to prevent compiler warnings with different
platforms/toolchins (as 64-bit integer can be either represented
as ld or lld depending on platform).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
486e0a8ff6 net: lwm2m: Fix lwm2m_parse_peerinfo misuse
`lwm2m_parse_peerinfo()` expects a boolean value, not a pointer.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
21e5cc7a31 tests: net: lwm2m: Add link-format content writer tests
Add unit tests for LwM2M link-format content encoder/decoder.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
735fd86c0e tests: net: lwm2m: Add OMA TLV content writer tests
Add unit tests for LwM2M OMA TLV conent encoder/decoder.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
e42c1ed924 net: lwm2m: Fix OMA TLV objlnk encoding
At some point OMA TLV integer encoding was optimised to use the smallest
size possible. This broke the objlnk encoding, which internally used
`put_s32()`, but should always be 4 bytes long. In case the result
32-bit integer would fit into 16 or 8 bytes, it'd get optimized.

Fix this, by creating and writing TLV manually for objlnk instead of
relying on int32 encoder.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
3595a7cdb5 net: lwm2m: Fix lwm2m_atof for integer input
In case a string with an integer was provided to the function (no
decimal point), the function did not update the output pointer value.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
cb6c5f37ca net: lwm2m: Improve content writers error handling in engine
Verify the restult of the content writer functions and return an error
if content writer fails to read/write field in the message.

This solves an issue when for example malformed packet was sent to the
server if the payload did not fit in the message.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
1a727b8571 net: lwm2m: Improve JSON content encoder/decoder error handling
It's now possible to return an error code instead of 0 where
appropriate.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
9e2bf49103 net: lwm2m: Improve TLV content encoder/decoder error handling
It's now possible to return an error code instead of 0 where
appropriate.

Make `buf_read()` return -ENODATA instead of -ENOMEM if there's not
enough data in the packet to serve the request, which is more meaningful
for this scenario.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
f1d86a0cd2 net: lwm2m: Improve plain-text content encoder/decoder error handling
It's now possible to return an error code instead of 0 where
appropriate.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
1c3dbd5af3 net: lwm2m: Improve link-format content encoder error handling
It's now possible to return an error code instead of 0 where
appropriate.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Robert Lubos
54ddf70945 net: lwm2m: Allow to return error codes by content encoders/decoders
Rework the content encoder/decoder API to allow to return negative
values as well. This allows a proper error reporting and error handling,
as it's now possible to differentiate when there is no content to write
(retuned 0) or and error occured, and further processing should be
aborted.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-02-02 11:12:56 +01:00
Efrain Calderon
6b936c0315 net: coap: Update coap context using payload length
When a file is download, `ctc->current` is increaed by the block
size, which is correct for all the blocks except the last one.

 Once the download is compelted, ctx->current must match
`ctx->total_size`.

Signed-off-by: Efrain Calderon <efrain.calderon@aquarobur.com>
2022-02-02 11:10:57 +01: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
Jarno Lamsa
a1c80e7374 net: lib: lwm2m: Add missing function declarations
Get-function declarations for fw update state and result were
missing from the engine header.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-02-01 14:14:29 -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
Robert Lubos
e718c8c2dc net: if: Leave all IPv4 mcast groups when interface goes down
In a similar way as its done for IPv6. This allows to rejoin the group
once the interface is up again.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-01-26 10:50:24 +01:00
Robert Lubos
4da1a75a6c net: llmnr: Rejoin IPv4 multicast group when iface is brought up
When network interface is brought up, rejoin the IPv4 multicast group
used by LLMNR service.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-01-26 10:50:24 +01:00
Robert Lubos
6f19b6e59e net: mdns: Rejoin IPv4 multicast group when iface is brought up
When network interface is brought up, rejoin the IPv4 multicast group
used by mDNS service.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-01-26 10:50:24 +01:00
Yong Cong Sin
4b40dce981 net: mgmt: Use mutex for net_mgmt_lock
Conceptually the net_mgmt_lock should be a mutex instead of a
semaphore. It is easier to identify the owner of a mutex and
debug when deadlock happens, so convert it.

Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2022-01-22 16:56:09 -05:00
Ryan Erickson
c6ace45a6c net: lwm2m: add uCIFI Battery object (3411)
Add the uCIFI Battery object to support
monitoring a devices battery.

Signed-off-by: Ryan Erickson <ryan.erickson@lairdconnect.com>
2022-01-21 11:32:08 -05:00
Robert Lubos
4557d183b9 net: http_client: Set body_start pointer unconditionally
Set `body_start` pointer regardless of the body position in the recv
buffer. In result, the pointer shall indicate correctly position of the
body for each fragment, it's also explicit now that if the pointer is
not set for a fragment, there's no body in that particular fragment.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-01-21 11:31:49 -05:00
Robert Lubos
d002f8a524 net: lwm2m: Fix attribute sanity check
Validate the respective attribute parameters only if both are provided
at given level. This prevents from comparing for instance unset pmax
value (equal to 0) with some new pmin value sent by the server.

Additionally, fix the sanity check for the `pmax` value set on observer,
after fetching the attribute value at all levels (including the default
value at from the server object). Instead of using wrong max(pmin, pmax)
formula, set the pmax value only if it's a valid one (>= pmin),
otherwise ignore the value and set it to 0. This makes the notification
engine ignore the pmax value set for observation.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2022-01-21 11:31:20 -05:00
Eduardo Montoya
587d77a637 net: openthread: blank otPlatLog when logging is disabled
Implement an empty `otPlatLog` function when `CONFIG_LOG` is not
enabled. This also fixes the issue with `log_count_args` not being
available when logging is disabled.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-01-19 14:15:57 -05:00
Gerard Marull-Paretas
35b9b20764 net: lib: capture: drop DEV_DATA/DEV_CFG usage
Stop using redundant DEV_DATA/DEV_CFG macros and use dev->data and
dev->config instead.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-01-19 18:16:02 +01:00
Andrew Hedin
7f004f1b35 net: lwm2m: Add LwM2M gateway object
Add support for the gateway object [EXPERIMENTAL] used by the
MG100, BT510, and BT610 LwM2M demo.

Signed-off-by: Andrew Hedin <andrew.hedin@lairdconnect.com>
2022-01-18 13:19:12 -05:00
Przemyslaw Bida
00ef3d2fa7 net: openthread: Add openthread CSL clock uncert
This commit adds OPENTHREAD_PLATFORM_CSL_UNCERToption to Kconfig.
This option will allow user to configure openthreads CSL clock
uncertianity during build time.

Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
2022-01-18 13:11:08 -05:00
Jarno Lamsa
8f4a1fd906 net: lwm2m: Instance specific callbacks
Provide possibility to have instance specific callbacks
for writing the FW image and executing the update

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-01-13 10:34:25 +01:00
Jarno Lamsa
eedbbdc61a net: lwm2m: Provide backwards compatibility for single object 5
Previously the object 5 was only single instance object. Provide
backwards compatibility, so it can be continued to use with single
instance.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-01-13 10:34:25 +01:00
Veijo Pesonen
9782f86450 net: lwm2m: separate FW update object instances - /5/*
This is a proof-of-concept implementation.

A device might have multiple firmware images which needs to be updated
separately. For example a single device might have

	* A bootloader image
	* An application image
	* External firmware image

Instead of pushing all these updates through the object instance 0 -
/5/0 - here a split to multiple has been made possible.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2022-01-13 10:34:25 +01:00
Daniel Leung
8d8369204f net: remove @return doc for void functions
For functions returning nothing, there is no need to document
with @return, as Doxgen complains about "documented empty
return type of ...".

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-12 16:02:16 -05:00
Andreas Chmielewski
fbae13122f net: lwm2m: enable monitoring of fw update state/result
The intention behind this patch is to know the current state/result
of a firmware update process in the application code. It makes it
possible to use pre/post_write_callbacks to get the proper value
of state (5/0/3) and result (5/0/5) resource.

Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
2022-01-11 11:52:50 +01:00
Henrik Brix Andersen
8af4bb722d drivers: can: rename API functions for better consistency
Rename a few CAN API functions for clarity and consistency with other
Zephyr RTOS APIs.

CAN_DEFINE_MSGQ() becomes CAN_MSGQ_DEFINE() to match K_MSGQ_DEFINE().

can_attach_isr() becomes can_add_rx_filter() since a filter callback
function is not an interrupt service routine (although it is called in
isr context). The word "attach" is replaced with "add" since filters are
added, not attached. This matches the terminology used is other Zephyr
APIs better.

can_detach() becomes can_remove_rx_filter() to pair with
can_add_rx_filter().

can_attach_msgq() becomes can_add_rx_filter_msgq() and documentation is
updated to mention its relationship with can_add_rx_filter().

can_register_state_change_isr() becomes can_set_state_change_callback()
since a state change callback function is not an interrupt service
routine (although it is called in isr context). The word "register" is
replaced with "set" since only one state change callback can be in
place.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-01-10 10:44:37 +01:00
Eduardo Montoya
c6e31a888f net: openthread: disable CLI prompt
Avoid printing OpenThread prompt in Zephyr.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-01-07 12:48:27 -05:00
Eduardo Montoya
e9245a6198 net: openthread: revert CLI prompt workaround
`OPENTHREAD_CONFIG_CLI_PROMPT_ENABLE` can be used now.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-01-07 12:48:27 -05:00
Eduardo Montoya
48a5d42313 net: openthread: remove obsolete define
Remove `OPENTHREAD_CONFIG_PLAT_LOG_MACRO_NAME` which has been
deprecated in OpenThread.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-01-07 12:48:27 -05:00
Kweh Hock Leong
d110e31a55 net: shell: Fix parser error on net ping command
The strtol() function use errno to return error code.
However, it is not being initialized in the parser_arg()
function before calling the strtol(). Thus, hitting error
when performing net ping command with -c / -i parameters.

Signed-off-by: Kweh Hock Leong <hock.leong.kweh@intel.com>
2022-01-07 10:48:49 -05:00
Jarno Lamsa
5c3fd79bdc net: lwm2m: Security object resource correct type
Changed resource IDs 11 and 12 of the security object to use
signed integer as they are defined in the OMA specification.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-01-04 09:08:55 -05:00
Jarno Lamsa
60160fb82f net: lwm2m: Update security object to 1.1
Add 1.1 version of the LWM2M security object.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-01-04 09:08:55 -05:00
Jarno Lamsa
50ebb0e233 net: lwm2m: Update connectivity monitor object
Update the connectivity monitor object to version 1.2.
OMA core specification for the object adds 2 optional
resources.

Signed-off-by: Jarno Lamsa <jarno.lamsa@nordicsemi.no>
2022-01-04 09:08:38 -05: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
Henrik Brix Andersen
b1b77c1774 drivers: can: change can_tx_callback_t function signature
Change the can_tx_callback_t function signature to use an "int" (not an
uint32_t) for representing transmission errors.

The "error" callback function parameter is functionally equivalent to
the return value from can_send() and thus needs to use the same data
type and needs to be able to hold negative errno values.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2022-01-01 07:40:29 -05:00
Krzysztof Chruscinski
e5d398faa9 net: ip: route: Fix log_strdup misuse
Log_strdup was used in NET_ASSERT macro which is not logging.
As a result linking fails when logging is disabled but asserts
are enabled.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-12-22 12:13:55 +01:00
Tomasz Bursztyka
6b03df6931 net/icmpv4: Do not send error on a packet that was broadcasted
For instance, DHCP (UDP protocol) can send broadcasted packet and if we
no not serve the requested destination port, let's not send an error
back.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-12-21 17:12:33 +01:00
Tomasz Bursztyka
11cf60d916 net/icmpv4: Fix logging messagse
Invert src/dst strings, the icmpv4 error is sent from the dst (us) to
src (sender of the ipv4 packet that generated the error).

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-12-21 17:12:33 +01:00
Marcin Niestroj
cbb3e9a065 net: l2: ppp: fix MRU when CONFIG_NET_L2_PPP_OPTION_MRU=n
When support for custom MRU/MTU was added with
CONFIG_NET_L2_PPP_OPTION_MRU=y, code flow with
CONFIG_NET_L2_PPP_OPTION_MRU=n has been broken due to lack of valid
'ctx->lcp.my_options.mru' initialization and its use (with value 0) in
the implementation.

Initialize 'ctx->lcp.my_options.mru' unconditionally in lcp_init(), so
that PPP works fine with CONFIG_NET_L2_PPP_OPTION_MRU=n.

Fixes: 8a51a79d89 ("net: l2: ppp: possibility to have a custom
  MRU/MTU")

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-12-21 17:12:24 +01:00
Nicolas Pitre
a3a31257df net: npf: add the ability to do MAC address masked matching
Add the ability to do matching on partial MAC addresses.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-12-21 17:06:35 +01:00
Nicolas Pitre
faa0b2a848 net: introduce a network packet filter framework
This provides the infrastructure to create network packet filter rules
and to apply them to the RX and TX packet paths. Rules are made of
simple condition tests that can be linked together, creating a facility
similarly to the Linux iptables functionality.

A couple of generic and Ethernet-specific condition tests are also
provided.

Additional tests can be easily created on top of this.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-12-21 17:06:35 +01:00
Michal Ciesielski
8b3d7f2a43 net: lwm2m: Add LWM2M object 9 software management
Adds support for LWM2M object 9 Software management.
This is implemented according to this release:
http://openmobilealliance.org/release/LWM2M_SWMGMT/V1_0_1-20200616-A/

Note that the XML is lacking some resources and for that reason those
resources are not included. This is a known problem by OMA and will be
fixed in a later releases.

This uses the lwm2m_pull_context to pull binaries in case
FIRMWARE_PULL_SUPPORT is enabled

Signed-off-by: Michal Ciesielski <michal.m.ciesielski@voiapp.io>
2021-12-21 13:36:50 +01:00
Michal Ciesielski
06b0a9c59d net: lwm2m: Make lwm2m_pull_context reusable
Add a semaphore to control that no collisions occur when multiple
sources want to use the pull_context

Add struct firmware_pull_context *ctx as an argument to the result_cb of
the context. This allows the receiver to do some kind of differentiation
on the source.

Signed-off-by: Michal Ciesielski <michal.m.ciesielski@voiapp.io>
2021-12-21 13:36:50 +01:00
Michal Ciesielski
2f046da6a1 net: lwm2m: FW Pull separate generic pull logic
Make it possible to reuse the pull logic from firmware_pull.c by
separating it to a separate file.

The firmware_pull_context is still owned and statically allocated in
firmware_pull.c and is being passed into lwm2m_pull_context.c as a
pointer.

In other words, pull_context, does not keep any state except for a
pointer to the context currently in use.

Signed-off-by: Michal Ciesielski <michal.m.ciesielski@voiapp.io>
2021-12-21 13:36:50 +01: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
f8b3516280 net: route: Add mutex protection
Since most of the functions will access non thread-safe resources like
SLIST, and can be invoked from different threads (like the expiry timer
delayed work), add mutex protection to the function calls.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-20 17:44:28 +01:00
Robert Lubos
e9db822635 net: route: Add support for route preference
Implement a concept of Route Preference, as specified in RFC 4191. The
Zephyr host will prefer routes with higher preference, if they lead to
the same prefix through different neighbours.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-20 17:44:28 +01:00
Robert Lubos
a841e27b3b net: shell: Add lifetime to printed route information
Print the lifetime information along with other route info.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-20 17:44:28 +01:00
Robert Lubos
56f14a9cd0 net: route: Add support for route lifetime
Add support for route lifetime, as defined in RFC 4191. The existing
route adding logic remains the same, if not specified, lifetime is set
to infinite. For routes added with Route Info option from ICMPv6 RA
message, set the expiration timer, according to the route lifetime value
received.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-20 17:44:28 +01:00
Robert Lubos
c1dc82cf7f net: icmpv6: Add support for Route Information option
This commits adds handling of the Route Information option from
the Router Advertisement message. This option allows to add/delete
routes in the host based on the information sent by the router.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-20 17:44:28 +01:00
Robert Lubos
43c6df5f9a net: route: Fix struct net_route_nexthop leak
When new route is allocated, a corresponding NBR entry (containing
`struct net_route_nexthop` data) is allocated from
`net_route_nexthop_pool`. When the route was deleted however, the entry
was not freed - only the "core" neighbor entry from the neighbor
management module (nbr.c) was dereferenced. This lead to a resource
leak, effecitevly leaking one `net_route_nexthop_pool` entry for each
deleted route.

Fix this, by defreferencing the NBR entry corresponding to the `struct
net_route_nexthop` data of the deleted route when route is removed.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-20 17:44:28 +01:00
Robert Lubos
6fe1c9041b net: route: Verify if neighbor entry is in use when iterating
Verify the `ref` value of the neighbor entry in `net_route_foreach()`,
so that it only executes the callback on routes in use. Otherwise, the
function could call the callback for the route that has already been
deleted.

This could be encountered when executing `net route` shell command,
which printed the already deleted routes along the existing ones.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-20 17:44:28 +01:00
Juha Heiskanen
87f4210450 net: lwm2m: Update LwM2m server object to v1.1
Added Kconfig configurable choise option for enable Server
object version 1.0 or 1.1.

Server Object v1.1 enable by default server initiated bootstrap
trigger when CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP is enabled.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2021-12-20 17:00:28 +01:00
Henrik Brix Andersen
f499559434 drivers: can: deprecate the use of CAN-specific error return values
Deprecate the use of CAN-specific error return values and replace them
with standard errno values.

Signed-off-by: Henrik Brix Andersen <hebad@vestas.com>
2021-12-09 12:37:40 -05:00
Lukasz Maciejonczyk
4dc0353bcd net: openthread: store settings in RAM if there is no flash driver
This commit adds an option to store OpenThread settings in RAM for the
case where the flash driver is not available. This can be useful
for testing openthread on new platforms which are still under
development.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-12-09 11:04:49 -06:00
Lukasz Majewski
9ee502188a net: dsa: Update iface description for mac table programming functions
The comment before this change was misleading, as those functions
(and other ones used from the level of user space application) require
DSA interface (like lan{012}), not the master one (like eth0).

Signed-off-by: Lukasz Majewski <lukma@denx.de>
2021-12-01 13:58:08 -06:00
Lukasz Majewski
0ef13f684a net: dsa: Use net_if_get_device() macro when applicable
The 'iface->if_dev->dev' idiom can be replaced with already defined
macro - namely net_if_get_device().

Signed-off-by: Lukasz Majewski <lukma@denx.de>
2021-12-01 13:58:08 -06:00
Lukasz Majewski
6b8666db8e net: dsa: Provide proper address for dsa_api structure
The address of DSA API functions' structure available for usage from
the level of user's application (like for example in
samples/net/dsa/src) is stored in dsa context, not per DSA interface
device.

The struct dsa_context is defined once for all DSA (i.e. not master)
interfaces.

Signed-off-by: Lukasz Majewski <lukma@denx.de>
2021-12-01 13:58:08 -06:00
Robert Lubos
5110629ac1 net: mqtt: Fix SOCKS5 setsockopt error handling
Transports should close the socket in case of `setsockopt()` failure,
otherwise we end up with a leaked socket, as it won't be closed
elsewhere.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-12-01 13:54:30 -06: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
Gerard Marull-Paretas
89a4f36fc8 device: remove inclusion of pm/device.h
The device PM subsystem _depends_ on device, not vice-versa. Devices
only hold a reference to struct pm_device now, and initialize this
reference with the value provided in Z_DEVICE_DEFINE. This requirement
can be solved with a forward struct declaration, meaning there is no
need to include device PM headers.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-11-29 11:08:38 +01:00
Jair Jack
0b06a06814 net: lwm2m: Supported Protocol to pull firmware update must be optional
The supported protocol must be delivered to the firmware update object
as optional, then configured in the application.

This information is device/server dependent so does not can be fixed
in library.

Signed-off-by: Jair Jack <jack@icatorze.com.br>
2021-11-26 10:26:32 -05:00
Robert Lubos
e6d619ea3d net: l2: ieee802154: Fix packed structure warning
`struct ieee802154_mpdu` access generates warnings related to unaligned
access to packed structure member. The structure itself however does not
need to be packed, since it is not mapped directly into the frame
buffer, but rather contains pointers to the structures representing
corresponding header regions in the frame. Those structures are
correctly defined as packed.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-25 10:46:35 -05:00
Robert Lubos
6dbd5c7876 net: icmpv6: Remove in6_addr from packed structs
Replace unpacked in6_addr structures with raw buffers in packed icmpv6
structs, to prevent compiler warnings about unaligned access.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-25 10:46:35 -05: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
Robert Lubos
bbdeef4ac4 net: arp: Remove in_addr/in6_addr from packed net_arp_hdr struct
Replace unpacked in_addr/in6_addr structures with raw buffers in
net_arp_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
Robert Lubos
0da228c57c net: ip: Verify that in_addr/in6_addr struct sizes are correct
Make sure that in_addr/in6_addr structure size match the respective
binary IP address size with BUILD_ASSERT.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-25 10:46:35 -05:00
Maik Vermeulen
f2ca6a8c22 net: lwm2m: Add observe callback for observe and notification events
Added an observe callback so that the application can register to
receive events like observer added/deleted, and notification acked/
timed out. The notifications can be traced back to the exact data
contained within them by use of the user_data pointer.

Fixes #38531.

Signed-off-by: Maik Vermeulen <maik.vermeulen@innotractor.com>
2021-11-25 10:45:36 -05:00
Lucas Dietrich
0a0e9079c3 net: mqtt: Add support for TLS option TLS_CERT_NOCOPY
Add an option in MQTT client context to take advantage of the
"TLS_CERT_NOCOPY" option when using  TLS socket transport.

Signed-off-by: Lucas Dietrich <ld.adecy@gmail.com>
2021-11-25 10:44:17 -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
Flavio Ceolin
6451626ce7 pm: Use pm_device_action_run instead of state_set
Since drivers implement a callback based on action and not the state,
we should be using the API based on the action instead of the one based
on the state.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-11-24 14:21:50 -05:00
Jordan Yates
8e99db5801 Kconfig: net: deprecate NET_BUF_USER_DATA_LEN
As user data sizes are now set on a per pool basis, this Kconfig option
has no purpose.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-11-24 16:04:50 +02:00
Jordan Yates
df327eeb58 net: buf: POOL_FIXED_DEFINE explicit user data
Update the macro prototype to explicitly require the length of the
desired user data. Update all in-tree usage of this macro.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-11-24 16:04:50 +02:00
Jordan Yates
8236b600f7 net: buf: POOL_VAR_DEFINE explicit user data
Update the macro prototype to explicitly require the length of the
desired user data. Update all in-tree usage of this macro.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-11-24 16:04:50 +02:00
Jordan Yates
bb780eff99 net: buf: move user_data to flexible arr member
Transition the `user_data` field in `struct net_buf` to be a flexible
array member instead of a hardcoded array. Compile-time asserts are
introduced at the location of the intermediate struct usage to ensure
that the assumptions utilised in runtime code hold true.

The primary assumptions are that the two `user_data` fields exist at the
same memory offset, and that the instantiated struct size can be
determined from the generic struct size and the length of the user data.

`net_buf_id` and `pool_get_uninit` must now use manual address
calculations as the `__bufs` type is no longer the actual size of the
instantiated variable.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-11-24 16:04:50 +02:00
Jordan Yates
ebe3e7d96a net: buf: store user_data size
Store the `user_data` array size on both the pool and net_buf structs.
This will enable length validation once `user_data` fields are not
globally the same size. The new variables fit inside existing padding,
and therefore do not increase the size of either structure.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-11-24 16:04:50 +02:00
Jordan Yates
719b512d7e net: l2: ieee802154: normalize net_buf usage
Replace the statically defined net_buf with the standard mechanism of
allocating the buffer from a pool. This introduces a minor memory
overhead, but has the benefit of ensuring that standard net_buf calls
will work correctly.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-11-24 16:04:50 +02:00
Robert Lubos
f3a9b8c83d net: l2: Add symbols for custom IEEE802154 L2
Define a custom IEEE802154 based L2. The user can then use those symbols
to implement their own 802.15.4 based L2, based on those symbols, w/o a
need to modify the Zephyr tree.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-23 13:25:01 -05:00
Robert Lubos
9a319226f8 net: ieee802154: Add common config for all 802154 L2s
Introduce a common config for all 802.15.4 based L2 implementations.
This way, any custom 15.4 L2 implementation will be able to
automatically enable use 15.4 driver, w/o a need to modify the actual
Kconfig.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-23 13:25:01 -05:00
Robert Lubos
5ff1022fa1 net: websockets: Fix send with large payload
In case the payload and header size exceeded the network MTU size,
`websocket_send_msg()` would only send a part of the payload,
effectively leading to erronous results if called again to send the
rest. Fix the issue, by calling `sendmsg()` in a loop internally in case
it did not manage to send the entire websocket message in a single call.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-23 13:21:09 -05:00
Robert Lubos
85e2bf2a2c net: ethernet: Fix vlan tag verification
`net_eth_vlan_enable()` allowed to use illegal vlan tag values, fix this
by disallowing any tag value higher or equal to 0xfff (which is a limit
for the tag and a reserved value).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-23 10:31:09 -05:00
Jani Hirsimäki
8a51a79d89 net: l2: ppp: possibility to have a custom MRU/MTU
Reading a set MTU from the used net_if when starting LCP.
This enables also other custom MTU/MRU to be set for the link than
the default CONFIG_NET_PPP_MTU_MRU (set by a ppp driver during
initialization).

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2021-11-16 21:25:47 -05:00
Christopher Friedt
3e86c627f7 kernel: atomics: update print specifiers for atomic_t
The print specifier for `atomic_t` should be updated
to `%ld`, `%lu`, or `%lx` to account for the type
change of `atomic_t` to `long`.

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2021-11-15 09:59:01 -05:00
Robert Lubos
c479458392 net: arp: Fix ARP retransmission source address selection
There was a problem with source address selection for ARP
retransmissions, when an ARP entry was already pending. In such case,
the `entry` value passed to `arp_prepare()` is NULL, which in result
caused the `current_ip` variable being used as the source value. The
problem with this approach is, that the `current_ip` is only set in
IPv4 autoconf, the Ethernet L2 does not set this variable. In result,
every retransmission of an ARP packet was sent with unspecified source
address, preventing the response from being handled.

Fix this by partially restoring the behaviour of the ARP source address
assignment from before IPv4 autoconf was introduced. If the ARP is sent
by the IPv4 autoconf, use the `current_ip` value provided. If entry is
not set, use the source IPv4 address set in the actual data packet.
Otherwise, search for a source address on the interface corresponding to
the `entry`.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-11 19:19:40 -05:00
Tomasz Bursztyka
32db35a721 net/tcp: Rename TCP2 to TCP
TCP2 is no longer needed as it is the unique implementation since the
legacy one has been removed.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-11-11 07:26:41 -05:00
Tomasz Bursztyka
65c9d19d51 net/tcp: Rewrite MSS setting function for better readability
Move the structure definition into the relevant header. Rename the
access relevantly as well. It's easier to read without mss_option being
used in various places (struct and access).

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-11-11 07:26:41 -05:00
Tomasz Bursztyka
09f44fc3a1 net/tcp: Fix tiny style issues
Too long lines and indentations mostly. Let's just keep it concistent
over the file.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-11-11 07:26:41 -05:00
Robert Lubos
8ac11b9b6f net: openthread: Fix for OT prompt in the Zephyr shell
OpenThread has changed it's behaviour in terms of prompt printing in the
CLI module. Previously it was only printed on the UART CLI backend, now
it's printed on every CLI backend. This results in a double prompt being
printed when combined with Zephyr shell (one from OT and other form
Zephyr).

This commit adds a temporary fix to prevent OT prompt from being printed
in Zehpyr shell. As a long term solution we should add an option to
OpenThread to allow to disable prompt on the output.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-10 16:36:18 +02:00
Andrew Hedin
a6f831fea6 net: lwm2m: Add IPSO filling sensor object
Add support for the filling sensor object used by the MG100
and BT610 LwM2M demo.

Signed-off-by: Andrew Hedin <andrew.hedin@lairdconnect.com>
2021-11-09 11:19:12 +01:00
Lukasz Maciejonczyk
2d7328af99 net: openthread: fix setting mac keys during stack reset in RCP
During stack reset in RCP, the mac keys are resseting my calling
otPlatRadioSetMacKey with aKeyId == 0. aKeyId == 0 was not handling
properly since it is not valid for mac keys. This commit fixes it.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-11-09 11:18:31 +01:00
Andrew Hedin
e0715556e7 net: lwm2m: Add IPSO current sensor object
Add support for the current sensor object used by the MG100
and BT610 LwM2M demo.

Signed-off-by: Andrew Hedin <andrew.hedin@lairdconnect.com>
2021-11-08 11:01:22 -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
Pavel Hübner
104714394f kernel: Introduce K_MEM_SLAB_DEFINE_STATIC
As the already existing macro K_MEM_SLAB_DEFINE results in
two variable definitions, the preceding static modifier leads to
a seemingly working solution, though linkage conflicts will occur
when the same memory slab name is used across multiple modules.

The new K_MEM_SLAB_DEFINE_STATIC macro duplicates the functionality of
K_MEM_SLAB_DEFINE with the difference that the static keywords are
internally prepended before both variable definitions.

The implementation has been tested on my Zephyr project (the build
issue faded out). The documentation has been updated altogether
with all incorrect occurences of static K_MEM_SLAB_DEFINE.

Signed-off-by: Pavel Hübner <pavel.hubner@hardwario.com>
2021-11-07 05:36:48 -05:00
Jair Jack
5b5417a1dd net: lwm2m: Way to pass a destination hostname to socket
net: lwm2m: When mbedtls CONFIG_MBEDTLS_SERVER_NAME_INDICATION is
enabled, a destination hostname must be passed to socket to properly
connect do lwm2m server.

Passing lwm2m context to lwm2m_parse_peerinfo

Signed-off-by: Jair Jack <jack@icatorze.com.br>
2021-11-06 21:37:12 -04:00
Tomasz Bursztyka
2ae9a54a09 net/tcp: Use highest priority for TCP internal work queue
Reason why the prority was at its lowest is unknown, but now that it may
be used to send local packets (which used to be sent right away),
it seems to affect TCP scheduling in loopback mode. Raising the prority
so it matches how it was previously (i.e. sent right away) should fix
things. (Note however that this issue was not broadly present, only
sockets.tls test seemed to be affected.)

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-11-04 13:54:28 +01:00
Tomasz Bursztyka
8a2e5b1648 net/context: Close TCP connection properly
Closing a connection, thus calling net_context_put() will not close a
TCP connection properly, and will leak tcp connection memory.

This is because: net_context_put calls net_context_unref which calls
net_tcp_unref which leads to unref tcp connection and thus sets
ctx->tcp to NULL. Back to net_context_put, that one finally calls
net_tcp_put: but that bails out directly since ctx->tcp is NULL.

Fixing it by inverting net_tcp_put() and net_context_unref() calls
within net_context_put().

Fixes #38598

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-11-04 13:54:28 +01:00
Tomasz Bursztyka
798588e709 net/tcp: Stop TCP state machine breaking when sending locally
On any target, running a TCP server and a net shell can show the issue:
net tcp connect local_ip port

will fail. Usally it ends up by consumming all tcp connection memory.

This is because in tcp_in(), state changes will most of the time lead to
sending SYN/ACK/etc... packets under the same thread, which will run all
through net_send_data(), back to tcp_in(). Thus a forever loop on SYN ->
SYN|ACK -> SYN -> SYN|ACK until tcp connection cannot be allocated
anymore.

Fixing it by scheduling any local packet to be sent on the queue.

Fixes #38576

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-11-04 13:54:28 +01:00
Sebastian Salveter
4d2e46ddd6 net: lwm2m: Add option to configure device service period
The device service creates a notification of the current time resource
every 10s. This commit adds the possibility to change this timer to a
different value thus giving more control over the way the device object
is notified.

Signed-off-by: Sebastian Salveter <sebastian.salveter@grandcentrix.net>
2021-11-04 07:30:29 -04:00
Marin Jurjević
b6ffd3cac8 net: lwm2m: add missing resources to Firmware Update object
Firmware Update object did not initialise resources PkgName,
PkgVersion and Firmware Update Protocol Support. Initialise
Firmware Update Protocol Support on creation and report CoAP
as default transfer protocol.

Signed-off-by: Marin Jurjević <marin.jurjevic@hotmail.com>
2021-11-03 15:34:15 +01:00
Robert Lubos
96b8ed85ad net: lwm2m: Fix removed engine_observer_list usage
`engine_remove_observer_by_path()` was not updated during some recent
LwM2M observer changes, still using the `engine_observer_list` which got
moved into the `lwm2m_context` structure. Update the function to align
with these changes.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-11-03 11:19:40 +01: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
Paul Gautreaux
50913bd6c8 net: lib: config: Fix the timeout when waiting on network
Loop by LOOP_DIVIDER counts instead of the number of seconds
specified in the timeout.

Fixes #39672

Signed-off-by: Paul Gautreaux <paulgautreaux@fb.com>
2021-11-02 13:23:10 +01:00
Gerhard Jörges
9c7734a63c net: pkt: clone ieee802154 fields in clone_pkt_attributes()
IEEE 802.15.4 fields were missing from cloned net_pkt

Signed-off-by: Gerhard Jörges <joerges@metratec.com>
2021-11-02 11:31:10 +02:00
Chris Pearson
c4842c1879 net: openthread: add log_strdup to role text, fix doc gender issue
- Add a `log_strdup` to the role text output for logging V1
  compatibility
- Fix style issues
- Change where the documentation refers to an OpenThread device as
  "himself" to "itself"

Signed-off-by: Chris Pearson <ctpearson@gmail.com>
2021-11-01 21:47:43 -04:00
Chris Pearson
b8dff131dd net: openthread: Change OT net log to display current role in text
If CONFIG_NET_LOG=y is set, OpenThread will output the current OT
role whenever the state changes.

To simplify understanding of the log output, this change replaces
the numerical role ID with the text name of the role. This also
required a change to a documentation file to replace an instance
of a numerical ID.

NOTE: This is potentially a breaking change should anyone be using
test scripts that monitor the OpenThread state changes and look
for the numerical ID. This does not seem to be the case for the
Zephyr tests, however.

Signed-off-by: Chris Pearson <ctpearson@gmail.com>
2021-11-01 21:47:43 -04:00
Robert Lubos
3a7016d99e net: lwm2m: Fix meaningless operant result coverity issue
There is no need to veirfy the result value of the strtol() operation,
as we copy the result to a 64 bit buffer anyway.

CID: 240696

Fixes #39810

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-10-31 15:31:05 -04:00
Pieter De Gendt
421ecb77a3 net: coap: Add coap_next_block_for_option function
Add a function to update the coap block context from a
packet, according to the block option enum provided.

The existing coap_next_block does not handle block1 transfers
properly because we need to inspect the block1 option
returned by the server. This function is reworked to make use
of the newly introduced one.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-10-27 13:46:19 -04:00
Pieter De Gendt
b966ba16a9 net: coap: Fix size1 for block1 transfers
According to RFC-7959:
When uploading with coap block1 requests the server may respond
with a size1 option (together with the response code 4.13).
This to indicate the maximum size the server is able and willing
to handle.

This commit changes the total_size in the current block context
being handled to the optional size1 option value from the server.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-10-27 13:46:19 -04:00
Pieter De Gendt
c89d5c5e45 net: openthread: Fix alarm timers reference calculation
The OpenThread stack uses uint32_t to calculate expiry time for
alarms, while comparing to zephyr's uint64_t uptime.

This commit fixes broken milliseconds alarms after ~49.7 days of
uptime.

Fixes #39704

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-10-26 09:28:27 -04:00
Veijo Pesonen
d3f4ae20cf net: coap: adds PATCH and iPATCH methods
Based on on RFC 8132 -
PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2021-10-25 13:26:19 +03:00
Veijo Pesonen
3071e97a3a net: coap: adds FETCH method
Based on on RFC 8132 -
PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2021-10-25 13:26:19 +03:00
Florian Vaussard
96c3fd12c4 net: if: ipv6_prefix_find() correctly tests if the prefix is used
ipv6_prefix_find() wrongly tests if the unicast address is in use
instead of the prefix. This has two implications:

- The function can return an expired prefix to net_if_ipv6_prefix_add(),
  which will do nothing more to enable it (since it assumes that it is
  already enabled). As a result, the prefix will not be used by the
  rest of the stack due to prefix->is_used being false.

- ipv6_prefix_find() loops using a bound of NET_IF_MAX_IPV6_PREFIX, but
  the size of the unicast[] array is defined by NET_IF_MAX_IPV6_ADDR.
  This could lead to an out-of-bound access if NET_IF_MAX_IPV6_ADDR is
  smaller than NET_IF_MAX_IPV6_PREFIX.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-10-25 13:19:37 +03: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
Torsten Rasmussen
587285e4de kconfig: canbus: experimental settings now uses select EXPERIMENTAL
With the introduction of `EXPERIMENTAL` and `WARN_EXPERIMENTAL` in
Zephyr all subsys/canbus, subsys/net/l2/canbus, and drivers/can 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.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2021-10-22 13:59:21 +02:00
Caspar Friedrich
c3ca5ada1a net: mqtt: Return meaningful error code from mqtt_init()
The condition checks whether the connection was established or not. The
return value should reflect that.

Signed-off-by: Caspar Friedrich <c.s.w.friedrich@gmail.com>
2021-10-21 10:56:32 -04:00
Damian Krolik
726656dda5 net: openthread: Add crypto backend based on PSA API
OpenThread has lately got an option to provide a custom
crypto backend that replaces the default, based on mbedTLS
API. Implement a backend based on ARM PSA crypto API that
is better suited for applications willing to take advantage
of the ARM trust zone technology.

Add Kconfig option: OPENTHREAD_CRYPTO_PSA_ENABLE which
enables that backend.

Also, another Kconfig option:
OPENTHREAD_PLATFORM_KEY_REFERENCES_ENABLE, implied by the
former, which enables usage of key references instead of
literal keys in OpenThread. It will eventually allow
OpenThread applications to keep sensitive data such as
encryption keys in the secure storage, accessible from the
secure world only.

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
2021-10-17 11:51:38 -04:00
Tjerand Bjornsen
938e0e4966 net: lwm2m: Add default firmware update port
If a firmware update is fetched from a server, and no port number is set
in the URI (e.g. coap://example.com/fw_update), the client will try
to connect on the port specified by CONFIG_LWM2M_PEER_PORT.
If a port different from the peer port is to be used for firmware
update, this has to be set explicitly in the URI:
coap://example.com:5683/fw_update.

This fix adds CONFIG_LWM2M_FIRMWARE_PORT, which will be used when
fetching a firmware update without specifying the port number in the
URI.

Signed-off-by: Tjerand Bjornsen <tjerand.bjornsen@nordicsemi.no>
2021-10-14 16:34:48 -04:00
Andrei Emeltchenko
3f9d980f7c net: tcp: Remove unneeded declaration
Remove unneeded declaration and change include logic.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2021-10-14 16:34:23 -04:00
Andrei Emeltchenko
636c7b1677 net: tcp: Remove redundant TCP option definitions
Use the same TCP option definitions.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2021-10-14 16:34:23 -04:00
Jukka Rissanen
fc5d46048d net: tcp2: Send our MSS to peer
Send our MSS to peer when sending SYN or SYN-ACK.

Fixes #30367

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-10-14 16:34:23 -04:00
Krzysztof Chruscinski
eb3375f47c shell: Add __printf_like to shell_fprintf
Add __printf_like modifier to validate strings used by shell.
Fixing warnings triggered by this change.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-10-14 16:32:19 -04:00
Robert Lubos
875c75c4f9 net: lwm2m: Replace float32_value_t with double
Replace the custom float32_value_t LwM2M type with native double, to
facilitate LwM2M API and improve floating point precission.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-10-13 10:13:32 -04:00
Andrei Emeltchenko
513d691dba net: tcp: Use BIT() macros
Use BIT() macro to make code more readable and consistent.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2021-10-13 06:23:59 -04:00
Andrei Emeltchenko
9d2899657a net: tcp: Fix macro tcp_slist()
Fix error in macro parameter.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2021-10-13 06:23:59 -04:00
Andrei Emeltchenko
2faae3c027 net: tcp: Fix macro conn_send_data_dump()
Fixes error in macro parameter.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2021-10-13 06:23:59 -04:00
Robert Lubos
4e9b9a7fdf drivers: net: loopback: Register loopback IP address to the interface
Regsiter loopback IPv4/IPv6 to the loopback interface during
interface initialization.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-10-13 11:17:51 +02:00
Robert Lubos
6f46124d6e net: if: Skip DAD when adding loopback IPv6 address
There's no point in perfoming DAD procedure for loopback address,
hence skip it.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-10-13 11:17:51 +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
Christopher Friedt
65b1c207f2 net: mdns + dns_sd: fix regression that breaks ptr queries
While adding support for service type enumeration, a regression was
introduced which prevented mDNS ptr query responses.

1. There was an off-by-one error with label size checking
2. Valid queries were failing to match in `dns_rec_match()` due to
   not checking for either NULL or 0 "wildcard" port

Fixes #39284

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2021-10-11 08:50:45 -04:00
Tjerand Bjornsen
872f560981 net: lwm2m: Fix device obj missing error code ri
From the OMA LwM2M Object and Resource Registry: "When the single Device
Object Instance is initiated, there is only one error code Resource
Instance whose value is equal to 0 that means no error."

This fix creates that initial error code resource instance, and makes
sure that it doesn't get deleted by the Reset Error Code resource.

Signed-off-by: Tjerand Bjornsen <tjerand.bjornsen@nordicsemi.no>
2021-10-07 15:44:46 -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
b78b7d5264 net: websocket: s/mbedtls_sha1_ret/mbedtls_sha1/
sha1 function signature changed in mbedTLS 3.0.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
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
b30958e85f net: tcp2: Fix mbedTLS usage
s/mbedtls_md5_ret/mbedtls_md5/

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
Robert Melchers
59fcf8c031 net: ethernet: ARP addresses being filled with mcast addresses
Fixes #38994, ARP messages were being sent to IPvXmcast MAC addresses
rather than the expected source MAC address or the broadcast address.

Signed-off-by: Robert Melchers <rmelch@hotmail.com>
2021-10-07 11:23:20 +02:00
Jani Hirsimäki
e913fda436 net: l2: wifi_shell: mac address in scanning results
Showing mac address in scanning results.

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2021-10-07 10:55:37 +02: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
Ryan Erickson
f7208bbb62 net: lwm2m: Add option to force close the connection
Add an option to force close the LwM2M connection
instead of always trying to deregister.
If on a cellular connection and the connection is dropped,
deregistering will never complete and take a long time
before retries fail. This option allows the app to close the
socket and quickly re-establish the connection when the
network connection is available again.

Signed-off-by: Ryan Erickson <ryan.erickson@lairdconnect.com>
2021-10-05 19:23:59 -04:00
Veijo Pesonen
b3bc827366 net: lwm2m: Decouple CoAP message- and block size
If blockwise transfer is not in use it must be possible to send bigger
CoAP messages than what is the block size used with blockwise transfers.

To compensate for the increased memory usage number of in-flight packets
allowed could be decreased.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2021-10-05 19:22:54 -04:00
Veijo Pesonen
32b4ec44fe net: lwm2m: Fix Kconfig help about allowed...
...range for LWM2M_COAP_BLOCK_SIZE.

The range has been set to start from 64 bytes and now the help text has
been brought up to date.

Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
2021-10-05 19:22:54 -04:00
Christopher Friedt
fa26dc0988 net: dns_sd, mdns: support service type enumeration
Support DNS-SD Service Type Enumeration in the dns_sd library
and mdns_responder sample application.

For more information, please see Section 9, "Service Type
Enumeration" in RFC 6763.

https://datatracker.ietf.org/doc/html/rfc6763

Fixes #38673

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2021-10-01 20:11:50 -04:00
Eduardo Montoya
b945d7aee4 openthread: align platform code to ARM PSA changes
Align `otPlatRadioSetMacKey` with latest upstream changes.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-10-01 11:37:38 +02: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
f0ec61ef70 net: mqtt: Handle incomplete zsock_sendmsg write
In case zsock_sendmsg did not send all of the data requested, update the
`struct msghdr` content and retry.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-29 11:08:40 +02:00
Robert Lubos
6e04a0f59d net: context: Do not overflow net_pkt when using msghdr
If data for `context_sendto()` was provided in a form of
`struct msghdr` (for instance via `sendmsg()`), it was not verified that
the provided data would actually fit into allocated net_pkt. In result,
and error could be returned in case the provided data was larger than
net_pkt allows.

Fix this, by verifying the remaining buffer length when iterating over
`struct msghdr`. Once the buffer is filled up, break the loop. In
result, functions like `sendmsg()` will return the actual length of data
sent instead of an error.

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
Markus Fuchs
fb082a6923 net: dns: Make mdns and llmnr responders join their multicast groups
As with IPv6, the mdns and llmnr responders should join their multicast
groups for IPv4 instead of just adding the multicast address to the
interface.

Signed-off-by: Markus Fuchs <markus.fuchs@ch.sauter-bc.com>
2021-09-28 20:04:49 -04:00
Markus Fuchs
7926657b27 net: if: Add IPv4 support to multicast monitor
Make multicast group join/leave monitor support both IPv6 and IPv4
addresses.

Fixes #26585

Signed-off-by: Markus Fuchs <markus.fuchs@ch.sauter-bc.com>
2021-09-28 20:04:49 -04:00
Alex Sergeev
e7778b8584 net: ptp: extract PTP interfaces outside gPTP subsys under NET_L2_PTP
As per #38352, we would like to start building out PTP (IEEE 1588)
support for superset of gPTP functionality in Zephyr. This is the first
step to abstract away some key interfaces from NET_GPTP umbrella to
NET_L2_PTP.

Signed-off-by: Alex Sergeev <asergeev@carbonrobotics.com>
2021-09-28 20:01:16 -04:00
Nicolas Pitre
fd3dd0c2d6 net_buf_slist_{put|get}: make SMP safe
Replace irq_lock() with a spin lock, and rework the `get` version
to be entirely SMP safe.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-09-28 11:37:56 +02:00
Nicolas Pitre
8cd7f1c98a net_buf_alloc_len: make SMP safe
Replace irq_lock() with a spin lock.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-09-28 11:37:50 +02:00
Florian Vaussard
52638a000f net: ipv6_fragment: send ICMPv6 Time Exceeded upon reassembly timeout
RFC 2460 Sec. 5 requires that a ICMPv6 Time Exceeded message is sent
upon reassembly timeout, if we received the first fragment (i.e. the one
with a Fragment Offset of zero).

Implement this requirement.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
c66b4288e0 net: ipv6_fragment: fix shift_packets() algorithm
The purpose of shift_packets() is to make room to insert one fragment in
the list. This is not what it does currently, potentially leading to
-ENOMEM even if there is enough free room.

To see the current behaviour, let's assume that we receive 3 fragments
in reverse order:
- Frag3(offset = 0x40, M=0)
- Frag2(offset = 0x20, M=1)
- Frag1(offset = 0x00, M=1)

After receiving Frag3 and Frag2, pkt[] will look like:

  .-------.-------.-------.
  | Frag2 | Frag3 | NULL  |
  | 0x20  | 0x40  |       |
  '-------'-------'-------'
    pkt[0]  pkt[1]  pkt[2]

When receiving Frag1, shift_packets(pos = 0) is called to make some room
at position 0. It will iterate up to i = 2 where there is a free
element. The current algorithm will try to shift pkt[0] to pkt[2], which
is indeed impossible but also unnecessary. It is only required to shift
pkt[0] and pkt[1] by one element in order to free pkt[0] to insert
Frag1.

Update the algorithm in order to shift the memory only by one element.
As a result, the ENOMEM test is only simpler: as long as we encounter
one free element, we are guaranteed that we can shift by one element.
Also assign a NULL value to the newly freed element since memmove() only
copy bytes.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
a9917d9bd4 net: ipv6_fragment: improve reassembly condition
Currently net_ipv6_handle_fragment_hdr() performs 2 distinct tests: it
checks the M-bit of the most recent fragment to decide if we can proceed
with the reassembly. Then it performs some sanity checks which can lead
to dropping the whole packet if not successful.

The test on the M-bit assumes that fragments arrive in order. But this
will fail if packets arrive out-of-order, since the last fragment can
arrive before some other fragments. In that case, we proceed with the
reassembly but it will fail because not all the fragments have been
received.

We need a more complete check before proceeding with the reassembly:
- We received the first fragment (offset = 0)
- All intermediate fragments are contiguous
- The More bit of the last fragment is 0

Since these conditions can also detect a malformed fragmented packet, we
can replace the existing sanity check that is performed before
reassembly. As a bonus, we can now detect and rejected overlapping
fragments, since this can have some security issues (see RFC 5722).

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
4fe978661a net: ipv6_fragment: store M-bit in addition to the offset
Currently we only store the fragment offset. But in some cases it might
be necessary to also inspect the M-bit (More Fragment) of all received
fragments.

Modify the semantics of the field to store all the flags, rename the
setter to account for this change, and add a getter for the M-bit.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
0fcf87540e net: ipv6_fragment: remove special handling of 1st fragment
The special handling of the 1st fragment in unnecessary, since it will
be correctly handled even without it. Moreover it causes some corner
cases, like a single packet with a fragment header (M=0), to be
incorrectly handled since the reassembly code is skipped.

Remove the special handling of the 1st fragment to fix these problems.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
108ccfe60c net: ipv6_fragment: check the length also for the first fragment
Currently the requirement of the length being a multiple of 8 is not
tested for the first fragment, since the first fragment takes a
different path due to the goto.

Move the test earlier in the process, so that it is performed on all
fragments, including the first one.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
e6a1643add net: ipv6_fragment: fix NULL pointer dereference issues
If we have less fragments than what can be stored in the reassembly
array, some loops will blindly dereference NULL pointers.

Add checks for NULL pointers when necessary and exit the loop.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
5252468c06 net: ip: replace hardcoded NET_IPV6_FRAGMENTS_MAX_PKT with a Kconfig
Currently the stack is limited to a maximum of 2 incoming fragments per
packet. While this can be enough in most cases, it might not be enough
in other cases.

Make this value configurable at build time.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
0b8a884931 net: ipv6: fix the logics of prev_hdr_offset
Currently prev_hdr_offset always equals 6, which is the offset of
the nexthdr field in the IPv6 header. This value is used to overwrite it
when removing an IPv6 Fragment header, so it will work as long as there
is no other Extension header between the IPv6 header and the Fragment
header.

However this does not work in the other cases: the nexthdr field of the
IPv6 header will be overwritten instead of the nexthdr field of the last
Extension header before the Fragment, leading to unwanted results.

Update prev_hdr_offset so that it always point to the nexthdr field of
the previous header, either the IPv6 header or an Extension header.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
4bacedb4f3 net: ipv6: reject invalid nexthdr early
The current validation code waits to process the header before rejecting
it, while some checks can be already enforced when reading the nexthdr
field of the previous header.

The main problem is a wrong pointer field in the resulting ICMPv6 error
message: the pointer should have the offset of the invalid nexthdr
field, while currently it will the offset the invalid header.

To solve that problem, reorganize the loop in two parts: the first
switch validates nexthdr, while the second switch processes the current
header. This allows to reject invalid nexthdr earlier.

The check for duplicated headers is also generalized, so that we can
catch other kind of headers (like the Fragment header).

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
cd1ab54525 net: ipv6: check for NET_IPV6_NEXTHDR_NONE earlier
By definition, NET_IPV6_NEXTHDR_NONE is void. So we must stop processing
before trying to read any data, since we will start reading values that
are outside the Extension Header (likely the payload, if any).

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
e9dff0fd1f net: ipv6: correctly set the offset to the unknown option
When an unknown option is encountered, an ICMPv6 error message must be
sent in some cases. The message contains a pointer field, which must be
the offset to the unknown option. Currently the offset is computed from
the beginning of the option list, while it should be computed with
respect to the beginning of the IPv6 header.

Record the offset when reading the option type and pass it later to
ipv6_drop_on_unknown_option() to correctly set the pointer field. Also
rename the argument in ipv6_drop_on_unknown_option() to make the
purpose more clear.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
1f402cc5c8 net: ipv6: correctly handle PADN option
Currently PADN data are not skipped, which results in the stack to think
that the next header starts in the middle of the padding. We have to
skip the bytes before going on.

Also clarify the PAD1 does not have any length field.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
ed1ca3e201 net: ipv6: rename nexthdr and next_nexthdr for readability
The current names are confusing. Indeed "nexthdr" if the type of the
header currently processed, while "next_nexthdr" is the nexthdr field of
the current header.

Rename them to improve readability and make it less error-prone.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Florian Vaussard
6ee4950230 net: icmpv6: fix net_icmpv6_send_error() dropping packets
ICMPv6 error messages are not sent (on native_posix) because the first
net_pkt_write() returns an error.

pkt has just been allocated using net_pkt_alloc_with_buffer(). Trying to
write an empty packet in overwrite mode will result in an error. There
is no need to be in overwrite mode, since we want to write the LL
src/dst addresses at the beginning.

Signed-off-by: Florian Vaussard <florian.vaussard@gmail.com>
2021-09-23 13:21:09 -04:00
Markus Fuchs
54dbfe2229 net: ethernet: Refactor IPv4 to MAC multicast address conversion
Refactor IPv4 multicast address to MAC multicast address conversion
into its own function, so it can be reused by drivers as it is already
possible for IPv6 multicast addresses.

Signed-off-by: Markus Fuchs <markus.fuchs@ch.sauter-bc.com>
2021-09-23 04:19:31 -04:00
Robert Lubos
2160e0fc36 net: lwm2m: Fix Registration failue reporting
In case LwM2M server or bootstrap server rejected
Registration/Registration Update/Deregsitration attempt, there were no
reasonable notification to the application. Fix this by reporting
LWM2M_RD_CLIENT_EVENT_*_FAILURE in such case.

Addtitionaly, remove pointless ENGINE_DEREGISTER_FAILED event, which
have no use in the state machine.

Finally, simplify the response code logging to prevent code duplication.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-21 09:32:31 -05:00
Robert Lubos
88c06aeb24 net: lwm2m: Fix IPSO Push Button counter incrementation
The Counter resource in the IPSO Push Button object was incremented
silently by the post write handler of the State resource. This prevented
the resource from being marked as updated, effectively preventing
the engine from sending notifications to observers.

Fix this, by setting the new counter value with `lwm2m_engine_set_u64()`
instead. This will update the resource value, and trigger the engine to
send notifications if needed.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-20 05:59:28 -04:00
Robert Lubos
be7faf7c08 net: http: Fix HTTP_DATA_FINAL notification
HTTP_DATA_FINAL was incorrectly notified in case Content Length field
was present in the HTTP respone - in such case it was set for every
response fragment, not only the last one.

Fix this by relying on `message_complete` flag instead of
`http_should_keep_alive()` function to determine whether to notify
HTTP_DATA_FINAL or not. As the HTTP parser calls the
`on_message_complete()` callback in either case (response is chunked or
not), this seems to be a more reasonable apporach to determine whether
the fragment is final or not.

Additinally, instead of calling response callback for
`on_body`/`on_message_complete` separately, call it directly from
`http_wait_data()` function, after the parsing round. This fixes the
case when headers were not reported correctly when the provided buffer
was smaller than the total headers length, resulting in corrupted data
being reported to the user.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-17 08:12:00 -04:00
Robert Lubos
81595ed4db net: lwm2m: Fix binary to float32_value_t conversion
The helper function to conver 32-bit binary float value to
float32_value_t incorrectly identified the "hidden" bit, resulting in
invalid conversion when TLV encoding was used to write a resource
(the output value was divided by 2).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 19:04:52 -04:00
Robert Lubos
36a72dd101 net: lwm2m: Fix JSON write handling
There were several issues preventing JSON format writes to work
correctly:

1. The formatter wrongly assumed that Base Name and Relative Name values
   read from the message are NULL terminated, which in result could give
   invalid results when combining them.
2. The formatter wrongly assumed that Relative Name is always present,
   which is not always the case. In result, it failed to parse messages,
   which contained full path in their Base Name Field
3. There were no boundaries check when reading JSON variable name/value,
   which could lead to buffer overflow in case malformed data was
   received.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 19:04:52 -04:00
Robert Lubos
a98d47b8eb net: lwm2m: Fix JSON floating point handling
Just like plain text, JSON parser ignored leading zeros after decimal
point, giving invalid results. Fix this in a similar way as for the
plain text.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 19:04:52 -04:00
Robert Lubos
20a4d181e1 net: lwm2m: Fix plain text floating point handling
Floating point parser for plain text format was parsing floats wrongly,
ignoring leading zeros after decimal points.

Fix this, by reusing atof32() function, already avaialbe in a different
part of the engine, which did the parsing correctly.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 19:04:52 -04:00
Robert Lubos
b6f69a6df1 net: lwm2m: Align float handling with specification
According to the specificaion, resources are not predefined to use 32 or
64 bit floating point numbers, but should rather accept any of them (as
indicated by the size of the TLV in the message). This lead to issues
for instance with Eclipse Leshan LWM2M server, where Leshan sent 64-bit
value, while Zephyr expected 32-bit, making it impossible to write
the resource.

Therefore, unify the float usage to 32-bit float representation and fix
the TLV parsing functions, to accept values sent as either 32 or 64 bit
float.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-16 19:04:52 -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
Jani Hirsimäki
9de47d2b0b net: ip: packet_socket: fixing raw sckt IPPROTO_RAW usage
net_packet_socket_input() was changed to hardcode the return of
NET_CONTINUE and that caused a segmentation fault/crash in
net_core/process_data(), in cases when pkt was unreferred and
NET_OK was returned from net_conn_input()
This happened with socket combo of: AF_PACKET+SOCK_RAW+IPPROTO_RAW.

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2021-09-14 08:37:36 -04:00
Stancu Florin
3eb203fd45 net: ipv6: fix NBR lock initialization
The nbr_lock var actually depends on CONFIG_NET_IPV6_NBR_CACHE
(not CONFIG_NET_IPV6_ND), so move its initialization call.

Signed-off-by: Stancu Florin <niflostancu@gmail.com>
2021-09-14 09:56:37 +02:00
Aleksander Wasaznik
fbe7699c82 Bluetooth: Host: Doc fixup for rename of BT_SECURITY_L*
BT_SECURITY_LOW and etc. were previously renamed and are no longer
valid.

The original rename is in the following commits:
1c48757d94 (New names, deprecate old)
5f2a9ba8e4 (Remove deprecated names)

Signed-off-by: Aleksander Wasaznik <aleksander.wasaznik@nordicsemiconductor.no>
2021-09-13 11:56:21 -04:00
Robert Lubos
083f3065b4 net: lwm2m: Remove LWM2M_RES_TYPE_U64 type
Since it's not possible to encode full range of 64-bit unsigned integer,
remove this type from the LwM2M implementation, and replace its uses
with 64-bit signed integer.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-10 11:04:41 +02:00
Robert Lubos
b474e0a8c3 net: lwm2m: Fix unsigned integers ecoding in TLV
As the resource values represented by the unsigned integers were casted
to integers of a corresponding size in the read handler, they were not
ecoded properly if the unsigned value was larger than the maximum
integer value of the corresponding size (i.e. they were encoded as
negative values).

Fix this by casting the unsinged value to a wider integer type, to
prevent incorrect interpratetion of the data provided. The TLV encoding
functions take care of the optimization (i. e. encoding integers on the
minimum number of bytes needed), so it should prevent bandwith waste if
the unsigned value would actually fit into the integer of the
corresponding size.

Similar case is for the write hander, where unsigned integers encoded at
8 bytes were not processed correctly. Fix this by using wider decoder as
well.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-10 11:04:41 +02:00
Robert Lubos
9886d18c5c net: shell: Fix assertion in net nbr command
Listing a neighbour table with "net nbr" command, when a  neighbour w/o
assigned link address was present, resulted in an assert condition. Add
additional check to prevent this.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-09-09 21:44:16 -04:00
Nicolas Marty
2f28059b1e net: tcp: accept [FIN, PSH, ACK] in TCP_FIN_WAIT_2 state
TCP state machine gets stuck in TCP_FIN_WAIT_2 state
when server responds with [ FIN, PSH, ACK ]

Fixes #37842

Signed-off-by: Nicolas Marty <nicolas.marty@zuehlke.com>
2021-09-09 21:18:25 -04:00
Benedikt Schmidt
a8b7caa58d net: http: switch to zsock_ for http_client
Using zsock_ in http_client instead of the POSIX API versions of the
functions allows the usage of http_client in combination with
CONFIG_POSIX_API.

Signed-off-by: Benedikt Schmidt <benedikt.schmidt@embedded-solutions.at>
2021-09-09 21:16:28 -04:00
Marcin Niestroj
02fa7be52d net: mqtt: check mqtt_abort() function parameters before locking
Function parameters can be checked without MQTT instance lock being
held. Additionally if NULL parameter would be passed (which this check
tries to handle), then function would return without releasing lock.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2021-09-02 19:36:03 -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
Eduardo Montoya
36459a95ea net: openthread: allow to enable/disable TCP
Allow to enable/disable the OpenThread TCP implementation. Disable
it by default.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-09-01 10:37:41 +02:00
Przemyslaw Bida
f77c7dc2c8 manifest: Regular upmerge to bring the openthread CSL fixes.
Periodic upmerge of OpenThread.

Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
2021-08-30 13:32:53 +02:00
Johann Fischer
f460848002 net: ot: rework NCP interface configuration
Rework NCP interface configuration and NCP sample. Remove
CONFIG_OPENTHREAD_COPROCESSOR_SPINEL_ON_UART_DEV_NAME and
CONFIG_OPENTHREAD_COPROCESSOR_SPINEL_ON_UART_ACM Kconfig
options in favor of chosen node zephyr,ot-uart usage.

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
2021-08-23 18:53:47 -04:00
Stancu Florin
4561ea0ae2 net: ieee802154: software dest address filtering
Checks PAN ID for matching self address / broadcast, then the short /
extended address based on the used address mode.

Only when IEEE802154_HW_FILTER is not advertised by driver.

Signed-off-by: Stancu Florin <niflostancu@gmail.com>
2021-08-17 09:19:39 -04:00
Daniel Leung
e912a0533a drivers: ethernet: build as static library
Instead of putting object files inside libzephyr.a,
simply build a separate static library as most other
driver types are doing this already.

Note that the include to subsys has been moved from
under the drivers into subsys, as it is actually
the subsystem's job to make sure the include
directories are correct.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2021-08-17 06:06:03 -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
Eduardo Montoya
570dab7a1a net: openthread: add Netdata Publisher Kconfig option
Enable new feature from the upmerge:
- OPENTHREAD_NETDATA_PUBLISHER

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-08-11 11:29:36 -04:00
Eduardo Montoya
4b4e298914 net: openthread: propagate security and header updated flags
When transmitting a frame, inform the radio driver whether
security processing and/or header updates are needed or not.

When a frame was transmitted, inform back to OpenThread whether
the security procedure and/or header updates were completed for
the frame or not.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-08-11 11:29:36 -04:00
Lingao Meng
8e1682d1ea samples: conn_cb replace to const zsector
It is more efficient and saves part of RAM
by replacing it with static one dynamically.

Signed-off-by: Lingao Meng <menglingao@xiaomi.com>
2021-08-11 13:42:28 +02:00
Berend Ozceri
46adc9eef5 net: icmp: add option to suppress destination unreachable errors.
By default ICMP desination unreachable error packets are generated when
input packets target ports that are not in a listening state. This not
only reveals the presence of the host on the network which may be
considered a security vulnerability depending on the application, it
also ends up triggering ARP lookups to respond to the sending host. With
a small ARP table and a network where there may be broadcast (or
multicast) service discovery traffic such as mDNS or uPnP, ARP table
thrashing can occur impacting network stack performance.

Signed-off-by: Berend Ozceri <berend@recogni.com>
2021-08-11 11:46:44 +02:00
Przemyslaw Bida
678a170925 net: openthread: Add capability to disable properly CSL.
This commit adds capability to disable CSL sampling by setting
CSL period to 0.

Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
2021-08-07 20:27:25 -04:00
Ramesh Babu B
d40d963bef net: fix for assert on enabling socket CAN
Socket CAN does not require interface link address to be
assigned, check is not applicable for socket CAN
interfaces. As this address is NULL for socket CAN interface
it results in assertion.

Signed-off-by: Ramesh Babu B <ramesh.babu.b@intel.com>
2021-08-07 20:10:48 -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
Lukasz Maciejonczyk
53531a7682 openthread: implement missing time service functionality
Add missing otPlatTimeGet implementation which is needed for proper
calculation the time offset in host-RCP communication.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-08-05 16:14:24 +02:00
Eduardo Montoya
3872812ffc net: openthread: fix error codes for TX done
Fix potential bug when returning error codes not handled by
OpenThread in `otPlatRadioTxDone`.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-08-05 11:26:27 +02:00
Robert Lubos
bbc6c66ed8 net: websocket: Fix poll handling for offloaded sockets
ZFD_IOCTL_POLL_OFFLOAD operation needed special handling, as it needed
to modify the fds table for the offloaded implementation, overwriting
websocket file descriptors with the underlying offloaded ones. This is
only needed for the offloaded sockets, as the native implmentation use
POLL_PREPARE/UPDATE operations instead.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-08-04 16:58:15 +02:00
Robert Lubos
a6a9d7a368 net: websocket: Fix ioctl implementation for websocket
The websocket implementation of ioctl wrongly passed websocket context
to the undrelying `ioctl` implementation instead of the context of the
underlying socket.

Additionally, currentl implementation used the vtable of the native
socket implementation unconditionally, making it unusable with an
offloaded underlying socket.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-08-04 16:58:15 +02:00
Gerard Marull-Paretas
d41dadc569 pm: rename PM_DEVICE_STATE_SUSPEND to PM_DEVICE_STATE_SUSPENDED
The verb tense for the suspended state was not consistent with other
states. The likely reason: state was being used as a command/action.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-08-04 08:23:01 -04:00
Maik Vermeulen
7a2a28b9d5 net: lwm2m: Synchronized functions mutating the RD client's state
A mutex is used to syncrhonize the start, stop and service() functions
of the RD client. Previously it could happen that while service() was
working on e.g. bootstrapping, a stop() call by another thread would
close the socket. Then the bootstrapping process would detect it as a
network error, and restart the process.

Fixes #37170.

Signed-off-by: Maik Vermeulen <maik.vermeulen@innotractor.com>
2021-08-03 10:22:10 -04:00
Pieter De Gendt
4192c8b83e net: coap: coap_next_token single sys_rand_get call
Improve coap_next_token by using a single sys_rand_get call.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-07-29 11:47:51 -04:00
Eduardo Montoya
cf57b86363 net: openthread: add three configuration options
Enable to configure:
- `OPENTHREAD_CONFIG_CLI_MAX_LINE_LENGTH`
- `OPENTHREAD_CONFIG_IP6_MAX_EXT_UCAST_ADDRS`
- `OPENTHREAD_CONFIG_IP6_MAX_EXT_MCAST_ADDRS`

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-07-29 11:00:19 -04:00
Arvin Farahmand
c95e0825d2 dsa: updated api to use net_if
Change DSA API to use `net_if` directly to make API calls instead of
indirectly via `dsa_context` and `switch_id`.
Remove unused `switch_id`, `switch_enable_port`, and `dsa_get_context`.

Signed-off-by: Arvin Farahmand <arvinf@ip-logix.com>
2021-07-26 19:37:22 -04:00
Fabio Baltieri
532a85ccd9 tests: net: dns-sd: add a test case for setup_dst_addr
Add a test case for mdns setup_dst_addr.

Signed-off-by: Fabio Baltieri <fabio.baltieri@gmail.com>
2021-07-26 10:46:50 -04:00
Fabio Baltieri
c25b04bfd3 net: mdns: set the correct type of dst addr
Check for the address family of the packet when setting the multicast
destination address used in the response. Current code checks either the
query type or the stack configuration, which can result in setting the
wrong type of address for the frame.

Signed-off-by: Fabio Baltieri <fabio.baltieri@gmail.com>
2021-07-26 10:46:50 -04:00
Fabio Baltieri
1d500f075c net: dns_sd, mdns: add few missing strdup
Add few missing log_strdup found when running the mdns code with
debugging enabled.

Signed-off-by: Fabio Baltieri <fabio.baltieri@gmail.com>
2021-07-26 10:46:50 -04:00
Lingao Meng
6e7939bc77 net: Fix missing __ASSERT_ON micro
Fix missing `__ASSERT_ON` cause build error
when not defined.

Signed-off-by: Lingao Meng <menglingao@xiaomi.com>
2021-07-22 06:21:55 -04:00
Nicolas Pitre
b6855b23b9 net: bridge: Ethernet bridge shell utility
This provides a command line interface to query and modify
bridge instances, similar to Linux's brctl utility.
It can be used to inspect an application's bridge usage,
or manage a bridge of its own in a generic way.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-07-21 18:20:01 -04:00
Nicolas Pitre
89482f0119 net: ethernet: bridging support
This adds the ability to create Ethernet bridges for connecting
separate Ethernet segments together to appear as a single
Ethernet network.

This mimics the Linux functionality of the same name.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-07-21 18:20:01 -04:00
Robert Lubos
0722e1d896 net: lwm2m: Prevent notifications on non-readable resources
In case a non-readable resource gets updated (either by the server or
with an API), it makes no sense to send a notification in such case, as
no such resources are not included in notifications anyway.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-20 13:33:22 +02:00
Jedrzej Ciupis
25ebb42bd9 net: pkt: remove ieee802154_frame_retry flag
Flag that indicates if a given packet is being retransmitted has become
obsolete since more detailed flags were added. This commit removes the
flag and references to it altogether.

Signed-off-by: Jedrzej Ciupis <jedrzej.ciupis@nordicsemi.no>
2021-07-19 18:15:56 +03: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
Pieter De Gendt
de13034502 net: openthread: add Kconfig options for periodic parent search
The openthread has enhanced features for periodic parent search,
this commit adds kconfig options to enable and configure these.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-07-15 15:16:32 +02:00
Marcin Niestroj
1ce1d19bb5 net: pkt: introduce net_pkt_remove_tail()
Introduce a helper function for being able to remove any arbitrary
length from tail of packet. This is handy in cases when removing
unneeded data, like CRC once it was verified.

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2021-07-15 06:54:33 -04:00
Eduardo Montoya
72cc39d843 net: openthread: handle NONE level logs
`OT_LOG_LEVEL_NONE` has some uses within OpenThread but it is not
hanled in the Zephyr's platform implementation. This commit makes
use of those logs as `LOG_LEVEL_ERR` level.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-07-14 13:14:59 -04:00
Gerard Marull-Paretas
26ad8376bd pm: remove callback from control function
The callback is not used anymore, so just delete it from the pm_control
callback signature.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-07-13 09:36:45 -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
Chih Hung Yu
13b2e5bac4 net: ip: Fix assertion failure when tcp_send_data()
When tcp_send_data() is called to resend data, but there is no data
to resend, zero length packet is allocated and NULL net_buf is passed
to net_buf_frag_insert() in which assertion fails.

Fixes #36578

Signed-off-by: Chih Hung Yu <chyu313@gmail.com>
2021-07-12 20:08:01 -04:00
Robert Lubos
942ece2a3d net: l2: ieee802154: Fix LL address handling on frame reception
6lowpan module can swap the original buffer with a newly allocated one
during decompression in case the decompressed header would not fit into
the original buffer. Therefore, storing the LL address offset and
restoring the pointer after decompression as it is done today is not
correct, as the new packet with decompressed IPv6 header will not
contain the LL header.

As the 6lowpan module doesn't deallocate the original buffer and
doesn't overwrite the LL header, its fine to use the original
pointers as they are.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-09 09:10:56 -04:00
Damian Krolik
bf3c6e7ba4 manifest: update openthread
Regular OpenThread upmerge to bring in a fix for a possible
infinite loop and support for DNS service subtypes.

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
2021-07-07 07:47:52 -05:00
Robert Lubos
b369156e28 net: lwm2m: Fix how payload offset is calculated
Instead of manually computing payload offset, let the CoAP library do
the work, and use the payload pointer returned by the
`coap_packet_get_payload()` function instead.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-07 07:40:55 -05:00
Robert Lubos
0bc4e7619b net: coap: Fix coap_packet_get_payload function
The function did not work correct for packets generated with Zephyr
APIs, as `max_len` holds the entire buffer size, not the actual packet
size.

Additionally, unify how Payload Marker is handled in the calculation -
currently the coap parsing function adds it to the `opt_len` field,
which is counter-intuitive.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-07 07:40:55 -05:00
Robert Lubos
78e84eb3e7 net: coap: Adjust offset value after packet parsing
It is important that offset is set in the same manner, regardless of the
origin packet - it should indicate the final packet length in both
cases, when the packet is generated on the Zephyr side with CoAP APIs,
and when it's parsed from the UDP datagram. This allows for functions
like `coap_packet_get_payload()` to work correcty in both cases.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-07-07 07:40:55 -05: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
Markus Rekdal
3221a1e8e7 net: lwm2m: Fix handling of multi instance resources with one instance
This will fix a bug caused by creating a multi instance resource with
only a single resource. Previously this was treated as a single instance
resource. This is now properly treated as a multi instance resource with
one instance
Signed-off-by: Markus Rekdal <markus.rekdal@nordicsemi.no>
2021-07-02 08:30:28 -04:00
Pieter De Gendt
13d5894e46 net: openthread: Implement otPlatAssertFail
Add a platform implementation for OpenThread's otPlatAssertFail
and enable it by default.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-07-01 13:22:01 -04:00
Vlad Tuhut
7580623a36 net: mqtt: Add custom transport type
Add new custom transport type.
This allows user defined transport for MQTT communication.
The user must implement the transport procedure.

Fixes **#27015**

Signed-off-by: Vlad Tuhut <vlad.tuhut@raptor-technologies.ro>
2021-06-29 11:34:57 -04:00
Pieter De Gendt
a5ec72418c net: openthread: Convert API worker thread to a work queue
Direct openthread API usage requires explicit locking,
which is also used internally.
Exposing a work queue through the openthread context allows
work to be submitted without the need to block other threads.

In particular with CONFIG_OPENTHREAD_MANUAL_START, application
logic can offload work which otherwise would need to wait for
the lock to become available.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-06-29 11:27:54 -04:00
Pieter De Gendt
cdf7d314fe net: coap: Fix coap client observe out-of-order messages
coap_response_received returned NULL if the observe option was out of
order, however it makes more sense to return the coap_reply handler
without actually calling it.

Additionally the reorder check has been modified to partially match
the RFC.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-06-29 10:27:22 -04:00
Piotr Mienkowski
ccc0999b80 net: refactor tftp library
- bugfix: Accept initial tftp server reply from a port different than
  the one used to establish the connection (typically 69) as mandated
  by RFC 1350. Previous implementation was not standard compliant.
- bugfix: close socket in case of error or timeout.
- bugfix: Reset retransmit counter after receipt of a good packet.
- bugfix: Use CONFIG_TFTP_LOG_LEVEL to set log level.
- api: upon successful receipt of the file set `client.user_buf_size`
  to the size of the file received.
- Restructure the code, comments.
- Limit usage of global variables.
- Limit usage of `goto`.

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
2021-06-29 09:15:55 -04:00
Eduardo Montoya
0f73fbdbfe drivers: ieee802154: add CSL receiver for nRF5
Implement CSL receiver functionality in nRF5 radio driver.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-06-24 11:31:24 -04:00
Pieter De Gendt
72985d5f32 net: openthread: Protect OT API calls during initialization
The openthread initialization in turn calls platform specific
functions, lock the API during this step.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-06-24 11:29:50 -04:00
John Power
3138d89fd9 net: lwm2m: notify timeout handling
Added notify_timeout_cb to struct lwm2m_ctx to allow application to
 handle notify timeout
Added lwm2m_rd_client_update to lwm2m.h to allow application to
 trigger registration update
Added notify_message_timeout_cb which calls notify_timeout_cb from
 struct lwm2m_ctx and logs an error message

Fixes #31499

Signed-off-by: John Power <john.power@xylem.com>
2021-06-23 08:02:06 -04:00
Przemyslaw Bida
976c413d75 openthread: fix not working ot diag repeat command
This commit fixes diag repeat command port by fixing issue with
incorrectly handled repeat timer.

Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
2021-06-22 08:21:41 -04:00
Jukka Rissanen
07bbc9045d net: context: Check null pointer access in check_used_port()
There is a small window between when socket is created and
before it is bound to a local address, where the local address
pointer might be NULL.

Fixes #36276

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-06-21 18:46:41 -04:00
Eduardo Montoya
3417c9a132 net: openthread: remove unneded Kconfig dependency
`OPENTHREAD_SHELL` does no longer dependend on
`OPENTHREAD_COPROCESSOR` being disabled.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-06-19 16:54:44 -05:00
Chih Hung Yu
421ff4758f net: ip: Fix TCP unacked_len
TCP unacked_len can be set to zero in tcp_resend_data(),
and then be minus by len_acked when ACK is received,
resulting in a negative unacked_len value.

Fixes #36390

Signed-off-by: Chih Hung Yu <chyu313@gmail.com>
2021-06-18 16:21:29 +03: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
Robert Lubos
d42eb134a0 net: dhcpv4: Prevent DHCP client from clearing the gateway
In case both, static IP address configuration and DHCP were used, and no
DHCP server was avaliable in the network, clearing the gateway address
rendered the network interface unusable as it's gateway configuration
was cleared.

Prevent this by removing the gateway clearing during the DHCP
inititalization. If the DHCP server is available in the network, the
gateway address will be overwriten after receiving the DHCP OFFER
message or cleared if there's no Router option is avaiable in the
DHCP OFFER message.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-06-16 10:40:54 +02:00
Kiril Petrov
613677daf8 net: lwm2m: fix build with bootstrap enabled
After lwm2m async io was introduced with 32989a38f0,
one instance of function lwm2m_send_message() was left unchanged,
and makes build to fail when boostrap support is enabled.

Signed-off-by: Kiril Petrov <retfie@gmail.com>
2021-06-14 14:10:36 +03:00
Kiril Petrov
a0fd010455 net: lwm2m: code clean-up after switch to async socket io
Three is no need to check return code as lwm2m_send_message_async()
never fails.

Signed-off-by: Kiril Petrov <retfie@gmail.com>
2021-06-14 14:10:36 +03:00
Jukka Rissanen
10762673db net: shell: Add more Ethernet capability strings
Add descriptions for Qbv, Qbu and TXTIME capability bits.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-06-14 07:00:10 -04:00
Kweh Hock Leong
77d8662454 net: eth: Add TXTIME configuration support
Allow caller to either set or receive per queue Ethernet TXTIME
configuration option.

Signed-off-by: Kweh Hock Leong <hock.leong.kweh@intel.com>
2021-06-14 07:00:10 -04:00
Jukka Rissanen
44efc18a78 net: eth: Add Qbu configuration support
Allow caller to either set or receive various Ethernet Qbu
configuration options defined in IEEE Std 802.1Qbu-2016
specification.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-06-14 07:00:10 -04:00
Jukka Rissanen
d0a45e243f net: eth: Add Qbv configuration support
Allow caller to either set or receive various Ethernet Qbv
configuration options defined in IEEE Std 802.1Qbv-2015
specification.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-06-14 07:00:10 -04:00
Dominik Dess
f55c473a06 net: lwm2m: lwm2m stops sending messages after encountering signals on send
Fixed issue that caused message to be not correctly reset even after
 it is consumed after send sets errno to EAGAIN or EWOULDBLOCK

Signed-off-by: Dominik Dess <dominik.dess@grandcentrix.net>
2021-06-12 08:51:08 -05:00
Pawel Dunaj
1286c8d105 net: depend dns resolver on native net
DNS resolver won't work for offloaded stack.

Signed-off-by: Pawel Dunaj <pawel.dunaj@nordicsemi.no>
2021-06-10 17:44:51 +03:00
Rafał Kuźnia
24b2ef4590 net: openthread: set ieee802154_frame_retry flag
The ieee802154_frame_retry will be set by the OpenThread integration
layer in the event of frame retransmission.

Signed-off-by: Rafał Kuźnia <rafal.kuznia@nordicsemi.no>
2021-06-10 11:03:40 +03:00
Eug Krashtan
86fc962a48 net: coap: Keep user data inside message
Keeping user data in the CoAP packet

Signed-off-by: Eug Krashtan <eug.krashtan@gmail.com>
2021-06-09 18:41:42 +03:00
Eduardo Montoya
ae44b30b41 drivers: ieee802154: include timestamp in acks
Fill the ACK timestamp field in nRF5 driver. This is required by
OpenThread for the proper CSL transmitter functioning.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-06-08 04:54:38 -05: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
Lukasz Maciejonczyk
1f0b783bbb drivers: ieee802154: replace enh ack probing with generic IE conf
Use IE variable of ieee802154 MAC frame instead of Thread specific
configuration call for configuring injection of vendor specific
data into enh ack.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-06-07 10:41:07 +03:00
Henning Fleddermann
05b2018ffa lwm2m: keep track of observations per client
this has a number of advantages:
- allows to only create notifications for each client if there are no
  messages already waiting to be send, in practice prioritizing the
  memory for messages for answers, thus staying more "responsive".
- saves a fair bit of memory by eliminationg now redundant client_ctx
  pointer per observer.
- fixes a potential subtle bug: previously, an observer reset would've
  stopped the first observation found with a matching token, which
  might've belonged to a differen client.

Signed-off-by: Henning Fleddermann <henning.fleddermann@grandcentrix.net>
2021-06-07 10:39:37 +03:00
Henning Fleddermann
32989a38f0 lwm2m: use asynchronous socket io
This restructures the lwm2m_engine to use a non-blocking socket access
instead of the previously used blocking style, and eliminates any
socket-access from outside of the main work loop.

The main motivation behind this is an issue within nordics
nrf_modem_lib/modem-fw on nrf9160, that leads to socket send() calls to
block indefinitely when the shared memory used for
rpc-communication with the modem is already exhausted because of
incoming data.

This lead to the lwm2m_engine locking up on send calls when there is
also a large amount of incoming data.

This works around this issue, by only issuing send calls when poll
reports the socket to be ready for sending, and (more importantly) by
always receiving all buffered incoming data before sending anything.

There might still be a (perhaps academic) possibility where this
situation might be triggered, when  the scheduler interrupts the lwm2m
thread in-between receiving and sending, but for now we have not yet
observed this.

Besides working around the aforementioned issue, this also simplifies
the way resends are handled as they are no longer send from the main
system-workqueue, and limits all interaction with the sockets to a
single thread.

Signed-off-by: Henning Fleddermann <henning.fleddermann@grandcentrix.net>
2021-06-07 10:39:37 +03:00
Hubert Miś
b39537d151 drivers: ieee802154: make keys management API generic
Keys management API for IEEE 802.15.4 drivers was specific for Thread
protocol. With this change API is more generic and aligned with Thread
needs.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-06-07 10:39:14 +03: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
Lukasz Maciejonczyk
8b12311bdf net: openthread: add option to configure software transmission security
If radio driver supports transmission security we need an option
to disable transmission security which by default is done by OT stack
for Thread v1.2

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-06-04 16:19:16 -05:00
Joakim Andersson
faae326648 net: l2: bluetooth: Handle error if failed to register server
Return error code if init code failed to register the L2CAP server.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
2021-05-28 10:44:47 -05:00
Pieter De Gendt
6d99e952cd net: mgmt: Initialize the event callbacks statically
This commit allows to add callbacks to NET_EVENT_IF_UP events before
the network initialization.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2021-05-28 07:00:23 -05:00
Eduardo Montoya
9c6895105d drivers: ieee802154: fix ACK length handling
OpenThread expects the FCS field at the end of the ACK frame to be
passed with `otPlatRadioTxDone`.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-05-27 12:59:06 -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
0f69123897 net: tcp2: Ack any data received in FIN_WAIT_1 state
If we receive any data in FIN_WAIT_1, then ack it even if we
are discarding it.

Fixes #33986

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
Signed-off-by: Jim Paris <jim@jim.sh>
2021-05-24 23:30:36 -04: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
Jukka Rissanen
46efe3ed70 net: packet: Do not drop net_pkt immediately
If there are no sockets in the system, then do not drop the
packet immediately as there can be other L2 network handlers
like gPTP in the system. This will also allow ICMP messages
to pass to local handler.

Fixes #34865

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-24 23:29:24 -04:00
Benjamin Lindqvist
f0f1a4d724 net: lwm2m: no duplicate device error codes
The resource description on the OMA LwM2M registry states that only the
first instance of a particular error should trigger creation of a new
error code instance.

Signed-off-by: Benjamin Lindqvist <benjamin.lindqvist@endian.se>
2021-05-21 04:55:26 -05:00
Jukka Rissanen
03e1872def net: tcp: Change locking order in connection establishment
When application calls TCP connect(), the call is blocked
by a semaphore which is then released when the connection
is established. Unfortunately the semaphore release was done
before the connection was marked as established. Depending
on the configuration options set, it is possible that after
the semaphore release, the thread that is waiting on connect()
is run immediately. Because of this, the connection bookeeping
still thought that the connection was not established even if
it was. A simple solution is to release the semaphore after
the connection is marked as established.

Fixes #35390

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-19 07:52:26 -05:00
Eduardo Montoya
68626227a3 net: openthread: fix CSL API
A couple of fixes on the OpenThread radio implementation.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-05-18 11:24:40 -05:00
Justin Morton
e3517e5080 net: http: update status if no status text is provided
Call on_status if the Reason-Phrase is not provided.
This allows for the numeric status code to be set.
Also, ensure the numeric status code is always set
in on_status, not just if the specific callback is set.

Signed-off-by: Justin Morton <justin.morton@nordicsemi.no>
2021-05-18 11:23:59 -05:00
Johann Fischer
21b3609824 net: enable TX thread if USB device support is enabled
Without TX thread support in network stack USB device stack
blocks it self by usb_transfer_sync() which is
called in the same context as usb_set_interface() in sequence
of netusb_enable(), net_if_up(), net_l2_send().

Fixes: #35338

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
2021-05-18 11:21:51 -05:00
Jan Buenker
6815ef4a46 net: lwm2m: Only parse TLV from the first block
This was already implemented for firmware update packages.
For other opaque resources it failed to determine the target resource
id, which is now stored in the block_context.

Signed-off-by: Jan Buenker <jan.buenker@grandcentrix.net>
2021-05-13 22:07:25 -04:00
Damian Krolik
643eb2080b openthread: shell: Do not execute OT commands when OT is not ready
OpenThread shell tries to execute commands without checking
if the shell has already been initialized. As a result, we
may hit an assertion in the OpenThread CLI code. It's
particularly painful in automated tests which spawn commands
very early in the firmware boot process.

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
2021-05-12 08:31:08 -05:00
Jukka Rissanen
f602801f91 net: igmp: Fix uninitialized variable
The return value might be uninitialized if there was no
suitable IPv4 address found for the network interface.

Coverity-CID: 224630
Fixes #35158

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-11 15:44:50 -05:00
Lukasz Maciejonczyk
977aba6d02 net: openthread: Fix multiple Kconfig enablers for Link Metrics
Remove duplicated enabler for Link Metrics feature.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-05-11 09:53:29 +03:00
Robert Lubos
eaeac46720 net: openthread: Fix OT shell crash
After the recent OpenThread upmerge, OpenThread changed its behaviour in
terms of CLI handling during commissioning procedure. OpenThread will
now call the registered CLI callback when it recieves the Discovery
message.

This resulted in a crash if no CLI command was executed by the user
before, because the `shell_p` pointer was only set in the command
handler. As it was not set to the actual shell backend instance, it
caused a crash (or assert if enabled) in the `shell_vfprintf()`
function.

Fix this by verifying the `shell_p` pointer in the
`otConsoleOutputCallback()` function before use. Additionally, set the
pointer to the most common UART shell backed (if enabled) in the
initialization function so that the initial messages from OpenThread are
not dropped.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-05-11 09:53:12 +03:00
Jukka Rissanen
29e023d4e0 net: shell: Fix crash when invoking dns command in shell
This fixes a crash when typing "net dns" command in net-shell

Fixes #35041

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-11 09:52:10 +03:00
Jukka Rissanen
6485e7d07f net: if: Do not check IPv4 multicast addr when selecting src addr
When destination address is a multicast address, select the source
address from non link local address first.

This means that for example if we are responding to mDNS query,
and we have both normal IPv4 and LL (169.254.x.y) address set for
the interface, we are now able to select the normal address instead
of the LL one.

Fixes #34409

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-11 09:51:31 +03:00
Aurelien Jarno
c387a0dd57 net: tcp: select MBEDTLS_MAC_MD5_ENABLED for ISN algorithm
The ISN algorithm from RFC 6528 doesn't need Mbed TLS, but rather the
MD5 algorithm from Mbed TLS. Therefore select MBEDTLS_MD and
MBEDTLS_MAC_MD5_ENABLED in addition to MBEDTLS.

This fixes the following build failure when using TLS version 1.2 is
selected:
  zephyr/subsys/net/ip/tcp2.c:1329: undefined reference to
  `mbedtls_md5_ret'

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2021-05-10 05:30:03 -05:00
Aurelien Jarno
c30339aa16 net: openthread: Select ECDSA when SRP is enabled
SRP client and server require ECDSA to be enabled otherwise the build
fails. Select OPENTHREAD_ECDSA for both OPENTHREAD_SRP_CLIENT and
OPENTHREAD_SRP_SERVER options.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2021-05-10 05:29:19 -05:00
Aurelien Jarno
bc9e759ca4 net: openthread: Move SRP Kconfig options to Kconfig.features
OPENTHREAD_SRP_CLIENT and OPENTHREAD_SRP_SERVER are Thread features and
not Thread configuration, so move them to Kconfig.features.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2021-05-10 05:29:19 -05:00
Aurelien Jarno
a80e28a26c net: openthread: Make child related options only visible on FTD
The OPENTHREAD_MAX_CHILDREN and OPENTHREAD_MAX_IP_ADDR_PER_CHILD options
make not sense for a MTD device. Make them depend on OPENTHREAD_FTD.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2021-05-10 05:29:19 -05:00
Torsten Rasmussen
3a0951fcd0 openthread: kconfig: rework OpenThread security configurations
With the updates to mbedTLS Kconfig it is now possible to update the
OpenThread security configurations by disabling the mbedTLS prompt and
avoid stuck symbol selection.

As part of this, the OpenThread security selection has been reworked
into a choice which ensures only a single security selection can be
chosen.

And the OPENTHREAD_MBEDTLS itself has been made promptless to ensure
other parts of the build system can select a specific OpenThread
security implementation and disable user selection, if the module or
sample require such behavior.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2021-05-09 15:24:23 -05: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
Ioannis Glaropoulos
61df25d867 Revert "openthread: kconfig: rework OpenThread security configurations"
This reverts commit 88f3a9899a.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2021-05-09 09:59:22 -05:00
Torsten Rasmussen
88f3a9899a openthread: kconfig: rework OpenThread security configurations
With the updates to mbedTLS Kconfig it is now possible to update the
OpenThread security configurations by disabling the mbedTLS prompt and
avoid stuck symbol selection.

As part of this, the OpenThread security selection has been reworked
into a choice which ensures only a single security selection can be
chosen.

And the OPENTHREAD_MBEDTLS itself has been made promptless to ensure
other parts of the build system can select a specific OpenThread
security implementation and disable user selection, if the module or
sample require such behavior.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2021-05-08 07:11:00 +02:00
Flavio Ceolin
0c607adb63 pm: device: Align state names with system states
Change device pm states to the same pattern used by system power
management.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-05-07 18:35:12 -04:00
Jukka Rissanen
bcdc762609 net: Use k_fifo instead of k_work in RX and TX processing
The k_work handler cannot manipulate the used k_work. This means
that it is not easy to cleanup the net_pkt because it contains
k_work in it. Because of this, use k_fifo instead between
RX thread and network driver, and between application and TX
thread.

A echo-server/client run with IPv4 and UDP gave following
results:

Using k_work
------------
TX traffic class statistics:
TC  Priority	Sent pkts	bytes	time
[0] BK (1)	21922		5543071	103 us	[0->41->26->34=101 us]
[1] BE (0)	0		0	-
RX traffic class statistics:
TC  Priority	Recv pkts	bytes	time
[0] BK (0)	0		0	-
[1] BE (0)	21925		6039151	97 us	[0->21->16->37->20=94 us]

Using k_fifo
------------
TX traffic class statistics:
TC  Priority	Sent pkts	bytes	time
[0] BK (1)	15079		3811118	94 us	[0->36->23->32=91 us]
[1] BE (0)	0		0	-
RX traffic class statistics:
TC  Priority	Recv pkts	bytes	time
[0] BK (1)	0		0	-
[1] BE (0)	15073		4150947	79 us	[0->17->12->32->14=75 us]

So using k_fifo gives about 10% better performance with same workload.

Fixes #34690

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-07 09:46:44 -05:00
Jukka Rissanen
2697275d23 net: ppp: Convert to use k_fifo instead of k_work
Following commits will remove k_work from net_pkt, so convert
PPP L2 to use k_fifo when sending PPP data.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-07 09:46:44 -05:00
Jukka Rissanen
0808ead6ff net: 6locan: Convert to use k_fifo instead of k_work
Following commits will remove k_work from net_pkt, so convert
6locan L2 to use k_fifo between application and TX thread, and
driver and RX error handler.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-05-07 09:46:44 -05:00
Lukasz Maciejonczyk
103b516a3c net: openthread: add Link Metrics API
This commit implements the OpenThread APIs to configure Enhanced-ACK
Based Probing in radio for a specific Initiator. This is needed for
Link Metrics functionality.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-05-06 09:57:15 -05:00
Eduardo Montoya
93fda9356f net: openthread: complete CSL receiver API
This commit implements the missing OpenThread APIs related to CSL
receiver configuration.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-05-06 07:47:10 -05:00
Gerard Marull-Paretas
7988ab4a26 pm: rename device_set/get_power_state to pm_device_set/get
Make name consistent with other device PM APIs.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-05-05 18:35:49 -04:00
Gerard Marull-Paretas
2c7b763e47 pm: replace DEVICE_PM_* states with PM_DEVICE_*
Prefix device PM states with PM.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-05-05 18:35:49 -04:00
Robert Lubos
126da28620 net: lwm2m: Trigger registration update only when registered
Add extra check for the LwM2M client state, to allow triggering of the
Registration Update message only when registered.

This fixes an issue, when the `trigger_update` flag could be set during
the bootstrap procedure (when the value of the Lifetime resource was
set), which resulted in an uneccessary Registration Update message just
after the successful registration.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-05-05 14:04:41 -05:00
Eduardo Montoya
121a164ec0 net: openthread: add CSL receiver API
This commit implements the OpenThread APIs to configure a radio
reception slot at a specific time. This is needed for the correct
functioning of a CSL receiver.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-05-05 14:04:14 -05:00
Eduardo Montoya
a47677da06 net: openthread: add CSL transmitter API
This commit implements the OpenThread APIs to pass MAC keys and
frame counter to the radio layer in order to process the
transmission security. This is needed for the correct functioning
of a CSL transmitter.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-05-05 14:33:47 +02:00
Lukasz Maciejonczyk
4500862af1 net: openthread: Init NCP after USB communication is established
The device has sent RESET_POWER_UP message before the communication
with the host hadn't been established. It could be observed with
pyspinel which displayed `Framing error`.

This commit fixes the bug by initializing NCP after the host stated
is ready to communicate.

This commit reverts initialization the USB stack into function
otPlatUartEnable to be consistent with others OpenThread platforms.
OpenThread co-processor samples are not affected by #27071 as they use
USB for SPINEL communication with host and not for UART console.

Note:
When co-processor communicates by USB CDC ACM and it is hard reset
(what is happening in current Zephyr OpenThread platform)
the connection needs to be properly handled by the host.

For posix platform used together with RCP it was implemented in:
https://github.com/openthread/openthread/pull/6454

and for NCP:
https://github.com/openthread/wpantund/pull/492 .

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-04-30 12:58:31 -05:00
Robert Lubos
39aee39cf9 net: openthread: Align with the new NCP API
OpenThread modified its NCP API, so we need to align with these changes
in Zephyr.

One of the major changes was removal of UART from the platform APIs.
`openthread/platform/uart.h` header file was moved to
`examples/platforms/util/uart.h` so we need to use the new location in
Zephyr. This means that OpenThread no longer impose the UART API but for
the simplicity of the upmerge I've kept the UART APIs as they are for
now.

The NCP initialization function have now to register a send handler,
and the appropriate transport driver have to call NCP callbacks when
transmission/reception is done. For now, re-use the existing code of
the UART driver, just as the upstream NCP application does.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-30 12:55:02 -05:00
Robert Lubos
c2ad0dff72 net: openthread: Use OT mutex in OT shell
Use OpenThread mutex in order to protect OT CLI API call instead of
halting the OpenThread thread.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-30 12:55:02 -05:00
Robert Lubos
983ee8b088 net: openthread: Align with the new CLI API
The OpenThread CLI API has changed therefore it's needed to align
OpenThread Shell implementation in Zephyr with these changes.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-30 12:55:02 -05:00
Robert Lubos
7ca3ccdd0d net: openthread: Introduce new OpenThread options
Introduce new OpenThread configuration options from the upmerge.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-30 12:55:02 -05:00
Robert Lubos
0d1577f7fe net: lwm2m: Add API function to delete object instance
Since the API already has a function to create an LwM2M object instance,
it makes sense to add a corresponding delete funtion, allowing the
application to delete created objects.

Additionally, for the remote delete set the Registration Update trigger
only when not in bootstrap mode.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-29 09:51:54 -04:00
Robert Lubos
66c5fdc984 net: lwm2m: Fix Registration Update send on object creation
The Registration Update message should be sent whenever an object
instance is created or deleted. Currently this was only the case when an
object instance was created by the server and not by the application.
Fix this by triggerng the Registration Update from the API function
as well.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-29 09:51:54 -04:00
Piotr Szkotak
c60d500bf9 net: openthread: Increase stack sizes with FP context
This PR increases the OpenThread stacks to compensate
for the runtime increase of the MPU stack guard
when the usage of the FP context is detected.

Signed-off-by: Piotr Szkotak <piotr.szkotak@nordicsemi.no>
2021-04-29 09:50:44 -04:00
Marcin Niestroj
d30b68a39a net: ppp: ipcp: use dns_resolve_reconfigure() API
Use recently introduced API, which takes care of gracefully closing any
pending DNS requests and replacing existing DNS server list with new
one.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-04-29 08:00:09 -04:00
Marcin Niestroj
de15a49640 net: dhcpv4: use dns_resolve_reconfigure() API
Use recently introduced API, which takes care of gracefully closing any
pending DNS requests and replacing existing DNS server list with new
one.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-04-29 08:00:09 -04:00
Marcin Niestroj
71c31c45c7 net: dns: add dns_resolve_reconfigure() API
So far there was no dedicated mechanism for replacing DNS servers with
new list. Add dns_resolve_reconfigure() API that allows to achieve that
in a thread-safe manner.

Introduce 3rd state in DNS context lifetime by converting from 'bool
is_used' to 'enum dns_resolve_context_state state'. This new
DEACTIVATING state allows to mark a DNS context as busy and safely close
context without holding lock. Closing DNS context with released lock
prevents deadlock in case net_context_close() has to synchronize with a
separate thread executing handler passed to net_context_recv() (which is
the case for example with ESP-AT WiFi driver).

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-04-29 08:00:09 -04:00
Marcin Niestroj
83e5953783 net: dns: protect 'is_used' with mutex
ctx->is_used member seemed to be used sometimes within a mutex acquired
block, sometimes not. Make it consistent by always using it with
acquired mutex.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-04-29 08:00:09 -04:00
Jukka Rissanen
a1c4952dfd net: ipv4: Add IGMPv2 support
Add Internet Group Management Protocol v2 support, see RFC 2236
for details.

Fixes #2336

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-29 14:49:55 +03:00
Jukka Rissanen
d28e64c602 net: stats: Add IGMP statistics support
Collect IPv4 IGMP sent/received/dropped statistics.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-29 14:49:55 +03:00
Jukka Rissanen
e5043f5a7f net: if: Add IPv4 multicast address join/leave functions
Allows caller to mark IPv4 multicast address to be used or not.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-29 14:49:55 +03:00
Gerard Marull-Paretas
f163bdb280 power: move reboot functionality to os lib
Reboot functionality has nothing to do with PM, so move it out to the
subsys/os folder.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-04-28 20:34:00 -04:00
Robert Lubos
653c987762 net: lwm2m: Fix lwm2m_path_log_strdup buffer usage
Currently the lwm2m_path_log_strdup allocates a temporary buffer on a
stack, and then passes it to the log_strdup function to create a copy
of the string for the logger. log_strdup however will not copy the
string if for instance immediate logging is used, therefore the logging
function will still use the memory address of the already invalid buffer
allocated within lwm2m_path_log_strdup.

Fix this by passing an addittional `buf` parameter to the
lwm2m_path_log_strdup function, therefore allowing the user to provide
the buffer within a valid scope.

CID: 220536
Fixes #34005

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-28 19:30:09 +02: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
Gerard Marull-Paretas
3daf9f2d97 net: remove usage of device_pm_control_nop
If device PM is not implemented just use NULL.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-04-27 16:28:49 -04:00
Robert Lubos
afaf52af66 net: trickle: Do not initialize a work item from its handler
Initializing a work item from its handler will destroy the content of
the kernel structures used to process the work item. This can lead to a
system crash for example when the delayed work is being rescheduled when
the previous run is already queued for processing but not yet executed.

Fix this by initializing the work item once during trickle timer
creation and moving the logic, previously achieved by switching the work
handler, into the new work handler.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-27 19:48:16 +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
3b08e87680 net: If userspace support is enabled, then we need TX/RX threads
If user enables CONFIG_USERSPACE, then at least one TX or RX thread
is needed to isolate the application from the kernel space components.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-27 12:02:19 +03:00
Jukka Rissanen
f5fb80750e net: Enable running without TX or RX threads
Set the default behaviour of the networking subsystem so that
no TX or RX threads are created. This will save RAM as there
is no need to allocate stack space for the RX/TX threads.
Also this will give small improvement to network packet latency
shown here:
* with 1 traffic class (1 TX and RX thread)

Avg TX net_pkt (42707) time 60 us	[0->22->15->22=59 us]
Avg RX net_pkt (42697) time 36 us	[0->10->3->12->7=32 us]

* with 0 traffic classes (no TX and RX threads)

Avg TX net_pkt (41608) time 42 us	[0->21->20=41 us]
Avg RX net_pkt (41593) time 31 us	[0->9->12->8=29 us]

In this qemu_x86 test run, 40k UDP packets was transferred between
echo-server and echo-client. In TX the speed increase was 30% and
in RX it was 14%.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-27 12:02:19 +03:00
Jukka Rissanen
d533f95e18 net: pkt: Set the pkt creation time more accurately
Set the net_pkt creation time just before the actual net_pkt
is allocated in order to get more accurate information for
statistics.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-27 12:02:19 +03:00
Jukka Rissanen
c59372b6e6 net: Push highest priority net_pkt directly to driver
If user has set the priority of the sent net_pkt to highest
priority (NET_PRIORITY_CA) and enabled CONFIG_NET_TC_SKIP_FOR_HIGH_PRIO
option, then push that packet directly to driver instead of TX queue.
This will make the TX sending latency smaller for the high priority
packet. This is not enabled by default.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-27 12:02:19 +03:00
Eduardo Montoya
8ff12f3ace net: openthread: enable CSL delayed transmissions
Add support for delayed transmission of frames for the CSL
Transmitter OpenThread function.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-04-26 13:40:43 +02:00
Trond Einar Snekvik
2d983a89ad net: shell: Wrap iface_flags2str in #ifdef to silence warning
The net_shell only uses iface_flags2str when CONFIG_NET_NATIVE is
enabled. Disabling this produces an "unused function" warning for this
function. Wrap the function in an #ifdef to silence the warning for this
configuration.

Signed-off-by: Trond Einar Snekvik <Trond.Einar.Snekvik@nordicsemi.no>
2021-04-26 12:41:13 +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
Marcin Niestroj
d98911d712 net: dns: add 10ms delay when rescheduling query timeout handler
Query timeout handler is rescheduled if DNS context mutex is locked. So
far there was no timeout used, which means that work is simply put at
the end of system workqueue. This solves cases when mutex is locked by
any higher priority cooperative threads.

If however mutex was locked in application code within lower priority
thread (which is very likely) and query timeout has expired in the
meantime, then system workqueue is busy looping by calling query timeout
handler and trying to acquire DNS context lock.

Reschedule query timeout handler with 10ms delay, so that all
threads, including those with lower priorities, have a chance to move
forward and release DNS context lock.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-04-23 15:05:41 -05:00
Maik Vermeulen
ae4c5193a3 net: coap: coap_find_options() now returns 0 when options empty
coap_find_options() now first checks if there is actual payload
to parse.

Fixes #34463.

Signed-off-by: Maik Vermeulen <maik.vermeulen@innotractor.com>
2021-04-22 19:34:11 +03:00
Paul Sokolovsky
01014a2c05 net: sntp: Depend on NET_SOCKETS_POSIX_NAMES || POSIX_API
This library is coded with standard POSIX names for socket functions,
so make that requirement explicit.

Also, switch it from select'ing NET_SOCKETS, to depend'ing on it. This
follows the general approach of avoiding unneeded select's in Zephyr,
which lead to conflicting dependencies and make debugging dependencies
complex overall. In this particular case, it's fair (for a user) to
expect that "simple network time protocol" requires networking API,
namely sockets, and have that explicitly on in their app configuration,
giving better overview of their app config overall.

Fixes: #34165

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2021-04-22 13:41:33 +03:00
Luiz Augusto von Dentz
33d95894e1 Bluetooth: Align error handling of send functions
This aligns the error handling of send function to never unref the
buffer in place so the caller retain the ownership of the buffer
whenever there is an error.

Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
2021-04-20 18:20:04 -04:00
Jukka Rissanen
d7321152a9 net: virtual: Remove unnecessary null check
The virtual_iface is already NULL checked by net_if_get_by_iface()
at the beginning of the function so no need to do it here too.

Coverity-CID: 220535
Fixes #34006

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-20 13:44:39 -04:00
Jukka Rissanen
c2877579ba net: virtual: Remove dead code
Simplifying the loop in order to remove dead code (ctx_up is
always NULL after the slist loop.

Coverity-CID: 220538
Fixes #34003

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-20 13:44:39 -04:00
Krzysztof Chruscinski
320f7c3808 net: lib: openthread: logging: Refactor logging function
Refactor logging function to avoid multiple macro calls.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-04-19 10:59:23 -04:00
Krzysztof Chruscinski
67fade04a0 net: l2: bluetooth: Add cast to forward declared struct
Logging v2 is using _Generic keyword for detecting type of
log message arguments. Apparently, it does not support handling
of pointers to forward declared structures. Added casting to void *.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-04-19 10:59:23 -04:00
Maik Vermeulen
4d85426688 net: lwm2m: Made pmin and pmax attributes optional
Made the LwM2M engine checks for pmin and pmax optional to adhere to
the LwM2M specificattion. We now first check that pmin and pmax are
actually set. Also changed the default CONFIG values for the attributes
pmin and pmax to 0 to indicate that they are not active by default.

Fixes #34329.

Signed-off-by: Maik Vermeulen <maik.vermeulen@innotractor.com>
2021-04-16 15:32:04 -04: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
Arvin Farahmand
e4a349ff76 net: icmpv4: fix broadcast ping reply bug
If `CONFIG_NET_ICMPV4_ACCEPT_BROADCAST` is enabled ICMPv4 should reply
to request packets sent to the broadcast address of an interface with
the unicast address of that interface from the same subnet.

Previously the code blindly copied the ICMP source address which meant
it would reply to broadcast packets with a broadcast source address.

Signed-off-by: Arvin Farahmand <arvinf@ip-logix.com>
2021-04-15 10:43:51 +03:00
Robert Lubos
19e7451c34 net: lwm2m: Fix unitialized variable error in Link Format writer
The `init_string` array could have been used uninitialized, fix this
by initializing it as an empty string, which is a desired content in
case it's not overwritten.

CID: 220302
Fixes #33839

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-04-14 14:36:35 -05:00
Asger Munk Nielsen
b9b1c7e19b Bluetooth: controller: ISO adaptation layer, Rx unframed
First design towards ISO adaptation layer, this PR introduces
data-structures and framework for Rx unframed PDUs (BT RX ingress).
Two callbacks are defined for the SDU production (BT RX egress), one for
SDU allocation as well as a callback for emitting a reassembled SDU.

Signed-off-by: Asger Munk Nielsen <asmk@oticon.com>
2021-04-14 18:17:09 +02:00
Justin Morton
35f598ba93 net: http: add numeric http status code to response struct
Add numeric http status code to the response struct to allow for
easier processing by the caller.   Textual status already exists.

Signed-off-by: Justin Morton <justin.morton@nordicsemi.no>
2021-04-14 18:46:47 +03:00
Eduardo Montoya
4289e46ae7 net: openthread: switch radio off when stopping diags
This commit puts the radio in sleep mode when the diagnostics are
stopped.

This fixes an assert on MAC code when `ot diag stop` command is
issued while `ot diag send` is still ongoing.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-04-14 17:38:27 +03:00
Peter Bigot
188cb2cb7c net: Conversion of k_work API
Replace all existing deprecated API with the recommended alternative.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-14 07:07:40 -04: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
Eduardo Montoya
1d668d4b7c net: openthread: add microseconds timer API
Add OpenThread API to handle microseconds timer, to be used initially
by CSL receiver.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-04-12 17:01:14 +03:00
Jukka Rissanen
ce2abc26b5 net: capture: Catch sent and received packets
Create net_l2_send() function which will be called by each L2
sending function so that we can catch all the network packets
that are being sent. Some L2 layers send things a bit differently,
so in those cases call the net_capture_send() directly by the L2
layer.
Add network packet capture call in receive side after the pkt has
been received by the RX queue handler. This avoids calling the
net_capture_send() from ISR context.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
af2711db23 net: shell: Print external net_pkt slab information
The "net mem" command did not print external net_pkt slabs
properly (the number of free net_pkt's was not printed).

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
313d973be0 net: shell: Show detailed interface information
Show detailed information about network interface that is down,
only when user asks such information about one specific network
interface. This means that for "net iface" command only
"Interface is down." is printed but the command "net iface 1"
will print detailed information even if interface is down.
This helps to view the information and user does not need
to bring interface up to see the details.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
c5d062a400 net: shell: Add network packet capture support
Add commands in shell to setup and enable/disable network
packet capture.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
e917d80473 net: capture: Add support for network packet capturing
Add infrastructure to allow user to configure the system so that
all the network packets, that are sent to or received from a specific
network interface, are sent to remote system for analysis.
The captured network packets are placed as a payload in UDP packet,
which is then sent inside a tunnel to a remote host. The host can
then receive the packets and for example show them in wireshark.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
0501957f26 net: pkt: Add helper to store capture bit
Add get/set helpers to store information whether the net_pkt
is captured already or not. This bit is used to detect capture
loop and avoid recursion.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
c6fac25e87 net: pkt: Make net_pkt_clone() to use the original slab
Instead of forcing net_pkt_clone() use the tx_pkts slab, use
the same slab that was used when allocating the original net_pkt.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
934caba82b net: l2: ipip: Support more than one IPIP tunnel
Alloc code to create more than one IPIP tunnel interface.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -04:00
Jukka Rissanen
574b8725e0 net: l2: ipip: Add capability bit for IPIP tunnel
The IPIP tunnel capability bit helps to detect which network
interface supports IPIP tunneling.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-02 07:24:06 -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
Jani Hirsimäki
5d76e8aca8 net: ppp: dialup enablers
Introducing PPP dialup features to enable e.g. usage of nrf9160
based board as a dialup modem for transferring ip data over PPP
 (e.g. windows dial up), i.e. usage of Zephyr PPP as a server for
 providing MTU/MRU, IP address and DNS addresses for a PC:
- PPP LCP MRU option (configurable)
- PPP server: IPCP ip and dns address peer options to enable
providing IP and DNS addresses for PPP peer.

Signed-off-by: Jani Hirsimäki <jani.hirsimaki@nordicsemi.no>
2021-04-01 09:43:56 +03:00
Benjamin Lindqvist
e3f8757b70 net: lwm2m: Allow cancel-observe to match path
The specification states that the server can cancel observations "at any
moment, by sendinga GET request with Observe option=1, the LwM2M Server
cancancel an “Observe”operation on a specified Resource, or specified
Object Instance(s)."

It does not mention any token matching requirement, but RFC 7641 does.
The correct interpretation is not obvious. The EMQx LwM2M implementation
uses a new token for instance, which does not work with Zephyrs token
matching cancel-observe.

This commit introduces cancel-observe via path matching as a Kconfig
option. This could hypothetically introduce problems when we are
connected to multiple peers simultaneously, but since that is not likely
to be supported for a long time (if ever), this change should be fairly
uncontroversial since path matching is only used as a fallback.

Signed-off-by: Benjamin Lindqvist <benjamin.lindqvist@endian.se>
2021-04-01 09:42: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
Hubert Miś
a41a3b703d net: ip: select src ip address with valid scope for mcast dst
IPv6 source address selection procedure selected link-local address
for any muticast destination with other scope than mesh-local. It
was a cause of problems for broader multicast scopes like admin-, or
site-local. For such broader scopes source address must be at least
as broad as the scope of multicast destination.

This patch updates IPv6 source address selection procedure. Now
link-local address is selected only for link-local destinations,
including multicast destinations. For broader destination scope,
source address with broader scope is selected.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-03-30 15:57:43 +03:00
James Harris
59a3def756 net: utils: fix strlen issue in net_addr_pton
Previously, a non null-terminated "string" could
be passed to z_impl_net_addr_pton if the string was
exactly `INET6_ADDRSTRLEN` long.

Signed-off-by: James Harris <james.harris@intel.com>
2021-03-29 16:22:58 -05:00
Robert Lubos
539e4edcc6 net: lwm2m: Remove obsolete LWM2M_IPSO_TIMESTAMP_EXTENSIONS option
All IPSO objects that utilized the non-standard timestamp extension now
implement their model in version 1.1, which contains the Timestamp
resource. As it's no longer needed to add timestamp in a non-standard
way, simply remove LWM2M_IPSO_TIMESTAMP_EXTENSIONS option.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
1efc8e7353 net: lwm2m: Add IPSO Buzzer object in version 1.1
Update IPSO Buzzer object implementation to support object model
version 1.1.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
885dd5ff1f net: lwm2m: Add IPSO Push Button object in version 1.1
Update IPSO Push Button object implementation to support object model
version 1.1.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
8853730dec net: lwm2m: Add IPSO On/Off Switch object in version 1.1
Update IPSO On/Off Switch object implementation to support object model
version 1.1.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
9b1f0e3da0 net: lwm2m: Add IPSO Accelerometer object in version 1.1
Update IPSO Accelerometer object implementation to support object model
version 1.1.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
ca21c03e8c net: lwm2m: Add IPSO Pressure Sensor object in ver. 1.1
Update IPSO Pressure Sensor object implementation to support object
model version 1.1.

Add missing optional resources for the object model version 1.0.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
7546c5bf29 net: lwm2m: Add IPSO Humidity Sensor object in ver. 1.1
Update IPSO Humidity Sensor object implementation to support object
model version 1.1.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
1bd6e5bde3 net: lwm2m: Add IPSO Generic Sensor object in version 1.1
Update IPSO Generic Sensor object implementation to support object model
version 1.1.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
c83fca2784 net: lwm2m: Add IPSO Temperature object in version 1.1
Update IPSO Temperature object implementation to support object model
version 1.1.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
49b0e2cc76 net: lwm2m: Unify reusable resources creation
Some of the objects redefined reusable resources IDs, while others used
a common header which defines resource IDs. Unify the approach and use
the header in every object.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Robert Lubos
c9f5337a91 net: lwm2m: Add support for object versioning
Each object now have to specify the object version it implements.
Based on this information the LwM2M engine can decide whether it's
needed to report the object version during Registration/Discovery
operations or not.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-29 13:42:11 -04:00
Jukka Rissanen
97bf53fdcf net: if: Add locking when setting/getting hoplimit or ttl
Locking was missing when setting or getting IPv6 hop limit
or IPv4 time-to-live values.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
b07ba6db85 net: ipv4: Discard pkt if TTL is 0
If the TTL value in the IPv4 header is 0, then the packet needs to
be discarded.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
fafb1b82f4 net: context: Print network interface index with pointer value
Makes debugging easier if interface index is printed with
the pointer.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
362591810f net: config: Try to only use auto started interface
If the first network interface is down when the net config init
is run, then the IP addresses etc would be set to wrong network
interface. So when initializing the network, try to first find
a network interface that is auto started and use that to configure
IP addresses etc.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
fd4928aedd net: shell: Print network interface index instead of pointer
When printing network interface information print index or
index + pointer, so that the output is more user friendly.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
5c4bcf110d net: if: Mark IPv6 address valid for point2point links
As DAD is not done for point-to-point links, we can mark them
valid immediately. If this is not done, then the address will
never be picked as a source address to a sent packet.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
e291cddb31 net: shell: Print network interface flags values
Useful to know what flags are set for the network interface
so print them in the shell by the "net iface" command.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
cf9edcd3b4 net: shell: Add command to show virtual interface information
Add "net virtual" to show virtual network interface information.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
10142ac99c net: virtual: ipip: Add IP tunneling driver
Add a IP-to-IP tunneling driver. It supports both IPv4 and IPv6.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
36be096c43 net: virtual: Add virtual network interface support
This can be used to implement tunneling, VPN etc. The virtual
interfaces can be chained together to support multilayer
network interfaces.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
3d34c5f4b7 net: ipv4: Add utility func to create IPv4 header
Add a function that allow caller to create IPv4 header with
possibility to set various fields in the header.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Jukka Rissanen
897698bc78 net: if: Allow app to disable IPv4 or IPv6 for the interface
Application can disable IPv4 or IPv6 later if those are not
needed nor used for a given network interface.

Fixes #14581

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-29 07:40:24 -04:00
Flavio Ceolin
9fd4ea91b7 coccinelle: Remove extra semicolon
coccicheck --mode=patch --cocci=semicolon.cocci

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-03-25 11:35:30 -05:00
Kumar Gala
0bb4665df7 include: Move ptp_clock.h to drivers/ptp_clock.h
Move ptp_clock.h out of the top level include/ dir into
include/drivers/ptp_clock.h and deprecated the old location.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2021-03-25 10:09:33 +02:00
Marcin Niestroj
c1f7b9f45a net: l2: ethernet: fix k_work API usage in carrier on/off handling
net_eth_carrier_on() and net_eth_carrier_off() call k_work_init() on
work item that can be pending or still be processed in another thread.
This results in undefined behavior.

Initialize work item once and use an atomic flag to switch between
up/down carrier state. Submit work to workqueue whenever up/down carrier
state changes, so that last state is always properly propagated to
network interface layer.

While at it, save network interface pointer during ethernet context
initialization, so that is becomes static (and thread-safe) during whole
ethernet context lifetime.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-03-23 16:18:29 +02:00
Marcin Niestroj
e3a41194f7 net: l2: ppp: fix k_work API usage in carrier on/off handling
net_ppp_carrier_on() and net_ppp_carrier_off() call k_work_init() on
work item that can be pending or still be processed in another thread.
This results in undefined behavior.

Initialize work item once and use an atomic flag to switch between
up/down carrier state. Submit work to workqueue whenever up/down carrier
state changes, so that last state is always properly propagated to
network interface layer.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2021-03-23 16:18:29 +02: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
5d6c219210 drivers: device: do not reuse tag name 'device'
Do not reuse tag name (misra rule 5.7).

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-22 19:48:14 -04:00
Jukka Rissanen
0af89fc4ec net: Remove legacy TCP stack
Remove legacy TCP stack as it is replaced by the new TCP2 stack.
The TCP2 stack has been the default stack since 2.4 release.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-22 13:06:54 -04: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
Peter Bigot
0f93d58994 net: dhcpv4: switch to new work API
Use the reschedule variant throughout.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-18 11:57:21 -04:00
Robert Lubos
c50c0f6d07 net: lwm2m: Use link_format writer for Register/Update
The payload of the Register/Register Update message is also formatted as
application/link-format. Therefore it's reasonable to reuse the new
content writer instead of filling the payload manually.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-18 10:18:57 +01:00
Robert Lubos
b17555eb9e net: lwm2m: Add application/link-format content writer
This commit adds a new content writer, application/link-format, which
can be used during the Discovery procedure, to fill the content of the
response payload.

Introducing this new content writer, which encapsulates some of the
details like attribute handling which is different for bootstrap/regular
discovery, allows to unify the discovery handler in the lwm2m_engine,
thus it's no longer needed to have spearate handler functions for
bootstrap/regular discovery.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-18 10:18:57 +01:00
Robert Lubos
6ba362b11b net: lwm2m: Remove .well-known/core handling
`.well-known/core` resource is described by the CoAP RFC as an optional
method of resource discovery. The LwM2M specification though makes no
mentionon about this mechanism and provides an alternative method of
resource discovery instead (Device Management Discover, sec 5.4.2, and
Bootstrap Discovery, sec 5.2.7.3).

Since LwM2M does not require to implement `.well-known/core` resource
and it complicates the existing Discovery mechanism (and likely cause a
security concern) remove its handling from the LwM2M implementation.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-18 10:18:57 +01:00
Robert Lubos
d53fb5700d net: lwm2m: Introduce attribute handling helper functions
Introduce LwM2M engine helper functions that allows to work with LwM2M
attributes outside of lwm2m_engine.c.

This is a groundwork for application/lwm2m-format content writer.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-18 10:18:57 +01:00
Jukka Rissanen
f63855c657 net: if: Mark not used args as unused
If the function parameter is not used, mark it as unused to
avoid compiler warning.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-17 21:58:49 +02:00
Jukka Rissanen
24b49f4399 net: if: Add locking
Add locking when accessing network interface.

Fixes #33374

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-17 21:58:49 +02: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
Eduardo Montoya
ddf5f607e1 net: openthread: enable deterministic ECDSA
When using `OPENTHREAD_ECDSA` deterministic variant has to be
enabled after some OpenThread changes. Also generic public key
functions are required.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-03-17 09:25:04 +02:00
Jukka Rissanen
d8d721e09b net: dhcpv4: Add locking
Add locking when accessing interface list and the DHCPv4 config
struct that is found in net_if.

Fixes #33348

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-17 09:23:00 +02:00
Peter Bigot
1c7bf96019 net: dns: update to new k_work API
Switch to the new API for delayed work related to DNS queries.

In the previous solution it was assumed that the work item could be
immediately cancelled at the point the query slot was released.  This
is not true.  We need a secondary condition to record the fact that
the query was completed while the work item was still pending, and an
additional check to detect when the work item completed and the slot
reclaimed.

Also annotate functions to indicate when they require the lock on
query content to be held, add some helpers that abstract core
operations like invoking a callback or releasing a query slot, and fix
some more cases where query slot content was accessed outside of the
new lock infrastructure.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-15 17:19:54 +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
Lukasz Maciejonczyk
1b7755e62a net: openthread: Fix otPlatUartSend
Make sure data for transmission do not overlap each other.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-03-15 13:46:36 +02:00
Lukasz Maciejonczyk
4acaae1b1b net: openthread: Fix UART platform callback
OpenThread UART tx callback has been processed even if it was not
triggered by OpenThread otPlatUartSend function.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-03-15 13:46:36 +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
Jukka Rissanen
8353225ce0 net: dns: Add locking to prevent concurrent access
Add mutex locks to avoid concurrent access to DNS context.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-12 11:26:16 -05:00
Krzysztof Chruscinski
7e125fe7e4 logging: Add backend parameter to the init function
Added backend parameter to the backend init interface function.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-03-12 09:24:54 -05:00
Jukka Rissanen
ac55c63f08 net: tcp2: Add more debugging for connection unref
Print information who is freeing the connection struct,
this is useful for debugging.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-12 15:59:30 +02:00
Jukka Rissanen
1269a23e97 net: shell: The tcp connect command must have a timeout
If there is no timeout, the connect will timeout immediately
and the connection is not established.

Fixes #33185

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-12 15:59:30 +02:00
Jukka Rissanen
b8d4d9bcec net: dhcpv4: The client needs info about network interfaces
DHCPv4 client code needs to know information when network
interfaces are going down and up. So make sure that network
management config options are enabled in that case.

Fixes #33137

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-11 12:24:10 +02:00
Robert Lubos
6a90baa21a net: lwm2m: Make validation cb support optional
Add option to disable validation callback support by setting the
validation buffer size to 0, which allows to save some memory in case
it's not needed.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-10 14:55:22 -05:00
Robert Lubos
31e5ec79b8 net: lwm2m: Add data validation callback
Add a data validation callback to the resource structure, which can be
registered by an application. It allows to verify the data before
actually modifying the resource data.

If the callback is registered for a resource, the data is decoded into a
temporary buffer first, and only copied into the actual resource buffer
if the validation is successfull. If no validation is required (and thus
no callback registered) the resource value is decoded directly into the
resource buffer, as it used to be.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-10 14:55:22 -05:00
Paul Sokolovsky
e031693e37 net/ip/tcp2_priv.h: th_off: More detailed docstring
Mention that it's "data offset" in 32-bit words. Helpful when doing
code review and using search for "th_off".

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2021-03-10 14:53:28 -05:00
Jukka Rissanen
d8d5179c00 net: tcp2: Fix mbedtls missing warnings
If CONFIG_NET_TCP_ISN_RFC6528 is disabled, then mbedtls include
files are not available so check this.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-10 16:08:46 +01:00
Robert Lubos
64c836d5e2 net: lwm2m: Check return value of option encoding on deregistration
Verify the result of option encoding while forming Deregister message
instead of silently ignoring it.

Coverity ID: 215373
Fixes #33096

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-09 09:23:48 -05:00
Jukka Rissanen
2ce87533aa net: tcp: Implement ISN calculation according to RFC6528
Calculate Initial Sequence Number (ISN) as described in RFC 6528
https://tools.ietf.org/html/rfc6528

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-09 04:54:14 -05:00
Jukka Rissanen
7e1ae869e4 net: context: Remove unnecessary null check
The address pointer cannot be null at this point so remove
the checks.

Coverity-CID: 219595
Fixes #33071

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-08 13:26:00 +02:00
James Harris
6fd147b612 net: config: ensure counter k_sem init'd before reset
check_interface resets the counter semaphore, but
net_config_init_by_iface first calls check_interface, then inits
the semaphore.

Initialize the semaphore up front to allow the k_sem_reset call
to work properly.

Signed-off-by: James Harris <james.harris@intel.com>
2021-03-06 07:39:43 -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
Pete Skeggs
e0de4ff227 net: mqtt: log struct mqtt_utf8 with hexdump
Add NET_HEXDUMP_DBG/ERR/WARN/INFO macros, then use them for new
MQTT_HEXDUMP_TRC/ERR/WARN/INFO macros.

Log struct mqtt_utf8 using MQTT_HEXDUMP_TRC. One cannot safely log
mqtt_utf8 strings due to no guarantee of a NULL terminator being
present.  Also, logging without log_strdup() as if it were a NULL
terminated string asserts when CONFIG_LOG_IMMEDIATE=n. This solves
both issues.

Signed-off-by: Pete Skeggs <peter.skeggs@nordicsemi.no>
2021-03-05 12:49:22 +02:00
Peter Bigot
7b8bce898f net: openthread: radio: switch to new API for k_work_pending
Uses of k_work_pending are to be replaced by k_work_is_pending which
conforms to current proposed naming guidelines.

Switch to the new function.

Also initialize the private work structure at build time, rather than
on each iteration (it is not permitted to invoke work API on an
uninitialized work item).

The implementation here is racy: that a work item is pending does not
mean changes since it was first submitted are guaranteed to be seen
when the work item begins (began) executing.

A better solution would be to have transmit_message be able to
determine whether there is unprocessed work.  Then the work item can
be submitted unconditionally.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-04 18:00:56 -05:00
Peter Bigot
e373004135 net: tcp: switch to new API for k_work_pending
Uses of k_work_pending are to be replaced by k_work_is_pending which
conforms to current proposed naming guidelines.

Both uses in this file are fragile: that a work item is pending does
not mean changes since it was first submitted are guaranteed to be
seen when the work item begins (began) executing.

As long as this module is expected to be replaced by tcp2 it doesn't
seem worth trying to fix the logic, so just switch to the new function
name.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-04 18:00:56 -05:00
Peter Bigot
4817a41484 net: ip: remove incorrect check of work item status
Checking whether a work item is pending before submitting it is racy:
the item may be finishing up in its handler, and essentially
completed, in which case chosing not to resubmit would leave work
unhandled.

In this case it appears very wrong, since the sole call site in
net_if.c has just initialized the work item, which is not permitted if
the work item is pending.

Remove the check.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-04 18:00:56 -05:00
Robert Lubos
7f3537f0d3 net: lwm2m: Initialize the variable to silence compiler warning
The compiler generates a warning regarding a variable being used
w/o being initialized in certian configuration. According to the logic
that's not the case, so just add some initial value to the variable to
silence the compiler.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-04 14:53:05 -05:00
Jukka Rissanen
d07c1c500b net: conn_mgr: Ignore network interfaces that are not used
As network interface array size might be larger than the actual
network interface count, check this condition and ignore those
interfaces that are not in use.
We cannot know for certain how many network interfaces there
are at built time, as the total count is only available at runtime.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-04 14:52:35 -05:00
Jukka Rissanen
1ccc67f759 net: conn_mgr: Print network interface index in debug
The network interface index is very useful info to see in
debug prints so add those to debug output.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-04 14:52:35 -05:00
Jukka Rissanen
924e433ffb net: context: Set target network interface in send if needed
If we are sending a network packet and if the remote address
is not set in the context (which means that connect() has not
been called), then we must set the target network interface
to a proper value.
This is done so that when we select the local source address,
we might select the wrong interface if we have multiple network
interfaces in the system. In this case the packet would be always
assigned to first network interface regardless of the destination
address.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-04 16:05:52 +02:00
Peter Bigot
b706a5e999 kernel: remove old work queue implementation
Now that the old API has been reimplemented with the new API remove
the old implementation and its tests.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-03 20:06:00 -05:00
Peter Bigot
753d56dd7b net: tcp2: work around limitations of legacy API
The tcp2 infrastructure is using the legacy delayed work API, and
relies heavily on the transient state indicated by an estimate of
delayed time remaining to determine whether a delayed work item is
still active.  While the wrappers for this work in most cases, one use
is unsanctioned: directly accessing the fields of k_delayed_work
structure to satisfy the calling parameters of the handler when
invoked directly.

The chosen solution for this specific need in the new API is to use a
schedule (rather than reschedule) operation, which leaves any previous
timer unchanged but allows immediate submission if the work is idle.
This changes behavior in that the resend is delegated to the work
queue, rather than done immediately.  The former behavior can be
supported by further refactoring that turns the work handler into a
wrapper around a function that takes a connection reference, and
invoking that here, while the handler invokes it after reconstructing
the connection from the contained work item.

For now put in a hack that also uses the non-public fields of the
delayed work structure to implement the required behavior.  The
complete fix if this solution is used requires replacing all use of
k_delayed_work in this module with k_work_delayable, leveraging the
new functionality of the API to avoid having to guess about the true
state of a work item based on its transient timer or flag states.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-03 20:06:00 -05:00
Jim Paris
ffec5aa7f7 ppp: add net events for PPP dead and running
This lets an application detect when a PPP connection fails to establish
or terminates, so that the connection can be reattempted (for example,
by setting carrier off and on).

Signed-off-by: Jim Paris <jim@jim.sh>
2021-03-03 15:56:13 +02:00
Robert Lubos
651e4ac62b net: lwm2m: Make sure that endpoint string is NULL terminated
In case the endpoint string provided by the application is longer or
equal to CLIENT_EP_LEN - 1, the strncpy() function will not add the NULL
terminator. As the endpoint buffer is treated as a C-string in other
places in the code, make sure it's NULL terminated by adding NULL
explicitly at the end of the buffer.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-02 09:16:01 -05:00
Robert Lubos
f14a9556d6 net: lwm2m: Make query buffer large enough to encode all query strings
Make sure query string used by the lwm2m_rd_client is large enough to
encode any query string that can be sent during bootstrap/registration.
As the maximum query string length is related to the endpoint name,
which is limited by `CONFIG_LWM2M_RD_CLIENT_ENDPOINT_NAME_MAX_LENGTH`,
make the query string corellated to the value of this config.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-03-02 09:16:01 -05:00
Hubert Miś
14b2b2d63e net: shell: UDP commands
This commit adds to network shell set of basic commands for UDP
protocol to receive and send datagrams.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-02 14:20:52 +02:00
Jukka Rissanen
9df116ed0f net: utils: Check null pointer in net_sprint_ll_addr_buf()
Check NULL value when we are trying to print link address
because the link address can be null.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-01 14:23:30 +02:00
Jukka Rissanen
b86b778ca5 net: utils: net_pkt_hexdump() was missing log_strdup()
As the input string can be allocated from stack, we need to use
log_strdup() in net_pkt_hexdump() to print the extra string.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-03-01 14:23:30 +02: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
Christian Taedcke
c467149ad9 net: pkt: Add function net_pkt_get_contiguous_len()
This returns the available contingous space in the packet starting from
the current cursor position.

Signed-off-by: Christian Taedcke <christian.taedcke@lemonbeat.com>
2021-02-24 09:43:52 +02:00
Eduardo Montoya
beed76247f net: openthread: style adjustments in radio.c
Avoid splitting lines when possible while keeping length below 100
chars. Some other minor style corrections.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-02-23 11:30:25 +01:00
Eduardo Montoya
2e8836f076 net: openthread: separated variable for rx/tx operations results
The use of a single error variable for RX and TX operations has
shown the OpenThread code to be asserting in some conditions.

This commit splits tx_rx_result into rx_result and tx_result
to avoid such cases.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-02-23 11:30:25 +01:00
Jukka Rissanen
157c11d6e7 net: context: Check interface status when sending
If the network interface is down when trying to send a message,
return -ENETDOWN as we cannot send a message in this case.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-23 11:30:08 +01:00
Reto Schneider
545fb92fc1 net: pkt: Fix headroom edge case
This commit fixes some edge cases when using net_bufs with reserved
bytes (headroom) as fragments of a net_pkt.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2021-02-22 19:33:16 +02:00
Reto Schneider
1919766d7b net: buf: Simplify querying maximum len
net_buf_max_len() provides the maximum number of bytes which can be put
behind the data pointer. This provides a save alternative to using the
size field of the net_buf structure directly, which does not take the
reserved bytes (headroom) into account.

This commit also replaces the usage of the size field in places where
size got used directly. Code has not been adjusted when it is easy to
recognise that the buffer does not have any reserved bytes, which is the
case after allocation or reset. Same goes for the faulty usage by
net_pkt as exposed by the last commit and begin fixed by a separate
commit.

Even though it would be cleaner, I decided to not rename the size field
to e.g. __buf_size in order to keep the amount of code changes low.

Signed-off-by: Reto Schneider <reto.schneider@husqvarnagroup.com>
2021-02-22 19:33:16 +02:00
Thomas LE ROUX
37dca20444 net: lwm2m: Utility functions added to LWM2M Engine
Added 3 utility functions :
- lwm2m_engine_update_period_service() which updates the period of a
given service.
- lwm2m_engine_update_period_min_observer() which updates the
min_period_sec for a given observe node.
- lwm2m_engine_update_period_max_observer() which updates the
max_period_sec for a given observe node.

Signed-off-by: Thomas LE ROUX <thomas.leroux@smile.fr>
2021-02-19 10:52:08 +02:00
Kamil Kasperczyk
7b26544547 net: openthread: added heap related otPlat methods implementation
* Added implementations of otPlatCAlloc and otPlatFree methods
necessary for the OpenThread in case of using EXTERNAL_HEAP.
* Added CONFIG_OPENTHREAD_DNSSD_SERVER option to allow enabling
OT_DNSS_SERVER feature.

Signed-off-by: Kamil Kasperczyk <kamil.kasperczyk@nordicsemi.no>
2021-02-18 18:23:06 +02:00
Jukka Rissanen
7699563d81 net: mgmt: Use proper coop thread priority value
If user sets CONFIG_NUM_PREEMPT_PRIORITIES=0, then the priority
of the net_mgmt thread will be -1 which is the same as idle thread.
This will trigger assert in kernel as then the minimum coop priority
is -2 in this case. Remove the net_mgmt thread priority setting from
Kconfig file as it is low value and set the coop thread priority
the same way as other network threads are doing it.

Fixes #32375

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-17 16:42:15 +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
0c324e7b14 net: tcp2: Use private work queue
As the work might have some delays, use private work queue
for TCP work.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-16 18:09:45 +02:00
Eduardo Montoya
99ccdabee3 net: openthread: remove misleading NCP configuration option
Remove `OPENTHREAD_CONFIG_NCP_BUFFER_SIZE` define since it does not
exist in OpenThread.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-02-16 15:30:36 +03: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ś
5e43418cf9 net: coap: acknowledgement initialization helper
When handling CoAP Confirmable requests, there is a common
Acknowledgement initialization procedure that repeats for each
response packet initialization. This patch adds a function that
simplifies Acknowledgement initialization procedure encapsulating
repeating code.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-02-15 10:17:11 +02:00
Anas Nashif
5d1c535fc8 license: add missing SPDX headers
Add SPDX header to files with existing license.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-02-11 08:05:16 -05:00
Eduardo Montoya
fb20d0022a net: openthread: add CoAP Block Kconfig option
Enable new feature from the upmerge:
- OPENTHREAD_COAP_BLOCK

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-02-08 11:36:45 -05:00
Tomasz Bursztyka
f729f82171 net/6lo: First buffer fragment should hold the full compressed header
Current 6lo implementation is unable to deal with scattered headers
(which should not happen usually, though it's a valid use case), so
let's just fail uncompressing such packet then.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-02-04 07:36:16 -05:00
Tomasz Bursztyka
a980762f70 net/ieee802154: Drop fragmented packet if first frag is not present
Bogus fragmented packet could be sent without a FRAG1 fragment and hit
reassembly. Let's make sure this does not happen.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-02-03 17:39:26 -05:00
Tomasz Bursztyka
2a423bc6d3 net/ieee802154: Do not unreference one time too many a fragmented packet
In case the current packet is the same as the cached one, let's not
unreference it while clearing the cache.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-02-03 17:39:26 -05:00
Tomasz Bursztyka
0ebd300001 net/ieee802154: Make sure L2 drop any ACK frames
Though ACK frames are not meant to reach L2 (drivers must ensure this
never happens), let's "re-enforce" the L2 by dropping them.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-02-03 17:39:26 -05:00
Tomasz Bursztyka
6917d26848 net/ieee802154: Avoid NULL pointer de-reference in packet reassembly
In case the very first fragment holds all the data already.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-02-03 17:39:26 -05:00
Tomasz Bursztyka
606807940c net/ieee802154: Each fragment should be at least of its header's length
Not validating this length could lead to integer underflow and memory
corruption.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-02-03 17:39:26 -05:00
Tomasz Bursztyka
6f1ab93c66 net/ieee802154: Invalidate frame in case of no address in relevant modes
All addressing mode but IEEE802154_ADDR_MODE_NONE should have a valid
address. If not, the frame is invalid.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2021-02-03 17:39:26 -05:00
Hubert Miś
77c68aa070 net: coap: clean up token usage in samples and tests
This patch replaces magic numbers with COAP_TOKEN_MAX_LEN value and
removes unnecessary castings of token buffer type.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-02-02 14:03:01 -05:00
Hubert Miś
22687c34e3 net: coap: define default CoAP version
RFC 7252 (CoAP) specifies value of the Version (Ver) field in the
protocol header to value 1. This patch defines value of the Version
field to make packet initialization easier. All samples and tests
are updated to use the new COAP_VERSION_1 field when initializing
a CoAP packet.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-02-02 14:03:01 -05:00
Jukka Rissanen
4c8760b299 net: tcp2: Properly cleanup receive queue
When pushing received data to the application, check that app
was able to receive the data. If the application already closed
the socket, then we must free the received net_pkt in order to
avoid memory leak.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-01 15:23:33 -05:00
Jukka Rissanen
de72faeb2c net: tcp2: slist API is not thread safe so use locking
Make sure we lock when accessing the slist, as it is not
a thread safe API.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-01 15:23:33 -05:00
Jukka Rissanen
a5f9520428 net: tcp2: Cleanup properly if running out of mem
If we cannot allocate net_pkt or net_buf, then check this condition
properly and release other resources that were already allocated.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-01 15:23:33 -05:00
Jukka Rissanen
7ae54adc37 net: tcp2: Create a timer for connection establishment
We need to make sure that when listening a connection establishment,
the connection gets cleared if we do not receive final ACK.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-02-01 12:32:30 -05:00
Kasun Hewage
7dad85695e net: coap: Fixed discovery response formatting according to RFC6690
CoAP RFC (RFC7252) states that end points should support
the CoRE Link Format of discoverable resources as described in RFC6690
(refer section 7.2 of the RFC7252).

Fixes #31609

Signed-off-by: Kasun Hewage <kasun.ch@gmail.com>
2021-01-27 18:26:13 -05:00
Eduardo Montoya
58fe3e1fd6 net: openthread: add SRP Kconfig options
Enable new features from the upmerge:
- OPENTHREAD_SRP_CLIENT
- OPENTHREAD_SRP_SERVER

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-01-26 07:29:10 -05:00
Eduardo Montoya
80c0f3fbb6 net: openthread: configure required masterkey
After the latest upmerge, OpenThread requires explicit configuration
of the Master Key. This commit adds a Kconfig symbol that can be
used to setup its value. By default no Master Key is configured and
OpenThread generates a random one.

The Sockets Echo samples are configured with a fixed key with this
commit.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2021-01-26 07:29:10 -05:00
Jukka Rissanen
1584c806a7 net: config: Tweak the startup of logging backend
Only start the network logging backend if the autostarting
option CONFIG_LOG_BACKEND_NET_AUTOSTART is enabled.
Also, call init to make sure that the backend is initialized
properly.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-01-26 07:12:14 -05:00
Hubert Miś
0475cd0eae net: coap: Allow encoding packets using data from constant buffers
Token and payload are appended from data buffers to a CoAP packet
being encoded. Keyword const was missing for parameters in functions
appending these parts to a packet.

Now token and paylod can be copied to CoAP packet from constant
buffers, that can be stored in ROM.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-01-26 06:17:41 -05:00
Hubert Miś
759f7454d8 net: coap: define max token length
This patch introduces COAP_TOKEN_MAX_LEN definition in coap.h file.
This definition replaces magic number across CoAP protocol
implementation and CoAP samples.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-01-26 06:17:41 -05:00
Anas Nashif
7f44d74433 doc: fix typo trough -> through
Fix common typo.

Fixes #31543

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-01-22 17:53:06 -05:00
Luiz Augusto von Dentz
d8a41c8179 net: buf: Allow passing NULL as allocator to net_buf_append_bytes
This enables to use net_buf_append_bytes without passing an allocator in
which case the code would attempt to use the net_buf_pool of the
original buffer.

Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
2021-01-22 16:30:19 +02:00
Lukasz Majewski
ca5e3ea654 eth: Add support for Distributed Switch Architecture [DSA] switches
This patch add support for DSA switches to Zephyr.

Signed-off-by: Lukasz Majewski <lukma@denx.de>
2021-01-20 10:03:42 +02: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ś
13aa4b2f9e net: coap: define Content-Format option values
CoAP protocol defines registry of Content-Format option values.
This patch adds this enumeration to coap header file to make it
available to all applications using CoAP protocol. It modifies
code using CoAP service to use new enumeration.

Signed-off-by: Hubert Miś <hubert.mis@nordicsemi.no>
2021-01-19 16:07:20 -05:00
Robert Lubos
c563736bd3 net: coap: Randomize initial ACK timeout
Add Kconfig option to randomize the initial ACK timeout, as specified in
RFC 7252. The option is enabled by default.

Additionally, finetune the default value of COAP_INIT_ACK_TIMEOUT_MS
option, to match the default ACK_TIMEOUT value specified by the RFC
7252. The RFC does not specify the minimum/maximum value of the
ACK_TIMEOUT parameter, but only suggests it should be no lower than 1
second, so adjust the option range to reflect this.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-01-18 23:22:37 -05:00
Robert Lubos
538e19ee2e net: coap: Rework pending retransmission logic
Introduce retransmission counter to the coap_pending structure. This
allows to simplify the retransmission logic and allows to keep track of
the number of remaining retranmissions.

Additionally, extend the `coap_pending_init()` function with `retries`
parameter, which allows to set the retransmission count individually for
each confirmable transaction.

Fixes #28117

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-01-18 23:22:37 -05:00
Robert Lubos
366a2147cc net: lwm2m: Add dimension discovery support
Multi-instance resources shall report its dimension (number of
resource instances) on discovery. Since it was not possible to tell
simply on the instance count whether the resource is multi-instance or
not (there could be a multi-instance resource with only one instance
avaialble) add a new parameter to the structure representing resource,
indicating whether it's multi-instance or not.

Add dimension information to the discovery result.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-01-18 11:59:50 +01:00
Robert Lubos
18cfc3761e net: lwm2m: Cleanup Device Management Discovery
Remove any references of Bootstrap Discovery from Device Management
Discovery procedure and fix some of it's logic following the
specification.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-01-18 11:59:50 +01:00
Robert Lubos
1c9fb5488b net: lwm2m: Implement bootstrap discovery
Bootstrap discovery was not implemented properly in the LwM2M engine.

Although, there were some indications in the source code that it is
implemented, it was not done according to spec (and actually broken).

Given that Bootstrap Discovery procedure differs a lot from the regular
Device Management Discovery (different permissions, different
information returned), it's easier to implement it as a separate
function (`bootstrap_discovery()`) instead of making the existing
`do_discovery_op()` function even more complicated.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-01-18 11:59:50 +01:00
Martin Åberg
9156c2d32e tests/websocket: improve portability
This commit improves portability somewhat on machines where sizeof
(int) is less than sizeof (void *). Note that the implementation is
still not portable and will fail when you start using addresses which
can not be represented by "int cast to unsigned int".

On RISC-V 64-bit with RAM on 0x80000000 we previously got hit by
  E: Exception cause Load access fault (5)
    ld      s0,16(a0)
    a0: 0xffffffff80025610

(The int should probably be changed to intptr_t if possible.)

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2021-01-15 13:06:33 -05:00
Lukasz Majewski
83f523f0a5 net: Add support for simultaneous UDP/TCP and raw sockets
This patch brings support for AF_PACKET and SOCK_RAW type of sockets.
In net_conn_input() function the new flag has been introduced -
'raw_pkt_continue' to indicate if there are other than AF_PACKET
connections registered.

If we do not have other connections than AF_PACKET, the packet is
solely handled in net_conn_input() (or to be more specific in its
helper function - conn_raw_socket()).

Otherwise, it is passed back to net_conn_input in IPv4/6 processing.

Signed-off-by: Lukasz Majewski <lukma@denx.de>
2021-01-15 09:30:17 +02:00
Lukasz Majewski
1f72b1f6bd net: Exclude code responsible for handling raw sockets processing
The new function - namely conn_raw_socket(); has been introduced to
handle raw sockets processing. Its code, up till now, only was
executed when IS_ENABLED(CONFIG_NET_SOCKETS_PACKET) was defined.

After this change it can be reused when one would like to handle
raw sockets also when CONFIG_NET_{UDP|TCP} are enabled.

Signed-off-by: Lukasz Majewski <lukma@denx.de>
2021-01-15 09:30:17 +02:00
Fabio Baltieri
4a4c63519d net: if: check for multicast address already registered
Add a check to stop a multicast address to be registered multiple times.
This can happen if the application is using net_if_ipv6_maddr_add()
directly.

Tested on the existing bluetooth/ipsp sample:

<wrn> net_if: Multicast address ff02::1 is is already registered.

Signed-off-by: Fabio Baltieri <fabio.baltieri@gmail.com>
2021-01-14 16:57:07 +02:00
Fabio Baltieri
36d8230d15 net: bt: enable solicit node multicast group registration
6lowpan over BLE should work without solicit node multicast messages
according to RFC7668[1], but that requires Neighbor Solicitation with
Address Registration Option, which is currently not implemented in
either Zephyr or Linux. This is causing the router to fallback to normal
neighbor solicitation based discovery, but the NS frames are being
discarded in the host stack because the solicit node multicast groups
are not registered.

This drops the NET_L2_MULTICAST_SKIP_JOIN_SOLICIT_NODE as a workaround
and adds a TODO about it.

[1] https://tools.ietf.org/html/rfc7668#section-3.2.3

Signed-off-by: Fabio Baltieri <fabio.baltieri@gmail.com>
2021-01-14 16:57:07 +02:00
Markus Fuchs
041c80748a net: hostname: Update unique hostname on link address change
Add Kconfig option NET_HOSTNAME_UNIQUE_UPDATE to allow the unique
hostname - which is derived from the network interface's link
address - to be updated on both initial assignment and updates of
the link address.

Signed-off-by: Markus Fuchs <markus.fuchs@de.sauter-bc.com>
2021-01-13 17:50:32 +02:00
Robert Lubos
4851611d55 net: coap: Fix long options encoding
`delta_size` was incorrectly used to assess whether extended option
length field shall be used. In result, options larger than 268 bytes
were not encoded properly.

Fixes #31206

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2021-01-13 08:02:03 -05:00
Lukasz Maciejonczyk
fb99ef639a net: openthread: Set a name for radio workqueue
Named workqueues are easier to identify for instance using Thread
Analyzer.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-01-13 11:29:30 +02:00
Lukasz Maciejonczyk
ad360c42af net: openthread: Make radio workqueue stack size configurable
Add Kconfig option for configuring OpenThread radio transmit workqueue
stack size.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2021-01-13 11:29:30 +02:00
Emil Gydesen
d661eb7605 net: tcp2: Fixed IS_ENABLED check for NET_TCP_MAX_SEND_WINDOW_SIZE
The #if statement used IS_ENABLED to check if it was defined.
IS_ENABLED will only return true if the value is 1, and false otherwise.
If the NET_TCP_MAX_SEND_WINDOW_SIZE value would be e.g. 8, then the
check would fail.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2021-01-12 13:40:42 +02:00
Jukka Rissanen
ef801886b6 net: tcp2: Queue received out-of-order data
If we receive data that is out-of-order, queue sequential
TCP segments until we have received earlier segment or a timeout
happens.

Note that we only queue data sequentially in current version i.e.,
there should be no holes in the queue. For example, if we receive
SEQs 5,4,3,6 and are waiting SEQ 2, the data in segments 3,4,5,6 is
queued (in this order), and then given to application when we receive
SEQ 2. But if we receive SEQs 5,4,3,7 then the SEQ 7 is discarded
because the list would not be sequential as number 6 is be missing.

Fixes #30364

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-01-12 13:40:05 +02:00
Joel Frazier
2d215484cc net: l2: openthread: join thread mcast addrs added to zephyr
Modifies openthread shim layer to automatically join multicast
addresses as they are added to zephyr from openthread, unless the
address is interface-local or link-local. This allows incoming
openthread multicast group messages to avoid being filtered by
zephyr ipv6 recv.

Fixes #31085

Signed-off-by: Joel Frazier <frazieje@gmail.com>
2021-01-11 10:48:26 +02:00
Maik Vermeulen
f03d1177d0 net: lwm2m: Direct firmware_transfer() call instead of work-item
The LwM2M firmware pull object no longer uses the system workqueue
to execute firmware_transfer(), but directly executes it itself.
Previously, the workqueue would be blocked because firmware_transfer()
indirectly calls a blocking connect(). This would lead to problems
with e.g. modem drivers that use UART to interface with the modem
hardware, as some UART drivers use the workqueue.

Fixes #31053.

Signed-off-by: Maik Vermeulen <maik.vermeulen@innotractor.com>
2021-01-08 15:46:57 +02:00
Jukka Rissanen
d904f95562 net: tcp2: Mark tcphdr struct as packed
As the tcp header struct can be cast to unaligned memory, mark
it as packed and access fields using UNALIGNED_GET/PUT when
needed.

Fixes #31145

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-01-08 11:31:43 +02:00
Peter Bigot
d510f1f84d net: if: tweak DAD and RS timeout handling
Both RS and DAD timeouts are simplified because the delay is a
constant, and by construction the list of timeouts is in increasing
time remaining.

Refactor to avoid repeating the expression that represents the time
until DAD state expires.  Uniformly use unsigned operands in deadline
calculation.

Note a case where the racy idiom for retaining an existing timeout is
required in the current work API, but can be replaced with a robust
solution in the proposed new API (the reschedule API replaces any
existing pending update, but the schedule API will leave an existing
scheduled submission in place).

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 11:14:38 +02:00
Peter Bigot
4882dd69af net: if: fix error in calculating router expiration
The existing implementation is inconsistent in that checking for
expired routers when a timeout is processed detects end-of-life
correctly (when the remaining duration exceeds the signed maximum),
but the calculation of time remaining before expiration uses only
unsigned calculation.  So when the set of routers is changed the newly
calculated timeout will not recognize routers that have expired, and
so those routers expired late.  In the worst case if the only
remaining router had expired the timer may be set for almost two
months in the future.

Refactor to calculate remaining time in one place and as a signed
value.  Change a function name to more clearly reflect what it does.
Avoid unnecessary race conditions in k_work API.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 11:14:38 +02:00
Peter Bigot
acd43cbaac net: timeout: refactor to fix multiple problems
The net_timeout structure is documented to exist because of behavior
that is no longer true, i.e. that `k_delayed_work_submit()` supports
only delays up to INT32_MAX milliseconds.  Nonetheless, use of 32-bit
timestamps within the work handlers mean the restriction is still
present.

This infrastructure is currently used for two timers with long
durations:
* address for IPv6 addresses
* prefix for IPv6 prefixes

The handling of rollover was subtly different between these: address
wraps reset the start time while prefix wraps did not.

The calculation of remaining time in ipv6_nbr was incorrect when the
original requested time in seconds was a multiple of
NET_TIMEOUT_MAX_VALUE: the remainder value would be zero while the
wrap counter was positive, causing the calculation to indicate no time
remained.

The maximum value was set to allow a 100 ms latency between elapse of
the deadline and assessment of a given timer, but detection of
rollover assumed that the captured time in the work handler was
precisely the expected deadline, which is unlikely to be true.  Use of
the shared system work queue also risks observed latency exceeding 100
ms.  These calculations could produce delays to next event that
exceeded the maximum delay, which introduced special cases.

Refactor so all operations that use this structure are encapsulated
into API that is documented and has a full-coverage unit test.  Switch
to the standard mechanism of detecting completed deadlines by
calculating the signed difference between the deadline and the current
time, which eliminates some special cases.

Uniformly rely on the scanning the set of timers to determine the next
deadline, rather than assuming that the most recent update is always
next.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 11:14:38 +02:00
Jordan Yates
7be105b86a net: buf: net_buf_remove_* API
Adds a new family of `struct net_buf` operations that remove data from
the end of the buffer.

The semantics of `net_buf_remove_mem` have been chosen to match those of
`net_buf_pull_mem`, i.e. the return value is a pointer to the memory
that was removed.

The opposite of this function, `net_buf_remove`, would need to return
the old end of the data buffer to be useful. However this value is
always an invalid target for reading or writing data to (It points to
the middle of unused data).The existance of the function would be
misleading, therefore it is not implemented.

Fixes #31069.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-01-05 14:31:13 +02:00
Jordan Yates
a5cd0c0c51 net: buf: net_buf_push_mem function
Add function that copies in new data to the start of a `struct net_buf`.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-01-05 14:31:13 +02:00
Peter Bigot
d489765be4 net: dhcp: correct timeout scheduling with multiple interfaces
If there are multiple interfaces a change to the timeout for one
cannot determine the correct delay until the next timeout event.  That
can be determined only by checking for the next event over all
interfaces, which is exactly what's done by the timeout worker.

Refactor interface timeout configuration to just set the start time
and request time, and trigger the worker to calculate the next
scheduled event.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
b4ed597afe net: dhcp: fix timeout on entry to bound state
When a renewal occurs the client enters RENEWING, sends a request,
then sets a short timeout (about 4 s) for the response.  In the common
case the response will arrive immediately, which will trigger an
attempt to reset the timer with T1 which is generally large.

However the check for updating the timer performs the update only if
the new deadline is closer than the currently set one.  Thus the timer
fires at the time the RENEWING request would have been retransmitted,
and only then updates to the correct deadline (T1) for the current
machine state.

Remove the extra timeout by unconditionally setting the timeout to the
new value.

This works when there is one interface; it could be wrong if there
were multiple interfaces one of which had a closer deadline, but
multiple interfaces are mishandled anyway and will be fixed next.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
65183422c7 net: dhcp: correct timeout calculation with multiple interfaces
When there is only a single interface the timeout infrastructure can
correctly calculate time to next event, because timeouts only occur
when an event for that interface is due.  This is not the case when
multiple interfaces are present: the timeout is scheduled for the next
event calculated over all interfaces.

When calculating the next event for an interface where the timeout is
not due the current code returns the original absolute delay
associated with its current state, without accounting for the time
that has passed since the start time.

For example if interface A's T1 is 3600 s and is due at 3610, but at
3605 a timeout for interface B occurs, the contribution of A to the
delay to the next scheduled event would be 3600 rather than 5,
preventing the renewal from occurring at the scheduled time.

Fix this by replacing the boolean timed-out state with the number of
seconds remaining until the interface event will occur, and
propagating that through the system so the correct delay over all
interfaces can be maintained.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
2c813bc620 net: dhcp: fix invalid timeout on send failure
If send_request() fails it would return UINT32_MAX as the next
timeout.  Callers pass the returned value to update_timeout_work
without validating it.  This has worked only because
update_timeout_work will not set a timeout if an existing timeout
would fire earlier, and the way the state is currently structured it
is likely there will be an existing timeout.  However, if work thread
retransmission from REQUESTING failed the timer would not be
rescheduled, causing the state machine to stop.

A more clean solution, which matches the behavior of send_discover(),
is to return the timeout for the next transmission even in the case
when the send fails.  The observed behavior is the same as if the
network, rather than the sender, failed to transport the request.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
508496f73b net: dhcp: rename variable for clarity
A variable named "timeout" is used to represent the current time in
comparisons against timeouts calculated from a start time and an
interval.  Since this current time is not the timeout change its name
to "now" to reduce maintainer confusion.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
07c5d2fe18 net: dhcp: avoid undefined behavior when assertions disabled
If assertions are disabled the send operation would continue on to
transmit a message.  Stop it from doing so.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
5da984e890 net: dhcp: fix bounds check in timeout
The flag value UINT32_MAX is returned from manage_timers() when a send
operation did not succeed.  This indicates that the timeout should not
be rescheduled, but because it will never replace the starting update
value UINT32_MAX-1 the check will never pass, and in cases where it
should work will be submitted to run at UINT32_MAX-1 seconds.

Fix the upper bound.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
d44b4252b7 net: dhcp: clear option state when selecting
When a connection is lost the client will first attempt to renew, and
then to rebind, and finally to select.  Options like gateway may have
been provided by the original connection, but not the new connection,
resulting in an inconsistent configuration for the new network.

Remove the partial state clearing when entering INIT, and expand the
state cleared when entering SELECTING to be more comprehensive.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
403c4974b0 net: dhcp: remove incorrect sign check
The start time is negative only if the interface came up in the the
first milliscond since startup; even then changing the sign of the
start is not appropriate.  Presumably a left-over from signed 32-bit
timestamps.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:02:58 +02:00
Peter Bigot
7e77370acb net: dns: review use of k_work APIs
It is documented that using transient information like whether a work
item is pending or a delayed work item has time left to determine the
state of the work item before subsequent reconfiguration is prone to
race conditions, and known to produce unexpected behavior in the
presence of preemptive threads, SMP, or use of the work item from
interrupts.  As a best practice such pre-validation steps should be
avoided unless algorithmically necessary.

All comparisons of remaining delayed time before canceling a delayed
work item in this module appear to be optimizations subject to the
above race conditions.  Remove the checks so that only the inherent
race conditions in the implementation of canceling a work item remain.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 10:01:47 +02: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
Kumar Gala
82767ef3bb bluetooth: Convert DEVICE_AND_API_INIT to DEVICE_DEFINE
Convert drivers to DEVICE_DEFINE instead of DEVICE_AND_API_INIT
so we can deprecate DEVICE_AND_API_INIT in the future.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-12-19 20:01:42 -05:00
Rafał Kuźnia
3bf526beea net: openthread: add shell dependency to OPENTHREAD_SHELL
This commit replaces the 'select SHELL' statement with
'depends on SHELL' in OPENTHREAD_SHELL config option.

This ensures, that shell will not be implicitly enabled
when OpenThread stack is built.

Signed-off-by: Rafał Kuźnia <rafal.kuznia@nordicsemi.no>
2020-12-18 12:56:33 -05:00
Robert Lubos
ae35d3000f net: openthread: Fix missed logging macro usage
During recent upmerge OPENTHREAD_CONFIG_PLAT_LOG_FUNCTION__COUNT_ARGS
macro was renamed to OPENTHREAD_CONFIG_PLAT_LOG_MACRO_NAME__COUNT_ARGS
but the code wasn't updated where the macro is actually used.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-12-17 20:58:00 +02:00
Alexander Wachter
05275ecf6e drivers: can: rework zcan_frame and zcan_filter
Reordering of the struct elements to match the Linux format.
The __packed() is not necessary anymore.
std_id and ext_id is merged to id in the frame and filter.
Additionally, the frames are ready for CAN-FD.

Signed-off-by: Alexander Wachter <alexander@wachter.cloud>
2020-12-17 11:07:53 +01:00
Eduardo Montoya
f0379e7ccb net: openthread: enable new CSL and TREL config options
Enable new OpenThread configuration options:
- OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE
- OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE
- OPENTHREAD_CONFIG_CSL_SAMPLE_WINDOW
- OPENTHREAD_CONFIG_CSL_RECEIVE_TIME_AHEAD

Update OPENTHREAD_CONFIG_PLAT_LOG_MACRO_NAME

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2020-12-16 18:06:47 +01: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
Jukka Rissanen
9080a46e68 net: tcp2: Use mutex instead of irq_lock
When needing to lock non-connection related access, use k_mutex
instead of locking irq. There is really no reason to prevent the
system from generating interrupts.

Fixes #30636

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-12-15 12:16:19 +02:00
Maik Vermeulen
4cfd2a1943 net: lwm2m: Added execute arguments support
A dedicated LwM2M execute callback type has been implemented which
supports execute arguments. The lwm2m engine, lwm2m_client sample and
lwm2m objects have been updated accordingly. Also the API change has
been documented, and the lwm2m engine reference has been updated.

Fixes #30551.

Signed-off-by: Maik Vermeulen <maik.vermeulen@innotractor.com>
2020-12-13 15:39:08 -05:00
Robert Lubos
5d038eb014 net: openthread: Add option to enable software CSMA backoff
Add option to enable software CSMA backoff in the OpenThread MAC layer.

This allows to run CSMA procedure correctly in radios that do not
support hardware CSMA backoff, and use them as RCP, where this feature
is required.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-12-10 12:58:07 +01:00
Rafał Kuźnia
065722fef0 net: openthread: add missing settings deinit function
This commit adds a missing otPlatSettingsDeinit function
to the Zephyr OpenThread platform implementation.

Signed-off-by: Rafał Kuźnia <rafal.kuznia@nordicsemi.no>
2020-12-09 22:53:53 +02:00
Anas Nashif
dd931f93a2 power: standarize PM Kconfigs and cleanup
- Remove SYS_ prefix
- shorten POWER_MANAGEMENT to just PM
- DEVICE_POWER_MANAGEMENT -> PM_DEVICE

and use PM_ as the prefix for all PM related Kconfigs

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-12-09 15:18:29 -05:00
Henning Fleddermann
061de0376a net: lwm2m: fix buffer length check in lwm2m_engine_set
Previously, lwm2m_engine set would check against the max_data_len
parameter of the ressource, but didn't take into consideration the
(possibly changed) max_data_len returned by the pre_write callback.

Fixes #30541

Signed-off-by: Henning Fleddermann <henning.fleddermann@grandcentrix.net>
2020-12-09 11:21:48 +02:00
Simen S. Røstad
adb8087707 net: mqtt: Return -1 if keepalive messages are disabled.
In mqtt_keepalive_time_left(), return -1 if keep alive messages are
disabled by setting CONFIG_MQTT_KEEPALIVE=0.

This allows to use mqtt_keepalive_time_left() directly as an input
for poll(). If no keep-alive is expected, -1 would indicate
that poll() can block until new data is available on the socket.

Signed-off-by: Simen S. Røstad <simen.rostad@nordicsemi.no>
2020-12-08 14:08:36 -05:00
Andy Ross
fcd392f6ce kernel: subsys: lib: drivers: Use k_heap instead of z_mem_pool wrappers
Use the core k_heap API pervasively within our tree instead of the
z_mem_pool wrapper that provided compatibility with the older mempool
implementation.

Almost all of this is straightforward swapping of one alloc/free call
for another.  In a few cases where code was holding onto an old-style
"mem_block" a local compatibility struct with a single field has been
swapped in to keep the invasiveness of the changes down.

Note that not all the relevant changes in this patch have in-tree test
coverage, though I validated that it all builds.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross
6965cf526d kernel: Deprecate k_mem_pool APIs
Mark all k_mem_pool APIs deprecated for future code.  Remaining
internal usage now uses equivalent "z_mem_pool" symbols instead.

Fixes #24358

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Robert Lubos
7eefde36c3 net: lwm2m: Fix msg find based on pending/reply
The message should only be returned if the requested pending/reply
pointer is not NULL. Otherwise it could get an incorrect match (for
instance if specific pending pointer is searched for and reply is NULL
the function could return any message that doesn't expect a reply (and
thus has its reply pointer set to NULL).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-12-03 13:53:33 -05:00
Robert Lubos
4331c05f17 net: lwm2m: Allow to acknowledge request early from the callback
LwM2M engine by default sends piggybacked responses for requests after
all callbacks are executed. This approach however isn't good enough if
the application callback executes some lenghty operations (for instance
during FW update). Delaying the ACK may result in unnecessary
retransmissions.

This commits adds an API function which allows to send an early empty
ACK from the application callback. This prevents further retransmissions
from the server side. After all callbacks are executed, the LwM2M engine
will send the response as a separate CON message.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-12-03 13:53:33 -05:00
Robert Lubos
b27c14e355 net: lwm2m: Verify if block transfer is used before skipping TLV parsing
Verify if block tranfer is used and not an initial block when skipping
directly to data processing during FW update in PUSH mode.

This fixes a bug, which caused TLV not to be processed when the FW
object was updated as a whole, and actual resource number was encoded in
a TLV (for instance when writing FW Update URI).

Fixes #30135

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-12-01 11:26:55 -05:00
Robert Lubos
1c8f52a670 net: lwm2m: Rework bootstrap DELETE operation
Rework the bootstrap DELETE operation, to support deletion of multiple
resources.

Current implementation had several oversimplifications, making it not
spec-compliant:
* DELETE `/` removed only Security object instances (!= 0)
* DELETE `/x` was handled as DELETE `/x/0`, therefore not removing all
  of the object instances.

Since the above is only supported during bootstrap and not regular
Device management, this functionality was implemented in the
`bootstrap_delete` function, which now will be called for all DELETE
operations initiated during bootstrap. The regular LwM2M DELETE handler
will only be called during regular Device management, as it has more
strict limitations on what can be deleted.

Additionally, handle empty URI Path option as `/`, therefore indicating
deletion of all resources.

Fixes #29964

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-12-01 11:17:12 -05:00
Jukka Rissanen
04a421d1b8 net: shell: Fix statistics for network interface
We did not check that user has supplied network interface index
in "net stats iface <idx>" command.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-12-01 12:37:52 +02:00
Peter Bigot
550a1f411d net: net_tc: change illicit reference to work queue internal state
Debug messages used the address of a member of the work_q structure as
an identifier; that field is not public API, so replace it with the
address of the work queue itself.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-24 13:04:48 +02:00
Jukka Rissanen
03df709a46 net: tc: Refactor RX and TX thread priorities
Set the RX/TX thread priorities so that if cooperative priorities
are used, then lowest priority thread will have priority -1 which
is the lowest cooperative priority. The higest net thread priority
will depend on number of traffic classes but with max value 8,
the highest priority will be -8.

If preemptive priorities are used, then highest priority thread
will have priority 0, which is the highest preemptive priority.
In this case, the lowest thread priority will be 7 if there are
8 traffic classes.

The motivation for this change is that for cooperative priorities
we want to let other cooperative priority threads to run before
networking. But if preemptive priorities are used, we want
networking threads to run reasonably often compared to other
preemptive priority threads.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-20 12:57:29 +02:00
Jukka Rissanen
f02fd19706 net: Adjust the thread priorities
If networking pre-emptive thread priorities are enabled,
then use the proper macro to enable them.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-20 12:57:29 +02:00
Jukka Rissanen
575fc5fe14 net: tc: Allow user to select pre-emptive threading for RX/TX
Let user to decide whether the RX/TX threads are run in either
co-operative or pre-emptive thread priority.
Default is co-operative threading.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-20 12:57:29 +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
Jukka Rissanen
753412bd23 net: tcp2: Fix llvm issue when printing mss
llvm uses wrong int type for some reason, force cast to uint16_t

Fixes #29997

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-19 10:56:26 -05:00
Markus Becker
638b5f389f net: openthread: OpenThread RCP mode integration into Zephyr
* Add RCP library.
* Conditionally remove non required libraries not required for RCP.
* Drop :option: marker for CONFIG_OPENTHREAD_NCP_SPINEL_ON_UART_ACM

Signed-off-by: Markus Becker <markus.becker@tridonic.com>
2020-11-19 12:34:14 +01:00
Anas Nashif
63b7313c06 net: lldp: use llabs with int64_t
subpress warnings from llvm:

warning: absolute value function 'abs' given an argument of type
'int64_t' (aka 'long long') but has parameter of type 'int' which may
cause truncation of value [-Wabsolute-value]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-11-19 08:41:56 +01:00
Marcin Niestroj
aac0f98d1d net: hostname: define public macro representing maximum hostname length
Add a macro in public header that represents maximum hostname string
length without terminating NULL character. This will allow other
modules, such as offloaded network drivers, to know how much space is
needed to allocate in order to fit whole hostname.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-11-17 19:21:43 -05:00
Martin Åberg
3658f74d17 net: ipv6: fixed endian issue
A cast made assumption on how data is stored.

This commit makes the following test pass on qemu_leon3:
- net.udp

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2020-11-17 11:44:16 +02:00
Martin Åberg
634b8fd58c net: dhcpv4: fixed endian issue
This makes the following test pass on qemu_leon3:
- net.dhcp

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2020-11-17 11:44:16 +02:00
Martin Åberg
fb18a6e2f7 net: ipv6_fragment: fixed endian issue
A cast made assumption on how data is stored.

This commit makes the following test pass on qemu_leon3:
- net.ipv6.fragment

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2020-11-17 11:44:16 +02:00
Marcin Niestroj
09f6e8a112 net: hostname: fix logging hostname string
Following errors occuring after enabling debug logs:

  log: argument 2 in source net_hostname log message "%s: (%s): \
    Hostname set to %s" missinglog_strdup().
  log: argument 2 in source net_hostname log message "%s: (%s): \
    New hostname %s" missinglog_strdup().

Fix that by printing CONFIG_NET_HOSTNAME directly in the first case and
using log_strdup() in the second.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-11-17 10:41:49 +02:00
Jukka Rissanen
82dbda3b57 net: tcp2: Use proper int type for connection MSS
When printing MSS (Maximum Segment Size) value, use uint16_t
always.

Fixes #29997

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-16 09:19:21 -05:00
Jukka Rissanen
7d5ef1f952 net: shell: Print detailed information when TCP2 is enabled
If user has enabled TCP debugging, print detailed internal TCP2
information too when user gives "net conn" command. This is useful
to have when debugging.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-16 16:07:10 +02:00
Jukka Rissanen
6a54b1f013 net: tcp: Reorganize internal TCP header file
Comment out TCP1 specific stuff when TCP2 is enabled. This means
shuffling the code around a bit so that common code is placed at
the end. Introduce also net_tcp_foreach() function to TCP2 so that
it can be used from net-shell.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-16 16:07:10 +02:00
Jukka Rissanen
b519ba54f5 net: tcp2: Only accept a valid RST packet
If the seq number is not valid, then drop incoming RST.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-16 14:29:07 +02:00
Kiril Petrov
539c3e7fa8 lwm2m: handle return code from lwm2m_socket_add
Handle return code from lwm2m_socket_add

Signed-off-by: Kiril Petrov <retfie@gmail.com>
2020-11-16 14:28:08 +02:00
Jukka Rissanen
be4380f5e2 net: tcp2: Remove unnecessary data length calculation
The data length is already calculated in tcp_in() so no need
to do it again in tcp_data_get(). Just pass the length to the
tcp_data_get() function.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-16 14:22:13 +02:00
Jan Georgi
5da68ea186 net: shell: Added missing check for eth iface in "net iface" cmd
checking if iface is ethernet, before calling ethernet api func

Signed-off-by: Jan Georgi <jan.georgi@lemonbeat.com>
2020-11-12 14:16:40 +02:00
Christopher Friedt
0fc80cf79f net: dns: enable dns service discovery for mdns responder
This change enables support for DNS service discovery
(RFC 6763) in the mdns_responder service and sample app.

Fixes #29429

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-11-09 16:15:02 -08:00
Christopher Friedt
e7e58439e7 net: dns: dns-sd: support dns service discovery
This change adds support for DNS Service Discovery (DNS-SD)
as described in RFC 6763.

Fixes #29099

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-11-09 16:15:02 -08:00
Christopher Friedt
5c691491a7 net: context: add net_context api to check if a port is bound
This change adds net_context_port_in_use(), which is a simple
wrapper around net_context_check_port() and is used to check
if a particular socket is bound to a given IP address.

Fixes #29649

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-11-09 16:15:02 -08:00
Jukka Rissanen
db6dac3bcf net: tcp2: Fix sending to 6lo based networks
Do not send the original pkt in 6lo based networks as in those
the IPv6 header is mangled and we would not be able to do any
resends of the original pkt. So for 6lo networks, clone the
pkt and send it to peer. The original pkt is kept in sent list
in case we need to resend to peer.

Fixes #29771

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-06 18:58:17 +02:00
Jukka Rissanen
f08285fd6f net: shell: Fix TCP statistics printing
Fix TCP statistics printing.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-06 09:50:02 -06:00
Jukka Rissanen
ab8fd8270a net: stats: Separate dropped TCP data segments and TCP packets
Track the number of dropped TCP data segments and number of dropped
TCP packets in network statistics. It is useful to see these
numbers separately.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-06 09:50:02 -06:00
Jukka Rissanen
d4320eedf2 net: tcp2: Update statistics
The amount of sent bytes and transmit errors should update
network statistics.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-06 09:50:02 -06:00
Robert Lubos
7127f0a742 net: lwm2m: Notify the application on network error
Add a simple backoff mechanism between consecutive registration attempts
in case of registration failures. Finally, notify the application in
case the registration failed several times.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-06 12:58:14 +01:00
Robert Lubos
571b65830b net: lwm2m: Move bootstrap registration send into a separate function
Refactor the boostrap regstration procedure, by splitting the message
creation and sending into a separate function, in similar manner as
it's done with regular registration.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-06 12:58:14 +01:00
Robert Lubos
397b2a71fa net: lwm2m: Add a callback to notify socket errors to engine users
Currently, when socket errors occur during receive, the LwM2M engine
restarts the state machine and registers again to the server. While this
works in simple use case (only RD client socket open), it's not a valid
approach when more sockets are open (FW update socket).

Fix this by introducing socket fault callback, which is registered by
the LwM2M engine users. This way, a proper socket owner is notified on
error and can pertake appropriate action.

For RD socket errors the behaviour remains the same - the state machine
is reset and the client registers again to the server. For FW update
socket, handle the error by reopening the socket and retransmitting the
last request. This allows to resume the download from the point the
error occured, w/o a need to start from scratch.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-06 12:57:32 +01: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
Eduardo Montoya
dc56ace3da net: openthread: fix maximum number of children range
This commit corrects the maximum allowed amount of children to
match Thread specification.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2020-11-04 18:08:48 +02:00
Eduardo Montoya
8399a6067d net: openthread: allow to configure platform info
This commit adds the option to configure the platform information
string of OpenThread.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2020-11-04 18:08:48 +02:00
Jukka Rissanen
c31148b04c net: tcp2: Update seq when peer closes connection
If the peer ACKs data when it closes the connection, update
our sequence number accordinly. The connection would eventually
be terminated but this will avoid extra resends by the peer.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-04 11:17:47 +02:00
Jukka Rissanen
f50c9e11f0 net: tcp2: Avoid deadlock when closing the connection
When a connection is being closed, it is possible that the application
will have a lock to net_context and TCP2 connection lock. If we then
receive a final TCP2 ACK and close the connection, the locking order
get switched and TCP2 will first try to get its own lock and then the
net_context lock. This will lead to deadlock as the locking ordering
is now mixed.

The solution is to unref the TCP connection after releasing the
connection lock. The TCP connection unref function will anyway get the
lock so no need to do double locking.

Fixes #29444

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-11-04 11:16:53 +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
Mohamed ElShahawi
a6d32a7a09 net: ping: add warning if ping is not supported
Warn the user that "ping" is not supported in case of offloaded
driver is being used.

Signed-off-by: Mohamed ElShahawi <ExtremeGTX@hotmail.com>
2020-11-03 19:18:57 +02:00
Robert Lubos
4625820354 net: lwm2m: Send Registration Update on lifetime change
According to LwM2M specfication v1.0.2, par. 5.3.2, the LwM2M client
MUST send an “Update” operation to the LwM2M Server whenever the
lifetime parameter of the Server object changes the server). The same
applies for the object instances created/deleted. The changes in objects
seem to already be handled, but the lifetime was not.

Additionally, the "Update" message shall only contain these parameters
which changed since the last update (including objects). As it's
straightforward to determine if the liftime  changed but it's not easy
to tell if there were updates in the object instances, add an
additional parameter to the engine_trigger_update() function, indicating
that new object information shall be sent in the "Update" message.

Eventually add a proper error checking in `sm_send_registration` as the
function is reworked anyway.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-03 16:25:13 +01:00
Robert Lubos
f747022d9e net: lwm2m: Fix PULL FW update in case of URI parse errors
The memset on firmware_ctx during PULL FW update initialization will
set the socket descriptor to a valid value of 0. This leads to an error
if parsing of the URI provided by the server fails, and the firware_ctx
is closed - the socket with a descriptor 0 will be accidently closed.
Fix this by invalidating the socket FD after the memset on
initialization.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-03 16:24:34 +01:00
Robert Lubos
d8912fe895 net: lwm2m: Remove handle_separate_response flag
It shouldn't be optional to handle separate response, as it's a
mandatory requirement according to the RFC7252:

"The protocol leaves the decision whether to
 piggyback a response or not (i.e., send a separate response) to
 the server.  The client MUST be prepared to receive either."

Therefore, remove the flag as separate responses are handled now
properly.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-03 16:23:59 +01:00
Robert Lubos
37681a7bef net: lwm2m: Fix separate response handling
Separate response handling implemented in the engine was faulty. The
separate response was not acknowledged by the client, resulting in
spurious retransmissions from the server side.

Also, the pending CON message was retransmitted by the client even after
it was acknowledged by an empty ACK, but the respnse haven't arrived
yet. Fix this by adding a new `acknowledged` flag to the `lwm2m_message`
structure. Once acknowledged, the flag is set and the confirmable
message is no longer retransmitted. We keep the message on the pending
list in order to timeout properly in case separate response does not
arrive in time.

Finally, prevent the reply callback from being called twice in case
the response is transmitted separately from ACk. The callback should
only be called on the actual reply, not the empty ACK.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-03 16:23:59 +01:00
Robert Lubos
94d62ca151 net: lwm2m: Add lwm2m_send_empty_ack() function to internal API
So far this function existed as a static function in LwM2M PULL FOTA
module. Since such functionality will be needed in other places, make it
an internal API function.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-11-03 16:23:59 +01:00
Ehud Naim
89928c3c8b net: dhcpv4: check dhcpv4 msg len is correct
check if dhcpv4 msg len is correct and drop it otherwise

Signed-off-by: Ehud Naim <ehudn@marvell.com>
2020-11-02 12:56:16 +02:00
Ehud Naim
c58c8b1257 net: buf: change avail_count variable to atomic type
using CONFIG_NET_BUF_POOL_USAGE monitor avail_count,
this variable should be protect.
Protecting it by using atomic variable

Signed-off-by: Ehud Naim <ehudn@marvell.com>
2020-10-28 18:45:11 +02:00
Viktor Sjölind
1b3abc096c net: lwm2m: Start notify sequence numbers on 0
Some LWM2M backends/servers, such as emxq, expect the sequence numbers
to begin on 0.

This change is in line with how other lwm2m clients, such as Anjay and
Wakama, starts the notification sequence.

Signed-off-by: Viktor Sjölind <viktor.sjolind@endian.se>
2020-10-27 11:25:22 +02:00
Jukka Rissanen
a1b0a98fbf net: context: Add locking to IPv6, CAN and packet socket bind
The commit 93e5181f ("net: context: Add locking for concurrent
access") added net_context locking to only IPv4 sockets.
That is not enough and we need locking also to other supported
socket address families like IPv6, SocketCAN and packet socket.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-26 11:03:03 -05:00
Benjamin Lindqvist
660ad9791b net: lwm2m: Pack TLV integers more efficiently
Prior to this commit, the LwM2M stack would TLV-encode integers
depending on their internal storage size. An integer with value 5 stored
in an int8_t would be encoded with length 1, but an integer stored in an
int32_t would be encoded as "00 00 00 05" with length 4.

This commit checks if the value is castable to a smaller int and encodes
it as such if so. This is cascading, so even a 64 bit integer with value
5 will be encoded with length 1.

Note that this does not seem to be required by the specification, but
this is how Anjay and the other LwM2M stack seem to do it.

Signed-off-by: Benjamin Lindqvist <benjamin.lindqvist@endian.se>
2020-10-26 11:31:28 +02:00
Jukka Rissanen
899228bb7f net: icmpv6: Store ll addresses to pkt when sending error msg
When we are sending ICMPv6 error message, we need to store the
link local addresses of the received packet somewhere in order
to know where to send the new error message.
Easiest is to store the ll addresses is to the error message
itself, just before where the sent packet will start in memory.
We cannot use the original pkt to store the ll addresses
as that packet might get overwritten if we receive lot of packets.

Fixes #29398

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-23 09:29:27 +03:00
Lukasz Maciejonczyk
06fdea7ec8 net: config: Fix improper condition in net_config_init
Currently, there is a case for net_config_init function that for
timeout==0 and when iface is already up, the ip setup is not proceed
and the error message "Timeout while waiting network..." is logged.

This commit fixes it.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2020-10-22 12:33:12 +03: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
Jukka Rissanen
0f9ec427bc net: tcp2: Lock conn when sending data from work queue
If we are sending data directly, we already have TCP lock so
there is no need to do any locking. But when data is re-sent,
the work queue handler is doing the sending so we need to lock
the TCP connection.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-21 12:57:23 -05:00
Jukka Rissanen
735fcc63bf net: tcp2: Pass data to application without any TCP locks
When receiving data that needs to be passed the data to application,
queue it for short time so that we do not have TCP connection lock
held. This way if the application wants to send data, there is no
possibility that the connection lock would prevent sending data.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-21 12:57:23 -05:00
Jukka Rissanen
6003c988e1 net: context: Release lock before passing RX data to socket
Release the context lock before passing data to the application
socket as that might cause deadlock if the application is run
before the RX thread and it starts to send data and if the RX
thread is never able to run (because of priorities etc).

Fixes #29347

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-21 12:57:23 -05:00
Jukka Rissanen
1807e93697 net: tcp: Deprecate legacy TCP stack
Mark the legacy TCP stack as deprecated and expect it to be
removed in 2.6 release.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-21 10:08:48 -04:00
Lukasz Maciejonczyk
102084f873 net: openthread: Add Kconfigs to change values in Zephyr port
Refactor openthead zephyr config file. Add missing KConfigs.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2020-10-21 16:09:56 +03:00
Lukasz Maciejonczyk
2015eab033 net: openthread: Remove unused defines from platform configuration
These defines are leftover of old platform settings implementation
and are not used any more.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2020-10-21 16:09:56 +03:00
Oliver Hitz
a704af4a3e net: Fix access to already unref'ed packet data
net_icmp4_input() may net_pkt_unref() a packet. The header mustn't be
accessed after this or the system may crash.

Signed-off-by: Oliver Hitz <oliver@net-track.ch>
2020-10-21 12:49:22 +03:00
Damian Krolik
62a5179b7b openthread: add openthread_api_mutex_try_lock()
Existing openthread_api_mutex_lock()/unlock() functions are
crucial to assure thread safety of an application which
needs to use OT API directly, but some applications may also
require a non-blocking version of the former for less critical
OT-related tasks.

Add openthread_api_mutex_try_lock() which never waits and
exits immediately if the mutex is held by another thread.

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
2020-10-20 16:39:22 +03:00
Jukka Rissanen
00f0d5729a net: tc: Make thread name unique
If there are more than one RX or TX threads, then make the name
of each of them unique so that it is easier to figure them out
in "kernel stacks" command.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-20 12:47:40 +03:00
Jukka Rissanen
25b924e45b net: conn_mgr: Change the name of the handler thread
The name of the connection manager thread (conn_mgr_thread) was
unnecessarily long in "kernel stacks" command. So make the name
to "conn_mgr" which fits nicely to the output of that command.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-20 12:47:40 +03:00
Benjamin Lindqvist
c7b6706b42 net: ppp: Ensure IPCP address is always removed
If an address was obtained by IPCP, it should always be removed in
ipcp_down(). This commit replaces the predicate with something slightly
more robust.

Signed-off-by: Benjamin Lindqvist <benjamin.lindqvist@endian.se>
2020-10-19 18:29:02 +02:00
Jukka Rissanen
3b6155bbf5 net: tcp2: Fix TCP connection from Windows 10
Windows 10 sends ECN-Echo and Congestion Window Reduced (CWR) flags
together with SYN flag in the connection establishment but the code
did not ignore these flags and send just SYN back (instead of SYN|ACK).
This caused the connection establishement in application level to
fail as the application was never notified about it.

Fixes #29258

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-19 15:25:56 +03:00
Eduardo Montoya
84158f54b9 net: openthread: fix unwanted 802.15.4 radio up
This commit moves IPv6 initialization from OT init to OT start to
avoid unwantedly bringing 802.15.4 radio up.

Previously, even when OT manual start was enabled, the radio would
be receiving frames resulting in unnecessary power consumption and
causing issues for instance when the device just wants to use
Bluetooth for provisioning befor moving to Thread.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2020-10-19 12:55:52 +03:00
Marek Porwisz
5d57b396b8 net: openthread: Increase the number of allowed children
Another team reported that current default values for number of allowed
IP addresses per child (4) and and max number of children (10) are too
small for some customers.
Increased the values allowed configuring child count.

Signed-off-by: Marek Porwisz <marek.porwisz@nordicsemi.no>
2020-10-19 12:55:07 +03:00
Marek Porwisz
791e09dfb3 lib: openthread: use the rx failed notification
OpenThread mac counters require rx failed notification to work properly.
Made use of previously implemented notification.

Signed-off-by: Marek Porwisz <marek.porwisz@nordicsemi.no>
2020-10-19 12:50:02 +03:00
Armand Ciejak
6a110f93c0 net: ip: dhcpv4: Add randomization to message interval
Add +1/-1 second randomization to the timeout as per RFC 2131
chapter 4.1.

Signed-off-by: Armand Ciejak <armand@riedonetworks.com>
2020-10-14 14:59:39 +03:00
Armand Ciejak
b98d3b125c net: ip: dhcpv4: Limit message interval to a maximum of 64 seconds
Clip the timeout to 64 seconds, this avoids the timeout value to
increase to high values (e.g. several years).

Signed-off-by: Armand Ciejak <armand@riedonetworks.com>
2020-10-14 14:59:39 +03:00
Armand Ciejak
ab5fd19c2b net: ip: dhcpv4: Add dhcpv4_update_message_timeout()
This avoids code duplication. The same logic was present
in dhcpv4_send_request() and dhcpv4_send_discover().

Signed-off-by: Armand Ciejak <armand@riedonetworks.com>
2020-10-14 14:59:39 +03:00
Jukka Rissanen
d3283231a5 net: tcp2: Socket was accepted too early
The TCP2 was calling accept callback before actually finalizing
the connection attempt.

Fixes #29164

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-14 12:17:54 +03:00
Jukka Rissanen
accaab2112 net: shell: Add network mgmt events monitor support
Add "net events [on|off]" command that can be used to monitor
the generated network management events.

The monitor output looks like this when enabled:

EVENT: L2 [1] up
EVENT: L3 [1] IPv6 mcast address add ff02::1:ff00:1
EVENT: L3 [1] IPv6 mcast join ff02::1:ff00:1
EVENT: L3 [1] IPv6 address add 2001:db8::1
EVENT: L4 [1] connected
EVENT: L3 [1] IPv6 prefix add 2002:5b9b:41a0::
EVENT: L3 [1] IPv6 address add 2002:5b9b:41a0:0:fec2:3dff:fe11:c147
EVENT: L3 [1] IPv6 neighbor add fe80::9ec7:a6ff:fe5e:4735
EVENT: L3 [1] IPv6 router add fe80::9ec7:a6ff:fe5e:4735
EVENT: L3 [1] IPv6 DAD ok fe80::fec2:3dff:fe11:c147
EVENT: L3 [1] IPv6 DAD ok 2001:db8::1
EVENT: L3 [1] IPv6 DAD ok 2002:5b9b:41a0:0:fec2:3dff:fe11:c147
EVENT: L3 [1] IPv4 address add 192.168.1.69
EVENT: L3 [1] DHCPv4 bound 192.168.1.69

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-13 13:42:50 +03:00
Jackie Ja
fac4a6a4fe net: lib: http: chunked encoding body support
We should not ignore the body when the Transfer-Encoding is
chunked.

Signed-off-by: Jackie Ja <qazq.jackie@gmail.com>
2020-10-12 13:58:19 +03:00
Jackie Ja
f07a9691ed net: websocket: Fix websocket loop close call
A normal websocket close sequence:
  close(websock) ->
    websocket_close_vmeth() ->
      websocket_disconnect()

close(ctx->sock) called in the function websocket_disconnect()
and cause websocket_close_vmeth() called again.
Finally stack overflow by loop close call.

It's maybe a side-effect by PR #27485

Signed-off-by: Jackie Ja <qazq.jackie@gmail.com>
2020-10-12 13:57:07 +03:00
Robert Lubos
2497958298 net: lwm2m: Improve token generation
Improve token handling by removing special meaning of tokenlen == 0,
which allows to handle server requests w/o a token (so far such
requests would cause the lwm2m engine to autogenerate token in the
response).

In order to autogenerate token during message initialization, use
special symbol `LWM2M_MSG_TOKEN_GENERATE_NEW`. If no token is wished to
be used, simply set the tokenlen to 0.

Additionally, fix an issue with token autogeneration, where invalid
token len was used (0 instead of 8).

Fixes #28299

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-09 10:46:53 +03:00
Robert Lubos
b932edc772 net: lwm2m: Fix bootstrap finish response code
LwM2M engine did not set response code for the Bootstrap-finish message,
hence it replied with the code copied from the request which is not
correct. Fix this by setting correct code for the Bootstrap-finish
reply.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-08 16:31:56 +03:00
Jackie Ja
1b79d5c279 net: websocket: Fix remnant of message type
Reset message type if all the data has been received.

Signed-off-by: Jackie Ja <qazq.jackie@gmail.com>
2020-10-06 12:01:39 +03:00
Robert Lubos
5fc7d86d7c net: lwm2m: Report boostrap complete after final response is sent
So far, `LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_TRANSFER_COMPLETE` event was
reported before the final ACK for the Bootstrap Finish was sent from the
client side. This could cause delays in the ACK sending, in case the
application wanted for instance to store the received data in flash.

Fix this, by reporting the
`LWM2M_RD_CLIENT_EVENT_BOOTSTRAP_TRANSFER_COMPLETE` event on the next
state tansition (before the actual registration starts).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-06 12:01:13 +03:00
Robert Lubos
f35d88503a net: lwm2m: Use the actual data size when provisioning PSK ID
"Public Key or Identity" resource is of opaque data type, therefore it's
not correct to assume it will be a NULL terminated string (the existing
servers, for instance Leshan, does not include NULL terminator). Use the
actual size associated with the resource instead.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-06 12:01:13 +03:00
Robert Lubos
f223d0a86f net: lwm2m: Store the actual resource size in the resource instance
So far, the resource instance structure kept only the information about
the buffer length provided to the resource (in the `data_len` field).
While this approach might be enough for integer resources, where the
actual data size is fixed, it did not work for opaque resources. It is
impossible to determine the actual opaque resource length after it's
been written into.

Fix this, by replacing the current `data_len` field of the
`lwm2m_engine_res_inst` with `max_data_len`, indicating the buffer
size, and making the `data_len` field to hold the actual data size of
the resource.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-06 12:01:13 +03:00
Robert Lubos
f7a5638871 net: lwm2m: Make bootstrap optional
Currently, after `CONFIG_LWM2M_RD_CLIENT_SUPPORT_BOOTSTRAP` is enabled,
the LwM2M engine will initiate bootstrap procedure on each run. This
approach limits the flexibility of the application, as it's not always
necessary to go over the bootstrap procedure (for instance, the
application may decide to store the security object obtained during the
bootstrap in flash, and restore it on boot).

Fix this by introducing an additional `flags` parameter to the
`lwm2m_rd_client_start()` function, which provides information whether
to run bootstrap in the current session or not.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-06 12:01:13 +03:00
Robert Lubos
40d25b8efa net: lwm2m: Introduce ENGINE_IDLE state
So far, the LwM2M state machine started in the `ENGINE_INIT` state,
which made it exectue the registration/bootstrap registration even when
`lwm2m_rd_client_start()` was not called. With a new `ENGINE_IDLE`
state, the state machine can wait for the application to actually start
the client before proceeding. It also makes sense to stay in the
ENGINE_IDLE state after successfull deregistration, until the
application restarts the client.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-06 12:01:13 +03:00
Benjamin Lindqvist
8c22983234 net: l2: ppp: Remove ipcp address on network down
Without removing the stale address obtained during IPCP, it will still
be present the next time we do IPCP, marked as "in use" by the network
stack even if it is stale. This turned out to be a showstopper for
restarting the PPP stack on devices without static IP.

Signed-off-by: Benjamin Lindqvist <benjamin.lindqvist@endian.se>
2020-10-06 11:57:46 +03:00
Robert Lubos
12e1fd653d net: lwm2m: Fix FOTA block transfer with opaque content-format
This commit fixes PUSH FOTA when opaque content-format is used.

This consists of the following fixes:
 * Moved `struct block_context` to a private header, so that it can be a
   part of `struct lwm2m_input_context`. This allows content decoders to
   make use of the block context data.
 * Removed faulty `get_length_left` function from the plain text
   decoder, and replace it with coap_packet_get_payload() to obtain the
   actual payload size.
 * Introduce `struct lwm2m_opaque_context` as a part of block context,
   which allows to keep track of opaque data download progress.
 * Simplify `lwm2m_write_handler_opaque()` function. It will now only
   make calls to `engine_get_opaque` - it's the decoder responsibility
   to update the opaque context according to it's content format (for
   instance TLV decoder should only update it with the actual opaque
   data size, not the whole TLV).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-10-05 12:16:57 +02:00
Jukka Rissanen
d4347b4015 net: dhcpv4: Generate start/bound/stop mgmt events
The L4 connected/disconnected events are usually used to detect
when the application is connected to the network. Unfortunately
if the device has also a static address, then the connected event
might be created (for the static address) even if DHCPv4 is not
ready yet and application would not be able to connect (yet) to the
network. In order to allow the application to fine tune the network
connection creation, generate start, bound and stop events for DHCPv4.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-03 17:15:15 +03:00
Jukka Rissanen
db889774c2 net: tc: Remove not used field from net_traffic_class struct
The "tc" field which was holding the traffic class thread
priority is not used nor needed so remove it from the struct
to save some space.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-02 13:20:17 +03:00
Xavier Chapron
824f423e54 misc: Replace assert include and calls by sys/__assert.h equivalent
Replace all calls to the assert macro that comes from libc by calls to
__ASSERT_NO_MSG(). This is usefull as the former might be different
depending on the libc used and the later can be customized to reduce
flash footprint.

Signed-off-by: Xavier Chapron <xavier.chapron@stimio.fr>
2020-10-02 11:42:40 +02: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
Jan Pohanka
fff28ad8ae net: mqtt: use zsock_ functions
Using zephyr's internals zsock_ calls make mqtt library more compatible,
now it does not depend on NET_SOCKETS_POSIX_NAMES.

Signed-off-by: Jan Pohanka <xhpohanka@gmail.com>
2020-10-01 17:35:45 +03:00
Kumar Gala
9c45673d8e net: sntp: Remove deprecated API function
Remove sntp_request as its been marked deprecated since at least Zephyr
2.3 release.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-10-01 07:14:08 -05:00
Jukka Rissanen
8bb83454b4 net: tcp2: Do not assert when cancelling send timer
No real need to assert when the send timer is cancelled. Just
check if there is re-transmission going on and do nothing if
there is not.

Fixes #28758

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-01 14:19:07 +03:00
Jukka Rissanen
cace577d68 net: tcp2: Local accepted socket was not bound
The local and accepted socket was not bound which caused the
local address to be set as NULL. This then caused issues when
zsock_getsockname() was called by the application.

Fixes #28735

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-10-01 14:19:07 +03:00
Christian Taedcke
fd6596d53b net: mgmt: Add const to info param of notify function
Since the info parameter is only read from and never written the const
in the function parameter should be present.

Signed-off-by: Christian Taedcke <christian.taedcke@lemonbeat.com>
2020-09-30 14:40:50 +03:00
Rafał Kuźnia
5b7efd3277 net: openthread: add kconfigs to change values in zephyr port
This commit adds additional Kconfigs that allow for changing
configuration values for the Zephyr port in OpenThread.

Those values are:
- number of the internal OT message buffers
- number of the state change callbacks
- number of the EID-to-RLOC cache entries
- size of the NCP buffer

Signed-off-by: Rafał Kuźnia <rafal.kuznia@nordicsemi.no>
2020-09-30 14:38:04 +03:00
Jukka Rissanen
ccea4d3258 net: ethernet: Check IPv4 multicast pkt using util function
Instead of directly checking the multicast IPv4 address, use
the net_ipv4_is_addr_mcast() utility function.

Fixes #26584

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-30 14:31:13 +03:00
Marcin Niestroj
9a791dd6bb net: mqtt: Reset client state before notifying MQTT_EVT_DISCONNECT
MQTT client state is protected using mutex. That mutex however is
temporarily unlocked when calling event callbacks. This means that in
client_disconnect() transport can already be disconnected, but without
marking it as such in client->internal.state.

When mutex is unlocked in event_notify() function, then there are two
possible paths of failure:

1) First possibility is when RX and TX are called from two separate
   threads, so that the other thread gets resumed and functions like
   verify_tx_state() (e.g. in mqtt_publish()) allow to continue
   communication over disconnected medium.
2) Another possibility is that user calls mqtt_abort() or
   mqtt_disconnect() in event handler.

In both cases MQTT library tries to send or receive data, possibly
followed by second close() of underlying file descriptor.

Prevent using disconnected transport by clearing MQTT client state right
after calling mqtt_transport_disconnect(), without releasing mutex, even
for a while.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-09-30 14:30:43 +03:00
Torsten Rasmussen
5fd53dcd8a net: tcp2: added struct const to *net_context_state()
When compiling with CONFIG_NET_NATIVE=n and CONFIG_NET_OFFLOAD=n
then the following error is printed.

```
In file included from zephyr/subsys/net/ip/ net_if.c:23:0:
zephyr/subsys/net/ip/net_private.h: In function 'net_context_state':
zephyr/subsys/net/ip/net_private.h:58:27:
error: type of 'context' defaults to 'int' [-Werror=implicit-int]
 static inline const char *net_context_state(context)
```

This add `struct net_context *` as type for context.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2020-09-30 14:29:44 +03:00
Jakub Rzeszutko
005103739c shell: examples cleanup
Remove obsolete include of the shell_uart.h file.
It is sufficient to include the shell.h file.

Signed-off-by: Jakub Rzeszutko <jakub.rzeszutko@nordisemi.no>
2020-09-29 10:48:47 +02:00
Aurelien Jarno
1df2de346b net: openthread: Remove old flash code
Since commit b3a1ede830 OpenThread uses the Zepyhr settings submodule
instead of writing to the flash directly. The flash.c file is not
compiled anymore, so let's just remove it. Also remove the
OT_PLAT_FLASH_PAGES_COUNT Kconfig option which was solely used by that
file.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2020-09-28 14:17:22 -05:00
Jukka Rissanen
3b64d57943 net: ethernet: Make sure Ethernet header is in the recv pkt
Check that Ethernet header is in the first net_buf fragment.
This is very unlikely to happen as device driver is expected
to only deliver proper Ethernet frames to upper stack.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-28 14:25:13 +03:00
Jukka Rissanen
6fcd945f1f net: conn: Check that TCP pointer is valid
Saw this crash with heavily loaded system in nucleo_f767zi:

<err> os: ***** MPU FAULT *****
<err> os:   Data Access Violation
<err> os:   MMFAR Address: 0x0
<err> os: r0/a1:  0x800f6d30  r1/a2:  0x80005d84  r2/a3:  0x00000006
<err> os: r3/a4:  0x00000000 r12/ip:  0x00000001 r14/lr:  0x60013f69
<err> os:  xpsr:  0x61000000
<err> os: Faulting instruction address (r15/pc): 0x60014304
<err> os: >>> ZEPHYR FATAL ERROR 0: CPU exception on CPU 0
<err> os: Current thread: 0x80001a18 (rx_workq)
<err> os: Halting system

Where the fault at 0x60014304 points to net_conn_input()

   } else if (IS_ENABLED(CONFIG_NET_TCP) && proto == IPPROTO_TCP) {
	src_port = proto_hdr->tcp->src_port;
60014300:	f8d9 3000 	ldr.w	r3, [r9]
60014304:	881a      	ldrh	r2, [r3, #0]

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-28 14:25:13 +03:00
Jukka Rissanen
be072b1255 net: ethernet: Check that header is valid
Saw this crash with heavily loaded system in mimxrt1050_evk:

<err> os: ***** MPU FAULT *****
<err> os:   Data Access Violation
<err> os:   MMFAR Address: 0xc
<err> os: r0/a1:  0x80000ab0  r1/a2:  0x800f6a60  r2/a3:  0x00000000
<err> os: r3/a4:  0x800f72a0 r12/ip:  0x00000000 r14/lr:  0x6000eb43
<err> os:  xpsr:  0x41000000
<err> os: Faulting instruction address (r15/pc): 0x6000dc82
<err> os: >>> ZEPHYR FATAL ERROR 0: CPU exception on CPU 0
<err> os: Current thread: 0x80001a18 (rx_workq)
<err> os: Halting system

Where the fault at 0x6000dc82 points to ethernet_recv()

	uint16_t type = ntohs(hdr->type);
6000dc82:	89ab      	ldrh	r3, [r5, #12]

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-28 14:25:13 +03:00
Jukka Rissanen
baf83c2faf net: tcp2: Lock connection when running from work queue
We run various TCP function from work queue. Make sure the
connection lock is taken before accessing the connection.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-28 14:25:13 +03:00
Pascal Brogle
e3e465a29c net: lwm2m: make max client endpoint name configurable
support longer name like urn:dev:ops:{OUI}-{ProductClass}-{SerialNumber}
or urn:imei-msisdn:###############-###############

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2020-09-28 14:24:14 +03:00
Marek Porwisz
4ad1e0cfd1 net: openthread: Fix stack overflow for joiner
Fixed stack being to small for joiner operations.
Enabled auto joining even in case of manual start.
Fixed attachement of SED on norfic radios.

Signed-off-by: Marek Porwisz <marek.porwisz@nordicsemi.no>
Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2020-09-24 15:55:30 -05:00
Jukka Rissanen
a95ae6712f net: tcp2: Access k_work in k_delayed_work using field name
Instead of casting k_delayed_work directly to k_work, use the
k_work field name. This avoids warnings from Coverity and
allows the code to work even if the k_delayed_work fields are
re-ordered in the future.

Coverity-CID: 214346
Fixes #28659

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-24 13:29:13 -05:00
Jukka Rissanen
66cdcb0b48 net: DHCPv4 needs UDP to work properly
Add dependency to UDP in DHCPv4 Kconfig option as UDP is needed
in DHPCv4 to work properly.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-23 13:28:38 -05:00
David Komel
c067463791 net: tcp2: fix sysworkq corruption in tcp_conn_unref()
Bug description:
When in tcp_conn_unref(), in case one of the delayed works is already
submitted to sysworkq (after delay period), e.g. send_timer, the check
of k_delayed_work_remaining_get() prevents calling
k_delayed_work_cancel().
This leads to corrupting sysworkq when zeroing struct tcp* conn.
Note that the "next" pointer for the work queue is part of the struct
work (in _reserved field). Which is, in this case, a member of struct
tcp.

Scenario leading to the bug:
(1) net_tcp_connect() is called from a work in sysworkq
(2) net_tcp_connect() submits conn->send_timer to sysworkq
(3) while net_tcp_connect() is waiting on connect_sem, delay period
    passes (z_timeout) and send_timer enters sysworkq work slist
(4) also, some other code (app) submits more works to queue, now pointed
    by conn->send_timer in sysworkq work list
(5) connection fails (no answer to SYN), causing a call to
    tcp_conn_unref()
(6) tcp_conn_unref() is calling tcp_send_queue_flush()
(7) checking k_delayed_work_remaining_get(&conn->send_timer) returns 0
    due to delay period end, but send_timer is still in sysworkq work
    slist (sysworkq thread still hasn't handled the work)
(8) BUG!: no call to k_delayed_work_cancel(&conn->send_timer)
(9) back in tcp_conn_unref(), a call to memset(conn, 0, sizeof(*conn))
    zeroes conn->send_timer
(10) conn->send_timer is pointed to in sysworkq work slist, but is
     zeroed, clearing pointer to following works submitted in stage (4)
(11) EFFECT! the works in stage (4) are never executed!!

NOTES:
* k_delayed_work_cancel(), handles both states:
  (1) delayed work pends on timeout and
  (2) work already in queue.
  So there is no need to check k_delayed_work_remaining_get()
* This is also relevant for conn->send_data_timer

Solution:
removing checks of k_delayed_work_remaining_get(), always calling
k_delayed_work_cancel() for work in struct tcp, in unref, before memset

Signed-off-by: David Komel <a8961713@gmail.com>
2020-09-23 08:37:44 -05:00
Jukka Rissanen
d312c6e7e6 net: gptp: Print priority1 and priority2 vars in net-shell
Print the default values of BMCA priority1 and priority2
variables in net-shell.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-22 16:45:45 -05:00
Jukka Rissanen
e3fd17072e net: gptp: Allow user to tweak priority1 and priority2 values
Instead of hardcoding the priority1 and priority2 values used
in BMCA, let the user tweak the values via Kconfig.

Fixes #28151

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-22 16:45:45 -05:00
Kumar Gala
fe7dd725f0 net: tcp2: Fix build failures on 64-bit platforms
Since conn->send_data_total is of time size_t we need to use %zu or
we'll get build errors in sanitycheck on 64-bit platforms

Fixes #28605

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-09-22 12:08:37 -05:00
Jukka Rissanen
c54a511d26 net: Drop incoming packet if there is no data in it
If the network driver for some reason did not set the data in
the network packet properly, then just drop it as we cannot do
anything with just plain net_pkt.

Fixes #28131

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-22 11:22:43 +02:00
Jukka Rissanen
8afaadd223 net: conn: Ignore unhandled IPv4 broadcast packets
If there is no handler for IPv4 broadcast packet, then ignore it
instead of trying to send an ARP message to resolve the senders
address.

Fixes #21016

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-21 10:04:57 -05:00
Jukka Rissanen
0e49f5570c net: tcp2: Check that connection exists in net_tcp_put()
Unit test tests/net/tcp2/net.tcp2.simple might have conn set to
null so check it here.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
ac7866c663 net: tcp2: Fix connection termination
We need to have timer that closes the connection for good if
we do not get the FIN and ACK reponse from the peer.

If there is any pending data when application does close(),
send them before sending FIN.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
13a7baf1e4 net: tcp2: Bail out if new connection cannot be created
If there is some error during connection creation, just bail
out in order to avoid null pointer access.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
4e3060a26b net: tcp2: Retrigger resend if sending window is full
If we try to send data but the sending window is full, then
try to kick the resend of the pending data.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
69459507b6 net: tcp2: Fix connection state debugging
The log buffer was too short and debug messages were truncated.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
bd9f707098 net: tcp2: Print context state when closing connection
Useful in debugging.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04: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
29f0895b93 net: tcp2: Adjust the send window according to avail bufs
We should have a max value for sending window so that application
is not able to use all our net_bufs for queueing packets.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
b00adf6965 net: tcp2: Re-order connection struct fields
Order the fields in connection struct so that they use minimal amount
of memory.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
ff2aff3a32 net: tcp2: Make sure the pkt if not null
If the send_queue pkt is null, then do not try to access it.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
037037cdaa net: context: Return -ENOBUFS to caller if we run out of bufs
The socket layer expects to receive -ENOBUFS if we do not have
any network buffers so cannot build a network message to be sent.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
3db319fbc3 net: tcp2: Avoid double free message
If there is an error, the net_context.c:context_sendto() will
free the net_pkt, so we must not do it here.

This commit fixes this error message:

<err> net_pkt: *** ERROR *** pkt 0x20421908 is freed already
                                     (context_sendto():1672)

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
65a3b5a68e net: tcp2: Do not close connection if we run out of memory
Usually the out-of-memory situation will clear itself eventually,
so if that happens in TCP, then keep the connection running and
let the user to decide what to do next.

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
Jukka Rissanen
80d04616de net: tcp2: Honor TCP retry count limit from Kconfig file
Instead of hardcoded value of 3, use the value from Kconfig file
so that user can tweak the TCP retry count.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
28177dad6f net: conn: Use safe slist macro when searching connection
Try to catch simultaneous insert to/delete from list when
searching the connection.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
6dfb11c781 net: tcp2: Use safe version of slist macro in conn search
Use SYS_SLIST_FOR_EACH_CONTAINER_SAFE() macro when searching
the connection list so that we notice if new entries are added
or removed in the list.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Jukka Rissanen
54d05efb34 net: tcp2: Use pointer to slist node
Instead of forcing the slist node to be first in the tcp struct,
use the pointer to node when accessing the slist. This way we
can change the ordering of fields in tcp struct.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-18 22:07:53 -04:00
Pascal Brogle
32f053403f net: lwm2m: remove special handling for message id 0
Change so that the caller of lwm2m_init_message is
responsible for generating a message id and remove message id generation
from lwm2m_init_message. Prevents generating a new id when the caller's
intent is to init a message with id 0.

Fixes #28283

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2020-09-17 13:34:19 -05:00
Pascal Brogle
18a51a0bf6 net: lwm2m: use defines for message id and token generation
message id 0 and token 0 have special semantics in the lwm2m engine,
they are used to request generation of new id, mark them as such.

Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
2020-09-17 13:34:19 -05:00
Eduardo Montoya
a136f2f695 net: openthread: fix initialization with link raw enabled
Fix the OpenThread initialization to prevent the IPv6 interface to
be enabled when `CONFIG_OPENTHREAD_RAW` is set.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2020-09-16 12:05:07 +02:00
Jukka Rissanen
e15aa4866e net: context: Fix sendmsg() handling in AF_CAN socket
Because the previous commit fixed the destination address check,
we need to handle msghdr (used by sendmsg()) in CAN socket.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-10 12:05:48 -05:00
Jukka Rissanen
0c7d2bcd4f net: context: Simplify the param check when sending data
No need to specifically check CAN sockets here. This also means
that SocketCAN will need to support sendmsg() call too. This will
come in following commit.

Fixes #28229

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-10 12:05:48 -05: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
bff0f954a9 net: lwm2m: Make sure Sensor Type string isn't too long
The default string representing Sensor Type resource in Generic IPSO
object would not fit into the predefined buffer. Increase the buffer
size and add extra BUILD_ASSERT to detect this situation.

Coverity ID: 214225

Fixes #28164

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-09-09 14:10:29 +03:00
Lukasz Maciejonczyk
80b02ec884 net: config: Fix missing error log when timeout happens
The timeout log error message condition in wrong. When the timout
happens the "count == -1" and the condition is invalid.

This commit fixes it.

Signed-off-by: Lukasz Maciejonczyk <lukasz.maciejonczyk@nordicsemi.no>
2020-09-09 13:06:05 +02:00
Jukka Rissanen
3e5a4d79b2 net: tcp2: Make sure all incoming data is given to app at eof
When the connection is terminated, make sure that any pending
data is feed to the application.

Fixes #28057

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-04 11:04:27 -04:00
Marin Jurjevic
1753fac49a net: lwm2m: Fix FOTA Pull firmware transfer when Package URI is empty
Fix for a problem in current lwm2m firmware object implementation.
Transfer should not begin when an empty string is received.

Signed-off-by: Marin Jurjevic <marin.jurjevic@hotmail.com>
2020-09-04 12:18:58 +03:00
Marek Porwisz
05972fff5a lib: openthread: allow passing multiple libraries as mbedtls
Some implementation consist of multiple libraries to be linked instead
of one. Added possibility to pass multiple libraries. Additionally
renamed the config name as it was stateing something different than it
does.

Signed-off-by: Marek Porwisz <marek.porwisz@nordicsemi.no>
2020-09-04 11:10:34 +02:00
Jukka Rissanen
9d064e6ae9 net: tcp2: Fix connection close ack values
If we receive a TCP segment with FIN | ACK | PSH flags, then
update the ack values properly.

Fixes #27982

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-09-03 18:04:01 -04: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