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


// #define JCW_DEBUG

#include <platform.h>
#include <BinBinInt.h>
#include <BinBinInit.h>
#include <pkiTask.h>
#include <x509.h>
#include <stdio.h>
#include <BinMsg.h>
#include <fsys.h>

uint32 serialA = 0;
uint32 serialB = 0;

certList certPool;

static FILE * binFile = NULL;
static FILE * iclFile = NULL;

static char osFileName[512];
static char binFileName[512];
static char iclFileName[512];
static char binFileDir[512];

static pki_mutex_t cpMutex = PKI_MUTEX_INIT;
static pki_mutex_t fileMutex = PKI_MUTEX_INIT;
static pki_mutex_t snoAMutex = PKI_MUTEX_INIT;
static pki_mutex_t snoBMutex = PKI_MUTEX_INIT;


uint32 BinInit(void) {
  bool created_bin = false;
  bool created_icl = false;
  buffer_t buffer;
  size_t data_len;
  uint32 status;
  int i;

#ifdef JCW_DEBUG
  fprintf(stdout, "Entering BinInit()\n"); fflush(stdout);
#endif

  if (!IniAmICA() && !IniAmIRA()) {
#ifdef JCW_DEBUG
    fprintf(stdout, "Neither CA nor RA.  Returning\n"); fflush(stdout);
#endif
    return 0;
  };

#ifdef JCW_DEBUG
  fprintf(stdout, "Initializing BinBin data file\n"); fflush(stdout);
#endif

  pkiCreateMutex(&fileMutex, 0);
  pkiCreateMutex(&snoAMutex, 0);
  pkiCreateMutex(&snoBMutex, 0);
  pkiCreateMutex(&cpMutex, 0);

#ifdef JCW_DEBUG
  fprintf(stdout, "Created mutexes\n"); fflush(stdout);
#endif

  if (!IniReadString("ObjectStore",
                     "Name",
                     osFileName,
                     sizeof(osFileName))) {
#ifdef JCW_DEBUG
    fprintf(stdout, "Bad ObjectStore name from IniFile\n"); fflush(stdout);
#endif
    return BIN_BAD_FILENAME;
  };

  if (!IniReadString("ObjectStore",
                     "Path",
                     binFileDir,
                     sizeof(binFileDir))) {
#ifdef JCW_DEBUG
    fprintf(stdout, "Bad ObjectStore path from IniFile\n"); fflush(stdout);
#endif
    return BIN_BAD_FILEPATH;
  };

  strcpy(binFileName, osFileName);
  strcat(binFileName, ".JBB");
#ifdef JCW_DEBUG
  fprintf(stdout, 
          "Opening BinBin data file %s in directory %s\n", 
          binFileName,
          binFileDir); 
  fflush(stdout);
#endif
  binFile = fnopen(binFileDir, binFileName, "r+");
  if (binFile == NULL) {
#ifdef JCW_DEBUG
    fprintf(stdout, "File doesn't exist.  Trying to create it...\n"); fflush(stdout);
#endif
    binFile = fnopen(binFileDir, binFileName, "w+");
    created_bin = true;
  };
  if (binFile == NULL) {
#ifdef JCW_DEBUG
    fprintf(stdout, "Can't open file.  Returning error\n"); fflush(stdout);
#endif
    return BIN_FOPEN_ERROR;
  };



// Initialize the serial numbers and certPool...
  if (created_bin) {

#ifdef JCW_DEBUG
    fprintf(stdout, "We created a new BinBin, so initialize it...\n"); fflush(stdout);
#endif


    if (status = certPool.write(buffer)) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Error %lu writing certPool\n", status); fflush(stdout);
#endif
      return status;
#ifdef JCW_DEBUG
    } else {
      fprintf(stdout, "Encoded certPool: %d bytes\n", buffer.data_len); fflush(stdout);
      for (i=0; i<buffer.data_len; i++) {
        fprintf(stdout, "%2.2x ", buffer.data[i]);
      };
      fprintf(stdout, "\n"); fflush(stdout);
#endif
    };
    data_len = buffer.data_len;

#ifdef JCW_DEBUG
    fprintf(stdout, "Writing data to file...\n", status); fflush(stdout);
#endif
    fseek(binFile, 0l, SEEK_SET);

    fwrite(&serialA, sizeof(serialA), 1, binFile);
    fwrite(&serialB, sizeof(serialB), 1, binFile);
    fwrite(&data_len, sizeof(data_len), 1, binFile);
    fwrite(buffer.data, data_len, 1, binFile);
    fflush(binFile);

  } else {

#ifdef JCW_DEBUG
    fprintf(stdout, "We opened an existing BinBin, so read it...\n", status);
    fflush(stdout);
#endif

    buffer.clear();

    fseek(binFile, 0l, SEEK_SET);

    if (fread(&serialA, sizeof(serialA), 1, binFile) != 1) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Error reading serial A\n");
      fflush(stdout);
#endif
      return BIN_JBB_FORMAT_ERROR;
    }
    if (fread(&serialB, sizeof(serialB), 1, binFile) != 1) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Error reading serial B\n");
      fflush(stdout);
