/* ***************************************************************** *
 * Copyright 1998 International Business Machines Corporation. All   *
 * Rights Reserved.                                                  *
 *                                                                   *
 * Please read this carefully.  Your use of this reference           *
 * implementation of certain of the IETF public-key infrastructure   *
 * specifications ("Software") indicates your acceptance of the      *
 * following.  If you do not agree to the following, do not install  *
 * or use any of the Software.                                       *
 *                                                                   *
 * Permission to use, reproduce, distribute and create derivative    *
 * works from the Software ("Software Derivative Works"), and to     *
 * distribute such Software Derivative Works is hereby granted to    *
 * you by International Business Machines Corporation ("IBM").  This *
 * permission includes a license under the patents of IBM that are   *
 * necessarily infringed by your use of the Software as provided by  *
 * IBM.                                                              *
 *                                                                   *
 * IBM licenses the Software to you on an "AS IS" basis, without     *
 * warranty of any kind.  IBM HEREBY EXPRESSLY DISCLAIMS ALL         *
 * WARRANTIES OR CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING,   *
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF       *
 * MERCHANTABILITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR    *
 * PURPOSE.  You are solely responsible for determining the          *
 * appropriateness of using this Software and assume all risks       *
 * associated with the use of this Software, including but not       *
 * limited to the risks of program errors, damage to or loss of      *
 * data, programs or equipment, and unavailability or interruption   *
 * of operations.                                                    *
 *                                                                   *
 * IBM WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL, *
 * INCIDENTAL, OR  INDIRECT DAMAGES OR FOR ANY ECONOMIC              *
 * CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN   *
 * IF IBM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  IBM  *
 * will not be liable for the loss of, or damage to, your records or *
 * data, or any damages claimed by you based on a third party claim. *
 *                                                                   *
 * IBM wishes to obtain your feedback to assist in improving the     *
 * Software.  You grant IBM a world-wide, royalty-free right to use, *
 * copy, distribute, sublicense and prepare derivative works based   *
 * upon any feedback, including materials, error corrections,        *
 * Software Derivatives, enhancements, suggestions and the like that *
 * you provide to IBM relating to the Software (this does not        *
 * include products for which you charge a royalty and distribute to *
 * IBM under other terms and conditions).                            *
 *                                                                   *
 * You agree to distribute the Software and any Software Derivatives *
 * under a license agreement that: 1) is sufficient to notify all    *
 * licensees of the Software and Software Derivatives that IBM       *
 * assumes no liability for any claim that may arise regarding the   *
 * Software or Software Derivatives, and 2) that disclaims all       *
 * warranties, both express and implied, from IBM regarding the      *
 * Software and Software Derivatives.  (If you include this          *
 * Agreement with any distribution of the Software or Software       *
 * Derivatives you will have met this requirement.)  You agree that  *
 * you will not delete any copyright notices in the Software.        *
 *                                                                   *
 * This Agreement is the exclusive statement of your rights in the   *
 * Software as provided by IBM.   Except for the rights granted to   *
 * you in the second paragraph above, You are not granted any other  *
 * patent rights, including but not limited to the right to make     *
 * combinations of the Software with products that infringe IBM      *
 * patents. You agree to comply with all applicable laws and         *
 * regulations, including all export and import laws and regulation. *
 * This Agreement is governed by the laws of the State of New York.  *
 * This Agreement supersedes all other communications,               *
 * understandings or agreements we may have had prior to this        *
 * Agreement.                                                        *
 * ***************************************************************** */

#include "transports.h"
#include "JonahIni.h"
#include <stdio.h>
#include <ApiNotify.h>
#include <Jonah.h>

#define CMP_PORT 829
#define TRANSPORT_TIMEOUT 10000

typedef struct {
  JnhTcpListener * thisPtr;
  TCP * tcp;
} tcpMsgBlock;

