/*
 * Secure Network Transport Layer Library implementation.
 * This is a proprietary software. See COPYING for further details.
 *
 * (c) 2013-2014 Copyright Askele, inc. <http://askele.com>
 * (c) 2013-2014 Copyright Askele Ingria, inc. <http://askele-ingria.com>
 */

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>

#include <uuid/uuid.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#include <tdata/usrtc.h>
#include <sexpr/sexp.h>

#include <sntl/connection.h>

/* this function is an ugly implementation to get C string with uuid */
char *__generate_uuid(void)
{
  char *uuidc = NULL;
  uuid_t uuid;
  int len, i = 0;

  len = sizeof(char)*(sizeof(uuid_t)*2) + sizeof(char);
  if(!(uuidc = malloc(len))) return NULL;

  uuid_generate_time_safe(uuid);

  for(i = 0; i < sizeof(uuid_t); i++)
    snprintf(uuidc+(2*i*sizeof(char)), len, "%02x", uuid[i]);

  return uuidc;
}

/* networking helpers */
int __resolvehost(const char *hostname, char *buf, int buf_len,
                         struct hostent **rhp)
{
  struct hostent *hostbuf = malloc(sizeof(struct hostent));
  struct hostent *hp = *rhp = NULL;
  int herr = 0, hres = 0;

  if(!hostbuf) return NO_ADDRESS;

  hres = gethostbyname_r(hostname, hostbuf,
                         buf, buf_len, &hp, &herr);

  if (!hp) return NO_ADDRESS;
  if(hres) return NO_ADDRESS;

  *rhp = hp;

  return NETDB_SUCCESS;
}

/* sexp helpers */
int sexp_list_car(sexp_t *expr, sexp_t **sx)
{
  if (!SEXP_IS_LIST(expr) || expr->list->ty != SEXP_VALUE)    return 1;

  *sx = expr->list;

  return 0;
}

int sexp_list_cdr(sexp_t *expr, sexp_t **sx)
{
  /* Dummy function. Can we do cdr properly? */
  if (!SEXP_IS_LIST(expr) || expr->list->ty != SEXP_VALUE)    return 1;

  if (!expr->list->next)    *sx = NULL;
  else    *sx = expr->list->next;

  return 0;
}