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

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

  \bug M. GASTINEAU 20/04/09 : update for SCSCP 1.3
  \bug M. GASTINEAU 27/08/09 : test for ticket [#6399] openmath encoded with namespaces are rejected
  \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*/
#include <stdio.h>
#include <stdlib.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#endif
#include <signal.h>
#define __SCSCP_WITHIN_SCSCP
#include "scscp.h"
#include "scscpsscommon.h"
#include "scscpdebug.h"
#include "scscpfileserver.h"


#if defined(SIGUSR2)
#define SIGNALINTERRUPT SIGUSR2
#else
#define SIGNALINTERRUPT SIGINT
#endif

/* SCSCP server  */
static SCSCP_socketserver server;
static int closesig=0; /* =1 if SIGUSR2 is received */

static int  processcall(SCSCP_incomingclient *incomingclient, SCSCP_status *status, int typeanswer);
static int server_sendreplycheck(SCSCP_incomingclient *incomingclient, SCSCP_returnoptions* returnopt, SCSCP_status *status, 
                          int res1, const char *value, const char *valueref);
static int server_sendreplycheckint(SCSCP_incomingclient *incomingclient, SCSCP_returnoptions* returnopt, SCSCP_status *status, 
                          int res1, int value, int valueref);
static int server_sendreplycheckdouble(SCSCP_incomingclient *incomingclient, SCSCP_returnoptions* returnopt, SCSCP_status *status, 
                          int res1, double value, double valueref);


/*-----------------------------------------------------------------*/
/*! stop the server when it receive SIGUSR2  */
/*-----------------------------------------------------------------*/
static void stopserver(int sig)
{

 SCSCP_status status = SCSCP_STATUS_INITIALIZER;

 SCSCP_debugprint("server receive SIGUSR2\n"); 
 closesig=1;
 /* close the connection */
 SCSCP_ss_close(&server, &status);
 /* exit the server */
 exit(0);
}

/*-----------------------------------------------------------------*/
/*! start the server and listen on a port. the server finds an random available port */
/*-----------------------------------------------------------------*/
static int runserver(int typeanswer, int fd)
{
 SCSCP_status status = SCSCP_STATUS_INITIALIZER;
 int res;
 SCSCP_incomingclient incomingclient;
 int port = SCSCP_PROTOCOL_DEFAULTPORT;
 
 /*printf("server thread started\n");*/
 /* register stopserver for the signal SIGUSR2 */
 signal(SIGNALINTERRUPT, stopserver);
 
 /*initialization of the server */
 res = SCSCP_ss_init(&server, &status, "MYCAS","1","myid", SCSCP_PROTOCOL_VERSION_1_3,
                     "1.001", NULL); 
               
 if (res)
 {
  if (fd==-1)
  {
     port = SCSCP_PROTOCOL_DEFAULTPORT;
     res = SCSCP_ss_listen(&server, port, 0, &status); 
  }
  else
  {
     /* choose a random port */
     port = 0;
     res = SCSCP_ss_listen(&server, port, 0, &status); 
     /* write the port used by the server to the client */
     if (res!=0) 
     {
      port = SCSCP_ss_getport(&server);
      SCSCP_debugprint("fd=%d -> port:%d\n", fd, port);
      write(fd,&port, sizeof(port));
     }
     close(fd);   
  }
 }
 
 if (res)
 {
     while (res!=0 && SCSCP_ss_acceptclient(&server, &incomingclient, &status))
      {
       SCSCP_debugprint("new client accepted !\n");
       while (res>0) res = processcall(&incomingclient, &status,typeanswer);
       SCSCP_ss_closeincoming(&incomingclient, &status);
       status = SCSCP_STATUS_INITIALIZER;
       res = 1;
      }
 }
 if (res==0) printf("error message= %s\n", SCSCP_status_strerror(&status));
 if (res==0) printf("destroy server\n");
 /* destroy the server */
 SCSCP_ss_close(&server, &status);
 res = SCSCP_ss_clear(&server, &status);
 SCSCP_status_clear(&status);
 SCSCP_debugprint("server exit %d typeanswer=%d\n", closesig, typeanswer); 
 if (res!=-1 && closesig==0) 
 {
  printf("server thread crash => exit with value 1\n");
  printf("----------------------------------------\n");
  printf(" reports this bug to %s \n", PACKAGE_BUGREPORT);
  printf("----------------------------------------\n");
  return 1; 
 }
 else
 {
  return 0;
 }
}

/*-----------------------------------------------------------------*/
/*! send the answer : if value==valueref then 
 send a completed message  */
/*-----------------------------------------------------------------*/
static int server_sendreplycheck(SCSCP_incomingclient *incomingclient, SCSCP_returnoptions* returnopt, SCSCP_status *status, 
                          int res1, const char *value, const char *valueref)
{
 int res;
 if (res1!=1 || strcmp(value,valueref)!=0)
 {
   SCSCP_ss_sendterminatedstr(incomingclient, returnopt, "scscp1", "error_system_specific", value!=NULL?value:"null", status);
   res = 0;
 }
 else
 {
    res = SCSCP_ss_sendcompletedstr(incomingclient, returnopt, "<OMI>1</OMI>", status); 
 }
 return res;
}

/*-----------------------------------------------------------------*/
/*! send the answer : if value==valueref then 
 send a completed message  */
/*-----------------------------------------------------------------*/
static int server_sendreplycheckint(SCSCP_incomingclient *incomingclient, SCSCP_returnoptions* returnopt, SCSCP_status *status, 
                          int res1, int value, int valueref)
{
 int res;
 if (res1!=1 || value!=valueref)
 {
   char buffer[128];
   sprintf(buffer, "%d %d", value, valueref);
   SCSCP_ss_sendterminatedstr(incomingclient, returnopt, "scscp1", "error_system_specific", buffer, status);
   res = 0;
 }
 else
 {
    res = SCSCP_ss_sendcompletedstr(incomingclient, returnopt, "<OMI>1</OMI>", status); 
 }
 return res;
}

/*-----------------------------------------------------------------*/
/*! send the answer : if value==valueref then 
 send a completed message  */
/*-----------------------------------------------------------------*/
static int server_sendreplycheckdouble(SCSCP_incomingclient *incomingclient, SCSCP_returnoptions* returnopt, SCSCP_status *status, 
                          int res1, double value, double valueref)
{
 int res;
 if (res1!=1 || value!=valueref)
 {
   char buffer[128];
   sprintf(buffer, "%23.16E %23.16E", value, valueref);
   SCSCP_ss_sendterminatedstr(incomingclient, returnopt, "scscp1", "error_system_specific", buffer, status);
   res = 0;
 }
 else
 {
    res = SCSCP_ss_sendcompletedstr(incomingclient, returnopt, "<OMI>1</OMI>", status); 
 }
 return res;
}

/*-----------------------------------------------------------------*/
/*! process the procedure call */
/*-----------------------------------------------------------------*/
static int  processcall(SCSCP_incomingclient *incomingclient, SCSCP_status *status,int typeanswer)
{
 int res, resopt;
 int res1=0;
 SCSCP_calloptions options, options2;
 SCSCP_returnoptions returnopt;
 SCSCP_msgtype msgtype;
 size_t timeusage, memsize;
 int debuglevel;
 SCSCP_option_return returntype;
 static char *buffer;
 static int counter=0;
 SCSCP_xmlnodeptr ptr;
 const char *valuestr = NULL;
 int valueint = -1, valueintref;
 const char *valuestrref;
 double valuedbl = 1E300;
 
 res = SCSCP_co_init(&options, status);
 res = SCSCP_ro_init(&returnopt, status);
 if (res) 
 {
     res = SCSCP_ss_callrecvheader(incomingclient, &options, &msgtype, status);
     if (res || typeanswer==28)
     {
      const char *callid;
      if (!SCSCP_co_get_callid(&options, &callid, status)) callid="N/A client id";
      SCSCP_ro_set_callid(&returnopt, callid, status);
      switch(msgtype)
      {
       case SCSCP_msgtype_ProcedureCall : 
            /*printf("Procedure Call '%s'\n", callid);*/
            switch(typeanswer)
            {
             case 0: 
               res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, 
                              "<OMI>0</OMI>", status); 
               break;
               
             case 1: 
               SCSCP_ro_set_runtime(&returnopt, 55, status);
               SCSCP_ro_set_memory(&returnopt, 100, status);
               SCSCP_ro_set_message(&returnopt, "my information message from libSCSCP", status);
               
               res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, 
                              "<OMI>0</OMI>", status); 
               if (res==0) printf("SCSCP_ss_sendcompletedstr failed! status=%d.\n",SCSCP_status_is(status));
               break;

             case 2: 
               res = SCSCP_ss_sendcompletedstr(incomingclient,  &returnopt, 
                              "<OMS cd=\"alg1\" name=\"zero\" /><OMS cd=\"arith1\" name=\"abs\" />", status); 
               if (res==0) printf("SCSCP_ss_sendcompletedstr failed! status=%d.\n",SCSCP_status_is(status));
               break;               

             case 3: 
               res = SCSCP_ss_sendterminatedstr(incomingclient, &returnopt, "scscp1", "error_system_specific",
                              "unknown symbol", status); 
               if (res==0) printf("SCSCP_ss_sendterminatedstr failed! status=%d.\n",SCSCP_status_is(status));
               break;
               

             case 4: 
               resopt = SCSCP_co_get_runtimelimit(&options, &timeusage, status);
               if (resopt) 
                  SCSCP_debugprint("runtime limit = %lld\n", (long long)timeusage);
               else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNRUNTIME)
                  SCSCP_debugprint("runtime limit not available\n");
                else res = 0;
               }
               resopt = SCSCP_co_get_minmemory(&options, &memsize, status);
               if (resopt) 
                  SCSCP_debugprint("minimum memory = %lld\n", (long long)memsize);
               else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNMINMEMORY)
                  SCSCP_debugprint("minimum memory not available\n");
                else res = 0;
               }
               
               resopt = SCSCP_co_get_maxmemory(&options, &memsize, status);
               if (resopt) 
                  SCSCP_debugprint("maximum memory = %lld\n", (long long)memsize);
               else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNMAXMEMORY)
                  SCSCP_debugprint("maximum memory not available\n");
                else res = 0;
               }
               
               resopt = SCSCP_co_get_debuglevel(&options, &debuglevel, status);
               if (resopt) 
                  SCSCP_debugprint("debug level = %d\n", debuglevel);
               else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNDEBUGLEVEL)
                  SCSCP_debugprint("debug level not available\n");
                else res = 0;
               }
               
               resopt = SCSCP_co_get_returntype(&options, &returntype, status);
               if (resopt) 
                  SCSCP_debugprint("return type = %d\n", (int)returntype);
               else 
               {
                if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNRETURNTYPE)
                  SCSCP_debugprint("return type not available\n");
                else res = 0;
               }
               
               res = SCSCP_ss_sendcompletedstr(incomingclient,  &returnopt,  "<OMI>0</OMI>", status); 
               if (res==0) printf("SCSCP_ss_sendcompletedstr failed! status=%d.\n",SCSCP_status_is(status));
               break;               

             case 6: 
               res = SCSCP_ss_infomessagesend(incomingclient,"debugging command from server", status); 
               if (res==0) printf("SCSCP_ss_infomessagesend failed! status=%d.\n",SCSCP_status_is(status));
               if (strncmp(callid,"libSCSCP",strlen("libSCSCP"))==0)
               {
                res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, "<OMI>0</OMI>", status); 
               }
               else
               {
                res = SCSCP_ss_sendterminatedstr(incomingclient, &returnopt, "scscp1", "error_system_specific",
                           "bad call ID name", status); 
               }
               break; 
               
             case 7: 
               SCSCP_co_init(&options2, status);
               res = SCSCP_ss_callrecvheader(incomingclient, &options2, &msgtype, status);
               if (msgtype!=SCSCP_msgtype_Interrupt )
               {
                res = SCSCP_ss_sendterminatedstr(incomingclient, &returnopt, "scscp1", "error_system_specific",
                           "msgtype must be SCSCP_msgtype_Interrupt", status); 
               }
               else
               {
                const char *newcallidinter;
                res = SCSCP_co_get_callid(&options2, &newcallidinter, status);
                if (strcmp(newcallidinter,callid)!=0) 
                {
                 printf("invalid call id: %s %s\n", newcallidinter,callid);
                 res = 0;
                } 
                res1 = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, "<OMI>0</OMI>", status); 
                if (res) res = res1;
               }
               SCSCP_co_clear(&options2, status);
               break; 
               
             case 8: 
               if (counter==0)
               {
                buffer = SCSCP_ss_getxmlnoderawstring(incomingclient, SCSCP_xmlnode_getnext(SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status))), status);
                res = SCSCP_ss_sendcompletedstr(incomingclient,  &returnopt, 
                              "<OMR href=\"objectid@localhost\"/>", status);
                counter++;
               }
               else if (counter<=2)
               {
                res = SCSCP_ss_sendcompletedstr(incomingclient,  &returnopt, 
                              buffer, status);
                counter++;
               }
               else
               {
                res = SCSCP_ss_sendcompletedstr(incomingclient,  &returnopt, 
                              "", status);
               }
               break;
               
             case 9: 
               if (counter==0)
               {
                buffer = SCSCP_ss_getxmlnoderawstring(incomingclient, SCSCP_xmlnode_getnext(SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status))), status);
                res = SCSCP_ss_sendcompletedstr(incomingclient,  &returnopt, 
                              "<OMR href=\"objectid@localhost\"/>", status);
                counter++;
               }
               else
               {
                res = SCSCP_ss_sendterminatedstr(incomingclient, &returnopt, "scscp1", "error_system_specific",
                              "unknown symbol", status); 
               }
               break;               

             case 10: 
               res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, 
                              "<OMF dec=\"1.0\" />", status); 
               break;

             case 11: 
               res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, 
                              "<OMV name=\"myvar\" />", status); 
               break;

             case 12: 
               if (counter==0)
               {
                res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, 
                              "<OM:OMI  xmlns:OM=\"http://www.openmath.org/OpenMath\" >1</OM:OMI>", status); 
                counter++;
               }
               else
               {
                res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt, 
                              "<OM:OMI  xmlns:OM=\"http://www.openmath.org/OpenMath\" >2</OM:OMI>", status); 
               }
               break;

            case 13:
               ptr = SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status));
               if (ptr!=NULL)  res1 = SCSCP_xmlnode_readOMV( &ptr, &valuestr);
               res = server_sendreplycheck(incomingclient, &returnopt, status, res1, valuestr, "xy");
               break;

            case 14:
               ptr = SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status));
               if (ptr!=NULL)  res1 = SCSCP_xmlnode_readOMV(&ptr, &valuestr);
               res = server_sendreplycheck(incomingclient, &returnopt, status, res1, valuestr, getlongstring());
               break;

            case 15: valueintref = 1;
            case 16: if (typeanswer==16) valueintref = 127;
            case 17: if (typeanswer==17) valueintref = 32768;
            case 18: if (typeanswer==18) valueintref = 2147483647;
            case 19: if (typeanswer==19) valueintref = -2147483647-1; /*-2147483648; : remove a warning from gcc */
               ptr = SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status));
               if (ptr!=NULL)  res1 = SCSCP_xmlnode_readOMIint(&ptr, &valueint);
               res = server_sendreplycheckint(incomingclient, &returnopt, status, res1, valueint, valueintref);
               break;

            case 20: valuestrref = "+1125899906842624";
            case 21: if (typeanswer==21) valuestrref = "-1125899906842624";
            case 22: if (typeanswer==22) valuestrref = "+1125899906842624";
               ptr = SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status));
               if (ptr!=NULL)  res1 = SCSCP_xmlnode_readOMIstr(&ptr, &valuestr);
               res = server_sendreplycheck(incomingclient, &returnopt, status, res1, valuestr, valuestrref);
               break;

            case 23:
               ptr = SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status));
               if (ptr!=NULL)  res1 = SCSCP_xmlnode_readOMFdouble(&ptr, &valuedbl);
               res = server_sendreplycheckdouble(incomingclient, &returnopt, status, res1, valuedbl, 1.0E-10);
               break;

            case 24: valuestrref = "1234567890";
            case 25: if (typeanswer==25) valuestrref = getlongstring();
               ptr = SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status));
               if (ptr!=NULL)  res1 = SCSCP_xmlnode_readOMSTR(&ptr, &valuestr);
               res = server_sendreplycheck(incomingclient, &returnopt, status, res1, valuestr, valuestrref);
               break;

            case 26: valuestrref = "scscp://test1";
            case 27: if (typeanswer==27) valuestrref = getlongstring();
               ptr = SCSCP_xmlnode_getchild(SCSCP_ss_getxmlnode(incomingclient, status));
               if (ptr!=NULL)  res1 = SCSCP_xmlnode_readOMR(&ptr, &valuestr);
               res = server_sendreplycheck(incomingclient, &returnopt, status, res1, valuestr, valuestrref);
               break;

             case 28: 
               if (SCSCP_status_is(status)==SCSCP_STATUS_OPENMATHNOTVALID)
               {
                res = SCSCP_ss_sendterminatedstr(incomingclient, &returnopt, "scscp1", "error_system_specific",
                              SCSCP_status_strerror(status), status); 
                if (res==0) printf("SCSCP_ss_sendterminatedstr failed! status=%d.\n",SCSCP_status_is(status));
               }
               break;

            }
            break;

       default :
            if (typeanswer!=28) printf("unknown message type !!!\n"); 
            res = 0;
            break;
      }
     }
     else
     {
      /* if client close the connection => return -1 */
    /*printf("SCSCP_ss_callrecvheader failed! status=%d.\n",SCSCP_status_is(status));*/
      if (SCSCP_status_is(status)==SCSCP_STATUS_RECVQUIT) res = -1;
      if (typeanswer==28 && SCSCP_status_is(status)==SCSCP_STATUS_OPENMATHNOTVALID) 
      {
       printf("detect SCSCP_STATUS_OPENMATHNOTVALID\n");
       res = 1;
      }
     }
  SCSCP_co_clear(&options, status);
  SCSCP_ro_clear(&returnopt, status);
 }
 else
 {
  printf("SCSCP_ro_init failed status=%d.\n",SCSCP_status_is(status));
 }
 return res;
}

/*-----------------------------------------------------------------*/
/*! main program */
/*-----------------------------------------------------------------*/
int main(int argc, char *argv[])
{
/* printf("scscpservertest started with %d\n", atoi(argv[1]));*/
 return runserver(atoi(argv[1]), argc==3?atoi(argv[2]):-1);
}
