Wykres commitów

1309 Commity (master)

Autor SHA1 Wiadomość Data
Maarten van der Schrieck 91ee8ac894 extmod/os_dupterm: Let mp_os_dupterm_tx_strn() return num bytes written.
In case of multiple outputs, the minimum successful write length is
returned.  In line with this, in case any output has a write error, zero is
returned.

In case of no outputs, -1 is returned.

The return value can be used to assess whether writes were attempted, and
if so, whether they succeeded.

Signed-off-by: Maarten van der Schrieck <maarten@thingsconnected.nl>
2023-12-22 10:26:52 +11:00
IhorNehrutsa b31eef6094 extmod/modhashlib: Support MD5 with mbedtls 3.x.
This change was missd in e7ae3ad92d.

Signed-off-by: IhorNehrutsa <Ihor.Nehrutsa@gmail.com>
2023-12-21 11:30:52 +11:00
Jim Mussared 8b24aa36ba extmod/modselect: Handle growing the pollfds allocation correctly.
The poll_obj_t instances have their pollfd field point into this
allocation.  So if re-allocating results in a move, we need to update the
existing poll_obj_t's.

Update the test to cover this case.

Fixes issue #12887.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-12-21 11:04:59 +11:00
Damien George f46269a1d1 extmod/asyncio: Remove non-working Stream __aenter__/__aexit__ methods.
It looks like these never worked and there are no tests for this
functionality.  Furthermore, CPython doesn't support this.

Fixes #12995.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-20 15:56:23 +11:00
Damien George 1f2ec4583d extmod/os_dupterm: Prevent recursive execution of mp_os_dupterm_rx_chr.
Signed-off-by: Damien George <damien@micropython.org>
2023-12-18 12:20:47 +11:00
Damien George 395886caa3 extmod/modos: Factor os.dupterm_notify() function to common extmod code.
esp8266 doesn't need ets task because the notify is now scheduled (see
commits 7d57037906 and
c60caf1995 for relevant history).

Signed-off-by: Damien George <damien@micropython.org>
2023-12-18 12:20:47 +11:00
Elias Wimmer 2e101a8e44 extmod/modonewire: Improve write timings for better reliability.
When using long cables for sensors on onewire e.g. ds18b20, the current
default timings are too optimistic, leading to bus failures and CRC errors.

Stable results are achieved with the timings given by
https://www.analog.com/en/technical-articles/1wire-communication-through-software.html
2023-12-15 17:08:09 +11:00
Patrick Van Oosterwijck 06df3b2925 extmod/modonewire: Adopt Maxim recommended read timings.
The timing of the onewire module was way too fast when reading.  This
commit adopts read timings as recommended in Maxim application note 126:
6 us (pulse) / 9 us (sample) / 55 us (bit slot).  See also:
https://www.analog.com/en/technical-articles/1wire-communication-through-software.html

Signed-off-by: Damien George <damien@micropython.org>
2023-12-15 17:04:33 +11:00
Carlosgg bfd6ad94ff extmod/asyncio: Add ssl support with SSLContext.
This adds asyncio ssl support with SSLContext and the corresponding
tests in `tests/net_inet` and `tests/multi_net`.

Note that not doing the handshake on connect will delegate the handshake to
the following `mbedtls_ssl_read/write` calls.  However if the handshake
fails when a client certificate is required and not presented by the peer,
it needs to be notified of this handshake error (otherwise it will hang
until timeout if any).  Finally at MicroPython side raise the proper
mbedtls error code and message.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-14 12:20:19 +11:00
Damien George f33dfb966a extmod/modssl_mbedtls: Fix parsing of ciphers in set_ciphers method.
Fixes two issues:
- None should not be allowed in the list, otherwise the corresponding entry
  in ciphersuites[i] will have an undefined value.
- The terminating 0 needs to be put in ciphersuites[len].

Signed-off-by: Damien George <damien@micropython.org>
2023-12-14 12:03:36 +11:00
Damien George ef996d15b9 extmod/modssl_mbedtls: Make SSLSocket.getpeercert() optional.
And only enable this method when the relevant feature is available in
mbedtls.  Otherwise, if mbedtls doesn't support getting the peer
certificate, this method always returns None and it's confusing why it does
that.  It's better to remove the method altogether, so the error trying to
use it is more obvious.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-12 21:21:54 +11:00
Carlosgg f3f215e9bd extmod/modssl_mbedtls: Add SSLContext certificate methods.
This commit adds:

1) Methods to SSLContext class that match CPython signature:

	- `SSLContext.load_cert_chain(certfile, keyfile)`
	- `SSLContext.load_verify_locations(cafile=, cadata=)`
	- `SSLContext.get_ciphers()` --> ["CIPHERSUITE"]
	- `SSLContext.set_ciphers(["CIPHERSUITE"])`

