/*-----------------------------------------------------------------*/
/*! 
  \file scscputil.c
  \brief SCSCP tools functions
  \author  M. Gastineau 
           Astronomie et Systemes Dynamiques, IMCCE, CNRS, Observatoire de Paris. 

   Copyright, 2008, 2010, 2012,  M. Gastineau, IMCCE-CNRS
   email of the author : gastineau@imcce.fr
  
  \bug M. GASTINEAU 12/09/08 : update for SCSCP 1.2
  \bug M. GASTINEAU 20/04/09 : update for SCSCP 1.3
  \bug M. GASTINEAU 28/04/09 : SCSCP_strdup accepts NULL as the 1st argument
*/
/*-----------------------------------------------------------------*/

/*-----------------------------------------------------------------*/
/* 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.
*/
/*-----------------------------------------------------------------*/

#include <stdio.h>
#if HAVE_CONFIG_H
#include "scscpconfig.h"
#endif /*HAVE_CONFIG_H*/
#if HAVE_WINDOWS_H
#include <windows.h>
#include <Winsock2.h>
#else
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#endif /*HAVE_WINDOWS_H*/
#if HAVE_STRING_H
#include <string.h>
#endif
#include <ctype.h>
#define __SCSCP_WITHIN_SCSCP
#include "scscp.h"
#include "scscpdebug.h"
#include "scscpinternal.h"
#include "scscpfileclient.h"
#include "scscpfileserver.h"
#include "scscputil.h"

/*-----------------------------------------------------------------*/
/* private functions */
/*-----------------------------------------------------------------*/
static int hostissameorderasnetwork(void);

/*-----------------------------------------------------------------*/
/*! initialize the windows socket DLL
    return 1 on success
*/
/*-----------------------------------------------------------------*/
int SCSCP_initsocket()
{
#if HAVE_WINDOWS_H
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 
  SCSCP_debugprint("SCSCP_initsocket() - enter\n");
  wVersionRequested = MAKEWORD( 2, 2 );
 
  err = WSAStartup( wVersionRequested, &wsaData );
  if ( err != 0 ) {
    /* Tell the user that we could not find a usable WinSock DLL. */
    SCSCP_debugprint("SCSCP_initsocket() - returns 0 (WSAStartup failed) \n");
    return 0;
  }
 
/* Confirm that the WinSock DLL supports 2.2.*/
 
 if ( LOBYTE( wsaData.wVersion ) != 2 ||HIBYTE( wsaData.wVersion ) != 2 ) 
 {
    /* Tell the user that we could not find a usable  WinSock DLL. */
    WSACleanup( );
    SCSCP_debugprint("SCSCP_initsocket() - returns 0 (version !=2.2) \n");
    return 0; 
 }

#endif
    SCSCP_debugprint("SCSCP_initsocket() - returns 1\n");
 return 1;
}

/*-----------------------------------------------------------------*/
/*!  allocate memory of ncount bytes (similar to malloc) 
  @param ncount (in) size in bytes to allocate
  @param status (inout) status
*/
/*-----------------------------------------------------------------*/
void* SCSCP_malloc(size_t ncount, SCSCP_status* status)
{
 void *pres = malloc(ncount);
 if (pres==NULL) SCSCP_status_seterror(status, SCSCP_STATUS_NOMEM);
 return pres;
}
 
/*-----------------------------------------------------------------*/
/*!  duplicate a string (similar to strdup) 
  @param src (in) string to duplicate (could be NULL)
  @param status (inout) status
*/
/*-----------------------------------------------------------------*/
char* SCSCP_strdup(const char* src, SCSCP_status* status)
{
  char *dst = NULL;
  if (src)
  {
   dst = (char*)SCSCP_malloc(strlen(src)+1, status);
   if (dst) strcpy(dst, src);
  }
  return dst; 
}

