/*-----------------------------------------------------------------*/
/*! 
  \file scscpsscommon.c
  \brief common subroutine for server tests
  \author  M. Gastineau 
           Astronomie et Systemes Dynamiques, IMCCE, CNRS, Observatoire de Paris. 

   Copyright, 2008, 2009, 2010, 2011, 2012, M. Gastineau, IMCCE-CNRS
   email of the author : gastineau@imcce.fr

  \bug M. GASTINEAU 01/10/12 : ticket [#8521] tests hangs or are too long
*/
/*-----------------------------------------------------------------*/

/*-----------------------------------------------------------------*/
/* License  of this file :
 This file is "dual-licensed", you have to choose one  of the two licenses 
 below to apply on this file.
 
    CeCILL-C
    	The CeCILL-C license is close to the GNU LGPL.
    	( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html )
 
 or CeCILL v2.0
      The CeCILL license is compatible with the GNU GPL.
      ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )
 

This library is governed by the CeCILL-C or the CeCILL license under 
French law and abiding by the rules of distribution of free software.  
You can  use, modify and/ or redistribute the software under the terms 
of the CeCILL-C or CeCILL license as circulated by CEA, CNRS and INRIA  
at the following URL "http://www.cecill.info". 

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability. 

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or 
data to be ensured and,  more generally, to use and operate it in the 
same conditions as regards security. 

The fact that you are presently reading this means that you have had
knowledge of the CeCILL-C or CeCILL license and that you accept its terms.
*/
/*-----------------------------------------------------------------*/

#if HAVE_CONFIG_H
#include "scscpconfig.h"
#endif /*HAVE_CONFIG_H*/
#if HAVE_WINDOWS_H
#include <windows.h>
#endif /*HAVE_WINDOWS_H*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#if HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#endif
#include "scscp.h"
#include "scscpsscommon.h"
#include "scscpdebug.h"


#if HAVE_FORK
typedef pid_t ospid_t; 
#elif HAVE_WIN32API
typedef PROCESS_INFORMATION ospid_t;
#endif

/*  id of the server */
static ospid_t pserverid;

/*-----------------------------------------------------------------*/
/*! synchronization between client and server. 
The client waits until the server is listening and accepts client 
 @param port (in) SCSCP port
*/
/*-----------------------------------------------------------------*/
static int writesync(int port)
{
 int res;
 int sleeptime = 1;
 SCSCP_socketclient client;
 SCSCP_status status = SCSCP_STATUS_INITIALIZER;

 SCSCP_sc_init(&client, &status, SCSCP_PROTOCOL_VERSION_1_3, NULL); 
 do
 {
  mysleep(sleeptime);
  res = SCSCP_sc_connect(&client, "localhost", port, &status);
  /*printf("writesync %d '%s'\n", res, SCSCP_status_strerror(&status));*/
 } while (res==0);
 SCSCP_sc_close(&client, &status); 
 SCSCP_sc_clear(&client, &status);
 return 1;
}

/*-----------------------------------------------------------------*/
/*! start a new thread which will run the server. update pserverid 
return the port used by the server
*/
/*-----------------------------------------------------------------*/
int startbackgroundserver(int typeanswer, int *port)
{
 int res = 0;
 char bufanswer[10];
 char sfd[10];
 int fd[2], nr;
 
 sprintf(bufanswer, "%d",typeanswer);
#if HAVE_FORK
   if (pipe(fd)<0)
   {
    printf("Can't create pipe!\n");
    return res;
   }
   pserverid = fork();
   switch(pserverid)
   {
   case -1:
      res = 0;
      break;
      
   case 0: /* child */ 
      close(fd[0]);
      sprintf(sfd, "%d", fd[1]);
      if (execl("scscpservertest", "scscpservertest", bufanswer, sfd, NULL)==-1)
      {
       res = 0;
       printf("startbackgroundserver failed on exec\n");
      }
      break;
      
   default: /* parent */ 
       close(fd[1]);
       res = 1;
       /*printf("parent process : child pid= %d\n",(int)pserverid);*/
       break;
   }
   /* read the port by the server */
   nr = (int)read(fd[0], port,sizeof(*port));
   if (nr!=(int)sizeof(*port))
   {
    printf("Can't read pipe : can't read the port sent by the server!\n");
    printf ("debug info : nr=%d size=%d\n", nr, (int)sizeof(*port));
    res = 0;
    return res;
   }

#elif HAVE_WIN32API

   {
   STARTUPINFO siStartInfo;
   BOOL bFuncRetn = FALSE; 
   char cmd[1024];
   
   sprintf(cmd,"scscpservertest.exe %d", typeanswer);
   
   ZeroMemory( &pserverid, sizeof(PROCESS_INFORMATION) );
   ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
   siStartInfo.cb = sizeof(STARTUPINFO); 
    
    res = CreateProcess(NULL, 
      cmd,      /* command line */
      NULL,          /* process security attributes */
      NULL,          /* primary thread security attributes */
      FALSE,          /* handles are inherited */
      CREATE_NEW_PROCESS_GROUP, /* creation flags */
      NULL,          /* use parent's environment */
      NULL,          /* use parent's current directory */
      &siStartInfo,  /* STARTUPINFO pointer */
      &pserverid);  /* receives PROCESS_INFORMATION */

  if (res==0)
   {
     printf("res=%d\n",res);
     printf( "CreateProcess failed (%d)\n", GetLastError() );
   }
   *port =  SCSCP_PROTOCOL_DEFAULTPORT;
  }
  
#endif /*HAVE_WIN32API*/
 SCSCP_debugprint("port=%d\n", *port);
 writesync(*port);
 SCSCP_debugprint("synchronization performed on port=%d\n", *port);
 return res;
}