2) `sslsocket.cipher()` to get current ciphersuite and protocol
   version.

3) `ssl.MBEDTLS_VERSION` string constant.

4) Certificate verification errors info instead of
   `MBEDTLS_ERR_X509_CERT_VERIFY_FAILED`.

5) Tests in `net_inet` and `multi_net` to test these new methods.

`SSLContext.load_cert_chain` method allows loading key and cert from disk
passing a filepath in `certfile` or `keyfile` options.

`SSLContext.load_verify_locations`'s `cafile` option enables the same
functionality for ca files.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-12 16:25:07 +11:00
Damien George 241dbac928 extmod: Add lists of libm/libm_dbl source files for ports to use.
So that ports don't need to specify each of these files, they can simply
refer to the appropriate make/cmake variable.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-08 15:39:28 +11:00
Angus Gratton df3948d3c2 extmod: Switch to use new event functions.
See previous commit for details of these functions.  As of this commit,
these still call the old hook macros on all ports.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
2023-12-08 12:48:50 +11:00
iabdalkader 0960d64d3b extmod/network_ninaw10: Switch to using soft-timer for polling.
This patch simplifies the connection and sockets polling code, by switching
to a soft-timer to schedule polling code, and by using one node for
scheduling.  This also fixes any issues that could result from using a heap
allocated machine_timer, and includes better handling of the sockets poll
list.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-12-06 17:32:21 +11:00
iabdalkader 50f31cc902 extmod/modnetwork: Add deinit function to NIC protocol.
This is usually called on soft-reboot, a NIC can implement this to do any
necessary cleaning up (such as invalidating root pointers).

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-12-06 17:32:00 +11:00
Damien George b5449b0f09 extmod/mbedtls: Enable certificate time/date validation by default.
All ports using this common configuration already enable time/date
validation, so this commit is a no-op change.

Signed-off-by: Damien George <damien@micropython.org>
2023-12-01 15:08:11 +11:00
Damien George 22d9116c8c nrf: Convert os module to use extmod version.
The os.dupterm() function has changed on this port, it now matches the
semantics used by all other ports (except it's restricted to accept only
machine.UART objects).

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:33:56 +11:00
Damien George f523b86541 extmod/modmachine: Provide common implementation of disable/enable_irq.
The ports esp32, mimxrt, rp2 and samd all shared exactly the same
implementation of machine.disable_irq() and machine.enable_irq(),
implemented in terms of MICROPY_{BEGIN,END}_ATOMIC_SECTION.  This commit
factors these implementations into extmod/modmachine.c.

The cc3200, esp8266, nrf, renesas-ra and stm32 ports do not yet use this
common implementation.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George e1ec6af654 extmod/modmachine: Provide common bindings for 6 bare-metal functions.
Minor changes for consistency are:
- nrf gains: unique_id(), freq() [they do nothing]
- samd: deepsleep() now resets after calling lightsleep()
- esp32: lightsleep()/deepsleep() no longer take kw arg "sleep", instead
  it's positional to match others.  also, passing 0 here will now do a 0ms
  sleep instead of acting like nothing was passed.
  reset_cause() no longer takes any args (before it would just ignore them)
- mimxrt: freq() with an argument and lightsleep() both raise
  NotImplementedError

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 48b5a7b060 extmod/modmachine: Provide common Python bindings for bootloader().
Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George e68aa40d2a extmod/modmachine: Add MICROPY_PY_MACHINE_PIN_BASE option.
And use it in qemu-arm, unix and windows ports to enable PinBase.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 30a63a204d extmod/modmachine: Provide common Python bindings for machine.idle().
And use it in all ports.  The ports are unchanged, except esp8266 which now
just returns None from this function instead of the time elapsed (to match
other ports), and qemu-arm which gains this function.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 7d39db2503 extmod/modmachine: Factor ports' machine module dict to common code.
This is a code factoring to have the dict for the machine module in one
location, and all the ports use that same dict.  The machine.soft_reset()
function implementation is also factored because it's the same for all
ports that did already implement it.  Eventually more functions/bindings
can be factored.

All ports remain functionally the same, except:
- cc3200 port: gains soft_reset, mem8, mem16, mem32, Signal; loses POWER_ON
  (which was a legacy constant, replaced long ago by PWRON_RESET)
- nrf port: gains Signal
- qemu-arm port: gains soft_reset
- unix port: gains soft_reset
- zephyr port: gains soft_reset, mem8, mem16, mem32

Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Damien George 14432b5da0 extmod/modmachine: Make I2C/SPI defns available when soft impl enabled.
Signed-off-by: Damien George <damien@micropython.org>
2023-11-30 16:11:11 +11:00
Peter Züger 1879db7105 extmod/extmod.mk: Allow enabling lwip loopback support.
Enabling MICROPY_PY_LWIP_LOOPBACK via make will turn on loopback support.

Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2023-11-17 13:35:47 +11:00
stijn 365913953a extmod/vfs_posix_file: Make standard file objects non-const.
Fixes undefined behavior when calling vfs_posix_file_ioctl with
MP_STREAM_CLOSE as request because that casts away the constness and
assigns -1 to the object's fd member.