static void JnhTcpMessageRoutine(void * context) {
  tcpMsgBlock * ctx = (tcpMsgBlock *)context;
// This buffer will be used for the incoming message if it's big enough.
// If not, a buffer will be allocated from the heap.
  unsigned char buffer[1024];  
  unsigned char * buf = buffer;
  union {
    unsigned char nbwb[4];
    unsigned long nbwl;
  } netBytesWanted;
  uint32 error = 0;

  unsigned long bytesWanted;
  unsigned long bytesReceived = 0;
  size_t data_len;
  unsigned char * respBuffer;
  size_t resp_length;
  void (* freeRtn)(void *) = NULL;
  char message[BUFSIZ];

// Read message length...
  while (bytesReceived < 4) {
    if ((error = ctx->tcp->rcv(&netBytesWanted.nbwb[bytesReceived],
                               4-bytesReceived,
                               data_len,
                               TRANSPORT_TIMEOUT)) != 0) return;
    bytesReceived += data_len;
    if (ctx->thisPtr->shuttingDown) {
      goto done;
    };
  };
  bytesWanted = ntohl(netBytesWanted.nbwl);
  sprintf(message, "Waiting for %d bytes", bytesWanted);
  //  ApiDisplay(DISPLAY_LOGDEBUG, (utf8String)message);
  
// Allocate buffer if necessary...
  if (bytesWanted > sizeof(buffer)) {
    if ((buf = (unsigned char *)malloc(bytesWanted)) == NULL) {
      goto done;
    };
  };

// Read data...  
  bytesReceived = 0;
  while (bytesReceived < bytesWanted) {
    if ((error = ctx->tcp->rcv(buf+bytesReceived,
                               bytesWanted-bytesReceived,
                               data_len,
                               TRANSPORT_TIMEOUT)) != 0) return;
    bytesReceived += data_len;
    if (ctx->thisPtr->shuttingDown) {
      goto done;
    };
    sprintf(message, "Read %d bytes total = %d", data_len, bytesReceived);
    //    ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) message);
  };



// Call the user's action routine...
  ctx->thisPtr->callback.callback2(buf, bytesReceived, 
                                   respBuffer, resp_length, freeRtn,
                                   ctx->thisPtr->callback_arg);

  if (buf != buffer) free(buf);

  if (respBuffer != NULL) {

    netBytesWanted.nbwl = htonl(resp_length);

    if (ctx->tcp->send(&netBytesWanted.nbwb[0], 4, TRANSPORT_TIMEOUT)) {
      freeRtn(respBuffer);
      ctx->tcp->close();
      return;
    };
      
    if (ctx->tcp->send(respBuffer, resp_length, TRANSPORT_TIMEOUT)) {
      freeRtn(respBuffer);
      ctx->tcp->close();
      return;
    };
    freeRtn(respBuffer);
  };

  
// Now we're done.  Close the TCP connection...
  ctx->tcp->close();
  
  return;

done:
  ctx->tcp->close();
  return;

}

static void JnhTcpListenerRoutine(void * thisVoidPtr) {
// TCP listener thread routine
  TCP * connection;
  tcpMsgBlock block;
  JnhTcpListener * thisPtr = (JnhTcpListener *) thisVoidPtr;
// wait until we're allowed to listen...
//  while (!thisPtr->okToListen) JnhSleep(2000);
  if (thisPtr->tcp == NULL) thisPtr->tcp = new TCP();
// Error constructing the TCP object - abort listener
  if ((thisPtr->error = thisPtr->tcp->error) != 0) return;
  if ((thisPtr->error = thisPtr->tcp->setLocalPort(thisPtr->myPort)) != 0) return;
  if ((thisPtr->error = thisPtr->tcp->listen()) != 0) return;
// Now loop, accepting and dispatching incoming connections...
  while (!thisPtr->shuttingDown) {
    if ((connection = thisPtr->tcp->accept()) == NULL) {
      thisPtr->error = thisPtr->tcp->error;
    } else {
      block.thisPtr = thisPtr;
      block.tcp = connection;
      pkiStartTask(JnhTcpMessageRoutine, &block);  // Kick off the message task
    };
//    while (!thisPtr->okToListen) JnhSleep(2000);
  };
  thisPtr->error = thisPtr->tcp->close();
  return;

}



JnhTcpListener::JnhTcpListener(uint32 (* act_rtn)(unsigned char * msg, size_t length, 
                                                  unsigned char *&respMsg, size_t &respLength, 
                                                  void (*& freeRtn)(void * ptr), void * arg),
                               void * arg,
                               uint16 port) : JnhMsgListener(act_rtn, arg) {
  int thePort;
  tcp = NULL;
  if (port == 0) {
    IniReadInteger("Transport", "TCPPort", thePort, CMP_PORT);
    myPort = thePort;
  } else myPort = port;
  pkiStartTask(JnhTcpListenerRoutine, this);  // Kick off the listener task
}

