[openssl-users] forking server question

Robert Cousins rec at Rcousins.com
Fri May 5 20:31:39 UTC 2017


Please excuse what is a simple question: what is the proper way to clean
up in the parent and child when writing a forking server using OpenSSL?
(I expected this would be a FAQ, but I couldn't find it.)  I have code
which works, but I have the nagging feeling that I'm leaking on the
parent side. Here is my main program:

int
main(int argc, char *argv[])
{
  BIO     *acc;
  SSL_CTX *ctx;
  install_sigchld();            /* Install signal handlers */
  init_OpenSSL(  );            /* Initialize library, RNG, etc. */
  ctx = setup_server_ctx(  );        /* Build Context */
  if (!(acc = BIO_new_accept(PORT)))    /* Get ready for connection */
    int_error("Error creating server socket");
  if (BIO_do_accept(acc) <= 0)        /* Bind to socket */
    int_error("Error binding server socket");
  while (1) {
    SSL     *ssl;
    int fd = -1;
    if (BIO_do_accept(acc) <= 0)     /* Accept the connection */
      int_error("Error accepting connection");
    BIO *client = BIO_pop(acc);        /* get the client off BIO */
    switch (fork()) {
    case -1: err(1,"Fork failed");     /* error */
    default:                /* parent */
      BIO_get_fd(client,&fd);        /* close the socket on parent side */
      close(fd);
      break;
    case 0:                /* child */
      if (!(ssl = SSL_new(ctx)))    /* create new context */
    int_error("Error creating SSL context");
      SSL_set_accept_state(ssl);
      SSL_set_bio(ssl, client, client);
      do_work(ssl);            /* go do some work */
      exit(0);                /* leave (we'll get sigchld) */
    }                   
  }
  SSL_CTX_free(ctx);
  BIO_free(acc);
  return 0;
}




More information about the openssl-users mailing list