Fixes issue #12670.

Signed-off-by: stijn <stijn@ignitron.net>
2023-11-09 15:01:34 +11:00
Daniël van de Giessen 3b954698fa extmod/modbluetooth: Initialise nlr_jump_callback_top for IRQ handlers.
Similar to 3883f29485 where this change was
implemented for threads: when the Bluetooth IRQ handler is called the
thread state is not not zero-initialized and thus we need to manually set
this to NULL.

Fixes issue #12239.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-11-09 14:51:20 +11:00
Andrew Leech 4cf741062b extmod/vfs_reader: Add file ioctl to set read buffer size.
Can be used to speed up importing a file from a vfs based filesystem.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
2023-11-09 11:20:31 +11:00
Damien George dff293840e extmod/machine_i2c: Do a fast poll during I2C.scan().
Fixes issue #12912.

Signed-off-by: Damien George <damien@micropython.org>
2023-11-08 23:34:08 +11:00
Damien George 03eae48847 extmod/machine_adc_block: Factor esp32 ADCBlock bindings to common code.
This is a code factoring to have the Python bindings in one location, and
all the ports use those same bindings.  At this stage only esp32 implements
this class, so the code for the bindings comes from that port.

The documentation is also updated to reflect the esp32's behaviour of
ADCBlock.connect().

Signed-off-by: Damien George <damien@micropython.org>
2023-11-07 16:44:35 +11:00
Jim Mussared b6a9778484 py/misc: Change sizeof to offsetof for variable-length alloc.
This fixes the case where e.g.

    struct foo_t {
      mp_obj_t x;
      uint16_t y;
      char buf[];
    };

will have `sizeof(struct foo_t)==8`, but `offsetof(struct foo_t, buf)==6`.

When computing the size to allocate for `m_new_obj_var` we need to use
offsetof to avoid over-allocating. This is important especially when it
might cause it to spill over into another GC block.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-11-03 16:03:18 +11:00
Daniël van de Giessen 7ad84e0422
lib/littlefs: Update LittleFS to v2.8.1.
Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
2023-11-01 17:07:18 +01:00
Damien George a614c1d501 extmod: Remove empty utime_mphal.h file.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-31 13:31:54 +11:00
iabdalkader 2fda94c286 extmod/network_ninaw10: Fix select flags handling in socket poll.
The flags returned from `select()` were misinterpreted to mean an error had
occurred for the socket, when it's actually just an exceptional condition
for the socket, such as OOB data.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-27 15:49:17 +11:00
Damien George 3e2706a18d extmod/modmachine: Consolidate mem, i2c and spi headers to modmachine.h.
The contents of machine_mem.h, machine_i2c.h and machine_spi.h have been
moved into extmod/modmachine.h.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 17:40:22 +11:00
Damien George d336c1b79b extmod/modmachine: Consolidate simple machine headers into modmachine.h.
The contents of machine_bitstream.h, machine_pinbase.h, machine_pulse.h and
machine_signal.h have been moved into extmod/modmachine.h.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 16:49:27 +11:00
Damien George 90023b4dcf extmod/modmachine: Clean up decls of machine types to use common ones.
The machine_i2c_type, machine_spi_type and machine_timer_type symbols are
already declared in extmod/modmachine.h and should not be declared anywhere
else.

Also move declarations of machine_pin_type and machine_rtc_type to the
common header in extmod.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 16:20:53 +11:00
Damien George 5b4a2baff6 extmod/machine_uart: Factor ports' UART Python bindings to common code.
This is a code factoring to have the Python bindings in one location, and
all the ports use those same bindings.  For all ports except the two listed
below there is no functional change.

The nrf port has UART.sendbreak() removed, but this method previously did
nothing.

