/* ***************************************************************** *
 * 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 <stdio.h>
#include <Jonah.h>
#include <base64.h>
#include <tid.h>
#include <x509.h>
#include <pkix_messages.h>
#include <PreReg.h>
#include <ObjectStore.h>
#include <ObjectDefs.h>
#include <JonahOst.h>
#include <jnhTimer.h>
#include <messaging.h>
#include <ApiNotify.h>
#include <apimsg.h>
#include <jkl.h>

// JNH_RA_Preregister_User -- Creates a pre-registration record in 
// preperation for end user registration
//
// ARGUMENTS:
//      CAName (in)             -- CA to recieve this request
//      UserName (in)           -- Entity requesting certificate
//      ExpirationSeconds(in)   -- Timeout for the pre-registration data
//      Password                -- Password to encrypt record
//      PreRegistrationRecord   -- Data to be given to requestor

uint32
JNH_preregister_user(const utf8String PreRegistrationRecord,
                     const utf8String passwd, uint32 *ReqId)
{
  CertReqMsg            *reqPtr = NULL;
  PreRegRecord          preRegRec;
  ObjStoreData          *objsPtr;
  r_buffer_t            buf;
  uint32                encSz;
  uint32                encPreRegLen;
  uint32                preRegLen;
  uint32                status;
  uint32                raURLLen;
  uint32                tidLen;
  uint32                objsid;
  uint32                objClass;
  unsigned char         *preReg = NULL;
  unsigned char         *encPreRegRec = NULL;
  unsigned char         *raURL= NULL;
  unsigned char         *tid = NULL;
  unsigned char         *newtid = NULL;
  buffer_t              raName;
  buffer_t              issuer;
  buffer_t              endEntity;
  unsigned char         message[512];
  
  ApiDisplay(DISPLAY_LOGDEBUG, 
             (utf8String)"Processing a preregistration record");
  do {
    encSz = strlen((char *) PreRegistrationRecord);
    if ((encPreRegRec = (unsigned char *) malloc(encSz)) == NULL) {
      ApiDisplay(DISPLAY_URGENTERROR, 
                 (utf8String)"Can't allocate memory for unwrapped prereg rec");
      throw "Out of memory in preregister_user";
    }
    if ((encPreRegLen = base64_decode((char *) PreRegistrationRecord, 
                                      encPreRegRec)) == -1)  {
      free(encPreRegRec);
      ApiDisplay(DISPLAY_LOGERROR, 
                 (utf8String)"Error decoding base64 for prereg record");
      status = API_BASE64DECODE_FAIL;
      break;
    }
#if 0 // Deal with this later. Right now we are clear text
    if ((status = decrypt_buffer(encPreRegRec, encPreRegLen, password, 
                                 &preReg &preRegLen))) {
      free(encPreRegRec);
      sprintf((char *)message, "Error %lu decrypting preregistration record", 
              status);
      ApiDisplay(DISPLAY_LOGERROR, 
                 message);
      break;
  }
#else 
    preRegLen = encPreRegLen;
    if ((preReg = (unsigned char *) malloc(preRegLen)) == NULL) {
      ApiDisplay(DISPLAY_URGENTERROR, 
                 (utf8String)"Can't allocate buffer for decrypted prereg rec");
      throw "Out of memory in preregister_user";
    }
    memcpy(preReg, encPreRegRec, preRegLen);
#endif
    free((unsigned char *) encPreRegRec);
    buf.data = preReg;
    buf.data_len = preRegLen;
    if ((status = preRegRec.read(buf))) {
      sprintf((char *)message, "Error %lu parsing prereg record", status);
      ApiDisplay(DISPLAY_LOGERROR, 
                 message);
      break;
    }
    if ((status = preRegRec.RA.directoryname.get_value_UTF8(raName))) {
      sprintf((char *)message, "Error %lu extracting RAname from prereg rec", 
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = preRegRec.raURL.get_value(raURL, raURLLen))) {
      sprintf((char *)message, "Error %lu extracting RA URL from prereg rec", 
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = preRegRec.transactionID.get_value(tid,tidLen))) {
      sprintf((char *)message, 
              "Error %lu extracting transaction ID from prereg record",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = preRegRec.CA.directoryname.get_value_UTF8(issuer))) {
      sprintf((char *)message, 
              "Error %lu extracting CAname from prereg record",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = preRegRec.endEntity.directoryname.
         get_value_UTF8(endEntity))) {
      sprintf((char *)message, 
              "Error %lu extracting my name from prereg record",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
#if 0 // Not yet, see above comment
    preRegRec.keyData.get_value(key, keyLen);
    preRegRec.protectionAlg.get_value(oid, oidLen);
#endif
    objClass = (ObjClStActive | ObjClTypeCert |  ObjStEECertReqActive);
    if ((status = JnhCreateObject(objClass, &objsPtr, &objsid))) {
      sprintf((char *)message, 
              "Error %lu creating objectstore slot for certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    sprintf((char *)message, "Allocated object-id %lu for this request",
            objsid);
    ApiDisplay(DISPLAY_LOGDEBUG,  message);
    if ((status = objsPtr->sender.value.select(2))) {
      sprintf((char *)message, 
              "Error %lu in sender.value.select(2) when creating cert req",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = objsPtr->sender.value.directoryname.
         set_value_UTF8(endEntity))) {
      sprintf((char *)message, 
	      "Error %lu setting sender name in certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = objsPtr->recipient.value.select(2))) {
      sprintf((char *)message, 
              "Error %lu in recipient.value.select(2) when creating cert req",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = objsPtr->recipient.value.directoryname.
         set_value_UTF8(raName))) {
      sprintf((char *)message, 
              "Error %lu setting recipient name in certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = objsPtr->recipientURL.value.set_value(raURL, raURLLen))) {
      sprintf((char *)message, 
              "Error %lu setting recipient URL in certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = tid_add_key(tid, objsid, &newtid, &tidLen))) {
      sprintf((char *)message, 
              "Error %lu in tid_add_key when creating certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = objsPtr->transactionID.value. set_value(newtid, tidLen))) {
      sprintf((char *)message, 
              "Error %lu getting transactionId when creating cert req",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = objsPtr->msg.value.select(1))) {
      sprintf((char *)message, 
              "Error %lu from msg.value.select(1) when creating cert req",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((reqPtr = objsPtr->msg.value.ireq.value.add_child()) == NULL) {
      sprintf((char *)message, 
              "Error %lu adding ireq child when creating certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = reqPtr->certReq.certReqId.set_value(0))) { // xxx hardcode 0
      sprintf((char *)message, 
              "Error %lu setting certReqId when creating certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;
    }
    if ((status = reqPtr->certReq.certTemplate.issuer.value.
         set_value_UTF8(issuer))) {
      sprintf((char *)message, 
             "Error %lu setting issuer name when creating certificate request",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);

      break;
    }
    if ((status = reqPtr->certReq.certTemplate.subject.value.
         set_value_UTF8(endEntity))) {
      sprintf((char *)message, 
              "Error %lu setting subject name when creating cert req",
              status);
      ApiDisplay(DISPLAY_LOGERROR, message);
      break;

    }

  } while(0);
  if (status) {
    ApiDisplay(DISPLAY_LOGDEBUG, 
               (utf8String)"Discarding objectstore slot because of an error");
    JnhDiscardObject(objsid);
  } else {
    ApiDisplay(DISPLAY_LOGDEBUG, (utf8String)"Saving objectstore slot");
    status = JnhSynchObject(objsid);
    if (status) {
      sprintf((char *)message, 
              "Error %lu saving objectstore slot %d",
              status, 
              objsid);
      ApiDisplay(DISPLAY_LOGERROR, message);
    } else {
      ApiDisplay(DISPLAY_LOGDEBUG, (utf8String)"Saved certificate request");
    };
    ApiNotify(objsid, objClass);
    *ReqId = objsid;
  }
  return status;
}

uint32
JNH_register_user(uint32 reqId)
{
  uint32                status = 0;
  unsigned char         *message;
  unsigned char         *url;
  unsigned char         *reply;
  uint32                replyLen;
  uint32                urlLen;
  uint32                messageLen;
  uint32                objClass;
  uint32                pollTime;
  uint32                pollReference;
  uint32                eventId;
  ObjStoreData          *objsPtr;

  do {
    if ((status = JnhLockObject(reqId))) {
      break;
    }
    if ((status = JnhGetObjectModify(reqId, &objClass, &objsPtr))) {
      break;
    }
    if ((status = generate_pkix_msg(objsPtr, &message, &messageLen))) {
      break;
    }

    status = objsPtr->recipientURL.value.get_value(url, urlLen);
    // make object store object surrogate.
    if ((status = send_message(message, messageLen, MSG_REQ, url, 
                               &pollReference, &pollTime, &reply, 
                               &replyLen))) {
      break;
    }
    if ((status = objsPtr->pollReference.value.set_value(pollReference))) {
      break;
    }
    if ((objsPtr->pollTime.value.set_value(pollTime))) {
      break;
    }
    if ((status = JnhRegisterEventAbs(pollTime, poll, (void *) reqId, 
                                      false, &eventId))) {
      break;
    }
    if (pollReference) {
      objClass = (ObjClStSurrogate | ObjClTypeCert  | 
                  ObjStEECertReqSubmittedS);
      if ((status = JnhSetObjectFlags(reqId, objClass))) {
        break;
      }
    } else {
      r_buffer_t        pbuf;
      PKIMessage        msg;
      pbuf.data = reply;
      pbuf.data_len  = replyLen;
      if ((status = msg.read(pbuf))) {
        break;
      }
      if ((status = process_pkix_msg(&msg, objsPtr, reqId))) {
        break;
      }
    }
  } while(0);
  JnhGetObjectFlags(reqId, &objClass);
  if (status) {
    JnhDiscardObject(reqId);
  } else {
    JnhSynchObject(reqId);
  }
  ApiNotify(reqId, objClass);
  return status;
}