/*-----------------------------------------------------------------*/
/*! send the stop action to the thread of the server  
   @bug M. GASTINEAU 13/01/2009 : send CTRL+BREAK 
   to stop the server on windows
*/
/*-----------------------------------------------------------------*/
int stopbackgroundserver()
{
 int res = 0;
 int status;
 
#if HAVE_FORK
 /*printf("send kill to  pid= %d\n",(int)pserverid);*/
 kill(pserverid, SIGUSR2);
 waitpid(pserverid, &status, WUNTRACED);
 
 if (WIFEXITED(status)) 
 {
   res = (WEXITSTATUS(status) != 0);
 }
#elif HAVE_WIN32API
 GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pserverid.dwProcessId);
 WaitForSingleObject( pserverid.hProcess, INFINITE );
 CloseHandle(pserverid.hProcess);
 CloseHandle(pserverid.hThread);
#endif 
 return res;
}

/*-----------------------------------------------------------------*/
/*! sleep for some seconds
   @param sec (in) number of seconds
*/
/*-----------------------------------------------------------------*/
void mysleep(int sec)
{
#if HAVE_FORK
 sleep(sec);
#elif HAVE_WIN32API
 Sleep(sec*1000);
#endif 
}

/*-----------------------------------------------------------------*/
/*! send a procedure call and check that the answer is <OMI>1</OMI>
   @param client (inout) client connection
   @param status (inout) error code
   @param callbackwrite (in) call back function write the arguments of the procedure call
   @param param (in) opaque user data given to callbackwrite
*/
/*-----------------------------------------------------------------*/
int sendprocedurecallcheck(SCSCP_socketclient* client, SCSCP_status* status,
                           int (*callbackwrite)(SCSCP_io* stream, void *param, SCSCP_status *status), 
                           void *param)
{
 int res;
 char *openmathbuffer;
 SCSCP_msgtype msgtype;
 
 res = SCSCP_sc_callsendhook(client, SCSCP_CALLOPTIONS_DEFAULT, callbackwrite, param, status);
 if (res) res = SCSCP_sc_callrecvstr(client, SCSCP_RETURNOPTIONS_IGNORE, &msgtype, &openmathbuffer, status);
 if (res)
 {
  res = (strcmp(openmathbuffer,"<OMI>1</OMI>")==0);
  if (res==0) printf("openmathbuffer='%s'\n", openmathbuffer);
  free(openmathbuffer);
 }
 else
 {
  printf("sendprocedurecallcheck failed ='%s'\n", SCSCP_status_strerror(status));
 }
 return res;
}


/*-----------------------------------------------------------------*/
/*! start the server and send a procedure call message and check the reply that must be <OMI>1</OMI>
   @param typeserver (in) value to start the server
   @param callbackwrite (in) call back function write the arguments of the procedure call
   @param param (in) opaque user data given to callbackwrite
*/
/*-----------------------------------------------------------------*/
int startserverandsendbincheck(int typeserver,
                           int (*callbackwrite)(SCSCP_io* stream, void *param, SCSCP_status *status), 
                           void *param)
{
 SCSCP_socketclient client;
 SCSCP_status status = SCSCP_STATUS_INITIALIZER;
 int res, reserver, port;
 
 res = startbackgroundserver(typeserver, &port);
 
 /* open connection with the server on port 26133 */
 if (res) res = SCSCP_sc_init(&client, &status, SCSCP_PROTOCOL_VERSION_1_3, NULL); 
 if (res) res = SCSCP_sc_connect(&client, "localhost", port, &status); 
 if (res) res = SCSCP_sc_set_encodingtype(&client, SCSCP_encodingtype_Binary, &status); 
 /* send a valid symbol */
 if (res) res = sendprocedurecallcheck(&client, &status, callbackwrite, param); 

 if (res) res = SCSCP_sc_close(&client, &status); 
 SCSCP_sc_clear(&client, &status);
 SCSCP_status_clear(&status);

 reserver = stopbackgroundserver();

 return !(res==1 && reserver==0);
}

/*-----------------------------------------------------------------*/
/*! return a long string >256 characters */
/*-----------------------------------------------------------------*/
const char *getlongstring(void)
{
 return "azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890azertyuiopqsdfghjklmwxcvbn1234567890";
}