The zephyr port has the following methods added:
- UART.init(): supports setting timeout and timeout_char.
- UART.deinit(): does nothing, just returns None.
- UART.flush(): raises OSError(EINVAL) because it's not implemented.
- UART.any() and UART.txdone(): raise NotImplementedError.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-26 10:46:42 +11:00
Damien George 95d8b5fd55 extmod/machine_adc: Factor ports' ADC Python bindings to common code.
No functional change, just code factoring to have the Python bindings in
one location, and all the ports use those same bindings.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-23 17:16:45 +11:00
Damien George 91a3f18391 extmod/machine_i2s: Factor comments, some enums and macros.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George 46ae3b5a34 extmod/machine_i2s: Factor init_helper argument parsing.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George 676f9bb78c extmod/machine_i2s: Factor print function.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George 1477986815 extmod/machine_i2s: Factor I2S.irq method.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George cdd9ad8d62 extmod/machine_i2s: Factor I2S.shift method.
It's exactly the same for all four port implementations.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George a2d7e0da0b extmod/machine_i2s: Factor stream and ring-buf code.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:40:17 +11:00
Damien George f2f3ef162d extmod/machine_i2s: Factor ports' I2S Python bindings to common code.
This factors the basic top-level I2S class code from the ports into
extmod/machine_i2s.c:
- I2S class definition and method table.
- The init and deinit method wrappers.
- The make_new code.

Further factoring will follow.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 17:39:57 +11:00
Damien George 7e7af71527 extmod/machine_pwm: Remove header file and move decls to .c file.
With public declarations moved to extmod/modmachine.h.  It's now mandatory
for a port to define MICROPY_PY_MACHINE_PWM_INCLUDEFILE if it enables
MICROPY_PY_MACHINE_PWM.  This follows how extmod/machine_wdt.c works.

All ports have been updated to work with this modified scheme.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 16:24:46 +11:00
Damien George 60929ec7e2 extmod/machine_wdt: Factor ports' WDT Python bindings to common code.
There are currently 7 ports that implement machine.WDT and a lot of code is
duplicated across these implementations.  This commit factors the common
parts of all these implementations to a single location in
extmod/machine_wdt.c.  This common code provides the top-level Python
bindings (class and method wrappers), and then each port implements the
back end specific to that port.

With this refactor the ports remain functionally the same except for:

- The esp8266 WDT constructor now takes keyword arguments, and accepts the
  "timeout" argument but raises an exception if it's not the default value
  (this port doesn't support changing the timeout).

- The mimxrt and samd ports now interpret the argument to WDT.timeout_ms()
  as signed and if it's negative truncate it to the minimum timeout (rather
  than it being unsigned and a negative value truncating to the maximum
  timeout).

Signed-off-by: Damien George <damien@micropython.org>
2023-10-20 15:36:09 +11:00
iabdalkader 7bbf7910fe extmod/network_ninaw10: Raise an error if nina_ioctl fails.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-10-20 12:18:00 +11:00
Christian Walther be28829ae8 extmod/vfs_posix: Fix getcwd() on non-root VFS.
The unwritten API contract expected of a VFS.getcwd() by mp_vfs_getcwd()
is that its return value should be either "" or "/" when the CWD is at
the root of the VFS and otherwise start with a slash and not end with a
slash. This was not correctly implemented in VfsPosix for instances with
a non-empty root - the required leading slash, if any, was cut off
because the root length includes a trailing slash. This would result in
missing slashes in the middle of the return value of os.getcwd() or in
uninitialized garbage from beyond a string's null terminator when the
CWD was at the VFS root.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:09 +02:00
Christian Walther 0c4fb16871 extmod/vfs_posix: Fix relative paths on non-root VFS.
The unwritten API contract expected of a VFS by mp_vfs_lookup_path() is
that paths passed in are relative to the root of the VFS if they start
with '/' and relative to the current directory of the VFS otherwise.
This was not correctly implemented in VfsPosix for instances with a
non-empty root - all paths were interpreted relative to the root. Fix
that. Since VfsPosix tracks its CWD using the "external" CWD of the Unix
process, the correct handling for relative paths is to pass them through
unmodified.

Also, when concatenating absolute paths, fix an off-by-one resulting in
a harmless double slash (the root path already has a trailing slash).

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:09 +02:00
Christian Walther e3ba6f952b extmod/vfs_posix: Fix relative root path.
A VfsPosix created with a relative root path would get confused when
chdir() was called on it and become unable to properly resolve absolute
paths, because changing directories effectively shifted its root. The
simplest fix for that would be to say "don't do that", but since the
unit tests themselves do it, fix it by making a relative path absolute
before storing it.

Signed-off-by: Christian Walther <cwalther@gmx.ch>
2023-10-19 16:21:08 +02:00
Jim Mussared 8eb7721b4a extmod/modframebuf: Remove FrameBuffer1 from natmod build.
This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-16 12:18:43 +11:00
Jim Mussared 03a9fa227d extmod/modframebuf: Fix FrameBuffer get-buffer implementation.
This wasn't correctly accounting for the bits-per-pixel and was returning a
bufinfo struct with the incorrect length.  Instead, just forward directly
to the underlying buffer object.

Fixes issue #12563.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-16 12:18:08 +11:00
Jim Mussared d040478d8a extmod/modframebuf: Validate FrameBuffer bounds against input buffer.
This ensures that the buffer is large enough for the specified width,
height, bits-per-pixel, and stride.