/*------------------------------------------------------------------*/
/*  snprintf                                                        */                     
/*------------------------------------------------------------------*/
#if !HAVE_SNPRINTF
int snprintf(char *string, size_t n, const char *format, ...)
{
 int res;
 va_list args;
 va_start(args, format);
 res = vsprintf(string, format, args);
 va_end(args);
 return res;
}
#endif 

/*------------------------------------------------------------------*/
/*  strtok_r                                                        */
/*------------------------------------------------------------------*/
#if !HAVE_STRTOK_R
char * strtok_r(char * str, const char * sep, char ** lasts)
{
    char *res = NULL;
    char *pcur;
    const char *psep;
    char *pstart = NULL;

    if(str!=NULL)
    {//first call
        pstart = str;
    }
    else if (*lasts!=NULL)
    {
        pstart = *lasts;
    }
    
    if (pstart!=NULL)
    {
       for (pcur=pstart; *pcur!='\0'; pcur++)
        {
            for (psep=sep; *psep!='\0'; psep++)
            {
                if (*psep==*pcur)
                {
                    *pcur = '\0';
                    *lasts = pcur+1;
                    res = pstart;
                    return res;
                }
            }
        }
        res = pstart;
        *lasts = NULL;
    }
    return res;
}
#endif

/*-----------------------------------------------------------------*/
/*!  find the beginning of the version string in c.
  replace the last " of the versions by '\0'.
  return the address just after version="
  return NULL on error.
  @param c (in) status to be updated
  @param scscp_versions (in) name of string version
*/
/*-----------------------------------------------------------------*/
char * SCSCP_findPIstring(char *c, const char*versionname)
{
  char *psubstr = NULL;
  char *lastquote;
  const char *begin="<?scscp";
  
  SCSCP_debugprint("SCSCP_findPIstring(%s, %s) - enter\n",c,versionname);
  
  if (strncmp(begin, c,strlen(begin))==0) psubstr = c+strlen(begin);
  
  if (psubstr)
  {
      while (*psubstr!='\0' && isspace(*psubstr)) psubstr++;
    
      while (psubstr!=NULL && *psubstr!='\0' 
          && strncmp(versionname, psubstr,strlen(versionname))!=0)
      {
        while (*psubstr!='\0' && !isspace(*psubstr) && *psubstr!='=') psubstr++;
        while (*psubstr!='\0' && isspace(*psubstr)) psubstr++;
        if (*psubstr=='=')
        {
         psubstr=strchr(psubstr,'\"');
         if (psubstr==NULL) break;
         psubstr=strchr(psubstr+1,'\"');
         if (psubstr==NULL) break;
         psubstr++;
         while (*psubstr!='\0' && isspace(*psubstr)) psubstr++;
        }
     }
      
      
      if (psubstr!=NULL && *psubstr!='\0')
      {
       psubstr=strchr(psubstr,'\"');
       if (psubstr!=NULL)
        {
         psubstr++;
         lastquote = strchr(psubstr,'\"');
         if (lastquote) 
           *lastquote = '\0';
         else 
           psubstr = NULL;
        }
      }
      else
      {
       psubstr = NULL;
      }  
  }
  
  SCSCP_debugprint("SCSCP_findPIstring() -returns %s\n", psubstr);
  return psubstr;
}


/*-----------------------------------------------------------------*/
/*!  find the string substr in a binary  buffer of length len (could contains some \0).
  return the address of substr
  return NULL if not found.
  @param buffer (in) binary buffer
  @param substr (in) string to search (length >0)
  @param len (in) length of buffer
*/
/*-----------------------------------------------------------------*/
const char *SCSCP_findstr(const char *buffer, const char *substr, int len)
{
 const char *pos;
 int curpos =  0;
 int bfound = 1;
 size_t lensubstr;
 
 SCSCP_debugprint("SCSCP_findstr(%p,%s, %d) - enter\n", buffer, substr, len);
 
 lensubstr = strlen(substr);
 do
 {
  pos = (const char *)memchr(buffer+curpos, substr[0], len-curpos);
  if (pos!=NULL)
  {
   curpos = pos-buffer;
   if (len-curpos>=lensubstr) bfound = memcmp(pos,substr, lensubstr*sizeof(char));
   curpos++;
  }
 } while (bfound!=0 && pos!=NULL);
 
 SCSCP_debugprint("SCSCP_findstr() -returns %p\n", pos);
 return pos;
}

