#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include "daemon.h"
#include "caller_id_api.h"
#include "caller_id_error.h"

/*--------------------
    GLOBAL variables
---------------------*/


/*--------------------------------
    PROTOTYPES
-----------------------------------*/


                                  

/*---------------------------
    FUNCTIONS
----------------------------*/


/*
  This function peforms authentication Caller Id authentication
*/
int dx_caller_id_authenticate()
{
  /* return value  */
  int                 ret_val;
  
  /* connection socket */
  int                 conn_socket;
  
  /* length */
  int                 len;
  
  /* sockaddr of the application */
  struct  sockaddr_un remote;
  
  /* command request structure */  
  dx_dm_app_request   command_arg;
  
  /* reply  structure */  
  dx_dm_app_reply     reply_arg;
  
  /*------------------------------------
      CODE
  ------------------------------------*/
  
  /* init the socket */
  conn_socket = socket(PF_UNIX, SOCK_STREAM, 0);
  if(conn_socket < 0)
  {
    ret_val = DX_CALLER_ID_SOCKET_CREATE_ERR;
    goto end_function;
  }
  
  /* prepare bind parameters */
  remote.sun_family = PF_UNIX;  /* local is declared before socket() ^ */
  strcpy(remote.sun_path, DX_DM_SOCK_PATH);
  len = strlen(remote.sun_path) + sizeof(remote.sun_family);
  
  /* bind */
  ret_val = connect(conn_socket, (struct sockaddr *)&remote, len);
  if(ret_val < 0)
  {
    ret_val = DX_CALLER_ID_CONNECT_ERR;
    goto end_function;
  }
  
  /* prepare caller id structure */
  command_arg.command_id = CALLER_ID_CMD;
  
  /* send caller id request */
  len = send(conn_socket , (void*)&command_arg , sizeof(dx_dm_app_request) , 0);
  if(len < 0 || len != sizeof(dx_dm_app_request))
  {
    ret_val = DX_CALLER_ID_SEND_CMD_ERR;
    goto end_function;
  }
  
  len = recv(conn_socket , (void*)&reply_arg , sizeof(dx_dm_app_reply) , 0);
  if(len < 0 || len != sizeof(dx_dm_app_reply))
  {
    ret_val = DX_CALLER_ID_RCV_RPLY_ERR;
    goto end_function;
  }
  
  /* check the reply status */
  if(reply_arg.status)
  {
    ret_val = DX_CALLER_ID_AUTH_ERR;
  }
  
end_function:

  return ret_val;
}