#endif
      return BIN_JBB_FORMAT_ERROR;
    };

    if (fread(&data_len, sizeof(data_len), 1, binFile) != 1) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Error reading certPool size\n");
      fflush(stdout);
#endif
      return BIN_JBB_FORMAT_ERROR;
    };
    buffer.extend(data_len);
    buffer.data_len = data_len;

    if (fread(buffer.data, data_len, 1, binFile) != 1) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Error reading certPool data\n");
      fflush(stdout);
#endif
      return BIN_JBB_FORMAT_ERROR;
    };

#ifdef JCW_DEBUG
    fprintf(stdout, "Read certPool: %d bytes\n", data_len); fflush(stdout);
    for (i=0; i<buffer.data_len; i++) {
      fprintf(stdout, "%2.2x ", buffer.data[i]);
    };
    fprintf(stdout, "\n"); fflush(stdout);
#endif

    if (status = certPool.read(buffer)) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Error %lu parsing certPool\n", status);
      fflush(stdout);
#endif
      return status;
    };
   
  };


  if (IniAmICA()) {
// Need to initialize the issued certlist too
#ifdef JCW_DEBUG
    fprintf(stdout, "I am CA: Need to initialize the ICL\n");
    fflush(stdout);
#endif
    strcpy(iclFileName, osFileName);
    strcat(iclFileName, ".JIC");
#ifdef JCW_DEBUG
    fprintf(stdout, "ICL file name %s in %s\n", iclFileName, binFileDir);
    fflush(stdout);
#endif

    iclFile = fnopen(binFileDir, iclFileName, "r+");
    if (iclFile == NULL) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Couldn't open ICL file.  Trying to create it...\n");
      fflush(stdout);
#endif
      iclFile = fnopen(binFileDir, iclFileName, "w+");
      created_icl = true;
    };
    if (iclFile == NULL) {
#ifdef JCW_DEBUG
      fprintf(stdout, "Couldn't create ICL file.\n");
      fflush(stdout);
#endif
      return BIN_FOPEN_ERROR;
    };

  };
  return 0;
}

uint32 Bin_LockSerialA(void) {
  return pkiLockMutex(&snoAMutex);
}

uint32 Bin_LockSerialB(void) {
  return pkiLockMutex(&snoBMutex);
}

uint32 Bin_UnlockSerialA(void) {
  return pkiUnlockMutex(&snoAMutex);
}

uint32 Bin_UnlockSerialB(void) {
  return pkiUnlockMutex(&snoAMutex);
}


uint32 Bin_LockCP(void) {
  return pkiLockMutex(&cpMutex);
}

uint32 Bin_unlockCP(void) {
  return pkiUnlockMutex(&cpMutex);
}

uint32 Bin_WriteSerialA(void) {
  fseek(binFile, 0l, SEEK_SET);
  fwrite(&serialA, sizeof(serialA), 1, binFile);
  fflush(binFile);
  return 0;
}

uint32 Bin_WriteSerialB(void) {
  fseek(binFile, sizeof(serialA), SEEK_SET);
  fwrite(&serialB, sizeof(serialB), 1, binFile);
  fflush(binFile);
  return 0;
}

uint32 Bin_WriteCP(void) {
  buffer_t buffer;
  uint32 status;
  size_t data_len;

  if (status = certPool.write(buffer)) return status;
  data_len = buffer.data_len;
  fseek(binFile, sizeof(serialA) + sizeof(serialB), SEEK_SET);
  fwrite(buffer.data, data_len, 1, binFile);
  fflush(binFile);
  return 0;

};