Search code examples
sslerlanggen-tcp

Looking for a simple ssl erlang example


In the book Erlang Programming one of the exercises proposed was to print on screen the request coming from a browser using gen_tcp. I made it for http requests as follows:

-module(tcp).
-export([server/0, wait_connect/2]).

server() ->
    {ok, ListenSocket} = gen_tcp:listen(1234, [binary, {active, false}]),
    wait_connect(ListenSocket,0).

wait_connect(ListenSocket, Count) ->
    {ok, Socket} = gen_tcp:accept(ListenSocket),
    spawn(?MODULE, wait_connect, [ListenSocket, Count+1]),
    get_request(Socket, [], Count).

get_request(Socket, BinaryList, Count) ->
    Request = gen_tcp:recv(Socket, 0),
    io:format("~p~n", [Request]).

Now I am wondering how this can be done in case of https request. Can you provide a very simple example, or point me to some resource on books or online?


Solution

  • Here is the user guide for Erlang SSL application: Erlang -- SSL User Guide

    The guide contains also, in the API chapter, a paragraph on updating existing connections to SSL.

    Regarding your code, you should do something like:

    • on server and client side you have to issue: ssl:start()
    • server side: handshake SSL (remember to set 'active' to false for the listening socket)

      {ok, SSLSocket} = ssl:ssl_accept(Socket, [{cacertfile, "cacerts.pem"}, {certfile, "cert.pem"}, {keyfile, "key.pem"}]).

      where "cacerts.pem", "cert.pem", "key.pem" are files related to SSL certification

    • client side: upgrade connection to SSL: {ok, SSLSocket} = ssl:connect(Socket, [{cacertfile, "cacerts.pem"}, {certfile, "cert.pem"}, {keyfile, "key.pem"}], infinity).

    As per documentation, now SSLSocket is a ssl channel that can be used to send messages like: ssl:send(SSLSocket, "foo").

    Hope this helps!