How do TLS connections work in EventMachine?

I have my own protocol based on the Protobuf protocol, which I implemented as the EventMachine protocol, and I would like to use it through a secure connection between the server and clients. Each time I send a message from the client to the server, I add a message with a 4-byte integer representing the size of the serialized Protobuf string to be sent, so that the server knows how many bytes the wire reads before parsing the data back into the Protobuf message .

I call start_tls in the start_tls callback method in both the client and server protocol handlers and the server handler to which the server’s private key and certificate are passed. At this stage, there are apparently no errors based on the log messages that I print.

When I start to understand, when I start to analyze the data in the receive_data callback in the server handler code ... I read 4 bytes of data from the wire and unpack it into an integer, but the integer that is unpacked is not the same integer that I I send from the client (i.e. I send 17, but I receive 134222349).

Please note that this does not happen when I do not use TLS ... everything works fine if I delete start_tls calls both in the client code and on the server.

Does it happen that SSL / TLS data is sent to the receive_data callback when using TLS? If so, how do I know when the data from the client will begin? I cannot find any sample code that discusses this use case ...

+4
source share
1 answer

OK, so through cross-mail to the Google EventMachine group, I found out what my problem was. Essentially, I tried to send data from the client to the server before the TLS handshake was completed, because I did not expect the ssl_handshake_completed callback to be called.

Here is the code I got to work, just in case anyone meets this post in the future. :)

Handler code for the server side:

 require 'eventmachine' class ServerHandler < EM::Connection def post_init start_tls :private_key_file => 'server.key', :cert_chain_file => 'server.crt', :verify_peer => false end def receive_data(data) puts "Received data in server: #{data}" send_data(data) end end 

Client side handler code:

 require 'eventmachine' class ClientHandler < EM::Connection def connection_completed start_tls end def receive_data(data) puts "Received data in client: #{data}" end def ssl_handshake_completed send_data('Hello World! - 12345') end end 

Code to start the server:

 EventMachine.run do puts 'Starting server...' EventMachine.start_server('127.0.0.1', 45123, ServerHandler) end 

Code to run the client:

 EventMachine.run do puts 'Starting client...' EventMachine.connect('127.0.0.1', 45123, ClientHandler) end 
+8
source

Source: https://habr.com/ru/post/1447093/


All Articles