pki: Add a certificate lifetime calculation helper function
authorMartin Willi <martin@revosec.ch>
Thu, 27 Mar 2014 13:46:41 +0000 (14:46 +0100)
committerMartin Willi <martin@revosec.ch>
Mon, 31 Mar 2014 09:14:59 +0000 (11:14 +0200)
src/pki/pki.c
src/pki/pki.h

index eb614dd..ae4ef1c 100644 (file)
  * for more details.
  */
 
+#define _GNU_SOURCE
 #include "command.h"
 #include "pki.h"
 
+#include <time.h>
 #include <unistd.h>
 
 #include <utils/debug.h>
@@ -102,6 +104,56 @@ bool get_form(char *form, cred_encoding_type_t *enc, credential_type_t type)
 }
 
 /**
+ * See header
+ */
+bool calculate_lifetime(char *format, char *nbstr, char *nastr, time_t span,
+                                               time_t *nb, time_t *na)
+{
+       struct tm tm;
+       time_t now;
+       char *end;
+
+       if (!format)
+       {
+               format = "%d.%m.%y %T";
+       }
+
+       now = time(NULL);
+
+       localtime_r(&now, &tm);
+       if (nbstr)
+       {
+               end = strptime(nbstr, format, &tm);
+               if (end == NULL || *end != '\0')
+               {
+                       return FALSE;
+               }
+       }
+       *nb = mktime(&tm);
+
+       localtime_r(&now, &tm);
+       if (nastr)
+       {
+               end = strptime(nastr, format, &tm);
+               if (end == NULL || *end != '\0')
+               {
+                       return FALSE;
+               }
+       }
+       *na = mktime(&tm);
+
+       if (!nbstr && nastr)
+       {
+               *nb = *na - span;
+       }
+       else if (!nastr)
+       {
+               *na = *nb + span;
+       }
+       return TRUE;
+}
+
+/**
  * Callback credential set pki uses
  */
 static callback_cred_t *cb_set;
@@ -188,4 +240,3 @@ int main(int argc, char *argv[])
        atexit(remove_callback);
        return command_dispatch(argc, argv);
 }
-
index 09c50c6..616fac4 100644 (file)
  */
 bool get_form(char *form, cred_encoding_type_t *enc, credential_type_t type);
 
+/**
+ * Calculate start/end lifetime for certificates.
+ *
+ * If both nbstr and nastr are given, span is ignored. Otherwise missing
+ * arguments are calculated, or assumed to be now.
+ *
+ * @param format       strptime() format, NULL for default: %d.%m.%y %T
+ * @param nbstr                string describing notBefore datetime, or NULL
+ * @param nastr                string describing notAfter datetime, or NULL
+ * @param span         lifetime span, from notBefore to notAfter
+ * @param nb           calculated notBefore time
+ * @param na           calculated notAfter time
+ * @return                     TRUE of nb/na calculated successfully
+ */
+bool calculate_lifetime(char *format, char *nbstr, char *nastr, time_t span,
+                                               time_t *nb, time_t *na);
+
 #endif /** PKI_H_ @}*/