/*
  At first the arguments are read and passed. Then the ssl context is gotten
  by calling 'BIO_get_ssl(client, &ssl)'. Afterwards the ssl handshake is 
  performed and the certificate verified. Then the line is read from the certificate. 
  This value is mapped to 'organizationalUnitName'.
  An example usage of the connection is shown and then the connectino will be
  terminated.
 */
void* handleConn(void *argsv){
  connArgs* args = (connArgs*) argsv;
  MessageHandler* msgHandler = args->msgHandler;
  BIO* client = args->conn;
  SSL* ssl;

  BIO_get_ssl(client, &ssl);

  /*ssl handshake*/
  msgHandler->debug("performing ssl handshake");
  if(BIO_do_handshake(client) != 1){
    string fail("handshake failed\nSSL_ERROR: ");
    fail.append(ERR_reason_error_string(ERR_get_error()));
    msgHandler->log(fail);
  } else
    msgHandler->log("handshake successful");

  /*verifying the certificate*/
  X509* peerCert;

  if(SSL_get_verify_result(ssl) != X509_V_OK){
    string error("verification failed\nSSL_Error: ");
    error.append(ERR_reason_error_string(ERR_get_error()));
    msgHandler->error(error, CRITICAL);
  } else {
    msgHandler->debug("verification successful");
    peerCert  = SSL_get_peer_certificate(ssl);
  }

  msgHandler->debug("trying to get the line");
  /*getting the line*/
  char lineN[6];
  X509_NAME* name = X509_get_subject_name(peerCert);
  X509_NAME_get_text_by_NID(name, NID_organizationalUnitName, lineN, 6);
  string line("line is: ");
  line.append(lineN);
  msgHandler->debug(line);

  /*example use of the connection (echoing the incoming msg)*/
  char buffer[1024];
  bzero(buffer, 1024);
  SSL_read(ssl, buffer, 1024);
  string debug("message received: ");
  debug.append(buffer);
  msgHandler->debug(debug);
  SSL_write(ssl, buffer, 1024);

  /*closing the connection*/
  BIO_reset(client);
  X509_free(peerCert);
  return NULL;
}