Also makes the legacy FrameBuffer1 constructor re-use the FrameBuffer
make_new to save some code size.

Fixes issue #12562.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-16 12:17:51 +11:00
Matthias Urlichs 5f0bd33b73 extmod/asyncio: Emit errors to stderr, not stdout.
Sometimes these are different file descriptors, not to mention the Unix
port, so use stderr to distinguish these error messages.

CPython prints to stdout, but it does it via a call to the logging module.
We don't want to introduce a dependency on logging, so printing to stderr
is a good alternative.  One can override default_exception_handler() if
needed.
2023-10-13 14:55:54 +11:00
Damien George 05cb1406ad extmod/moductypes: Validate that uctypes.struct addr argument is an int.
Fixes issue #12660.

Signed-off-by: Damien George <damien@micropython.org>
2023-10-12 15:47:15 +11:00
Jim Mussared 5015779a6f py/builtinevex: Handle invalid filenames for execfile.
If a non-string buffer was passed to execfile, then it would be passed
as a non-null-terminated char* to mp_lexer_new_from_file.

This changes mp_lexer_new_from_file to take a qstr instead (as in almost
all cases a qstr will be created from this input anyway to set the
`__file__` attribute on the module).

This now makes execfile require a string (not generic buffer) argument,
which is probably a good fix to make anyway.

Fixes issue #12522.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-12 15:17:59 +11:00
stijn cac666f38c extmod/vfs_posix_file: Fix flush handling in msvc builds.
Flushing console output in msvc builds always fails because that
output is not buffered so don't propagate that as an error (in a
simlar way as was done in 1c047742 for macOS).

Signed-off-by: stijn <stijn@ignitron.net>
2023-10-05 10:18:24 +11:00
Jim Mussared 65a3ce39a3 extmod/modnetwork: Forward if.config(hostname) to network.hostname.
This removes the duplicate code in cyw43, esp32, esp8266 that implements
the same logic as network.hostname.

Renames the `mod_network_hostname` (where we store the hostname value in
`.data`) to `mod_network_hostname_data` to make way for calling the shared
function `mod_network_hostname`.

And uses memcpy for mod_network_hostname_data, because the length of source
is already known and removes reliance on string data being null-terminated.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-04 12:39:51 +11:00
Jim Mussared b329fdcb73 extmod/modnetwork: Increase max hostname length to 32.
This changes from the previous limit of 15 characters.  Although DHCP and
mDNS allow for up to 63, ESP32 and ESP8266 only allow 32, so this seems
like a reasonable limit to enforce across all ports (and avoids wasting the
additional memory).

Also clarifies that `MICROPY_PY_NETWORK_HOSTNAME_MAX_LEN` does not include
the null terminator (which was unclear before).

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-04 12:39:23 +11:00
Damien George cf490a7091 all: Fix various spelling mistakes found by codespell 2.2.6.
Signed-off-by: Damien George <damien@micropython.org>
2023-10-03 11:24:50 +11:00
Jim Mussared 977dc9a369 extmod/asyncio/stream.py: Fix cancellation handling of start_server.
The following code:

  server = await asyncio.start_server(...)
  async with server:
    ... code that raises ...

would lose the original exception because the server's task would not have
had a chance to be scheduled yet, and so awaiting the task in wait_closed
would raise the cancellation instead of the original exception.

Additionally, ensures that explicitly cancelling the parent task delivers
the cancellation correctly (previously was masked by the server loop), now
this only happens if the server was closed, not when the task was
cancelled.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-10-02 14:11:52 +11:00
Damien George fbe58553c2 extmod/btstack/btstack_hci_uart: Trigger a poll after UART data is sent.
Prior to this commit, BTstack would only be notified of sent UART data when
the mp_bluetooth_hci_poll() function was called for some other reason, eg
because of incoming data over UART.  This is highly suboptimal.

With this commit, BTstack is now notified immediately after UART data has
been sent out.  This improves the multi_bluetooth/perf_gatt_char_write.py
performance test by about a factor of 10x for write-without-response, and
about 4x for write-with-response (tested on LEGO_HUB_NO6 as instance1).

Signed-off-by: Damien George <damien@micropython.org>
2023-09-29 18:01:42 +10:00
Jim Mussared cfe6a11e39 extmod/asyncio/event.py: Fix ThreadSafeFlag.ioctl return.
iobase_ioctl expects that an ioctl method must return an integer, and will
raise otherwise.

This was tripping up aioble on Unix, where the new hybrid modselect.c
implementation will attempt to extract a file descriptor from the pollable
via ioctl(MP_STREAM_GET_FILENO).

However, ThreadSafeFlag's ioctl only supported MP_STREAM_POLL, and returned
None otherwise.

