/* ***************************************************************** *
 * 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 <JonahIni.h>
#include <jnhTimer.h>
#include <ApiNotify.h>
#include <messaging.h>
#include <apimsg.h>
#include <POLICY/CertPol.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_RA_preregister_user(const utf8String CAName, const  utf8String UserName, 
                        uint32 ExpirationSeconds, const utf8String password, 
                        utf8String *PreRegistrationRecord) 
{
  EncPreRegRecord       enc;
  ObjStoreData          *objsPtr = NULL;
  uint32                objClass;
  uint32                objsid;
  uint32                tidLen;
  uint32                status;
  uint32 	        b64Len = NULL;
  int			localPort;
  bool			ibool;
  unsigned char         *MyName = NULL;
  unsigned char         *b64 = NULL;
  unsigned char         *hostName = NULL;
  unsigned char         *tid = NULL;
  unsigned long         oid[6] = {1, 3, 14, 3, 2, 26 }; // XXX
  char                  *url = NULL;
  char			iniURL[BUFSIZ];
  buffer_t              regData;
  buffer_t              regASN1;
  r_buffer_t            nameBuf;


    if (CAName == NULL || UserName == NULL || password == NULL) {
      return API_INVALID_ARGUMENT;
    }

  do {
#if 0 // Not for July 24
    objsPtr->msg.value.regrec.value.alg.algorithm.set_value(oid, 6);
    if ((buf = malloc(KEY_SIZE)) == NULL) {
      throw "Out of memory error in RA_preregister_user";
    }
    generate_random_bytes(&buf, &bufLen, KEY_SIZE);
    if (bufLen != KEY_SIZE) {
      status =  GENERATE_BYTES_FAILURE;
      break;
    }
    objsPtr->msg.value.regrec.value.keyData.set_value(buf, bufLen);
    memset(buf, 0, bufLen);
    free(buf);
    bufLen = 0;
#endif 
    objClass = (ObjClStSurrogate | ObjClTypeCert | ObjStRAPrereqS);
    if ((status = JnhCreateObject(objClass, &objsPtr, &objsid))) {
      break;
    }
    objsPtr->msg.value.select(0);
    nameBuf.data = CAName;
    nameBuf.data_len = strlen((char *) CAName);
    objsPtr->msg.value.regrec.value.CA.select(2); // XXX
    status = objsPtr->msg.value.regrec.value.CA.directoryname.
      set_value_UTF8(nameBuf);
    if ((MyName = (unsigned char *) malloc(BUFSIZ)) == NULL) {
      throw "Out of memory in RA_preregister_user";
    }
    if ((ibool = IniReadString(GEN_SECTION, GEN_NAME, (char *)  MyName, 
				BUFSIZ)) == FALSE) {
	status = API_WHO_AM_I;
	break;
    }
    nameBuf.data = MyName;
    nameBuf.data_len = strlen((char *) MyName);
    objsPtr->msg.value.regrec.value.RA.select(2); // XXX
    if ((status = objsPtr->msg.value.regrec.value.RA.directoryname.
         set_value_UTF8(nameBuf))) {
      break;
    }
    nameBuf.data = UserName;
    nameBuf.data_len = strlen((char *) UserName);
    objsPtr->msg.value.regrec.value.endEntity.select(2); // XXX
    if ((status = objsPtr->msg.value.regrec.value.endEntity.directoryname.
         set_value_UTF8(nameBuf))) {
      break;
    }
    objsPtr->recipient.value.select(2);
    objsPtr->recipient.value.directoryname.set_value_UTF8(nameBuf);
    if ((hostName = (unsigned char *) malloc(BUFSIZ)) == NULL) {
      throw "Out of memory in RA_preregister_user";
    }
    if ((url = (char *) malloc(BUFSIZ * 2)) == NULL) {
      throw "Out of memory in RA_preregister_user";
    }
    sprintf(iniURL, "%s%d%s%d", GEN_ISSUER, 1, GEN_URL, 1);
    if ((ibool = IniReadString(GEN_SECTION, iniURL, (char *) url, 
			       BUFSIZ*2, "pkix://localhost")) == FALSE) {
      status = API_NO_URL;
      break;
    }
    if ((status = objsPtr->recipientURL.value.set_value((unsigned char *) url, 
							strlen(url)+1))) {
      break;
    }
    IniReadString(GEN_SECTION, GEN_NETWORK, (char *) hostName, BUFSIZ, 
                  "localhost");
    IniReadInteger(TRANS_SECTION, TRANS_PORT, localPort, TRANS_PORTDEF);
    sprintf(url, "pkix://%s:%d", hostName, localPort);
    if ((status = objsPtr->msg.value.regrec.value.raURL.
	 set_value((unsigned char *) url, strlen(url)+1))) {
      break;
    }
    if (status = tid_create(0, objsid, 0, &tid, &tidLen)) {
      break;
    }
    if ((status = objsPtr->transactionID.value.set_value((unsigned char *) tid,
                                                   tidLen))) {
      break;
    }
    if ((status = objsPtr->msg.value.regrec.value.transactionID.
         set_value((unsigned char *) tid, tidLen))) {
      break;
    }
    if ((status = objsPtr->msg.value.regrec.value.write(regData))) {
      break;
    }
    if ((b64Len = base64_encode(regData.data, regData.data_len, 
                                (char **) &b64)) == -1) {
      status = API_BASE64ENCODE_FAIL;
      break;
    }
  } while(0);
  if (status) {
    JnhDiscardObject(objsid);
  } else {
    JnhSynchObject(objsid);
    ApiNotify(objsid, objClass);
    *PreRegistrationRecord = b64;
  }
  if (tid) tid_release(tid);
  if (MyName) free(MyName);
  if (hostName) free(hostName);
  if (url) free(url);
  return status;
}

uint32
JNH_authorize_registration(uint32 reqId, uint32 keyID) 
{
  uint32                status = 0;
  unsigned char         *message = NULL;
  unsigned char         *url = NULL;
  unsigned char         *reply;
  uint32                replyLen;
  uint32                urlLen = 0;
  uint32                messageLen = 0;
  uint32                objClass;
  uint32                pollTime;
  uint32                pollReference;
  uint32                eventId;
  buffer_t              templateBuf;
  ObjStoreData          *objsPtr = NULL;
  CertTemplate          *ct;
  char                  dispmsg[BUFSIZ];
  char			iniAlg[BUFSIZ];


  do {
    if ((status = JnhLockObject(reqId))) {
      break;
    } 
    if ((status = JnhGetObjectModify(reqId, &objClass, &objsPtr))) {
      break;
    }
    switch(objsPtr->msg.value.selected()) {
    case OBJ_MSG_IREQ:
      ct = &objsPtr->msg.value.ireq.value[0]->certReq.certTemplate;
      break;
    case OBJ_MSG_CERTREQ:
      ct = &objsPtr->msg.value.certreq.value[0]->certReq.certTemplate;
      break;
    default:
      status =  API_IMPROPER_MESSAGE_TYPE;
      break;
    }
    if (status) break;
    if (!ct->version.value.is_present()) {
      if ((status = ct->version.value.set_value(2))) {
        break;
      }
    }
    if (!ct->signingAlg.value.is_present()) {
      char *algname = (char *) malloc(BUFSIZ);
      if (algname == NULL) {
        throw "Out of memory error in RA_authorize_registration";
      }
      sprintf(iniAlg, "%s%d", CP_SIGALG, 1);
      IniReadString(CP_SECTION, iniAlg, algname, BUFSIZ, "id-dsa");
      if ((status = ct->signingAlg.value.algorithm.set_value(algname))) {
        free(algname);
        break;
      }
      free(algname);
    }
    if ((status = CP_NewCertVerify(*ct))) {
      break;
    }
    if ((status = generate_pkix_msg(objsPtr, &message, &messageLen))) {
      break;
    }
    if ((status = objsPtr->recipientURL.value.get_value(url, urlLen))) {
      break;
    }
    if ((status = send_message(message, messageLen, MSG_REQ, url, 
                               &pollReference, &pollTime, &reply, 
                               &replyLen))) {
      break;
    }
    if ((status = objsPtr->pollReference.value.set_value(pollReference))) {
      break;
    }
    if ((status = objsPtr->pollTime.value.set_value(pollTime))) {
      break;
    }
    sprintf(dispmsg, "OBJSID = %d POLL REFERENCE = %d TIME = %d", 
            reqId, pollReference, pollTime);
    ApiDisplay(DISPLAY_LOGDEBUG, (utf8String) dispmsg);
    if ((status = JnhRegisterEventAbs(pollTime, poll, (void *) reqId, 
                                      false, &eventId))) {
      break;
    }
    objClass = (ObjClStSurrogate | ObjClTypeCert | 
                ObjStRACertReqWaitingForCAS);
    if ((status = JnhSetObjectFlags(reqId, objClass))) {
      break;
    }
  } while(0);
  if (status) {
    JnhDiscardObject(reqId);
  } else {
    ApiNotify(reqId, objClass);
    status = JnhSynchObject(reqId);
  }
  return status;
}
