OK. We have written a simple echo service, serving both on tcp and udp. Now we want our echo service to be working for TLS, too.
The tls module fits well into implementing TLS based secure connections, for it has the following advantages over the defaut erlang ssl module:
It is implemented using C and has better performance.
It supports starttls i.e. start tls over the tcp connection depending on situations, without having to re-establish a new connection.
To enable tls connections, use tls:tcp_to_tls/2 to transform a tcp socket to a tls one:
in set_opts/1, we use tls:tcp_to_tls/2 to transform the accepted tcp socket in to a tls socket, then we use tls:recv_data/2 to receive all the tls data. tls:tls_recv_data will automatically do the handshakes needed, returning data if presents (handshake data excluded). Finally, we use tls:send/2 to send any data back to the client.
Now let’s take our echo service up to the next level: what about receiving xml streams as input , and echoing xml stanzas?
That’s also very simple.
We first change the socket_type() to return xml_stream, which tells ejabberd to use ejabberd_receiver as our receiver. Then we override the fsm state call back process/2 to process any incoming xml stanzas. Note that we do no-op for activate_socket and set_opts, for any incoming data are automatically taken care of by the ejabberd_receiver module.
To test it, let’s run nc to connect to the 5555 port:
We have modified our echo service module to accept tls connections as well as xml_stream stanzas. Next time we’ll be talking about something else, but also fun!