JnhTcpListener::~JnhTcpListener() {
  if (tcp) tcp->close();
}

uint32 JnhTcpListener::listen(void) {
  okToListen = true;
  return 0;
}

uint32 JnhTcpListener::stop_listening(void) {
  okToListen = false;
  return 0;
}





JnhMsgListener::JnhMsgListener(uint32 (* act_rtn)(unsigned char * msg, size_t length, void * arg), void * arg) {
  callback_arg = arg;
  callback.callback1 = act_rtn;
  okToListen = true;
  shuttingDown = false;
  listenerThread = PKI_NULL_THREAD;
}

JnhMsgListener::JnhMsgListener(uint32 (* act_rtn)(unsigned char * msg, size_t length, 
                                                  unsigned char *& respMsg, size_t & respLength, 
                                                  void (*& freeRtn)(void *), void * arg), void * arg) {
  callback_arg = arg;
  callback.callback2 = act_rtn;
  okToListen = true;
  shuttingDown = false;
  listenerThread = PKI_NULL_THREAD;
}

JnhMsgListener::~JnhMsgListener() {
}

JnhMsgSender::JnhMsgSender(void) {
  error = 0;
}

JnhMsgSender::~JnhMsgSender() {
}


JnhTcpSender::JnhTcpSender(uint16 sourcePort) {
  tcp = new TCP();
  if (error = tcp->error) return;

  if (sourcePort) {
    tcp->setLocalPort(sourcePort);
  };

}

JnhTcpSender::~JnhTcpSender() {
  if (tcp) tcp->close();
}

uint32 JnhTcpSender::send(const unsigned char * msg, 
                          size_t length, 
                          const ipAddressV4 & target,
                          uint16 port) {
  
  union {
    unsigned char nbb[4];
    unsigned long nbl;
  } netBytes;
  int thePort;
  
  netBytes.nbl = htonl((unsigned long)length);
  
  if (port == 0) {
    IniReadInteger("Transport", "TCPPort", thePort, CMP_PORT);
    port = thePort;
  };

  if (error = tcp->open(target, port)) return error;
  if (error = tcp->send(&netBytes.nbb[0], 4, TRANSPORT_TIMEOUT)) {
    tcp->close();
    return error;
  };
  if (error = tcp->send(msg, length, TRANSPORT_TIMEOUT)) {
    tcp->close();
    return error;
  };
  tcp->close();
  return 0;
}


uint32 JnhTcpSender::send(const unsigned char * msg, 
                          size_t length, 
                          unsigned char * respBuffer,
                          size_t respBufferLength,
                          size_t * respLength,
                          const ipAddressV4 & target,
                          uint16 port) {
  union {
    unsigned char nbb[4];
    unsigned long nbl;
  } netBytes;
  int thePort;
  size_t bytesReceived;
  size_t data_len;
  size_t bytesWanted;

  *respLength = 0;

  netBytes.nbl = htonl((unsigned long)length);
  
  if (port == 0) {
    IniReadInteger("Transport", "TCPPort", thePort, CMP_PORT);
    port = thePort;
  };

  if (error = tcp->open(target, port)) return error;
  if (error = tcp->send(&netBytes.nbb[0], 4, TRANSPORT_TIMEOUT)) {
    tcp->close();
    return error;
  };
  if (error = tcp->send(msg, length, TRANSPORT_TIMEOUT)) {
    tcp->close();
    return error;
  };
  
  bytesReceived = 0;
  while (bytesReceived < 4) {
    if ((error = tcp->rcv(&netBytes.nbb[bytesReceived],
                          4-bytesReceived,
                          data_len,
                          TRANSPORT_TIMEOUT)) != 0) return error;
    bytesReceived += data_len;
  };
  
  bytesWanted = ntohl(netBytes.nbl);
  bytesReceived = 0;
  while (bytesReceived < bytesWanted) {
    if ((error = tcp->rcv(&respBuffer[bytesReceived],
                          respBufferLength-bytesReceived,
                          data_len,
                          TRANSPORT_TIMEOUT)) != 0) return error;
    bytesReceived += data_len;
  };
  *respLength = bytesReceived;
  tcp->close();
  return 0;
}


/*
  static int JnhMailListenerRoutine(JnhMailListener * thisPtr) {
  return 0;
}
*/
