mosquitto_want_write() can wrongfully return true
mosquitto_want_write() currently returns true when there's a packet to be sent or when mosq->want_write is set. The latter only happens when OpenSSL needs to write something but couldn't.
However, this fails to return the correct value in the following scenario:
- We're setting up a connection to the broker over TLS.
- CONNECT packet is queued.
- TLS handshake is started: we've sent our part and we're waiting for the server to respond.
mosquitto_want_write()returns true in this case because there's a packet queued.
The result is that the mosquitto socket is added to the write set of the application event loop, even though it can't send anything because the TLS handshake is not complete yet. Since the socket is practically always writable we keep getting a write event, tell mosquitto it can send and then go back to the event loop, only to immediately get another write event. A nice busy-wait loop until we get a read event from the server to complete the TLS handshake. Usually that happens quickly and the impact is limited, but sometimes it can take a while to get a server response and all that time we're pegging a CPU core to 100%.
I've noticed that in loop.c the logic to decide if the socket needs to be added to the write set is slightly different: it primarily uses mosq->want_write and otherwise only looks at whether there's a packet queued when SSL_is_init_finished() returns true. That latter check is missing in mosquitto_want_write()
Source: eclipse-mosquitto/mosquitto