This makes it return `-1` (to match tests/extmod/select_poll_custom.py). It
should probably be `-22` (corresponding to MP_EINVAL), but the value is
never checked, and MP_EINVAL can be a different value on different ports.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-09-29 17:58:40 +10:00
Damien George 58f63497e5 extmod/modssl_axtls: Only close underlying socket once if it was used.
To match the behaviour of the mbedtls implementation, and pass the
ssl_basic.py test.

Signed-off-by: Damien George <damien@micropython.org>
2023-09-29 12:03:00 +10:00
iabdalkader 474bf4e1e3 extmod/network_esp_hosted: Add ESP-Hosted networking interface.
Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-09-14 23:51:30 +10:00
iabdalkader ecedd78302 drivers/esp-hosted: Add host driver for ESP-Hosted firmware.
This is a host driver for ESP32 chips running the esp-hosted firmware,
which turns ESP32s into a WLAN/BT co-processor.

Signed-off-by: iabdalkader <i.abdalkader@gmail.com>
2023-09-14 23:51:30 +10:00
Damien George 8dbdac8c82 extmod/modlwip: Fix setting of IP option SOF_BROADCAST.
Follow up to 25b89cbe94.

Signed-off-by: Damien George <damien@micropython.org>
2023-09-12 12:49:14 +10:00
Mirko Vogt 65f0cb11af extmod/modssl_mbedtls: Ignore err ERR_SSL_RECEIVED_NEW_SESSION_TICKET.
It appears a new session ticket being issued by the server right after
completed handshake is not uncommon and shouldn't be treated as fatal.

mbedtls itself states "This error code is experimental and may be changed
or removed without notice."

Signed-off-by: Mirko Vogt <mirko-dev|mpy@nanl.de>
2023-09-03 21:42:52 +10:00
Mirko Vogt 1b03518e37 extmod/modssl_mbedtls: Call func psa_crypto_init if PSA is used.
Whenever the PSA interface is used (if MBEDTLS_PSA_CRYPTO is defined),
psa_crypto_init() needs to be called to initialise the global PSA data
struct, before any PSA related operations.

TLSv1.3 depends on the PSA interface, TLSv1.2 only uses the PSA stack if
MBEDTLS_USE_PSA_CRYPTO is defined.

Without psa_crypto_init() every PSA related call will result in
-0x6C00/-27648 which translates to "SSL - Internal error (eg, unexpected
failure in lower-level module)".

The error is misleading, especially since mbedtls in its docs itself
advices "to return #PSA_ERROR_BAD_STATE or some other applicable error.".

Signed-off-by: Mirko Vogt <mirko-dev|mpy@nanl.de>
2023-09-03 20:32:06 +10:00
Wang Xuancong 25b89cbe94 extmod/{modlwip,modsocket}: Add support for SO_BROADCAST socket option.
Signed-off-by: Wang Xuancong <xuancong84@gmail.com>
2023-09-01 18:34:18 +10:00
stephanelsmith db06041d59 extmod/vfs_posix_file: Implement sys.std*.buffer objects.
Add the buffer attribute to sys.stdin, sys.stdout and sys.stderr.  This
provides raw access to underlying stdio streams for the unix port (and
others that use VfsPosix).

Signed-off-by: stephanelsmith <stephane.smith@titansensor.com>
2023-09-01 17:39:38 +10:00
stephanelsmith 1c047742a2 extmod/vfs_posix_file: Fix flush handling on macOS.
On macOS, if running micropython from subprocess.check_output, then a
stdout.flush() raises error 45.

Here's a test case.  This will run fine on linux, but crashes on macOS with
error 45.

    import sys
    import subprocess
    import tempfile
    with tempfile.NamedTemporaryFile('w') as fp:
        fp.write('''
    import sys
    sys.stdout.write('hello world')
    sys.stdout.flush()
    print('')
    ''')
        fp.flush()
        print('py3')
        o = subprocess.check_output(f'python3 {fp.name}'.split())
        print(o)
        print('upy')
        o = subprocess.check_output(f'micropython {fp.name}'.split())
        print(o)

On macOS:

    py3
    b'hello world\n'
    upy
    Traceback (most recent call last):
      File "...", line 4, in <module>
    OSError: 45

On unix:

    py3
    b'hello world\n'
    upy
    b'hello world\n'

Signed-off-by: stephanelsmith <stephane.smith@titansensor.com>
2023-09-01 17:39:38 +10:00
Jim Mussared 32db4c58f7 extmod/moddeflate: Change default window size.
The primary purpose of this commit is to make decompress default to
wbits=15 when the format is gzip (or auto format with gzip detected). The
idea is that someone decompressing a gzip stream should be able to use the
default `deflate.DeflateIO(f)` and it will "just work" for any input
stream, even though it uses a lot of memory.

