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

//------------------------------------------------------------
// includes
//------------------------------------------------------------

#include <time.h>
#include "x509.h"
#include "functiontrace.h"
#include "pkixvalidator.h"


//------------------------------------------------------------
// utility functions
//------------------------------------------------------------

// thread-safe, platform-independent time utility routines

void   compute_ctime     (time_t value, char* fillThisOut, int fillThisOutLen);
void   compute_asctime   (tm* value,    char* fillThisOut, int fillThisOutLen);
void   compute_localtime (time_t value, tm* fillThisOut);
void   compute_gmtime    (time_t value, tm* fillThisOut);
time_t compute_seconds_localtime_behind_gmtime();

bool   within(time_t startDate, time_t endDate, time_t compareDate);

time_t convertToLocalTime(asn_UTCtime& utcTime);
time_t convertToLocalTime(asn_generalizedtime& generalizedTime);
time_t convertToLocalTime(unsigned year,
                          unsigned month,  // 1..12
                          unsigned day,    // 0..31
                          unsigned hour,   // 0..23
                          unsigned minute, // 0..59
                          unsigned second, // 0..59
                          int tz_hour,     // -12..+12
                          int tz_min);


//------------------------------------------------------------
// method: validateValidity 
//------------------------------------------------------------

void
pkix_validator::validateValidity(pkix_certificate& subject)
{
   TPTRACE(jonahtp_trace_info, "void pkix_validator::validateValidity(pkix_certificate&)");

   //------------------------------------------------------------
   // ASSUMPTION: _validationTime is expressed in local time
   // Goal is to convert certificate validity dates to local time
   // and do direct comparsion with _validationTime.
   //------------------------------------------------------------

   int notBeforeType = subject.tbsCertificate.validity.notBefore.selected();
   time_t notBeforeTime = (notBeforeType == 0 ? 
      convertToLocalTime( subject.tbsCertificate.validity.notBefore.utcTime ) :
      convertToLocalTime( subject.tbsCertificate.validity.notBefore.generalizedTime ));

   int notAfterType = subject.tbsCertificate.validity.notAfter.selected();
   time_t notAfterTime = (notAfterType == 0 ? 
      convertToLocalTime( subject.tbsCertificate.validity.notAfter.utcTime ) :
      convertToLocalTime( subject.tbsCertificate.validity.notAfter.generalizedTime ));

   if ( !within(notBeforeTime, notAfterTime, _validationTime) )
      throw TPException(TP_VALIDITY_RANGE_VIOLATION);
}


//------------------------------------------------------------
// method: within
//------------------------------------------------------------

bool 
within(time_t startDate, time_t endDate, time_t compareDate)
{
   if ( difftime(compareDate,startDate) >= 0 && difftime(endDate,compareDate) >= 0 )
      return true;
   else
      return false;
}


//------------------------------------------------------------
// method: convertToLocalTime 
//------------------------------------------------------------

time_t 
convertToLocalTime(asn_UTCtime& utcTime) 
{
   int status = 0;

   unsigned year;    // 1950..2049
   unsigned month;   // 1..12
   unsigned day;     // 0..31
   unsigned hour;    // 0..23
   unsigned minute;  // 0..59
   unsigned second;  // 0..59
   int      tz_hour; // -12..+12
   int      tz_min;  // -59..+59

   if ((status = utcTime.get_value(year,month,day,hour,minute,second,tz_hour,tz_min)) != 0)
      throw TPASNException(status);

   return convertToLocalTime(year,month,day,hour,minute,second,tz_hour,tz_min);
}


//------------------------------------------------------------
// method: convertToLocalTime 
//------------------------------------------------------------

time_t 
convertToLocalTime(asn_generalizedtime& generalizedTime)
{
   int status = 0;

   unsigned year;        // 0..9999
   unsigned month;       // 1..12
   unsigned day;         // 0..31
   unsigned hour;        // 0..23
   unsigned minute;      // 0..59
   unsigned second;      // 0..59
   unsigned millisecond; // 0..999
   int tz_hour;          // -12..+12, 100 -> local time
   int tz_min;           // -59..+59

   if ((status = generalizedTime.get_value(year,month,day,hour,minute,second,millisecond,tz_hour,tz_min)) != 0)
      throw TPASNException(status);

   // drop milliseconds, not relevant to this calculation

   return convertToLocalTime(year,month,day,hour,minute,second,tz_hour,tz_min);
}


