ScottPeterJohnson / purelymail-issues

Issues repository for the Purelymail email service.
34 stars 0 forks source link

Delay or timeout at the end of every IMAP session #213

Open ality opened 6 months ago

ality commented 6 months ago

I've been encountering a roughly nine second delay at the end of every IMAP session. It started about a month or so ago and I finally got annoyed enough to investigate. Below is a paraphrasing of the tail end of my packet captures under three different scenarios.

Using TLSv1.2: -> IMAP 6 CLOSE <- IMAP 6 OK CLOSE completed. -> IMAP 7 LOGOUT <- IMAP * BYE Bye <- IMAP 7 OK LOGOUT completed. -> TLSv1.2 Alert: Close Notify <- TLSv1.2 Alert: Close Notify -> TCP FIN ACK <- TCP FIN ACK -> TCP ACK

Using TLSv1.3: -> IMAP 6 CLOSE <- IMAP 6 OK CLOSE completed. -> IMAP 7 LOGOUT <- IMAP * BYE Bye <- IMAP 7 OK LOGOUT completed. -> TLSv1.3 Alert: Close Notify <- TCP ACK ... 9.114s delay ... <- TLSv1.3 Alert: Close Notify <- TCP FIN ACK -> TCP FIN ACK <- TCP ACK

Using TLSv1.2 with the client modified to omit the close notify alert: -> IMAP 6 CLOSE <- IMAP 6 OK CLOSE completed. -> IMAP 7 LOGOUT <- IMAP * BYE Bye <- IMAP 7 OK LOGOUT completed. -> TCP ACK ... 9.278s delay ... <- TLSv1.2 Alert: Close Notify <- TCP FIN ACK -> TCP FIN ACK <- TCP ACK

The first case is explained by the differences in the RFC for TLS versions 1.2 and 1.3. Before version 1.3, it was a requirement to send an immediate reply upon receipt of a close notify alert so this is usually handled internally in the record layer of a TLS implementation. Version 1.3 allows completing pending writes before sending the close notify reply.

The latter two cases appear to be some kind of timeout during polling a socket for incoming data.

I'm not very familiar with Java or Kotlin but after perusing the JDK source, it looks like the SSLSocket.close method contains all the necessary logic for sending the close notify alert. Is there a reason you don't call the close method immediately after sending the OK LOGOUT message?

Let me know if you need any more details.

Cheers, Anthony

nmasur commented 5 months ago

I've noticed this too, running mbsync -a it syncs up for a bit, and then there's 9 seconds of nothing before it seems to close (or time out?).

ScottPeterJohnson commented 5 months ago

Apparently per the IMAP spec the server is supposed to close the connection after the logout command, and Purelymail somehow doesn't. I'm not sure it ever did, or if I broke it refactoring a few months back. But this should be a simple fix.