This is done by making uzlib report gzip files as having wbits set to 15
in their header (where it previously only set the wbits out parameter for
zlib files), and then fixing up the logic in `deflateio_init_read`.

Updates the documentation to match.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-09-01 12:23:37 +10:00
Damien George 313068a5b3 extmod/modssl_mbedtls: Clear sock member if error creating SSLSocket.
Otherwise if/when the finaliser runs for this newly created SSLSocket the
mbedtls state will be freed again.

Signed-off-by: Damien George <damien@micropython.org>
2023-08-30 13:52:31 +10:00
Jim Mussared 9573d31071 all: Remove query-variants make target.
This is difficult to implement on cmake-based ports, and having the list
of variants in mpconfigboard.{cmake,mk} duplicates information that's
already in board.json.

This removes the existing query-variants make target from stm32 & rp2
and the definition of BOARD_VARIANTS from the various board files.

Also renames the cmake variable to MICROPY_BOARD_VARIANT to match other
variables such as MICROPY_BOARD. The make variable stays as
BOARD_VARIANT.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-08-15 17:37:44 +10:00
Jim Mussared ad123ed013 esp32/Makefile: Implement `make submodules` to match other ports.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-08-15 17:37:44 +10:00
Damien George f6af48416d extmod/modselect: Properly track number of poll objects that are fd's.
Signed-off-by: Damien George <damien@micropython.org>
2023-08-14 18:48:47 +10:00
Damien George d529c20674 extmod/modssl_mbedtls: Fix ioctl of a socket in closed/error state.
Signed-off-by: Damien George <damien@micropython.org>
2023-08-09 13:22:57 +10:00
Damien George 20d3a6b196 extmod/modssl_mbedtls: Reject ioctls that are not supported.
An SSL stream can only handle CLOSE and POLL ioctls.  Other ones do not
make sense, or at least it doesn't make sense to pass the ioctl request
directly down to the underlying stream.

In particular MP_STREAM_GET_FILENO should not be passed to the underlying
stream because the SSL stream is not directly related to a file descriptor,
and the SSL stream must handle the polling itself.

Signed-off-by: Damien George <damien@micropython.org>
2023-08-09 13:22:32 +10:00
Damien George 3f417e8943 extmod/modselect: Remove undocumented support for flags arg to poll.
The signature of this method was poller.poll(timeout=-1, flags=0, /) but
the flags argument was not documented and is not CPython compatible.  So
it's removed in this commit.

(The optional flags remains for the ipoll() method, which is documented.)

Signed-off-by: Damien George <damien@micropython.org>
2023-08-07 12:37:47 +10:00
Damien George ef71028f77 extmod/modselect: Add optimisation to use system poll when possible.
A previous commit removed the unix-specific select module implementation
and made unix use the common one.

This commit adds an optimisation so that the system poll function is used
when polling objects that have a file descriptor.  With this optimisation
enabled, if code registers both file-descriptor-based objects, and non-
file-descriptor-based objects with select.poll() then the following occurs:

- the system poll is called for all file-descriptor-based objects with a
  timeout of 1ms

- then the bare-metal polling implementation is used for remaining objects,
  which calls into their ioctl method (which can be in C or Python)

In the case where all objects have file descriptors, the system poll is
called with the full timeout requested by the caller.  That makes it as
efficient as possible in the case everything has a file descriptor.

Benefits of this approach:

- all ports use the same select module implementation

- the unix port now supports polling of all objects and matches bare metal
  implementations

- it's still efficient for existing cases where only files and sockets are
  polled (on unix)

- the bare metal implementation does not change

- polling of SSL objects will now work on unix by calling in to the ioctl
  method on SSL objects (this is required for asyncio ssl support)

Note that extmod/vfs_posix_file.c has poll disable when the optimisation is
enabled, because the code is not reachable when the optimisation is used.

Signed-off-by: Damien George <damien@micropython.org>
2023-08-07 12:11:40 +10:00
Damien George ebc6556346 extmod/modselect: Factor low-level polling code into common function.
Signed-off-by: Damien George <damien@micropython.org>
2023-08-07 12:11:40 +10:00
Damien George 7f2efb4144 extmod/modselect: Abstract out a poll_set_t struct and functions.
To make it easier to extend and modify this polling implementation.

Signed-off-by: Damien George <damien@micropython.org>
2023-08-07 12:11:40 +10:00
Damien George 22106bf2fa extmod/vfs_posix_file: Add poll support for missing ERR,HUP,NVAL values.
Signed-off-by: Damien George <damien@micropython.org>
2023-08-06 11:54:06 +10:00
Jim Mussared 70c564324c extmod/modssl_mbedtls: Reference SSLContext from SSLSocket.
Prevent the GC cleaning up (and finalising) the SSLContext while the
socket is still live.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-08-01 15:12:33 +10:00
Jim Mussared 3533924c36 extmod/moddeflate: Add deflate module providing the DeflateIO class.
This provides similar functionality to the former zlib.DecompIO and
especially CPython's gzip.GzipFile for both compression and decompression.

