Search code examples
csslembeddedmongoose-web-server

How to implement SSL/TLS in cesanta mongoose embedded?


I am trying to implement SSL/TLS in my web server in an embedded system, according to mongoose tutorial I have written the following code which uses mongoose builtin TLS1.3. But I get "TLS not enabled" error once server accept the connection. Can someone tell me what is the problem in code. I have also enabled the pre-processor variable MG_TLS=MG_TLS_BUILTIN.



static const char *s_tls_cert ="-----BEGIN CERTIFICATE-----\n" 
                    "ABCD\n"
                    "-----END CERTIFICATE-----\n"; // Actual certificate created will be copied here as a string

static const char *s_tls_key = "-----BEGIN PRIVATE KEY-----\n"    
                    "ABCD\n"
                    "-----END PRIVATE KEY-----\n"; // Actual private key created will be copied here


void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data)
{


if (ev == MG_EV_ACCEPT)
    {
      struct mg_tls_opts opts = {
     .cert = s_tls_cert,
     .certkey = s_tls_key};
     mg_tls_init(c, &opts);
   }


  if (ev == MG_EV_HTTP_MSG)
    {
      struct mg_http_message *hm = (struct mg_http_message *) ev_data;
      if (mg_http_match_uri(hm, "/api/login"))
    {
      mg_http_reply(c, 200, "Content-Type: text/html\r\n", "<!DOCTYPE html><html><body>Welcome User</body></html>");
    }
    }
}



void task1(void)
{
  struct mg_mgr mgr;
  mg_mgr_init(&mgr);                                     
  mg_log_set(MG_LL_DEBUG);
  mg_http_listen(&mgr, "https://0.0.0.0:8443", fn, &mgr);
  for (;;)mg_mgr_poll(&mgr, 1000, 1);
  mg_mgr_free(&mgr);
} 

Solution

  • You're using a quite old version. The ev_data argument in the event handler is long gone. I suggest to use the latest version. Take http-restful-server as an example, it starts both HTTP and HTTPS listener.

    See https://github.com/cesanta/mongoose/tree/master/tutorials/http/http-restful-server