/* ***************************************************************** *
 * 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 <stdlib.h>
#include <stdio.h>
#include <Jonah.h>
#include <JonahIni.h>
#include <transports.h>
#include <JonahOst.h>
#include <messaging.h>
#include <ApiNotify.h>
#include <winsock2.h>
#include <apimsg.h>
#include <jnhTimer.h>
#include <tid.h>

void
release_reply(void *reply) 
{
  ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) "Reply has been released");
  free(reply);
  return;
}

static uint32
SignedCert()
{
  if (IniAmICA()) {
    return ObjStCACertSigned;
  } else if (IniAmIRA()) {
    return ObjStRACertCAApproved;
  } else return 0;
}

static uint32
RejectedCert()
{
  if (IniAmICA()) {
    return ObjStCACertReqRejected;
  } else if (IniAmIRA()) {
    return ObjStRACertReqRejecting;
  } else return 0;
}

uint32 
accept_message(unsigned char *msg, size_t length, unsigned char *&reply, 
                size_t &replylen, void (*& freeRtn) (void *ptr), void *type)
{
  
  uint32                objClass;
  uint32		origObjClass;
  uint32                status;
  uint32                state;
  uint32                rsize = 0;
  uint32                tref;
  unsigned char         *pkixmsg = NULL;
  unsigned char         *r = NULL;;
  unsigned char         *tr = NULL;
  unsigned char         *message = NULL;
  unsigned char         *msgTID;
  unsigned char         *newTID;
  unsigned int          len;
  unsigned int          pkixmsgLen;
  unsigned int          msgTIDlen;
  unsigned int          newTIDlen;
  unsigned int          objsid;
  time_t                now;
  time_t                pollTime;  
  bool                  pollAgain = false;
  bool                  deleteObj = false;
  ObjStoreData          *objsPtr = NULL;
  PKIMessage            pmsg;
  r_buffer_t            pbuf;
  buffer_t              sender;
  char                  dispmsg[BUFSIZ];


  if ((int) type == TCP_LISTNER) {
    switch(msg[0]) {
    case MSG_REQ:  // Contains a ASN.1 encoded PKIX message
      do {
        ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) "PKIX Message Recieved");
        if ((pkixmsg = (unsigned char *) malloc(length)) == NULL) {
          throw "Out of memory error in accept_message";
        } 
        pkixmsgLen = length - 1;
        memset(pkixmsg, 0, length);
        memcpy(pkixmsg, &msg[1], length - 1);
        pbuf.data = pkixmsg;
        pbuf.data_len = pkixmsgLen;
        if ((status = pmsg.read(pbuf))) {
          break;
        }
        if (!pmsg.header.transactionID.value.is_present()) {
          status = API_MISSING_TRANSACTION_ID;
          break;
        }
        if ((status = pmsg.header.transactionID.value.
             get_value(msgTID, msgTIDlen))) {
          break;
        }
        if ((status = tid_get_key(msgTID, &objsid))) {
          break;
        }
        // This should be the CA
        if (objsid == 0) {
          if (!IniAmICA()) {
            status = API_BAD_TRANSACTION;
            break;
          }
          ApiDisplay(DISPLAY_LOGDEBUG, 
                     (utf8String) "PKIX message for non-existant object");
          if ((status = JnhCreateObject(0, &objsPtr, &objsid))) {
            break;
          }
          if ((status = tid_add_key(msgTID, objsid, &newTID, &newTIDlen))) {
            break;
          }
          if ((status = objsPtr->transactionID.value.
               set_value(newTID, newTIDlen))) {
            break;
          }
          if (pmsg.header.sender.selected() != 2) { // XXX x.500 names
            status = API_UNSUPPORTED_NAME_TYPE;
            break;
          }
          if ((status = pmsg.header.sender.directoryname.
               get_value_UTF8(sender))) {
            break;
          }
          objsPtr->recipient.value.select(2);
          if ((status = objsPtr->recipient.value.directoryname.
               set_value_UTF8(sender))) {
            break;
          }
          objsPtr->recipient.value.select(2);
          if ((status = objsPtr->recipientURL.value.
               set_value((unsigned char *) "", 0))) {
            break;
          }
          if ((status = JnhSynchObject(objsid))) {
            break;
          }
          objsPtr = NULL;
          if ((status = JnhLockObject(objsid))) {
            break;
          }
          if ((status = JnhGetObjectModify(objsid, &objClass, &objsPtr))) {
            break;
          }
        } else {
          if ((status = JnhLockObject(objsid))) {
            break;
          }
          if ((status = JnhGetObjectModify(objsid, &objClass, &objsPtr))) {
            break;
          }
        }
	origObjClass = objClass;
        if ((status = process_pkix_msg(&pmsg, objsPtr, objsid))) {
          break;
        }
      } while(0);
      if (pkixmsg) free(pkixmsg);
      if (newTID) tid_release(newTID);
      if (!status) {
        rsize = MSG_FLAG_SIZE + POLL_REFERENCE_SIZE + POLL_CHECK_BACK_SIZE;
        if ((r = (unsigned char *) malloc(rsize)) == NULL) {
          throw "Out of memory error in accept_message";
        }
        memset(r, 0, rsize);
        tr = r;
        *tr = POLL_REP;
        tr = tr + MSG_FLAG_SIZE;
        tref = htonl(objsid);
        memcpy(tr, (void *) &tref,  POLL_REFERENCE_SIZE);
        tr = tr + POLL_REFERENCE_SIZE;
        time(&now);
        pollTime = htonl(now + DEFAULT_POLL_TIME);
        memcpy(tr, (void *) &pollTime, POLL_CHECK_BACK_SIZE);
        sprintf(dispmsg, "Poll Reference is %d", objsid);
        ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
      } else {
        sprintf(dispmsg, "Error status is %d", status);
        ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
        rsize = MSG_FLAG_SIZE + (POLL_REFERENCE_SIZE*2);
        if ((r = (unsigned char *) malloc(rsize)) == NULL) {
          throw "Out of memory error in accept_message";
        };
        tr = r;
        *tr = ERROR_MSG_REP;
        tr = tr + MSG_FLAG_SIZE;
        pollTime = htonl(status);
        memcpy(tr, (void *) &pollTime, sizeof(pollTime));
        status = 0;
      }
      break;
      case POLL_REQ:    // Request status
        do {
          memcpy(&tref, ++msg, POLL_REFERENCE_SIZE);
          objsid = ntohl(tref);
          sprintf(dispmsg, "Received poll request for %d", objsid);
          ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
          if ((status = JnhLockObject(objsid))) {
            break;
          }
          if ((status = JnhGetObjectModify(objsid, &objClass, &objsPtr))) {
            break;
          }
          state = (objClass & 0xffff0000);
	  origObjClass = objClass;
          if (state == SignedCert() || state == RejectedCert()) {
            if ((status = generate_pkix_msg(objsPtr, &message, &len))) {
              break;
            }
            rsize = MSG_FLAG_SIZE + len; 
            if ((r = (unsigned char *) malloc(rsize)) == NULL) {
              throw "Out of memory error in accept_message";
            }
            tr = r;
            *tr = FINAL_MSG_REP;
            tr = tr + MSG_FLAG_SIZE;
            memcpy(tr, message, len);
	    deleteObj = TRUE;
          } else {
            pollAgain = true;
          }
        } while(0);
        if (status) {
          sprintf(dispmsg, "Error status is %d", status);
          ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
          rsize = MSG_FLAG_SIZE + (POLL_REFERENCE_SIZE*2);
          if ((r = (unsigned char *) malloc(rsize)) == NULL) {
            throw "Out of memory error in accept_message";
          };
          tr = r;
          *tr = ERROR_MSG_REP;
          tr = tr + MSG_FLAG_SIZE;
          pollTime = htonl(status);
          memcpy(tr, (void *) &pollTime, sizeof(pollTime));
          status = 0;
        } else if (pollAgain == true) {
          rsize = MSG_FLAG_SIZE + POLL_REFERENCE_SIZE + POLL_CHECK_BACK_SIZE;
          if ((r = (unsigned char *) malloc(rsize)) == NULL) {
            throw "Out of memory error in accept_message";
          }
          memset(r, 0, rsize);
          tr = r;
          *tr = POLL_REP;
          tr = tr + MSG_FLAG_SIZE;
          tref = htonl(objsid);
          memcpy(tr, (void *) &tref,  POLL_REFERENCE_SIZE);
          tr = tr + POLL_REFERENCE_SIZE;
          time(&now);
          pollTime = htonl(now + DEFAULT_POLL_TIME);
          memcpy(tr, (void *) &pollTime, POLL_CHECK_BACK_SIZE);
          sprintf(dispmsg, "Sending back pollReference = %d time = %s",
                  objsid, ctime(&pollTime));
          ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
        } 
        break;
    default:
      status = API_UNKNOWN_MESSAGE_TYPE; 
      break;
    }
  } else {
    status = API_UNKNOWN_LISTNER_TYPE;
  }
  JnhGetObjectFlags(objsid, &objClass);
  if (!status) {
    reply = r;
    replylen = rsize;
    freeRtn = release_reply;
    sprintf(dispmsg, "Sending backing message length = %d bytes id = %d", 
	    rsize, objsid);
    ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
    if (deleteObj == TRUE) {
      if (IniAmICA()) {
	objClass = ObjStCAGone;
      } else if (IniAmIRA()) {
	objClass = ObjStRAGone;
      } else {
	objClass = ObjStEEGone;
      }
      JnhDeleteObject(objsid);
      sprintf(dispmsg, "Object %d is gone.", objsid);
      ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
    }
  } else {
    objClass = (objClass | ObjFlagError);
    sprintf(dispmsg, "ACCEPT_MESSAGE error %d", status);
    ApiDisplay(DISPLAY_LOGERROR, (utf8String) dispmsg);
  }
  if (objClass != origObjClass) {
    ApiNotify(objsid, objClass);
  }
  JnhSynchObject(objsid);
  return status;
}

void
JnhListnerInitialize(void)
{
  JnhTcpListener        *listener;
  if (IniAmIRA() || IniAmICA()) {
    listener = new JnhTcpListener(accept_message, (void *) TCP_LISTNER);
  } 
  return;
}

void
reset_polling(uint32 id, uint32 state)
{
  uint32                status;
  uint32                objClass;
  uint32                eventId;
  const ObjStoreData    *objsPtr = NULL;  
  long                  pollTime;
  long                  pollReference;
  char                  dispmsg[BUFSIZ];

  sprintf(dispmsg, "reset_polling called for Object %d", id);
  ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
  do {
    if ((status = JnhLockObject(id))) {
      break;
    }
    if ((status = JnhGetObject(id, &objClass, &objsPtr))) {
      break;
    }
    objsPtr->pollTime.value.get_value(pollTime);
    objsPtr->pollReference.value.get_value(pollReference);
    sprintf(dispmsg, "Poll Time = %d Poll Reference = %d", pollTime, 
	    pollReference);
    ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
    if (pollTime && pollReference) {
      sprintf(dispmsg, "Re-scheduling poll for %d (reference = %d, time = %s)",
              id, pollReference, ctime(&pollTime));
      ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
      if ((status = JnhRegisterEventAbs(pollTime, poll, (void *) id, false, 
                                        &eventId))) {
        break;
      }
      sprintf(dispmsg, "No need to reschedule %d (time = %d reference = %d)",
	      id, pollTime, pollReference);
      ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
    }
  } while(0);
  JnhDiscardObject(id);
  return;
}

void
JnhPollInitialize(void)
{
  JnhListSurrogateObjects(&reset_polling);
  return;
}
