extmod/modussl_mbedtls: Support non-blocking handshake.
For this, add wrap_socket(do_handshake=False) param. CPython doesn't have such a param at a module's global function, and at SSLContext.wrap_socket() it has do_handshake_on_connect param, but that uselessly long. Beyond that, make write() handle not just MBEDTLS_ERR_SSL_WANT_WRITE, but also MBEDTLS_ERR_SSL_WANT_READ, as during handshake, write call may be actually preempted by need to read next handshake message from peer. Likewise, for read(). And even after the initial negotiation, situations like that may happen e.g. with renegotiation. Both MBEDTLS_ERR_SSL_WANT_READ and MBEDTLS_ERR_SSL_WANT_WRITE are however mapped to the same None return code. The idea is that if the same read()/write() method is called repeatedly, the progress will be made step by step anyway. The caveat is if user wants to add the underlying socket to uselect.poll(). To be reliable, in this case, the socket should be polled for both POLL_IN and POLL_OUT, as we don't know the actual expected direction. But that's actually problematic. Consider for example that write() ends with MBEDTLS_ERR_SSL_WANT_READ, but gets converted to None. We put the underlying socket on pull using POLL_IN|POLL_OUT but that probably returns immediately with POLL_OUT, as underlyings socket is writable. We call the same ussl write() again, which again results in MBEDTLS_ERR_SSL_WANT_READ, etc. We thus go into busy-loop. So, the handling in this patch is temporary and needs fixing. But exact way to fix it is not clear. One way is to provide explicit function for handshake (CPython has do_handshake()), and let *that* return distinct codes like WANT_READ/WANT_WRITE. But as mentioned above, past the initial handshake, such situation may happen again with at least renegotiation. So apparently, the only robust solution is to return "out of bound" special sentinels like WANT_READ/WANT_WRITE from read()/write() directly. CPython throws exceptions for these, but those are expensive to adopt that way for efficiency-conscious implementation like MicroPython.
Showing
Please register or sign in to comment