Topic: adapting reader/writer thread design to cyassl

I have a standard TCP socket application running with lwip and FreeRTOS, and I would like to secure it with cyassl.

The application is a CAN packet relay, so we don't know if the next io over the network will be a read or a write.  I currently implement this by having 1 thread dedicated to reading the socket and another thread for writing.

As I understand it, this will not work for cyassl.  Protecting read/write with a mutex will also not work, because the reader thread will hold the mutex and block the writer until something is received.

So my question is, what is a good way to do random read/write with cyassl?

Thanks,
Dan.

Re: adapting reader/writer thread design to cyassl

Hi Dan,

It sounds like there are a couple of ways you could go about using CyaSSL in your application:

1.  If your application uses non-blocking sockets, you can just call CyaSSL_read() when data is available for reading and CyaSSL_write() when data is available to be written.  LwIP has a select() function which is designed for this purpose.  Using this method the calls shouldn't block each other since CyaSSL_read() and CyaSSL_write() would never block.

2.  You could use CyaSSL's default I/O callbacks with a mutex.  If your application didn't get the mutex until right before the CyaSSL_read() or CyaSSL_write() call, they wouldn't block each other.  If CyaSSL needed more data but it wasn't ready yet, CyaSSL_read() will return SSL_ERROR_WANT_READ while CyaSSL_write() would return SSL_ERROR_WANT_WRITE.

Best Regards,
Chris

Re: adapting reader/writer thread design to cyassl

Thank you for the response.

I was under the (probably incorrect) assumption that CyaSSL_read() may do both reads and writes on the underlying transport.  Same with CyaSSL_write().  If this is *not* the case and SSL_read only does reads and SSL_write only does writes, then things get a little easier.

Still wrapping my head around all the details.  One aspect I struggle with is breaking a select() call when a packet comes in on CAN hardware.  On linux I would use a pipe to patch into the select(), but that's not available in this environment.  My solution of last resort will be to use non-blocking sockets in a polling loop, but would prefer to do something more elegant and less busy.

Re: adapting reader/writer thread design to cyassl

Dan,

Your understanding is correct in that if the SSL handshake has not been completed by CyaSSL_connect() or CyaSSL_accept(), the CyaSSL_read() and CyaSSL_write() calls will end up calling CyaSSL_negotiate(), which will try to complete the handshake - doing both reads and writes. 

If for example CyaSSL_read() ends up doing both writes and reads to finish the SSL handshake, they won't interfere with each other because they are in the same thread, right?

- Chris