/*-----------------------------------------------------------------*/
/*! allocate the buffer list and set the next field to next
  @param next (inout) buffer to attach at the end
  @param minsize (in) minimal size of the buffer
*/
/*-----------------------------------------------------------------*/
SCSCP_buffer_listptr SCSCP_buffer_list_init(SCSCP_buffer_listptr next, size_t minsize)
{
 const size_t len = minsize+2*sizeof(SCSCP_buffer_list)<16000*4?16000*4:(minsize+sizeof(SCSCP_buffer_list)+2);
 SCSCP_buffer_listptr node;
 SCSCP_debugprint("SCSCP_buffer_list_init(%p, %lu) - enter len=%lu\n",next, (unsigned long) minsize, (unsigned long)len);
 node = (SCSCP_buffer_listptr)SCSCP_malloc(len, SCSCP_STATUS_IGNORE);
 if (node)
 {
  node->m_next = next;
  node->m_len  = len-sizeof(SCSCP_buffer_list);
  node->m_data = node+1;
 }
 SCSCP_debugprint("SCSCP_buffer_list_init() - return %p m_data=%p\n", node, node->m_data);
 return node;
}

/*-----------------------------------------------------------------*/
/*! clear the buffer list 
  @param buffer (inout) buffer to be destroyed
*/
/*-----------------------------------------------------------------*/
void SCSCP_buffer_list_clear(SCSCP_buffer_list *buffer)
{
 SCSCP_buffer_list *tmp;
 SCSCP_debugprint("SCSCP_buffer_list_clear(%p) - enter\n",buffer);
 while (buffer!=NULL)
 {
  tmp = buffer->m_next;
  free(buffer);
  buffer = tmp;
 }
 SCSCP_debugprint("SCSCP_buffer_list_clear() - exit\n");
}

/*-----------------------------------------------------------------*/
/*! return 1 if host has same byte order as network byteorder */
/*-----------------------------------------------------------------*/
static int hostissameorderasnetwork(void)
{
  union { long l; char c[sizeof (long)]; } u;
  u.l = 1;
  return (u.c[sizeof (long) - 1] == 1);
}

/*-----------------------------------------------------------------*/
/*! swap the bytes in network byte order of the double x 
 @param x (inout) double
*/
/*-----------------------------------------------------------------*/
double SCSCP_htond(double x)
{
  double res;
  /* tests for big-endian : same as network order */
  if (hostissameorderasnetwork())
  { /* already in network order : no swap */
   res = x;
  }
  else
  { /* little endian => network order  : swap */
   unsigned char *cx=(unsigned char*) &x;
   unsigned char *cres=(unsigned char*) &res;
   int j;
   for (j=0; j<sizeof(double); j++) cres[j]=cx[sizeof(double)-1-j];
  }
  return res;
}
/*-----------------------------------------------------------------*/
/*! swap the bytes from network byte order to host of the double x 
 @param x (inout) double
*/
/*-----------------------------------------------------------------*/
double SCSCP_ntohd(double x)
{
  double res;
  /* tests for big-endian : same as network order */
  if (hostissameorderasnetwork())
  { /* already in network order : no swap */
   res = x;
  }
  else
  { /* network order => little endian   : swap */
   unsigned char *cx=(unsigned char*) &x;
   unsigned char *cres=(unsigned char*) &res;
   int j;
   for (j=0; j<sizeof(double); j++) cres[j]=cx[sizeof(double)-1-j];
  }
  return res;
}

