When writing string data to resources which are string types,
we should count in the terminating character into the data length.
Corner cases exist where LwM2M resource type is opaque but
lwm2m_get_string() or lwm2m_set_string() are used to read/write
the data. We must ensure string termination on those case, but
terminating character must not be stored in the engine buffer
or counted in the data length as this might be considered
as part of the binary data.
Fixes#59196
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
Add a new Kconfig parameter NET_CONFIG_MY_VLAN_ID as initial network
configuration to enable users to set VLAN identifier at startup.
Add a new setup_vlan(...) function to setup the VLAN identifier in
the device, the call have an effect only when NET_CONFIG_MY_VLAN_ID
is above zero.
Signed-off-by: Luca Fancellu <luca.fancellu@arm.com>
websocket_disconnect api does not closes mqtt's tcp socket, so
tcp socket must be closed after done.
Signed-off-by: Saravanan Sekar <saravanan@linumiz.com>
The websocket_connect api expects connected tcp socket, do not close
the user supplied socket so that the caller can re-use it if needed.
Signed-off-by: Saravanan Sekar <saravanan@linumiz.com>
The PAN ID in IEEE 802.15.4 frames is little endian while in the
IEEE 802.15.4 context it is kept in CPU byte order.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The ACK procedure had the following issues:
- MAC commands were not acknowledged.
- When the package is a broadcast package the package must not be
acknowledged.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Acknowledgment is mandatory if legitimately requested by the package's
"ACK requested" flag. The L2 layer will have to ensure that compliant
ACK packages will always be sent out automatically as required by the
standard.
For IEEE 802.15.4 compliance, the NET_L2_IEEE802154_ACK_REPLY option is
therefore being deprecated.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The existing calls to ieee802154_radio_send() and soft MAC ACK handling
were inconsistent and/or not properly integrated with more recent
radio driver capabilities as CSMA/CA and ACK in hardware.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The method ieee802154_radio_handle_ack() does not belong to the
PHY/radio layer but to the L2 layer. It is a callback called from the
radio layer into the L2 layer and to be implemented by all L2 stacks.
This is the same pattern as is used for ieee802154_init(). The
'_radio_' infix in this function is therefore confusing and
conceptually wrong.
This change fixes the naming inconsistency and extensively documents
its rationale.
It is assumed that the change can be made without prior deprecation of the
existing method as in the rare cases where users have implemented custom
radio drivers these will break in obvious ways and can easily be fixed.
Nevertheless such a rename would not be justified on its own if it were
not for an important conceptual reason:
The renamed function represents a generic "inversion-of-control" pattern
which will become important in the TSCH context: It allows for clean
separation of concerns between the PHY/radio driver layer and the
MAC/L2 layer even in situations where the radio driver needs to be
involved for performance or deterministic timing reasons. This
"inversion-of-control" pattern can be applied to negotiate timing
sensitive reception and transmission windows, it let's the L2 layer
deterministically timestamp information elements just-in-time with
internal radio timer counter values, etc.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The IEEE 802.15.4 standard clearly separates clear channel assessment
from retransmission. This separation of concern was not represented in
the current channel access vs. retransmission implementation which
resulted in considerable duplication of code and logic.
This change removes the duplication of logic and encapsulates the
resulting functions in a private API that may only be used from within
Zephyr's native L2 layer.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The CSMA/CA algorithm had multiple issues:
- Timing of backoff periods depends on the PHY's symbol rate and other
PHY-specific settings. We introduce a preliminary solution that works
with current drivers. A fully standard-compliant long-term solution
has already been conceptualized but requires further pre-conditions,
see #50336 (issuecomment-1251122582).
- We enforce the condition defined in the standard that macMinBe must be
less than or equal macMaxBe.
- According to the standard a CSMA/CA failure should lead to immediate
abortion of the transmission attempt, no matter how many
retransmissions have been configured.
- The number of retransmissions was off by one. It is now used as
defined in the standard algorithm.
- Retransmissions are only allowed when acknowledgement is requested in
the packet.
- prepare_for_ack() has side effects and must be called before each
retransmission.
We also replace variables by constants where possible.
The function was renamed as it represents unslotted CSMA/CA and does not
support other CSMA/CA modes. These may be introduced in the future.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The ALOHA algorithm had two minor implementation errors:
- The number of retransmissions was off by one.
- Retransmissions are only allowed when acknowledgement is requested
otherwise it is to be assumed that the transmission was successful.
- prepare_for_ack() has side effects and must be called before each
retransmission.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The allowable ranges of several CSMA/CA-related settings were not
conforming to the standard, see IEEE 802.15.4-2020, section
8.4.3.1, table 8-94 (MAC PIB attributes). This change fixes the ranges.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
This adds a few line use zephyr_syscall_header() to include
headers containing syscall function prototypes.
Signed-off-by: Daniel Leung <daniel.leung@intel.com>
If a user tries to enable TWT too early in the connection, then we might
enter TWT sleep even before DHCP is completed, this can result in packet
loss as when we wakeup we cannot receive traffic and completing DHCP
itself can take multiple intervals. Though static ip address can be
assigned too. Reject TWT till Wi-Fi interface has
a valid IP address.
Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
This commit replaces the workarounds spread around the
drivers and subsystems with the updated PPP L2
interface.
Signed-off-by: Bjarki Arge Andreasen <baa@trackunit.com>
Currently, the L2 PPP subsystem is not using the network
interface subsystem appropriately. Here are the issues:
1. net_if_up hidden away internally in net L2 PPP
2. net_if_down not used at all...
3. net_if_carrier_on / off is not used, a workaround is
used instead, which results in duplicated code
4. L2 PPP does not listen for network events, instead
it needs the workaround callbacks from drivers.
5. The carrier_on workaround is delegated to a complex
and broken sys work queue item.
This commit fixes all above issues. net_if_up/down and
net_if_carrier_on/off now work as expected. workaround
for carrier_on/off has been removed.
Signed-off-by: Bjarki Arge Andreasen <baa@trackunit.com>
The RSSI value in net_pkt (net_pkt_cb_ieee802154.rssi) was used
inconsistently across drivers. Some drivers did cast a signed dBm value
directly to net_pkt's unsigned byte value. Others were assigning the
negative value of the signed dBm value and again others were offsetting
and stretching the signed dBm value linearly onto the full unsigned byte
range.
This change standardizes net_pkt's rssi attribute to represent RSSI on
the RX path as an unsigned integer ranging from 0 (–174 dBm) to 254 (80
dBm) and lets 255 represent an "unknown RSSI" (IEEE 802.15.4-2020,
section 6.16.2.8). On the TX path the rssi attribute will always be
zero. Out-of-range values will be truncated to max/min values.
The change also introduces conversion functions to and from signed dBm
values and introduces these consistently to all existing call sites. The
"unknown RSSI" value is represented as INT16_MIN in this case.
In some cases drivers had to be changed to calculate dBm values from
internal hardware specific representations.
The conversion functions are fully covered by unit tests.
Fixes: #58494
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Fix for not getting expected event information at application.
net_mgmt_event_notify_with_info() expects the address
not the value as pointer.
Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
Fix corner case when client RX request with same token than
own request where it wait responses.
Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
A bug was introduced in one of my earlier commits: The shell does no
longer print the full extended address. Fixes the issue.
Fixes: #59125
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Compiling an application with CONFIG_NET_ZPERF=y leaving
CONFIG_ZPERF_WORK_Q_THREAD_PRIORITY at its default value would
systematically cause a kernel panic during thread initialization.
The Kconfig variable is NUM_PREEMPT_PRIORITIES by default. Application
threads may not define a priority lower than NUM_PREEMPT_PRIORITIES - 1,
though.
This change limits zperf's thread priority to a valid range. It does not
change the default value as it makes sense to default the thread
priority to the lowest possible value (which is NUM_PREEMPT_PRIORITIES)
but Kconfig does not allow for arithmentic. So the combination of
CLAMP() plus the Kconfig default will ensure min priority plus limit the
range to valid values no matter what has been defined as priority in
Kconfig.
Fixes: #59141
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
In previous patch fixing this issue, I've missed the fact that offloaded
drivers would not set the context->local address, which resulted in a
regression, where the previously introduced assert would hit in
offloaded cases. Not setting laddr is not a problem in case of
offloading, as it's only used in net_tcp_connect() which would not be
reached in this case.
Therefore I propose to remove previous patch to get rid of regression.
As an alternative fix, verify the laddr just before use, so that it is
only checked when native net stack is in use.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Coverity reported, that laddr pointer used in net_context_connect()
could be passed as NULL to net_tcp_connect() where it could be
dereferenced. This is because the actual setting of laddr to a valid
address structure was only done after
net_sin/sin6_ptr(&context->local)->sin/sin6_addr verification.
In practice though, the aforementioned pointer verification would always
pass, as the bind_default() guarantee that the context->local address is
set to an unspecified address (if it hasn't been set earlier).
Therefore refactor the code a bit: replace the pointer verification
with NET_ASSERT - only to assure that we can catch regression in case
for any reason the behavior of bind_default() changes. This should also
ensure that Coverity no longer reports that laddr is NULL when reaching
net_tcp_connect().
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
As since commit bff6a5c, params.dst.ext_addr is no longer assigned with
the ctx->coord_ext_addr pointer, but a endianness swap is included, it
should be assigned with a proper buffer before the memcpy.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Coverity reported potential issues with implicit signed/unsigned type
conversions and potential problems with this. Fix this, by casing the
byte-shifted data variable to uint64_t type explicitly.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Coverity reported that assigning ret = 0 is pointless, as in any
scenario (loop continues or ends) the ret variable is overwritten
anyway, w/o using the assigned value. Therefore remove the needless
assignment.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
obj_inst_id should not be used directly to index the instance array, as
the instance ID is not tightly bound to the maximum instance count and
can exceed this value, causing out-of-bound access.
Therefore, perform some extra validation when choosing the array index
for the object instance to make sure we stay in the array bounds, or
return an error if there's no more room for more object instances, in a
similar way it's done for Security object.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
In case TCP connection is being closed from the TCP stack, due to for
instance retransmission timeout, the stack should also switch the TCP
state to CLOSED. Otherwise, there was a risk of dereferencing the TCP
context twice, for example if the application was in active socket
send(), and tried to reschedule data transmission.
Additionally, make sure that the TCP_CLOSED state handling is a no-op
state - otherwise, there is a risk that if packets keep incoming before
the application dereferences the TCP context on its side, TCP stack
will incorrectly dereference the context for the second time from
within due to current TCP_CLOSED state logic.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
The port we are connecting to is stored in network byte order,
thus, we need to convert it to the CPU's byte order before logging
Signed-off-by: Mark Oude Elberink <mark@oude-elberink.de>
`local_addr` would only be initialized if `context->local->sin*_addr` was
non-null. However, since `context` is a fresh context object, `local_addr`
always remains at its initial value of `INADDR_ANY`, which is propagated to
the context by `net_context_bind()`.
By populating `local_addr` using the TCP endpoint, `getsockname()` now
returns the correct local address.
Signed-off-by: Armin Brauns <armin.brauns@embedded-solutions.at>
In order to support external IP stacks that might have Connection
ID support, the LwM2M engine should allow client to bypass default
behaviour.
New set_socketoptions() callback added into client context
that allows overriding all socket opetions. This is called
after a socket is opened, but before the connect() is
called. This cannot be combined with load_credentials() callback
on all platforms as for example nRF91 requires modem offline
when credentials are written. This would cause socket to be closed
as well.
Second change is that we allow fine tuning of what we do with
socket handle when QUEUE mode is enabled and engine enters idle
state.
First option would be to close the socket. That would cause
TLS Alert(Close Notify) to be send. This is a band choice if
LTE modem was already in PSM or eDRX power saving mode.
Second option would be to delay socket closing until we
are going to send LwM2M update. There TLS Alert is also send,
but most probably lost due to NAT mapping timed out. This
is a best choice for LTE modem with DTL session cache enabled.
Two new options are to keep socket open, and either stop listening
or just keep listening. Both of these options work fine when
we have DTLS Connection ID support.
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
In case lwm2m_socket_start() internal error, it should only do cleanup
on the socket, i. e. call lwm2m_socket_close(), not lwm2m_engine_stop().
The latter resets the entire lwm2m_context, which results in removal of
active observations.
This should not be done, as it collides with the RD client logic, where
connection resumption may skip the full registration phase, in result
not notifying the server that it should restart the observations.
At the same time, the RD client should clean the lwm2m_context when it's
done trying to update the registration and proceeds with regular
registration/bootstrap in the network error handler. In that case, only
the socket was closed, so the lwm2m_context needs to be reset
separately.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
The number of buffer provided was verified in the final else block of a
long validation sequence. It would never be executed though, as one of
the conditions before would always evaluate to true.
As the number of buffers provided verification appears to be significant
in this case, as the buffers are referenced during other validations,
move this check at the beginning of the sequence instead. This also
eliminates the dead-code problem.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
For IEEE 802.15.4 compliance, the NET_L2_IEEE802154_ACK_REPLY option must
automatically be active if the radio driver does not AUTOACK and inactive
otherwise. No user interaction is required.
Future changes will deprecate this option and replace it by a standard
compliant automatic mechanism.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The IEEE 802.15.4 standard does not specify a "Sub-GHz" option.
Therefore this option will be deprecated in the foreseeable future.
Rationale: Selecting PHYs and frequency bands is abstracted by the
concept of channel pages (see IEEE 802.15.4-2020, 10.1.3).
Radio drivers may expose additional configuration options that
specify the low level frequency band, operating mode and other
PHY-specific parameters. Such parameters should be exposed on a driver
instance level, e.g. via devicetree or as runtime options of the driver.
PHY-specific attributes derived from driver settings (e.g. available
channels) can then be announced to L2 w/o the user having to be aware of
any implementation details of the specific PHY.
Future changes will introduce the necessary infrastructure to define
channel pages and other PHY-specific configuration options to
replace this option. New drivers should therefore not rely on this
option.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
In theory, coap_header_get_token() should only be used on already parsed
packets, and coap_packet_parse() would detect an invalid token length in
a packet. Coverity however complains about possible out-of-bound access,
as in theory the function can return token length up to 15. Therefore
add an extra validation of the token length within the function, to
avoid out-of-bound access due to programming errors and to make Coverity
happy.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
This patch fixes commit b70f92e570
("net: buf: keep memory alignment provided by k_heap_alloc and k_malloc").
One-line was overlooked in the above patch and may result in a
cloned net_buf using a data block that has already been freed.
Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
Although websocket_recv_msg function accepts timeout parameter, the
functionality was rather limited, allowing only to either work in
non-blocking manner, or to block indefinitely. Any timeout value
other than -1 (forever) ended up in non-blocking operation.
This PR fixes this by implementing a basic timeout mechanism, built on
top of poll(). For now on, only timeout of 0 will result in non-blocking
operation, any other timeout will make the function block for the
specified amount of time.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
In order to allow the TLS accept() call to be interrupted, it should
release the top-level TLS socket mutex before blocking. As the
underlying TCP accept() makes no use of TLS resources, and has its own
mutex protection, it should be safe to do so.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
The accept() so far would block with mutex held, making it impossible to
interrupt it from another thread when the socket was closed.
Fix this, by reusing the condvar mechanism used for receiving. It's OK
to use the same routine, as underneath accept() is monitoring the same
FIFO as recv().
Additionally, simplify k_fifo_get() handling in accept() - as the
waiting now takes place on condvar, it can be used in a non-blocking
manner. Blocking accept() call should not reach this place if there's no
new incoming connection waiting on the FIFO.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Installing recv callback with net_context_recv() after
net_context_connect() left an opening for a possible race - in case the
server send some data immediately after establishing TCP connection, and
Zephyr did not manage to install the callback on time, the data would be
lost, corrupting the stream.
This can be avoided, by installing the recv callback before the
connection is triggered. As net_context_recv() called w/o timeout only
registers the callback function, it should have no negative impact. The
only change on the TCP side is when the connection is closed - in case
TCP is in connect stage, do not call the recv callback (before this
change it'd be NULL at that point).
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
The coap client takes requests and provides responses
asynchronously to callback given in a request.
Currently supports only 1 request at a time.
Signed-off-by: Jarno Lämsä <jarno.lamsa@nordicsemi.no>
In case recv() call was waiting for data, and the socket was closed from
another thread, the recv() call would not be interrupted, causing the
receiving thread to be blocked indefinitely.
Fix this, by signalling the condvar the recv() call is waiting on
close(). Additionally, close will now set the socket into error mode,
with EINTR as the error condition, allowing the blocked calls to
recognise that the call was interrupted, and return a proper error code
on the event.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Variable declarations are moved to the beginning of the block in
which they are visible to ensure consistency with the remainder
of the code base.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The encryption-only security level has been removed from the
spec, see IEEE 802.15.4-2020, 9.4.2.2 Security Level field.
The standard provides the following explanation (ibid):
"This security level is deprecated and shall not be used in
implementation compliant with this standard. Devices that
receive frames with security level 4 shall discard them, as
described in 9.2.4. The counter mode encryption and cipher
block chaining message authentication code (CCM) used allows
trivial changes to the underlaying encrypted data unless
data authenticity is provided, thus using data confidentiality
only is not useful. In the case of TSCH mode, security level 4
allows higher security level frames to be downgraded to
security level 4 frames."
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
See IEEE 802.15.4-2020, 7.2.2.11 Source Addressing Mode field and
7.2.2.9 Destination Addressing Mode field, table 7-3: The
previously deprecated "Simple addressing mode" was removed
from the spec.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Currently the insertion of an authentication tag requires a memcpy() call
and breaks encapsulation.
This change removes the need for memcpy() and improves the encapsulation
by calculating and reserving the required headspace early on while
keeping insertion where it belongs in the outgoing security procedure.
This is also a preparation for improved standard compliance of the
outgoing security procedure which is scheduled for a later commit.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The naming of variables and arguments containing the authentication
tag length was inconsistent:
* Naming inconsistency between header "length" vs. authtag "size"
in the same API calls
* "Tag" rather than "Auth[orization ]Tag" in external API calls
which is too generic from a compliance and readability viewpoint.
This is in preparation to zero-copy authentication support.
Almost all call sites will be subject to required structural changes
later on so no relevant git blame noise/history loss will be introduced
by this naming change in the long run.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Over time, some non-standard concepts and extensions were introduced
into the stack (in KConfig, in drivers, in the internal API and into the
implementation) which makes introduction of additional standard-
compliant extensions like TSCH (and others) unnecessarily difficult.
To introduce extensions like TSCH it is required for the IEEE 802.15.4
stack to become more structurally aligned with the standard again which
will be the focus of some of the upcoming preparatory changes.
One way to check and prove standard compliance is to reference the
standard from within the source code. This change therefore introduces
inline references to the IEEE 802.15.4-2020 standard wherever possible.
Deviations from the standard are documented with TODO or deprecation
labels to be addressed in future changes.
In the future, new code introduced to the IEEE 802.15.4 stack should
be documented and reviewed for standard-compliance to avoid further
divergence. Most importantly:
* MAC/PHY configuration (via net mgmt, radio API, devicetree or
KConfig) should always be directly linked to well-defined MAC/PHY
PIB attributes if visible to the MAC API or the end user.
* Net management/shell/radio API commands should have a documented
reference to the corresponding MLME action from the standard.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
According to RFC768 UDP packets with zero checksum are allowed with IPv4.
Enable this by default.
For example, some routers use zero checksum in DHCP packets.
Signed-off-by: Nils Ruf <nils.ruf@endress.com>
The current implicit MAC payload length algorithm (based on
an otherwise irrelevant footer pointer) produces invalid
(non-standard) values for beacon and command frames.
This change produces standard-conforming MAC payload length
values and simplifies access to payload length.
It would have been possible to fix the current footer pointer
based approach but there are arguments in favor of the new
approach:
- The footer pointer is used nowhere in the current code
base and makes length calculations rather non-obvious.
- The new approach does not use more memory and is easier
to understand and use.
- This change is a first step to support of IEEE 802.15.4
information element (IE) support. At a later stage the
distinction between MAC payload length and frame payload
length will be introduced and become relevant to
distinguish between header and payload IEs. At that point
the current implicit length calculation algorithm will
break down anyways.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The current IEEE 802.15.4 stack would not accept beacons
unless hardware filtering was active.
This change fixes the bug.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The shell command calling the IEEE 802.15.4 scanning procedure
did not properly release its net management event callback.
This change fixes the memory leak.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Active and passive scanning requires the channel and PAN to
be set temporarily.
This change ensures that the temporary configuration will
be reverted even when the scan is aborted due to an error.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Beacon and command frames are consumed by the IEEE 802.15.4
stack internally and should therefore be released before
returning control to the generic net stack.
This change fixes the resource leak.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
In certain scenarios, it may be necessary to get values of additional
options from the application layer. With this patch, this can be
accomplished by registering a callback with the DHCP client.
This change has been tested using the posix build in qemu.
Signed-off-by: Matthias Breithaupt <m.breithaupt@vogl-electronic.com>
Until now iterable sections APIs have been part of the toolchain
(common) headers. They are not strictly related to a toolchain, they
just rely on linker providing support for sections. Most files relied on
indirect includes to access the API, now, it is included as needed.
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
This change splits the IEEE 802.15.4 test into two separate
test profiles, one with and one without sockets enabled to ensure
that both configurations work correctly.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
The current IEEE 802.15.4 stack assumes that drivers will
not provide more than one fragment in incoming packages.
This change exposes and enforces the pre-existing assumption
made by the implementation.
So far this is not a limiting restriction as MPDUs with more
than 127 bytes are not supported yet. It will probably have to
be changed as soon as larger payloads (as allowed by PHYs
introduced more recently into the spec) might want to allocate
smaller fragments.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
When changing IEEE 802.15.4 security settings or setting security
to 'none' then the previous session must be cleaned up to avoid
resource leaks.
This change introduces proper clean-up of the security session.
Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
Shifting "timeout <<= conn->zwp_retries" by more then 63 bits results in
undefined behaviour.
Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
If a socket has DSCP set then the packets from the socket should also be
marked with appropriate priority in case traffic classes are used in
networking stack.
Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
This is needed for applications that rely on WPA supplicant being
in disconnected state before issue subsequent commands (e.g., issue scan
immediately after disconnect fails, until disconnect is completed).
Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
In the FIN_WAIT_1 any incoming data is dropped, but anknowledged. Add a
check to see if the data is already acknowleged to prevent double
acknowledging of the data and bringing the acknowlegde counter out of
sync. When the acknowledge counter gets out of sync, the connection will
never properly terminate any more.
Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
After sending a CoAP block and receiving the CONTINUE response
code the next block is sent.
Signed-off-by: Lukas Woodtli <lukas.woodtli@husqvarnagroup.com>
Allow to use a buffer for the complete message body if block transfer is
enabled. This buffer is used when serializing the message. For sending
the message the body is split into blocks.
Signed-off-by: Lukas Woodtli <lukas.woodtli@husqvarnagroup.com>
The function gets the the BLOCK1 option from a received message
and extracts the block number, block size and has-more flag from
it.
Signed-off-by: Lukas Woodtli <lukas.woodtli@husqvarnagroup.com>
The function adds a block option to a CoAP message. If the message
is a request the BLOCK1 option is added. Otherwise (response) the
BLOCK2 option is added.
Signed-off-by: Lukas Woodtli <lukas.woodtli@husqvarnagroup.com>
Add a trailing _ to the section iterable name. This is useful, for
example, to implement numeric sorting like this:
SORT(.z_device_LEVEL_?_)
SORT(.z_device_LEVEL_??_)
Without the trailing _ it would not be possible to use the ?? wildcard
without triggering into trigraphs issues, because linker-defs.h header
is included in C files as well.
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
Rather than raise error on connect if iface is down, just take the iface
up.
Rather than raise error on disconnect if iface is down, just ignore the
disconnection request.
Adjust tests and documentation accordingly.
This should make the API easier to use for applications and is more in
line with the original L2 agnostic connectivity RFC.
Also replace some instances of net_if_flag_is_set with
net_if_is_admin_up, which is cleaner and identical in function.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
The current method for handling DAD directly tracks a DAD state for each
iface.
This does not reflect the fact that each individual IP has a separate
DAD state.
This also does not align with the logic in conn_mgr_initial_state, which
instead uses net_if_ipv6_get_global_addr(NET_ADDR_PREFERRED, ...).
Thus, the current approach falsely reports IPv6 ready when DAD adds
the link_addr, and also fails to report IPv6 ready if DAD is disabled.
This commit removes DAD tracking completely, and relies solely on
net_if_ipv6_get_global_addr(NET_ADDR_PREFERRED, ...), fixing both
problems, and simplifying the event tracking.
For consistency, slight modifications to IPv4 handling as well.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
Currently, conn_mgr fires L4_CONNECTED and L4_DISCONNECTED events for
every individual iface that gains or loses connectivity.
After this commit, these events are only fired when the first iface gains
connectivity, and the last iface loses connectivity, respectively.
This is so that applications can rely on conn_mgr as a simple way to
track whether connectivity is available.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
Adds a flag to allow ifaces and L2s to be ignored.
This is so that applictions have better control over what ifaces they
want connectivity management for.
Enabling the flag forces conn_mgr to consider the iface
unready.
Also increase NET_CONNECTION_MANAGER_PRIORITY default value from 0 to 1
so that applications can register SYS_INIT callbacks that fire just
before conn_mgr initializes. This allows ignored ifaces to be configured
before conn_mgr starts, if needed.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
In preparation for altering the conditions under which conn_mgr
fires NET_EVENT_L4_CONNECTED and NET_EVENT_L4_DISCONNECTED,
refactor the event logic without changing its behavior.
These changes do not alter the behavior of conn_mgr. They merely change
how that behavior is expressed so that it is easier to understand, and so
that upcoming changes are easier to implement.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
Current implementation does not prevent the net_mgmt thread from
preempting during state change handling and generating more
state changes. Add a mutex to protect internal state of conn_mgr
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
Relocate conn_mgr_if_get_binding to conn_mgr_private.h so that it
can be used by test suites.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
Since conn_mgr is a subsystem rather than a library, relocate it
directly into subsys/net rather than subsys/net/lib/
Rename header files to better match their function.
Remove net_ prefix from conn_mgr types, API, and files, since it is
unnecessary.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
Provide an extra struct net_if * iface parameter to
net_if_ipv*_maddr_join/leave functions, so that the corresponding
interface context, the mcast address belong to, can be locked for the
operation.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
As `net_if_get_link_addr()` returns a pointer to the link layer
structure, some extra protection is needed to prevent its contents from
being changed while accessed. Using the mutex lock associated with an
interface should do the trick.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Instead of having a single global mutex, covering, in most cases
unrelated, access to all network interfaces, introduce a separate mutex
for each network interface.
Wherever interface function operates on an individual interface context
data, use local mutex protection instead. The global mutex remains only
to protect access to shared resources (IPv4/6 context pool, timer lists
etc.).
Finally, rework the timer expiry handlers, to prevent interface
functions from being called while the global lock is held (the global
mutex has to be held when iterating over the timer list, as lists are
not thread safe). The reason for this is to avoid possible deadlock
scenario. The global mutex is sometimes being locked, while inside
interface function (protected by a local mutex), so if it was allowed
the other way as well, a deadlock could occur.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
LLDP start timer is executed when iface is up
at startup, then once more when iface up event
is received.
When iface is up before net_lldp_init call, then multiple
entries are added to the lldp_ifaces related to the
same iface.
That leads to continuous loop execution within
lldp_tx_timeout.
This commit checks if lldp tx_timer_start is set and
doesn't append new entry into the slist.
The tx_timer_start is set at startup and reset on
down event.
Signed-off-by: Georgij Cernysiov <geo.cgv@gmail.com>
'ps_wakeup_mode' is used to set the wake up interval
to either 'dtim or 'listen_interval'. By default the
sta wakes up every dtim interval.
With 'ps_wakeup_mode' set to 'listen_interval' sta
will wake up for every listen interval period configured.
Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
listen interval is the time periods the STAs may be in idle
without listening beacons.
By default STA wakes up for every DTIM period.
If listen interval based power save is used
STA uses configured listen interval period(default 10
beacon intervals) to wake up.
Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
As we are using a generic validation function for limits, due to data
type mismatch the check for TWT interval overflow and fails.
Fix the data type and accordingly the maximum value in the help.
Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
Fix possible NULL dereference at net_pkt_cursor_operate() and
resolve 'Dereference after null check' warnings from the Coverity
static code analysis.
Signed-off-by: Dmitrii Golovanov <dmitrii.golovanov@intel.com>
TFM is not the only provider for PSA API, which means
the PSA config shouldn't depend only on it.
Signed-off-by: Piotr Jasiński <piotr.jasinski@nordicsemi.no>
Print new NET_IF_IPV6_NO_ND and NET_IF_IPV6_NO_MLD flags when
the "net iface" command is used.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
OpenThread networks do not use ND or MLD as they have their own set of
protocols to cover this functionality. So far, the use of OpenThread
with Zephyr relied on disabling those protocols support statically with
Kconfig, which prevented OT interfaces from being used along with other
IPv6 interfaces.
With the new network interface flags, it's now possible to disable ND
and MLD on individual interfaces, therefore disable them for OT
specifically.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Add new network interface flag, which allows to disable Multicast
Listener Discovery protocol from being used on the interface. This
allows to interfaces that do not support ND (like OpenThread) to
coexist with other IPv6 interfaces.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Add new network interface flag, which allows to disable Neighbour
Discovery protocol from being used on the interface. This allows to
interfaces that do not support ND (like OpenThread) to coexist with
other IPv6 interfaces.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Fix dhcpv4_create_message() dereferenced NULL return value from
net_pkt_alloc_with_buffer() in case of no memory available.
Signed-off-by: Dmitrii Golovanov <dmitrii.golovanov@intel.com>
Fix net_ipv4_send_fragmented_pkt() dereference of NULL return value
from net_pkt_get_data() possible with non contiguous packet data.
Signed-off-by: Dmitrii Golovanov <dmitrii.golovanov@intel.com>
The arm-clang compiler/linker does not optimize away unused function
symbols and thus will error if symbols that are referenced are not
defined. To fix this add needed ifdef'ry.
Build various network samples that utilize ethernet but don't have
CONFIG_NET_PROMISCUOUS_MODE will get a link error for:
Error: L6218E: Undefined symbol
net_mgmt_NET_REQUEST_ETHERNET_SET_PROMISC_MODE
(referred from ethernet.o).
Fix by adding ifdef protection around promisc code.
Signed-off-by: Kumar Gala <kumar.gala@intel.com>
TWT flow id is of 3 bit value(maximum mnumber of flows
supported is 8). Flow id range limited to 0 to 7.
Signed-off-by: Ajay Parida <ajay.parida@nordicsemi.no>
Fix tcp_send_zwp() retransmission timeout calculation to avoid sign
extension on bit shift operation: the uint16_t value was implicitly
promoted to 32-bit signed type with sign extension to uint64_t.
Signed-off-by: Dmitrii Golovanov <dmitrii.golovanov@intel.com>
Fixes the compiler error that occurs when attempting to build
the SNTP library with CONFIG_NET_SOCKETS_POSIX_NAMES=n, while
using native_posix.
Closes#57133
Co-authored-by: Chris Friedt <cfriedt@meta.com>
Signed-off-by: Hein Wessels <heinwessels93@gmail.com>
Cleanup linker scripts for net_buf_pool section to use the linker
script related iterable section macros.
Also replace _net_buf_pool_list with macro's instead to complete
iterable section usage.
Signed-off-by: Kumar Gala <kumar.gala@intel.com>
This commit simplifies the arguments for sending dns responses
and fixes an issue where both the ipv4 and ipv6 member of a header
union were accessed.
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
Duplicate logging prints make it hard to find the origin.
This commit does a cleanup of the debug messages printed.
Also change the level of an invalid record to debug as this
is out of our control.
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
For offloaded iface net_tcp_get is never called, so context->tcp
is always NULL. In that case net_tcp_tx_sem_get will return wrong pointer.
For pollout k_poll will be called with NULL semph,
which cause HardFault.
Signed-off-by: Wojciech Slenska <wsl@trackunit.com>
Remove all init functions that do nothing, and provide a `NULL` to
*DEVICE*DEFINE* macros.
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
Do patch file application before clang-format.
Add copyright to generated files using the --file-header option in zcbor.
Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
Allows L2s to declare generic association/connection routines
that can be bound by name to ifaces.
Allows L2-agnostic control over connectivity/association for
iface that support it.
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
Calls put instead of unref on net contexts
in the socket accept function.
Mere unref didn't subtract the reference
count of net context which leaves
it in used state. This situation happens
in case of accepting already
closed connection.
Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
Added a feature of socket connect
being asynchronous. If socket is set
to nonblock with O_NONBLOCK flag,
then connect() is non-blocking aswell.
App can normally poll the socket to
test when the connection is established.
Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
Fixes#56657, incorrect TCP MSS calculation for IPv6.
Previously the supported MSS would incorrectly returned as the MTU if it
was less than the MTU, probably to account for the case where
the network interface MTU check returns 0.
New behaviour is to return the supported MSS as MTU minus header length,
using default MTU for this calculation if network interface MTU check
returns 0.
Signed-off-by: Kenny Johansson <wirehell@gmail.com>
MISRA Rule 5.7 requires uniqueness of tag identifiers. Shell is
frequently problematic because many code uses `const struct shell
*shell`. This causes CI noise every time one of these shell files is
edited, so let's update all of them with `const struct shell *sh`
instead.
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
Some utility functions belong to lwm2m_util.c.
Block contexts belong to lwm2m_message_handling.c
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
The init infrastructure, found in `init.h`, is currently used by:
- `SYS_INIT`: to call functions before `main`
- `DEVICE_*`: to initialize devices
They are all sorted according to an initialization level + a priority.
`SYS_INIT` calls are really orthogonal to devices, however, the required
function signature requires a `const struct device *dev` as a first
argument. The only reason for that is because the same init machinery is
used by devices, so we have something like:
```c
struct init_entry {
int (*init)(const struct device *dev);
/* only set by DEVICE_*, otherwise NULL */
const struct device *dev;
}
```
As a result, we end up with such weird/ugly pattern:
```c
static int my_init(const struct device *dev)
{
/* always NULL! add ARG_UNUSED to avoid compiler warning */
ARG_UNUSED(dev);
...
}
```
This is really a result of poor internals isolation. This patch proposes
a to make init entries more flexible so that they can accept sytem
initialization calls like this:
```c
static int my_init(void)
{
...
}
```
This is achieved using a union:
```c
union init_function {
/* for SYS_INIT, used when init_entry.dev == NULL */
int (*sys)(void);
/* for DEVICE*, used when init_entry.dev != NULL */
int (*dev)(const struct device *dev);
};
struct init_entry {
/* stores init function (either for SYS_INIT or DEVICE*)
union init_function init_fn;
/* stores device pointer for DEVICE*, NULL for SYS_INIT. Allows
* to know which union entry to call.
*/
const struct device *dev;
}
```
This solution **does not increase ROM usage**, and allows to offer clean
public APIs for both SYS_INIT and DEVICE*. Note that however, init
machinery keeps a coupling with devices.
**NOTE**: This is a breaking change! All `SYS_INIT` functions will need
to be converted to the new signature. See the script offered in the
following commit.
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
init: convert SYS_INIT functions to the new signature
Conversion scripted using scripts/utils/migrate_sys_init.py.
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
manifest: update projects for SYS_INIT changes
Update modules with updated SYS_INIT calls:
- hal_ti
- lvgl
- sof
- TraceRecorderSource
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
tests: devicetree: devices: adjust test
Adjust test according to the recently introduced SYS_INIT
infrastructure.
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
tests: kernel: threads: adjust SYS_INIT call
Adjust to the new signature: int (*init_fn)(void);
Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
Currently, the handshake operation could only be fully blocking or
non-blocking. This did not play well if SO_RCVTIMEO was set for DTLS
server, as the recv() call where the blocking handshake was used, could
block indefinitely, ignoring the timeout parameter. Fix this, by
allowing for the handshake operation to timeout.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
As the underlying socket operations for TLS/DTLS are now non-blocking,
it's no longer possible to rely on the underlying socket timeout
handling. Instead, implement SO_RCVTIMEO/SO_SNDTIMEO at the TLS socket
layer.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
As for TLS, switch to use non-blocking operations on underlying socket.
This is a bit tricker for DTLS, as there were not truly blocking bio
(binary input/output) function for DTLS, as timeout had to been
implemented. It is possible though to implement non-blocking mbedTLS bio
function instead, and handle timeout outside of mbedTLS context, which
has been done in this commit.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Switch TLS sockets to use non-blocking socket operations underneath.
This allows to implement the socket blocking outside of the mbedTLS
context (using poll()), and therefore release the mutex for the time the
underlying socket is waiting for data. In result, it's now possible to
do blocking TLS RX/TX operations simultaneously from separate threads.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Implement ZFD_IOCTL_SET_LOCK so that TLS socket layer gets access to the
mutex protecting socket calls.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
TCP packet allocation timeout is currently 100ms, but there are cases
where it is not enough and as a side effect, the kernel internals are
printing some errors on the log before retrying again, create a
Kconfig parameter to be able to tune this value.
Signed-off-by: Luca Fancellu <luca.fancellu@arm.com>
If server or bootstrap writes a lifetime value less than
configured default lifetime, client will automatically overwrite
the value with default one.
This gives better control for the application where client
behaviour is fine tuned on the Kconfig, but default values
from bootstrap server cannot be fine-tuned.
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
This function had only one use in SenML CBOR formatter and it
contained some specific tweaks, so move the function to be a
static member of that module.
Fixes#53674
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
When LwM2M engine is paused, stop functionality just
marks the intent and when we resume, it will send the
de-registration if that was requested.
Otherwise it will stay in SUSPENDED state until resumed
and then goes into ENGINE_DEREGISTERED -> IDLE.
This also removes the blocking loop from lwm2m_rd_client_stop().
It does not need to block because lwm2m_rd_client_start()
is already checking if client is in IDLE.
Fixes#56254
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
Instead of passing the test parameters to the websocket function, by
casting the pointer to integer (which may not work on 64-bit platform
due to int/pointer size mismatch), let the test allocate a file
descriptor, and initialize it with test context. The tested functions
expect a file descriptor as an argument anyway, so it's a more intuitive
approach.
The conditional test code within WS implementation can retrieve the test
context by using FD APIs to obtain the object represented by the FD.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
C only permits labels on statements, not declarations. Separate the
declarations from the assignments so that the labels can target
statements instead.
Signed-off-by: Keith Packard <keithp@keithp.com>
We get compile warnings of the form:
error: converting the result of
'<<' to a boolean; did you mean
'((__aeabi_ctype_table_ + 1)[(byte)] << 28) != 0'?
[-Werror,-Wint-in-bool-context]
if (!isprint(byte)) {
^
Since isprint (and the other is* functions) return an int, change check
to an explicit test against the return value.
Signed-off-by: Kumar Gala <kumar.gala@intel.com>
We get compile warnings of the form:
error: converting the result of
'<<' to a boolean; did you mean
'((__aeabi_ctype_table_ + 1)[(byte)] << 28) != 0'?
[-Werror,-Wint-in-bool-context]
if (!isprint(byte)) {
^
Since isprint (and the other is* functions) return an int, change check
to an explicit test against the return value.
Signed-off-by: Kumar Gala <kumar.gala@intel.com>
Add is_suspended() routine to have control over the rd client from the
outside whether it is suspended.
Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
Socketpair functionality has matured enough to be used in a
consistent way now regardless of architecture or platform,
even on `native_posix`.
Remove the experimental status to reflect that.
Signed-off-by: Chris Friedt <cfriedt@meta.com>
In case native IPv6 is disabled, Kconfig entries related to native IPv6
stack should not be enabled. Otherwise, circular dependencies can be
created if native stack is disabled, as in case of recent changes in
NET_IPV6_RA_RDNSS option (where a dependency for a native stack module
was enabled).
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
The TX timeout configured with SO_SNDTIMEO on a socket did not work
properly. If the timeout was set on a socket, the TX would work as if
the socket was put into non-blocking mode. This commit fixes this.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
The timeout recalculation logic was duplicated across several routines,
therefore it makes sense to make a helper function out of it,
especially, that the same functionality would be needed for the send
routines.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
SO_RCVBUF option processing at the TCP level was broken. The option
value was only checked once, when the TCP context was allocated. This
made little sense, as at this point the option would not even get a
chance to have custom value. If the user modified the option after the
socket (net_context) was created, it had no effect on the TCP operation.
This commit fixes this, by checking the option value whenever new packet
is processed, so that the configured window size is updated at the TCP
level before we report it in the TCP ACK. In order to achieve this,
introduce a new helper function, to refresh the configured window sizes,
to avoid bloating `tcp_in()` even further.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Adds dummy link layer for offloaded ifaces, allowing
ifaces to directly receive l2_enable calls
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
In order to take granular input use micro seconds as input for TWT
intervals, this helps us in providing inputs such as 65.28ms without the
need of using floating points.
This also expands the TWT wake interval range to 262.144ms, earlier as
we want to use uint8, limited to 256ms.
Also, remove the units from the variable names, this is unnecessary and
also avoids doing breaking changes.
Update release notes as this is a breaking change, both type and
variable names are changed.
Signed-off-by: Krishna T <krishna.t@nordicsemi.no>
Currently the zperf_tcp_receiver can handle only one TCP connection
each time, modify the code to poll and handle multiple connections.
Take the occasion to unify the bind and listen part of the code
between ipv4 and ipv6 part using a structure introduced to handle
the multiple connections.
Now in case the zsock_recv fails, we can't stop every connection
and fail through the error label, so just print the error message
and report the failure through the callback.
Signed-off-by: Luca Fancellu <luca.fancellu@arm.com>
Reduce the scope of in4_addr_my and in6_addr_my pointer variables
that are currently global, but they are used only inside
tcp_receiver_thread.
Take the occasion to fix a typo in one error message.
Signed-off-by: Luca Fancellu <luca.fancellu@arm.com>
Cast pointer to `void *` for `%p` parameter.
Otherwise lots of warnings in the log like below:
`<wrn> cbprintf_package: (unsigned) char * used for %p argument.
It's recommended to cast it to void * because it may cause
misbehavior in certain configurations. String:"%s: (%p): >>
length:0x%08x cur:%p, end:%p" argument:3`
Signed-off-by: Jun Qing Zou <jun.qing.zou@nordicsemi.no>
This moves net_buf_simple related code to separate source file.
Having those in separate file makes unit testing easier as simple
network buffers do not use kernel objects, thus can be used
in unit tests without a need for adding any mocks.
Signed-off-by: Mariusz Skamra <mariusz.skamra@codecoup.pl>
As there is dedicated NET_BUF_SIMPLE_* logging macros set,
NET_BUF_SIMPLE_DBG shall be used in this place instead.
Signed-off-by: Mariusz Skamra <mariusz.skamra@codecoup.pl>
In dns_resolve_reconfigure() check if the DNS servers already exist
before cancel all ongoing queries. This will solve an issue with
getaddrinfo() returning DNS_EAI_CANCELED when receiving a retransmitted
DHCP offer and when receiving a IPv6 Router Advertisement.
Signed-off-by: Stig Bjørlykke <stig.bjorlykke@nordicsemi.no>
The multi resource and create flags were reversed, meaning that resources
were defined as multi resource but weren't being created by default. That
doesn't reflect the LWM2M Software Management, which specifies which
objects can be multi resource and which are mandatory.
The post write callbacks were assigned to the validate callbacks.
Signed-off-by: Michal Ciesielski <michal.m.ciesielski@voiapp.io>
1. `zsock_socket()` gets the right packet familiy.
2. `inet_pton()` returns 1 on success.
This should address #55193.
Signed-off-by: Sebastian Arnd <sebastianarnd@gmail.com>
Provide a means of declaring zero or more HTTP services, each
with zero or more static HTTP resources.
Static HTTP resources are those which have fixed paths[1] which
are known prior to system initialization. Some examples of
static http resources would be
* a forwarder from '/' to '/index.html'
* a REST endpoint with fixed path '/api/foo' and detail
pointing at some implementation-specific function
* a Javascript file in string form with fixed path '/js/util.js'
* a 'construction' image with path '/res/work.png'
* a gzip-compressed 'Hello' HTML file at '/hello.html'
Without describing in any detail how static HTTP resources are
organized or served by any given HTTP server, we can describe
what static resources exist on a system in a common way that
does not require any optional facilities (e.g. filesystem) and
relies only on addressable memory.
Additionally, for the purposes of simply allowing others
to implement custom HTTP servers in a consistent way, or
benchmarking implementations, or having a consistent testsuite
to use across multiple implementations, it is helpful to have
a common method to declare HTTP services and static resources
for Zephyr.
[1] https://en.wikipedia.org/wiki/URL
Signed-off-by: Chris Friedt <cfriedt@meta.com>
Allow to register a callback function which is called when a firmware
update is canceled by the cancel command.
Signed-off-by: Marc Lasch <marc.lasch@husqvarnagroup.com>
Use internal constant ZSOCK_POLLIN instead of POLLIN to
make the http_client source file compile without error with
CONFIG_NET_SOCKETS_POSIX_NAMES disabled.
Fixes#55423
Signed-off-by: Lucas Dietrich <ld.adecy@gmail.com>
When a query is done, the query isn't set to NULL.
This can cause a nullptr exception in invoke_query_callback().
Signed-off-by: Jeroen van Dooren <jeroen.van.dooren@nobleo.nl>
Packet handlers registered with net_conn API should not use NET_CONTINUE
to report packet processing status. As they register for a specific
local port, it cannot be assumed someone else will handle the packet,
and for net_conn this status is not really handled differently from
NET_OK. Therefore, reporting NET_CONTINUE, and not freeing the packet,
can result in a packet leak.
Too short packets should not really be handled differently from other
malformed packets in DHCPv4 module, therefore report NET_DROP instead of
NET_CONTINUE.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Currently, in tcp_received function defined in zperf_tcp_receiver
module, the assignment of session->state to STATE_COMPLETED is
overwritten on the same path to STATE_NULL and a session is
considered free for both STATE_COMPLETED and STATE_NULL, so remove
the assignment to STATE_NULL.
Remove the break from the STATE_COMPLETED case handling so that it
can fallthrough, in case the same session is used after finish.
Remove also the STATE_LAST_PACKET_RECEIVED case because this state
is never reached.
Signed-off-by: Luca Fancellu <luca.fancellu@arm.com>
The modules zperf_udp_receiver and zperf_tcp_receiver use two
different functions to get a zperf session to store the
statistics, there is a TODO comment in the zperf_session module
suggesting to unify that part.
So delete the get_tcp_session function and use get_session for
both TCP and UDP receiver module.
Delete sock field from struct session because it's not used
anymore.
Signed-off-by: Luca Fancellu <luca.fancellu@arm.com>
Currently the maximum number of zperf sessions handled is hardcoded
to 4, create a Kconfig parameter, with default value 4, to make the
maximum number of sessions configurable.
Signed-off-by: Luca Fancellu <luca.fancellu@arm.com>
Use client context to seperate buffer usage.
Use new `TFTP_EVT_DATA` event to send data to application.
Use new `TFTP_EVT_ERROR` event to report error to application.
Update `tftp_get()` and `tftp_put()` API to use the client context.
Signed-off-by: Jun Qing Zou <jun.qing.zou@nordicsemi.no>
Actually `execute_cb` is fed with an array of char* and the size of
that array, instead of a single char* buffer and its byte size.
This fix expects a single, already joined, optional shell argument and
feeds `execute_cb` with proper arguments.
Signed-off-by: Stefan Schwendeler <Stefan.Schwendeler@husqvarnagroup.com>
In the header the websocket protocol needs a SHA1 hash. This is
implemented using the mbedtls_sha1 function. Select the option
MBEDTLS_MAC_SHA1_ENABLED from the Kconfig of websocket to ensure this
function is build in.
Signed-off-by: Sjors Hettinga <s.a.hettinga@gmail.com>
TCP implementation abused the packet processing result reporting
mechanism, by reporting NET_DROP for every packet other than data
packets (which were passed to the application). This simplified the TCP
implementation a bit, as it didn't need to deal with packet releasing.
While technically it worked, it gave incorrect results when it comes to
packet statistics, as a lot of valid TCP packets were counted as
dropped.
This commit fixes this. Each packet that was properly processed by the
TCP stack is not either released at the TCP level, or passed to the
application. In both cases, NET_OK is returned to the network core,
indicating the packet has been properly processed and consumed.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
There was a corner case that last registration timestamp was used
to detect if we can try UPDATE instead of full registration.
When timestamp was not cleared and DNS resolving failed, it might
cause engine to skip the resolving and continue retrying an UPDATE
message until timeout.
Fixes#54504
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
When we have establised an DTLS handshake and try LwM2M Update,
if the server rejects it, we fall back to sending full registration
but when doing so, we should also clear out any observations.
It was intentional that we don't go to ENGINE_DO_REGISTRATION
state as that would close the socket and cause DTLS handshake.
Fixes#54974
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
Only socket error that we should ignore is EAGAIN (EWOULDBLOCK),
others might be indicating that there are some serious errors
in network layer.
When network stack would block us, just drop the packet and
let CoAP layer handle the retrying.
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
Various functions, mostly concerning time-series cache, were not
using const pointer while they still did not modify the content.
Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
Minor refactoring in getaddrinfo() to make the code easier to
read and to make handling IPv4 and IPv6 support more equal.
- Move common wait and error handling code to exec_query()
- Use the same check for CONFIG_NET_IPV4 and CONFIG_NET_IPV6
- Add extra sanity check for family before exec_query()
- Do not set errno when return DNS_EAI_ADDRFAMILY
Fix issue with setting port number for all DNS servers.
Signed-off-by: Stig Bjørlykke <stig.bjorlykke@nordicsemi.no>
Handle RA RDNSS and use the first DNS server fetched. This is needed
when building IPv6 only without static DNS server IP addresses.
This implementation does not handle the lifetime, because the current
resolve logic does not have support for a DNS server lifetime.
Signed-off-by: Stig Bjørlykke <stig.bjorlykke@nordicsemi.no>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
* 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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
under certain conditions the current implementation did not maintain
the desired sort order.
Signed-off-by: Pascal Brogle <pascal.brogle@husqvarnagroup.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
`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>
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>
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>
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>
Call lwm2m_send_message_async() from function
lwm2m_information_interface_send() and remove duplicate code.
Signed-off-by: Juha Ylinen <juha.ylinen@nordicsemi.no>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
* 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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Skip IP header checksum calculation when the network interface reports
support for this feature.
Signed-off-by: Daniel DeGrasse <daniel.degrasse@nxp.com>
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>
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>
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>
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>
Registration should only be updated if update of the registration was
succesful.
Signed-off-by: Andreas Chmielewski <andreas.chmielewski@grandcentrix.net>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Following zephyr's style guideline, all if statements, including single
line statements shall have braces.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Prevent local "addrlen_copy" variable from being used uninitialized in
accept() userspace verification function.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
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>
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>
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>
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)
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)
Fixed couple possible place for leak Coap pending entry.
Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
(cherry picked from commit 3c175951383be56fa9c1451845a15b66df41ff64)
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>
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>
...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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Integrated updated JSON library to LwM2M 1.0 JSON.
Removed Old Json format default choice.
Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
...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>
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>
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>
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>
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>
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>
'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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Use defines instead of hardcoded strings to avoid future errors if the
values would change.
Signed-off-by: Andreas Pettersson <andreaspettersson95@gmail.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Adds an official behavior in response to null response from HTTP
endpoint.
Fixes#42988
Signed-off-by: Georges Oates_Larsen <georges.larsen@nordicsemi.no>
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>
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>
This commit moves openthread CMakeLists.txt from openthread submodule
to zephyr/modules/openthread.
Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
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>
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>
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>
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>
correction field in sync follow up message must be converted from host
endianness to network endianness.
Signed-off-by: Lu Ding <lucasdinglu@gmail.com>
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>
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>
This commit utilizes psa_crypto_get function to fetch cryptographically
secure pseudorandom numbers.
Signed-off-by: Lukasz Duda <lukasz.duda@nordicsemi.no>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Add EtherCAT protocol support, now applications can
transmit/receive EtherCAT packets via RAW socket.
Signed-off-by: Hou Zhiqiang <Zhiqiang.Hou@nxp.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
`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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
`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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
`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>
`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>
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>
- 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>
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>
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>
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>
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>
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>
Based on on RFC 8132 -
PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)
Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
Based on on RFC 8132 -
PATCH and FETCH Methods for the Constrained Application Protocol (CoAP)
Signed-off-by: Veijo Pesonen <veijo.pesonen@nordicsemi.no>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
...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>
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/rfc6763Fixes#38673
Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Fix potential bug when returning error codes not handled by
OpenThread in `otPlatRadioTxDone`.
Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
`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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
- 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>
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>
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>
This commit fixes diag repeat command port by fixing issue with
incorrectly handled repeat timer.
Signed-off-by: Przemyslaw Bida <przemyslaw.bida@nordicsemi.no>
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>
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>
Allow caller to specify microsecond accuracy and not convert
to milliseconds.
Fixes#36072
Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>