//------------------------------------------------------------
// method: convertToLocalTime 
//------------------------------------------------------------

time_t 
convertToLocalTime(unsigned year,   // 4-digit year
                   unsigned month,  // 1..12
                   unsigned day,    // 0..31
                   unsigned hour,   // 0..23
                   unsigned minute, // 0..59
                   unsigned second, // 0..59
                   int tz_hour,     // -12..+12
                   int tz_min)      // -59..+59)
{
   tm myTm;
 
   myTm.tm_year  = year - 1900; // Year (current year minus 1900)
   myTm.tm_mon   = month - 1;   // Month (0 - 11; January = 0)
   myTm.tm_mday  = day;         // Day of month (1 - 31)
   myTm.tm_hour  = hour;        // Hours since midnight (0 - 23)
   myTm.tm_min   = minute;      // Minutes after hour (0 - 59)
   myTm.tm_sec   = second;      // Seconds after minute (0 - 59)
   myTm.tm_isdst = 0;           // Positive if daylight saving time is in effect; 
                                // 0 if daylight saving time is not in effect; 
                                // negative if status of daylight saving time is unknown.
   
   // *********************************************************
   // *** WARNING: mktime works only up to February 5, 2036 *** 
   // *********************************************************

   time_t subjectLocalTime;
   if ((subjectLocalTime = mktime(&myTm)) == (time_t)-1)
      throw TPException(TP_VALIDITY_RANGE_VIOLATION);

   // factor in subject's time differential from Zulu

   subjectLocalTime += 60*(60*tz_hour + tz_min);

   // factor in our time differential from Zulu

   subjectLocalTime -= compute_seconds_localtime_behind_gmtime();

   return subjectLocalTime;
}


// thread-safe, platform-independent time utility routines

//------------------------------------------------------------
// function: compute_ctime 
//------------------------------------------------------------

void 
compute_ctime(time_t value, char* fillThisOut, int fillThisOutLen)
{
#if defined (AIX4) && !defined (_OE_)
   (void) ctime_r(&value, fillThisOut);
#elif defined (HPUX) || defined (SOLARIS)
   (void) ctime_r(&value, fillThisOut, fillThisOutLen);
#else
   char * timeString = ctime((const time_t*)&value);
   strcpy(fillThisOut, timeString);
#endif
}


//------------------------------------------------------------
// function: compute_asctime 
//------------------------------------------------------------

void 
compute_asctime(tm* value, char* fillThisOut, int fillThisOutLen)
{
#if defined (AIX4) && !defined (_OE_)
   (void) asctime_r(value, fillThisOut);
#elif defined (HPUX) || defined (SOLARIS)
   (void) asctime_r(value, fillThisOut, fillThisOutLen);
#else
   char * timeString = asctime(value);
   strcpy(fillThisOut, timeString);
#endif
}


//------------------------------------------------------------
// function: compute_localtime 
//------------------------------------------------------------

void 
compute_localtime(time_t value, tm* fillThisOut)
{
#if defined (AIX4) && !defined (_OE_)  || defined (SOLARIS) || defined (HPUX)
   (void) localtime_r(&value, fillThisOut);
#else
   *fillThisOut = *( localtime((const time_t*)&value) );
#endif
}


//------------------------------------------------------------
// function: compute_gmtime 
//------------------------------------------------------------

void 
compute_gmtime(time_t value, tm* fillThisOut)
{
#if defined (AIX4) && !defined (_OE_)  || defined (SOLARIS) || defined (HPUX)
   (void) gmtime_r(&value, fillThisOut);
#else
   *fillThisOut = *( gmtime((const time_t*)&value) );
#endif
}


//------------------------------------------------------------
// function: compute_seconds_localtime_behind_gmtime 
//------------------------------------------------------------

time_t
compute_seconds_localtime_behind_gmtime()
{
   time_t localTime = time(NULL);
   struct tm theUTCTime;
   compute_gmtime(localTime, &theUTCTime);

   return mktime(&theUTCTime) - localTime;
}