This class can be used directly, and also can be used from Python to
implement (via io.BytesIO) zlib.decompress and zlib.compress, as well as
gzip.GzipFile.

Enable/disable this on all ports/boards that zlib was previously configured
for.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-07-21 19:32:40 +10:00
Jim Mussared 198311c780 py/stream: Add mp_stream___exit___obj that calls mp_stream_close.
There are enough places that implement __exit__ by forwarding directly to
mp_stream_close that this saves code size.

For the cases where __exit__ is a no-op, additionally make their
MP_STREAM_CLOSE ioctl handled as a no-op.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-07-21 18:49:03 +10:00
Jim Mussared add1200343 all: Remove the zlib module.
This will be replaced with a new deflate module providing the same
functionality, with an optional frozen Python wrapper providing a
replacement zlib module.

binascii.crc32 is temporarily disabled.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-07-21 18:48:29 +10:00
Damien George e8a4c1dd53 extmod/modssl: Add SSLContext class.
This commit adds the SSLContext class to the ssl module, and retains the
existing ssl.wrap_socket() function to maintain backwards compatibility.

CPython deprecated the ssl.wrap_socket() function since CPython 3.7 and
instead one should use ssl.SSLContext().wrap_socket().  This commit makes
that possible.

For the axtls implementation:
- ssl.SSLContext is added, although it doesn't hold much state because
  axtls requires calling ssl_ctx_new() for each new socket
- ssl.SSLContext.wrap_socket() is added
- ssl.PROTOCOL_TLS_CLIENT and ssl.PROTOCOL_TLS_SERVER are added

For the mbedtls implementation:
- ssl.SSLContext is added, and holds most of the mbedtls state
- ssl.verify_mode is added (getter and setter)
- ssl.SSLContext.wrap_socket() is added
- ssl.PROTOCOL_TLS_CLIENT and ssl.PROTOCOL_TLS_SERVER are added

The signatures match CPython:
- SSLContext(protocol)
- SSLContext.wrap_socket(sock, *, server_side=False,
    do_handshake_on_connect=True, server_hostname=None)

The existing ssl.wrap_socket() functions retain their existing signature.

Signed-off-by: Damien George <damien@micropython.org>
2023-06-26 16:34:41 +10:00
Damien George 18caf49a7f extmod/modbtree: Undefine queue macros before including berkeley-db.
To prevent warnings when building with ESP IDF v5.

Signed-off-by: Damien George <damien@micropython.org>
2023-06-23 15:34:22 +10:00
Damien George 402fdc40fb extmod/modplatform: Set MICROPY_PLATFORM_ARCH on riscv platforms.
Signed-off-by: Damien George <damien@micropython.org>
2023-06-23 15:34:22 +10:00
Damien George e7ae3ad92d extmod: Update to support mbedtls 3.x.
Signed-off-by: Damien George <damien@micropython.org>
2023-06-23 15:22:27 +10:00
Duncan Lowther ae77836370
extmod/modbinascii: Fix buffer length error.
The mod_binascii_a2b_base64() function allocates a buffer which may be
too small. It needs to be no less than three-quarters of the input
length, but is calculated as (<length> / 4) * 3 + 1, which may be less
due to integer division. Changed to (<length> * 3) / 4 + 1.

Signed-off-by: Duncan Lowther <Duncan.Lowther@glasgow.ac.uk>
2023-06-21 09:48:11 +01:00
Jim Mussared ca79b49619 extmod/asyncio/uasyncio.py: Add backwards-compatible uasyncio alias.
This allows existing code that does `import uasyncio` or
`import uasyncio as asyncio` to continue working.

It uses the same lazy-loading as asyncio to prevent loading of unused
features.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-06-19 18:37:34 +10:00
Jim Mussared 2fbc08c462 extmod/asyncio: Rename uasyncio to asyncio.
The asyncio module now has much better CPython compatibility and
deserves to be just called "asyncio".

This will avoid people having to write `from uasyncio import asyncio`.

Renames all files, and updates port manifests to use the new path. Also
renames the built-in _uasyncio to _asyncio.

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-06-19 17:33:03 +10:00
Peter Harper ba83f6d50c extmod/btstack: Fix marking of static addresses in set_random_address.
Marking address as static was not applied to all code paths.

Signed-off-by: Damien George <damien@micropython.org>
2023-06-14 22:20:20 +10:00
Peter Harper 35182a8688 extmod/btstack: Add cmake support for BTstack.
Signed-off-by: Damien George <damien@micropython.org>
2023-06-14 22:20:20 +10:00