aboutsummaryrefslogtreecommitdiff
path: root/libjava
diff options
context:
space:
mode:
Diffstat (limited to 'libjava')
-rw-r--r--libjava/ChangeLog43
-rw-r--r--libjava/classpath/lib/java/lang/PosixProcess$EOFInputStream.classbin567 -> 567 bytes
-rw-r--r--libjava/classpath/lib/java/lang/PosixProcess$ProcessManager.classbin2645 -> 2656 bytes
-rw-r--r--libjava/classpath/lib/java/lang/PosixProcess.classbin4197 -> 4098 bytes
-rw-r--r--libjava/include/posix-threads.h8
-rw-r--r--libjava/java/lang/PosixProcess$ProcessManager.h32
-rw-r--r--libjava/java/lang/PosixProcess.h7
-rw-r--r--libjava/java/lang/PosixProcess.java151
-rw-r--r--libjava/java/lang/natPosixProcess.cc157
-rw-r--r--libjava/posix-threads.cc22
10 files changed, 248 insertions, 172 deletions
diff --git a/libjava/ChangeLog b/libjava/ChangeLog
index 385e26d..dce1558 100644
--- a/libjava/ChangeLog
+++ b/libjava/ChangeLog
@@ -1,3 +1,46 @@
+2007-05-12 David Daney <ddaney@avtrex.com>
+
+ PR libgcj/29324
+ * include/posix-threads.h (_Jv_BlockSigchld): Declare.
+ (_Jv_UnBlockSigchld): Same.
+ * posix-threads.cc: Include posix-threads.h.
+ (block_sigchld) Rename to...
+ (_Jv_BlockSigchld) ... this.
+ (_Jv_UnBlockSigchld): New function.
+ (_Jv_InitThreads): Call _Jv_BlockSigchld in place of block_sigchld.
+ (_Jv_ThreadStart): Same.
+ * java/lang/PosixProcess$ProcessManager.h: Regenerate.
+ * java/lang/PosixProcess.java: Clean up imports.
+ (ProcessManager): Make final.
+ (ProcessManager.queue): Genericise and make private.
+ (ProcessManager.pidToProcess): Remove.
+ (ProcessManager.liveProcesses): New field.
+ (ProcessManager.reaperPID): Remove.
+ (ProcessManager.nativeData): New field.
+ (ProcessManager.removeProcessFromMap): Remove.
+ (ProcessManager.addProcessToMap):Remove.
+ (ProcessManager.addToLiveProcesses): New method.
+ (ProcessManager.run): Rewritten.
+ (ProcessManager.reap): Change method signature,
+ (getErrorStream): Correct formatting.
+ (getInputStream): Same.
+ (spawn): Add process to liveProcesses list.
+ (pid): Make package private.
+ * java/lang/PosixProcess.h: Regenerate.
+ * java/lang/natPosixProcess.cc: Include posix.h and posix-threads.h.
+ Add useing namespace java::lang.
+ (ProcessManagerInternal): New struct.
+ (sigchld_handler): Rewritten.
+ (init): Rewritten.
+ (waitForSignal): Same.
+ (reap): Same.
+ (signalReaper): Same.
+ (nativeDestroy): Call kill as ::kill.
+ (nativeSpawn): Correct formatting.
+ * classpath/lib/java/lang/PosixProcess$EOFInputStream.class: Regenerate.
+ * classpath/lib/java/lang/PosixProcess.class: Same.
+ * classpath/lib/java/lang/PosixProcess$ProcessManager.class: Same.
+
2007-05-07 Ian Lance Taylor <iant@google.com>
PR java/31842
diff --git a/libjava/classpath/lib/java/lang/PosixProcess$EOFInputStream.class b/libjava/classpath/lib/java/lang/PosixProcess$EOFInputStream.class
index a7103f8..c4cc6c3 100644
--- a/libjava/classpath/lib/java/lang/PosixProcess$EOFInputStream.class
+++ b/libjava/classpath/lib/java/lang/PosixProcess$EOFInputStream.class
Binary files differ
diff --git a/libjava/classpath/lib/java/lang/PosixProcess$ProcessManager.class b/libjava/classpath/lib/java/lang/PosixProcess$ProcessManager.class
index 2e260c3..1d80a2d 100644
--- a/libjava/classpath/lib/java/lang/PosixProcess$ProcessManager.class
+++ b/libjava/classpath/lib/java/lang/PosixProcess$ProcessManager.class
Binary files differ
diff --git a/libjava/classpath/lib/java/lang/PosixProcess.class b/libjava/classpath/lib/java/lang/PosixProcess.class
index 0227add..0241ae7 100644
--- a/libjava/classpath/lib/java/lang/PosixProcess.class
+++ b/libjava/classpath/lib/java/lang/PosixProcess.class
Binary files differ
diff --git a/libjava/include/posix-threads.h b/libjava/include/posix-threads.h
index d5f6495..806ee55 100644
--- a/libjava/include/posix-threads.h
+++ b/libjava/include/posix-threads.h
@@ -92,6 +92,14 @@ _Jv_GetPlatformThreadID(_Jv_Thread_t *t)
}
//
+// Signal helpers.
+//
+
+void _Jv_BlockSigchld();
+void _Jv_UnBlockSigchld();
+
+
+//
// Condition variables.
//
diff --git a/libjava/java/lang/PosixProcess$ProcessManager.h b/libjava/java/lang/PosixProcess$ProcessManager.h
index d8d0d59..4b3b62e 100644
--- a/libjava/java/lang/PosixProcess$ProcessManager.h
+++ b/libjava/java/lang/PosixProcess$ProcessManager.h
@@ -7,31 +7,37 @@
#pragma interface
#include <java/lang/Thread.h>
+extern "Java"
+{
+ namespace gnu
+ {
+ namespace gcj
+ {
+ class RawDataManaged;
+ }
+ }
+}
class java::lang::PosixProcess$ProcessManager : public ::java::lang::Thread
{
public: // actually package-private
PosixProcess$ProcessManager();
-private:
- ::java::lang::PosixProcess * removeProcessFromMap(jlong);
-public: // actually package-private
- virtual void addProcessToMap(::java::lang::PosixProcess *);
- virtual void startExecuting(::java::lang::PosixProcess *);
- virtual void waitUntilReady();
+ void addToLiveProcesses(::java::lang::PosixProcess *);
+ void startExecuting(::java::lang::PosixProcess *);
+ void waitUntilReady();
public:
- virtual void run();
+ void run();
private:
void init();
void waitForSignal();
- jboolean reap();
+ jboolean reap(::java::lang::PosixProcess *);
void signalReaper();
-public: // actually package-private
- ::java::util::List * __attribute__((aligned(__alignof__( ::java::lang::Thread)))) queue;
-private:
- ::java::util::Map * pidToProcess;
+ ::java::util::LinkedList * __attribute__((aligned(__alignof__( ::java::lang::Thread)))) queue;
+ ::java::util::LinkedList * liveProcesses;
jboolean ready;
- jlong reaperPID;
+public: // actually package-private
+ static ::gnu::gcj::RawDataManaged * nativeData;
public:
static ::java::lang::Class class$;
};
diff --git a/libjava/java/lang/PosixProcess.h b/libjava/java/lang/PosixProcess.h
index a43fa07..3254f52 100644
--- a/libjava/java/lang/PosixProcess.h
+++ b/libjava/java/lang/PosixProcess.h
@@ -32,17 +32,16 @@ private:
void nativeSpawn();
public: // actually package-private
PosixProcess(JArray< ::java::lang::String * > *, JArray< ::java::lang::String * > *, ::java::io::File *, jboolean);
- static jlong access$0(::java::lang::PosixProcess *);
- static ::java::lang::Object * access$1();
- static void access$2(::java::lang::PosixProcess$ProcessManager *);
+ static ::java::lang::Object * access$0();
+ static void access$1(::java::lang::PosixProcess$ProcessManager *);
private:
JArray< ::java::lang::String * > * __attribute__((aligned(__alignof__( ::java::lang::Process)))) progarray;
JArray< ::java::lang::String * > * envp;
::java::io::File * dir;
jboolean redirect;
::java::lang::Throwable * exception;
- jlong pid;
public: // actually package-private
+ jlong pid;
static const jint STATE_WAITING_TO_START = 0;
static const jint STATE_RUNNING = 1;
static const jint STATE_TERMINATED = 2;
diff --git a/libjava/java/lang/PosixProcess.java b/libjava/java/lang/PosixProcess.java
index 6b14964..dd59e7b 100644
--- a/libjava/java/lang/PosixProcess.java
+++ b/libjava/java/lang/PosixProcess.java
@@ -13,11 +13,10 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.util.HashMap;
+import java.util.Iterator;
import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
+import gnu.gcj.RawDataManaged;
/**
* @author Tom Tromey <tromey@cygnus.com>
@@ -27,7 +26,7 @@ import java.util.Map;
*/
final class PosixProcess extends Process
{
- static class ProcessManager extends Thread
+ static final class ProcessManager extends Thread
{
/**
* A list of {@link PosixProcess PosixProcesses} to be
@@ -35,10 +34,12 @@ final class PosixProcess extends Process
* for all process related operations. To avoid dead lock
* ensure queueLock is obtained before PosixProcess.
*/
- List queue = new LinkedList();
- private Map pidToProcess = new HashMap();
+ private LinkedList<PosixProcess> queue = new LinkedList<PosixProcess>();
+ private LinkedList<PosixProcess> liveProcesses =
+ new LinkedList<PosixProcess>();
private boolean ready = false;
- private long reaperPID;
+
+ static RawDataManaged nativeData;
ProcessManager()
{
@@ -53,27 +54,14 @@ final class PosixProcess extends Process
}
/**
- * Get the PosixProcess object with the given pid and
- * remove it from the map. This method is called from the
- * native code for {@link #reap()). The mapping is removed so
- * the PosixProcesses can be GCed after they terminate.
- *
- * @param p The pid of the process.
- */
- private PosixProcess removeProcessFromMap(long p)
- {
- return (PosixProcess) pidToProcess.remove(new Long(p));
- }
-
- /**
- * Put the given PosixProcess in the map using the Long
- * value of its pid as the key.
+ * Add a process to the list of running processes. This must only
+ * be called with the queueLock held.
*
* @param p The PosixProcess.
*/
- void addProcessToMap(PosixProcess p)
+ void addToLiveProcesses(PosixProcess p)
{
- pidToProcess.put(new Long(p.pid), p);
+ liveProcesses.add(p);
}
/**
@@ -122,61 +110,66 @@ final class PosixProcess extends Process
// Now ready to accept requests.
synchronized (this)
{
- ready = true;
- this.notifyAll();
+ ready = true;
+ this.notifyAll();
}
for (;;)
{
- try
- {
- synchronized (queueLock)
- {
- boolean haveMoreChildren = reap();
- if (! haveMoreChildren && queue.size() == 0)
- {
- // This reaper thread could exit, but we
- // keep it alive for a while in case
- // someone wants to start more Processes.
- try
- {
- queueLock.wait(1000L);
- if (queue.size() == 0)
- {
- processManager = null;
- return; // Timed out.
- }
- }
- catch (InterruptedException ie)
- {
- // Ignore and exit the thread.
- return;
- }
- }
- while (queue.size() > 0)
- {
- PosixProcess p = (PosixProcess) queue.remove(0);
- p.spawn(this);
- }
- }
-
- // Wait for a SIGCHLD from either an exiting
- // process or the startExecuting() method. This
- // is done outside of the synchronized block to
- // allow other threads to enter and submit more
- // jobs.
- waitForSignal();
- }
- catch (Exception ex)
- {
- ex.printStackTrace(System.err);
- }
+ try
+ {
+ synchronized (queueLock)
+ {
+ Iterator<PosixProcess> processIterator =
+ liveProcesses.iterator();
+ while (processIterator.hasNext())
+ {
+ boolean reaped = reap(processIterator.next());
+ if (reaped)
+ processIterator.remove();
+ }
+ if (liveProcesses.size() == 0 && queue.size() == 0)
+ {
+ // This reaper thread could exit, but we keep it
+ // alive for a while in case someone wants to
+ // start more Processes.
+ try
+ {
+ queueLock.wait(1000L);
+ if (queue.size() == 0)
+ {
+ processManager = null;
+ return; // Timed out.
+ }
+ }
+ catch (InterruptedException ie)
+ {
+ // Ignore and exit the thread.
+ return;
+ }
+ }
+ while (queue.size() > 0)
+ {
+ PosixProcess p = queue.remove(0);
+ p.spawn(this);
+ }
+ }
+
+ // Wait for a SIGCHLD from either an exiting process or
+ // the startExecuting() method. This is done outside of
+ // the synchronized block to allow other threads to
+ // enter and submit more jobs.
+ waitForSignal();
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace(System.err);
+ }
}
}
/**
* Setup native signal handlers and other housekeeping things.
- *
*/
private native void init();
@@ -187,12 +180,14 @@ final class PosixProcess extends Process
private native void waitForSignal();
/**
- * Try to reap as many children as possible without blocking.
+ * Try to reap the specified child without blocking.
+ *
+ * @param p the process to try to reap.
*
- * @return true if more live children exist.
+ * @return true if the process terminated.
*
*/
- private native boolean reap();
+ private native boolean reap(PosixProcess p);
/**
* Send SIGCHLD to the reaper thread.
@@ -295,7 +290,7 @@ final class PosixProcess extends Process
returnedErrorStream = EOFInputStream.instance;
else
returnedErrorStream = errorStream;
-
+
return returnedErrorStream;
}
@@ -308,7 +303,7 @@ final class PosixProcess extends Process
returnedInputStream = EOFInputStream.instance;
else
returnedInputStream = inputStream;
-
+
return returnedInputStream;
}
@@ -329,7 +324,7 @@ final class PosixProcess extends Process
/**
* Start this process running. This should only be called by the
- * ProcessManager.
+ * ProcessManager with the queueLock held.
*
* @param pm The ProcessManager that made the call.
*/
@@ -342,7 +337,7 @@ final class PosixProcess extends Process
// There is no race with reap() in the pidToProcess map
// because this is always called from the same thread
// doing the reaping.
- pm.addProcessToMap(this);
+ pm.addToLiveProcesses(this);
state = STATE_RUNNING;
// Notify anybody waiting on state change.
this.notifyAll();
@@ -426,7 +421,7 @@ final class PosixProcess extends Process
private Throwable exception;
/** The process id. This is cast to a pid_t on the native side. */
- private long pid;
+ long pid;
// FIXME: Why doesn't the friend declaration in PosixProcess.h
// allow PosixProcess$ProcessManager native code access these
diff --git a/libjava/java/lang/natPosixProcess.cc b/libjava/java/lang/natPosixProcess.cc
index 252da6e..c7b8b6e 100644
--- a/libjava/java/lang/natPosixProcess.cc
+++ b/libjava/java/lang/natPosixProcess.cc
@@ -30,6 +30,8 @@ details. */
#include <gcj/cni.h>
#include <jvm.h>
+#include <posix.h>
+#include <posix-threads.h>
#include <java/lang/PosixProcess$ProcessManager.h>
#include <java/lang/PosixProcess.h>
@@ -48,6 +50,7 @@ details. */
#include <java/lang/PosixProcess$EOFInputStream.h>
using gnu::java::nio::channels::FileChannelImpl;
+using namespace java::lang;
extern char **environ;
@@ -91,13 +94,37 @@ myclose (int &fd)
fd = -1;
}
+namespace
+{
+ struct ProcessManagerInternal
+ {
+ int pipe_ends[2];
+ struct sigaction old_sigaction;
+ };
+}
+
+
// There has to be a signal handler in order to be able to
// sigwait() on SIGCHLD. The information passed is ignored as it
// will be recovered by the waitpid() call.
static void
-sigchld_handler (int)
+sigchld_handler (int sig, siginfo_t *si, void *third)
{
- // Ignore.
+ if (PosixProcess$ProcessManager::nativeData != NULL)
+ {
+ ProcessManagerInternal *pmi =
+ (ProcessManagerInternal *)PosixProcess$ProcessManager::nativeData;
+ char c = 0;
+ ::write(pmi->pipe_ends[1], &c, 1);
+ if (pmi->old_sigaction.sa_handler != SIG_DFL
+ && pmi->old_sigaction.sa_handler != SIG_IGN)
+ {
+ if ((pmi->old_sigaction.sa_flags & SA_SIGINFO) != 0)
+ pmi->old_sigaction.sa_sigaction(sig, si, third);
+ else
+ (*pmi->old_sigaction.sa_handler)(sig);
+ }
+ }
}
@@ -105,22 +132,35 @@ sigchld_handler (int)
void
java::lang::PosixProcess$ProcessManager::init ()
{
- using namespace java::lang;
- // Remenber our PID so other threads can kill us.
- reaperPID = (jlong) pthread_self ();
+ // The nativeData is static to avoid races installing the signal
+ // handler in the case that it is chained.
+ if (nativeData == NULL )
+ {
+ ProcessManagerInternal *pmi =
+ (ProcessManagerInternal *)JvAllocBytes(sizeof(ProcessManagerInternal));
- // SIGCHLD is blocked in all threads in posix-threads.cc.
- // Setup the SIGCHLD handler.
- struct sigaction sa;
- memset (&sa, 0, sizeof (sa));
+ if (0 != ::pipe(pmi->pipe_ends))
+ goto error;
- sa.sa_handler = sigchld_handler;
- // We only want signals when the things exit.
- sa.sa_flags = SA_NOCLDSTOP;
+ // Make writing non-blocking so that the signal handler will
+ // never block.
+ int fl = ::fcntl(pmi->pipe_ends[1], F_GETFL);
+ ::fcntl(pmi->pipe_ends[1], F_SETFL, fl | O_NONBLOCK);
- if (-1 == sigaction (SIGCHLD, &sa, NULL))
- goto error;
+ nativeData = (::gnu::gcj::RawDataManaged *)pmi;
+ // SIGCHLD is blocked in all threads in posix-threads.cc.
+ // Setup the SIGCHLD handler.
+ struct sigaction sa;
+ memset (&sa, 0, sizeof (sa));
+
+ sa.sa_sigaction = sigchld_handler;
+ // We only want signals when the things exit.
+ sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
+
+ if (-1 == sigaction (SIGCHLD, &sa, &pmi->old_sigaction))
+ goto error;
+ }
// All OK.
return;
@@ -132,79 +172,52 @@ void
java::lang::PosixProcess$ProcessManager::waitForSignal ()
{
// Wait for SIGCHLD
- sigset_t mask;
- pthread_sigmask (0, NULL, &mask);
- sigdelset (&mask, SIGCHLD);
+ _Jv_UnBlockSigchld();
+ ProcessManagerInternal *pmi = (ProcessManagerInternal *)nativeData;
- // Use sigsuspend() instead of sigwait() as sigwait() doesn't play
- // nicely with the GC's use of signals.
- sigsuspend (&mask);
+ // Try to read multiple (64) notifications in one go.
+ char c[64];
+ ::read(pmi->pipe_ends[0], c, sizeof (c));
- // Do not check sigsuspend return value. The only legitimate return
- // is EINTR, but there is a known kernel bug affecting alpha-linux
- // wrt sigsuspend+handler+sigreturn that can result in a return value
- // of __NR_sigsuspend and errno unset. Don't fail unnecessarily on
- // older kernel versions.
+ _Jv_BlockSigchld();
- // All OK.
return;
}
-jboolean java::lang::PosixProcess$ProcessManager::reap ()
+jboolean java::lang::PosixProcess$ProcessManager::reap (PosixProcess *p)
{
- using namespace java::lang;
-
- pid_t pid;
-
- for (;;)
- {
- // Get the return code from a dead child process.
- int status;
- pid = waitpid ((pid_t) - 1, &status, WNOHANG);
- if (pid == -1)
- {
- if (errno == ECHILD)
- return false;
- else
- goto error;
- }
-
- if (pid == 0)
- return true; // No children to wait for.
-
- // Look up the process in our pid map.
- PosixProcess * process = removeProcessFromMap ((jlong) pid);
-
- // Note that if process==NULL, then we have an unknown child.
- // This is not common, but can happen, and isn't an error.
- if (process)
- {
- JvSynchronize sync (process);
- process->status = WIFEXITED (status) ? WEXITSTATUS (status) : -1;
- process->state = PosixProcess::STATE_TERMINATED;
- process->processTerminationCleanup();
- process->notifyAll ();
- }
- }
-
-error:
- throw new InternalError (JvNewStringUTF (strerror (errno)));
+ pid_t rv;
+
+ // Try to get the return code from the child process.
+ int status;
+ rv = ::waitpid ((pid_t)p->pid, &status, WNOHANG);
+ if (rv == -1)
+ throw new InternalError (JvNewStringUTF (strerror (errno)));
+
+ if (rv == 0)
+ return false; // No children to wait for.
+
+ JvSynchronize sync (p);
+ p->status = WIFEXITED (status) ? WEXITSTATUS (status) : -1;
+ p->state = PosixProcess::STATE_TERMINATED;
+ p->processTerminationCleanup();
+ p->notifyAll ();
+ return true;
}
void
java::lang::PosixProcess$ProcessManager::signalReaper ()
{
- int c = pthread_kill ((pthread_t) reaperPID, SIGCHLD);
- if (c == 0)
- return;
- // pthread_kill() failed.
- throw new InternalError (JvNewStringUTF (strerror (c)));
+ ProcessManagerInternal *pmi = (ProcessManagerInternal *)nativeData;
+ char c = 0;
+ ::write(pmi->pipe_ends[1], &c, 1);
+ // Ignore errors. If EPIPE the reaper has already exited.
}
void
java::lang::PosixProcess::nativeDestroy ()
{
- int c = kill ((pid_t) pid, SIGKILL);
+ int c = ::kill ((pid_t) pid, SIGKILL);
if (c == 0)
return;
// kill() failed.
@@ -427,9 +440,9 @@ java::lang::PosixProcess::nativeSpawn ()
char c;
int r = read (msgp[0], &c, 1);
if (r == -1)
- throw new IOException (JvNewStringUTF (strerror (errno)));
+ throw new IOException (JvNewStringUTF (strerror (errno)));
else if (r != 0)
- throw new IOException (JvNewStringUTF (strerror (c)));
+ throw new IOException (JvNewStringUTF (strerror (c)));
}
catch (java::lang::Throwable *thrown)
{
diff --git a/libjava/posix-threads.cc b/libjava/posix-threads.cc
index 6ea724b..287d6b7 100644
--- a/libjava/posix-threads.cc
+++ b/libjava/posix-threads.cc
@@ -14,6 +14,7 @@ details. */
#include <config.h>
#include "posix.h"
+#include "posix-threads.h"
// If we're using the Boehm GC, then we need to override some of the
// thread primitives. This is fairly gross.
@@ -472,8 +473,8 @@ handle_intr (int)
// Do nothing.
}
-static void
-block_sigchld()
+void
+_Jv_BlockSigchld()
{
sigset_t mask;
sigemptyset (&mask);
@@ -484,6 +485,17 @@ block_sigchld()
}
void
+_Jv_UnBlockSigchld()
+{
+ sigset_t mask;
+ sigemptyset (&mask);
+ sigaddset (&mask, SIGCHLD);
+ int c = pthread_sigmask (SIG_UNBLOCK, &mask, NULL);
+ if (c != 0)
+ JvFail (strerror (c));
+}
+
+void
_Jv_InitThreads (void)
{
pthread_key_create (&_Jv_ThreadKey, NULL);
@@ -501,7 +513,7 @@ _Jv_InitThreads (void)
// Block SIGCHLD here to ensure that any non-Java threads inherit the new
// signal mask.
- block_sigchld();
+ _Jv_BlockSigchld();
// Check/set the thread stack size.
size_t min_ss = 32 * 1024;
@@ -581,7 +593,7 @@ _Jv_ThreadRegister (_Jv_Thread_t *data)
}
# endif
// Block SIGCHLD which is used in natPosixProcess.cc.
- block_sigchld();
+ _Jv_BlockSigchld();
}
void
@@ -629,7 +641,7 @@ _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
// Block SIGCHLD which is used in natPosixProcess.cc.
// The current mask is inherited by the child thread.
- block_sigchld();
+ _Jv_BlockSigchld();
param.sched_priority = thread->getPriority();
6'>1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
/*
 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

/* The PPKI stuff has been donated by Jeff Barber <jeffb@issl.atl.hp.com> */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <openssl/conf.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/txt_db.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/objects.h>
#include <openssl/ocsp.h>
#include <openssl/pem.h>

#ifndef W_OK
# ifdef OPENSSL_SYS_VMS
#  include <unistd.h>
# elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS)
#  include <sys/file.h>
# endif
#endif

#include "apps.h"

#ifndef W_OK
# define F_OK 0
# define X_OK 1
# define W_OK 2
# define R_OK 4
#endif

#ifndef PATH_MAX
# define PATH_MAX 4096
#endif
#ifndef NAME_MAX
# define NAME_MAX 255
#endif

#define CERT_MAX (PATH_MAX + NAME_MAX)

#define BASE_SECTION            "ca"

#define ENV_DEFAULT_CA          "default_ca"

#define STRING_MASK             "string_mask"
#define UTF8_IN                 "utf8"

#define ENV_NEW_CERTS_DIR       "new_certs_dir"
#define ENV_CERTIFICATE         "certificate"
#define ENV_SERIAL              "serial"
#define ENV_CRLNUMBER           "crlnumber"
#define ENV_PRIVATE_KEY         "private_key"
#define ENV_DEFAULT_DAYS        "default_days"
#define ENV_DEFAULT_STARTDATE   "default_startdate"
#define ENV_DEFAULT_ENDDATE     "default_enddate"
#define ENV_DEFAULT_CRL_DAYS    "default_crl_days"
#define ENV_DEFAULT_CRL_HOURS   "default_crl_hours"
#define ENV_DEFAULT_MD          "default_md"
#define ENV_DEFAULT_EMAIL_DN    "email_in_dn"
#define ENV_PRESERVE            "preserve"
#define ENV_POLICY              "policy"
#define ENV_EXTENSIONS          "x509_extensions"
#define ENV_CRLEXT              "crl_extensions"
#define ENV_MSIE_HACK           "msie_hack"
#define ENV_NAMEOPT             "name_opt"
#define ENV_CERTOPT             "cert_opt"
#define ENV_EXTCOPY             "copy_extensions"
#define ENV_UNIQUE_SUBJECT      "unique_subject"

#define ENV_DATABASE            "database"

/* Additional revocation information types */
typedef enum {
    REV_VALID             = -1, /* Valid (not-revoked) status */
    REV_NONE              = 0, /* No additional information */
    REV_CRL_REASON        = 1, /* Value is CRL reason code */
    REV_HOLD              = 2, /* Value is hold instruction */
    REV_KEY_COMPROMISE    = 3, /* Value is cert key compromise time */
    REV_CA_COMPROMISE     = 4  /* Value is CA key compromise time */
} REVINFO_TYPE;

static char *lookup_conf(const CONF *conf, const char *group, const char *tag);

static int certify(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509,
                   const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
                   STACK_OF(CONF_VALUE) *policy, CA_DB *db,
                   BIGNUM *serial, const char *subj, unsigned long chtype,
                   int multirdn, int email_dn, const char *startdate,
                   const char *enddate,
                   long days, int batch, const char *ext_sect, CONF *conf,
                   int verbose, unsigned long certopt, unsigned long nameopt,
                   int default_op, int ext_copy, int selfsign);
static int certify_cert(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509,
                        const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
                        STACK_OF(CONF_VALUE) *policy, CA_DB *db,
                        BIGNUM *serial, const char *subj, unsigned long chtype,
                        int multirdn, int email_dn, const char *startdate,
                        const char *enddate, long days, int batch, const char *ext_sect,
                        CONF *conf, int verbose, unsigned long certopt,
                        unsigned long nameopt, int default_op, int ext_copy);
static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey,
                         X509 *x509, const EVP_MD *dgst,
                         STACK_OF(OPENSSL_STRING) *sigopts,
                         STACK_OF(CONF_VALUE) *policy, CA_DB *db,
                         BIGNUM *serial, const char *subj, unsigned long chtype,
                         int multirdn, int email_dn, const char *startdate,
                         const char *enddate, long days, const char *ext_sect, CONF *conf,
                         int verbose, unsigned long certopt,
                         unsigned long nameopt, int default_op, int ext_copy);
static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
                   const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
                   STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
                   const char *subj, unsigned long chtype, int multirdn,
                   int email_dn, const char *startdate, const char *enddate, long days,
                   int batch, int verbose, X509_REQ *req, const char *ext_sect,
                   CONF *conf, unsigned long certopt, unsigned long nameopt,
                   int default_op, int ext_copy, int selfsign);
static int get_certificate_status(const char *ser_status, CA_DB *db);
static int do_updatedb(CA_DB *db);
static int check_time_format(const char *str);
static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type,
                     const char *extval);
static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg);
static int make_revoked(X509_REVOKED *rev, const char *str);
static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str);
static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext);

static CONF *extconf = NULL;
static int preserve = 0;
static int msie_hack = 0;

typedef enum OPTION_choice {
    OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
    OPT_ENGINE, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SUBJ, OPT_UTF8,
    OPT_CREATE_SERIAL, OPT_MULTIVALUE_RDN, OPT_STARTDATE, OPT_ENDDATE,
    OPT_DAYS, OPT_MD, OPT_POLICY, OPT_KEYFILE, OPT_KEYFORM, OPT_PASSIN,
    OPT_KEY, OPT_CERT, OPT_SELFSIGN, OPT_IN, OPT_OUT, OPT_OUTDIR,
    OPT_SIGOPT, OPT_NOTEXT, OPT_BATCH, OPT_PRESERVEDN, OPT_NOEMAILDN,
    OPT_GENCRL, OPT_MSIE_HACK, OPT_CRLDAYS, OPT_CRLHOURS, OPT_CRLSEC,
    OPT_INFILES, OPT_SS_CERT, OPT_SPKAC, OPT_REVOKE, OPT_VALID,
    OPT_EXTENSIONS, OPT_EXTFILE, OPT_STATUS, OPT_UPDATEDB, OPT_CRLEXTS,
    /* Do not change the order here; see related case statements below */
    OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE, OPT_CRL_CA_COMPROMISE
} OPTION_CHOICE;

const OPTIONS ca_options[] = {
    {"help", OPT_HELP, '-', "Display this summary"},
    {"verbose", OPT_VERBOSE, '-', "Verbose output during processing"},
    {"config", OPT_CONFIG, 's', "A config file"},
    {"name", OPT_NAME, 's', "The particular CA definition to use"},
    {"subj", OPT_SUBJ, 's', "Use arg instead of request's subject"},
    {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
    {"create_serial", OPT_CREATE_SERIAL, '-',
     "If reading serial fails, create a new random serial"},
    {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
     "Enable support for multivalued RDNs"},
    {"startdate", OPT_STARTDATE, 's', "Cert notBefore, YYMMDDHHMMSSZ"},
    {"enddate", OPT_ENDDATE, 's',
     "YYMMDDHHMMSSZ cert notAfter (overrides -days)"},
    {"days", OPT_DAYS, 'p', "Number of days to certify the cert for"},
    {"md", OPT_MD, 's', "md to use; one of md2, md5, sha or sha1"},
    {"policy", OPT_POLICY, 's', "The CA 'policy' to support"},
    {"keyfile", OPT_KEYFILE, 's', "Private key"},
    {"keyform", OPT_KEYFORM, 'f', "Private key file format (PEM or ENGINE)"},
    {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
    {"key", OPT_KEY, 's', "Key to decode the private key if it is encrypted"},
    {"cert", OPT_CERT, '<', "The CA cert"},
    {"selfsign", OPT_SELFSIGN, '-',
     "Sign a cert with the key associated with it"},
    {"in", OPT_IN, '<', "The input PEM encoded cert request(s)"},
    {"out", OPT_OUT, '>', "Where to put the output file(s)"},
    {"outdir", OPT_OUTDIR, '/', "Where to put output cert"},
    {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
    {"notext", OPT_NOTEXT, '-', "Do not print the generated certificate"},
    {"batch", OPT_BATCH, '-', "Don't ask questions"},
    {"preserveDN", OPT_PRESERVEDN, '-', "Don't re-order the DN"},
    {"noemailDN", OPT_NOEMAILDN, '-', "Don't add the EMAIL field to the DN"},
    {"gencrl", OPT_GENCRL, '-', "Generate a new CRL"},
    {"msie_hack", OPT_MSIE_HACK, '-',
     "msie modifications to handle all those universal strings"},
    {"crldays", OPT_CRLDAYS, 'p', "Days until the next CRL is due"},
    {"crlhours", OPT_CRLHOURS, 'p', "Hours until the next CRL is due"},
    {"crlsec", OPT_CRLSEC, 'p', "Seconds until the next CRL is due"},
    {"infiles", OPT_INFILES, '-', "The last argument, requests to process"},
    {"ss_cert", OPT_SS_CERT, '<', "File contains a self signed cert to sign"},
    {"spkac", OPT_SPKAC, '<',
     "File contains DN and signed public key and challenge"},
    {"revoke", OPT_REVOKE, '<', "Revoke a cert (given in file)"},
    {"valid", OPT_VALID, 's',
     "Add a Valid(not-revoked) DB entry about a cert (given in file)"},
    {"extensions", OPT_EXTENSIONS, 's',
     "Extension section (override value in config file)"},
    {"extfile", OPT_EXTFILE, '<',
     "Configuration file with X509v3 extensions to add"},
    {"status", OPT_STATUS, 's', "Shows cert status given the serial number"},
    {"updatedb", OPT_UPDATEDB, '-', "Updates db for expired cert"},
    {"crlexts", OPT_CRLEXTS, 's',
     "CRL extension section (override value in config file)"},
    {"crl_reason", OPT_CRL_REASON, 's', "revocation reason"},
    {"crl_hold", OPT_CRL_HOLD, 's',
     "the hold instruction, an OID. Sets revocation reason to certificateHold"},
    {"crl_compromise", OPT_CRL_COMPROMISE, 's',
     "sets compromise time to val and the revocation reason to keyCompromise"},
    {"crl_CA_compromise", OPT_CRL_CA_COMPROMISE, 's',
     "sets compromise time to val and the revocation reason to CACompromise"},
#ifndef OPENSSL_NO_ENGINE
    {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
#endif
    {NULL}
};

int ca_main(int argc, char **argv)
{
    CONF *conf = NULL;
    ENGINE *e = NULL;
    BIGNUM *crlnumber = NULL, *serial = NULL;
    EVP_PKEY *pkey = NULL;
    BIO *in = NULL, *out = NULL, *Sout = NULL;
    ASN1_INTEGER *tmpser;
    ASN1_TIME *tmptm;
    CA_DB *db = NULL;
    DB_ATTR db_attr;
    STACK_OF(CONF_VALUE) *attribs = NULL;
    STACK_OF(OPENSSL_STRING) *sigopts = NULL;
    STACK_OF(X509) *cert_sk = NULL;
    X509_CRL *crl = NULL;
    const EVP_MD *dgst = NULL;
    char *configfile = default_config_file, *section = NULL;
    char *md = NULL, *policy = NULL, *keyfile = NULL;
    char *certfile = NULL, *crl_ext = NULL, *crlnumberfile = NULL, *key = NULL;
    const char *infile = NULL, *spkac_file = NULL, *ss_cert_file = NULL;
    const char *extensions = NULL, *extfile = NULL, *passinarg = NULL;
    char *outdir = NULL, *outfile = NULL, *rev_arg = NULL, *ser_status = NULL;
    const char *serialfile = NULL, *subj = NULL;
    char *prog, *startdate = NULL, *enddate = NULL;
    char *dbfile = NULL, *f, *randfile = NULL;
    char new_cert[CERT_MAX + 1];
    char tmp[10 + 1] = "\0";
    char *const *pp;
    const char *p;
    int create_ser = 0, free_key = 0, total = 0, total_done = 0;
    int batch = 0, default_op = 1, doupdatedb = 0, ext_copy = EXT_COPY_NONE;
    int keyformat = FORMAT_PEM, multirdn = 0, notext = 0, output_der = 0;
    int ret = 1, email_dn = 1, req = 0, verbose = 0, gencrl = 0, dorevoke = 0;
    int i, j, selfsign = 0;
    long crldays = 0, crlhours = 0, crlsec = 0, days = 0;
    unsigned long chtype = MBSTRING_ASC, nameopt = 0, certopt = 0;
    X509 *x509 = NULL, *x509p = NULL, *x = NULL;
    REVINFO_TYPE rev_type = REV_NONE;
    X509_REVOKED *r = NULL;
    OPTION_CHOICE o;

    new_cert[CERT_MAX] = '\0';

    prog = opt_init(argc, argv, ca_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(ca_options);
            ret = 0;
            goto end;
        case OPT_IN:
            req = 1;
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_VERBOSE:
            verbose = 1;
            break;
        case OPT_CONFIG:
            configfile = opt_arg();
            break;
        case OPT_NAME:
            section = opt_arg();
            break;
        case OPT_SUBJ:
            subj = opt_arg();
            /* preserve=1; */
            break;
        case OPT_UTF8:
            chtype = MBSTRING_UTF8;
            break;
        case OPT_CREATE_SERIAL:
            create_ser = 1;
            break;
        case OPT_MULTIVALUE_RDN:
            multirdn = 1;
            break;
        case OPT_STARTDATE:
            startdate = opt_arg();
            break;
        case OPT_ENDDATE:
            enddate = opt_arg();
            break;
        case OPT_DAYS:
            days = atoi(opt_arg());
            break;
        case OPT_MD:
            md = opt_arg();
            break;
        case OPT_POLICY:
            policy = opt_arg();
            break;
        case OPT_KEYFILE:
            keyfile = opt_arg();
            break;
        case OPT_KEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
                goto opthelp;
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_KEY:
            key = opt_arg();
            break;
        case OPT_CERT:
            certfile = opt_arg();
            break;
        case OPT_SELFSIGN:
            selfsign = 1;
            break;
        case OPT_OUTDIR:
            outdir = opt_arg();
            break;
        case OPT_SIGOPT:
            if (sigopts == NULL)
                sigopts = sk_OPENSSL_STRING_new_null();
            if (sigopts == NULL
                || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
                goto end;
            break;
        case OPT_NOTEXT:
            notext = 1;
            break;
        case OPT_BATCH:
            batch = 1;
            break;
        case OPT_PRESERVEDN:
            preserve = 1;
            break;
        case OPT_NOEMAILDN:
            email_dn = 0;
            break;
        case OPT_GENCRL:
            gencrl = 1;
            break;
        case OPT_MSIE_HACK:
            msie_hack = 1;
            break;
        case OPT_CRLDAYS:
            crldays = atol(opt_arg());
            break;
        case OPT_CRLHOURS:
            crlhours = atol(opt_arg());
            break;
        case OPT_CRLSEC:
            crlsec = atol(opt_arg());
            break;
        case OPT_INFILES:
            req = 1;
            goto end_of_options;
        case OPT_SS_CERT:
            ss_cert_file = opt_arg();
            req = 1;
            break;
        case OPT_SPKAC:
            spkac_file = opt_arg();
            req = 1;
            break;
        case OPT_REVOKE:
            infile = opt_arg();
            dorevoke = 1;
            break;
        case OPT_VALID:
            infile = opt_arg();
            dorevoke = 2;
            break;
        case OPT_EXTENSIONS:
            extensions = opt_arg();
            break;
        case OPT_EXTFILE:
            extfile = opt_arg();
            break;
        case OPT_STATUS:
            ser_status = opt_arg();
            break;
        case OPT_UPDATEDB:
            doupdatedb = 1;
            break;
        case OPT_CRLEXTS:
            crl_ext = opt_arg();
            break;
        case OPT_CRL_REASON:        /* := REV_CRL_REASON */
        case OPT_CRL_HOLD:
        case OPT_CRL_COMPROMISE:
        case OPT_CRL_CA_COMPROMISE:
            rev_arg = opt_arg();
            rev_type = (o - OPT_CRL_REASON) + REV_CRL_REASON;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        }
    }
end_of_options:
    argc = opt_num_rest();
    argv = opt_rest();

    BIO_printf(bio_err, "Using configuration from %s\n", configfile);

    if ((conf = app_load_config(configfile)) == NULL)
        goto end;
    if (configfile != default_config_file && !app_load_modules(conf))
        goto end;

    /* Lets get the config section we are using */
    if (section == NULL
        && (section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_CA)) == NULL)
        goto end;

    if (conf != NULL) {
        p = NCONF_get_string(conf, NULL, "oid_file");
        if (p == NULL)
            ERR_clear_error();
        if (p != NULL) {
            BIO *oid_bio;

            oid_bio = BIO_new_file(p, "r");
            if (oid_bio == NULL) {
                /*-
                BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
                ERR_print_errors(bio_err);
                */
                ERR_clear_error();
            } else {
                OBJ_create_objects(oid_bio);
                BIO_free(oid_bio);
            }
        }
        if (!add_oid_section(conf)) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");
    if (randfile == NULL)
        ERR_clear_error();
    app_RAND_load_file(randfile, 0);

    f = NCONF_get_string(conf, section, STRING_MASK);
    if (!f)
        ERR_clear_error();

    if (f && !ASN1_STRING_set_default_mask_asc(f)) {
        BIO_printf(bio_err, "Invalid global string mask setting %s\n", f);
        goto end;
    }

    if (chtype != MBSTRING_UTF8) {
        f = NCONF_get_string(conf, section, UTF8_IN);
        if (!f)
            ERR_clear_error();
        else if (strcmp(f, "yes") == 0)
            chtype = MBSTRING_UTF8;
    }

    db_attr.unique_subject = 1;
    p = NCONF_get_string(conf, section, ENV_UNIQUE_SUBJECT);
    if (p) {
        db_attr.unique_subject = parse_yesno(p, 1);
    } else
        ERR_clear_error();

    /*****************************************************************/
    /* report status of cert with serial number given on command line */
    if (ser_status) {
        dbfile = lookup_conf(conf, section, ENV_DATABASE);
        if (dbfile == NULL)
            goto end;

        db = load_index(dbfile, &db_attr);
        if (db == NULL)
            goto end;

        if (!index_index(db))
            goto end;

        if (get_certificate_status(ser_status, db) != 1)
            BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status);
        goto end;
    }

    /*****************************************************************/
    /* we definitely need a private key, so let's get it */

    if (keyfile == NULL
        && (keyfile = lookup_conf(conf, section, ENV_PRIVATE_KEY)) == NULL)
        goto end;

    if (!key) {
        free_key = 1;
        if (!app_passwd(passinarg, NULL, &key, NULL)) {
            BIO_printf(bio_err, "Error getting password\n");
            goto end;
        }
    }
    pkey = load_key(keyfile, keyformat, 0, key, e, "CA private key");
    if (key)
        OPENSSL_cleanse(key, strlen(key));
    if (pkey == NULL) {
        /* load_key() has already printed an appropriate message */
        goto end;
    }

    /*****************************************************************/
    /* we need a certificate */
    if (!selfsign || spkac_file || ss_cert_file || gencrl) {
        if (certfile == NULL
            && (certfile = lookup_conf(conf, section, ENV_CERTIFICATE)) == NULL)
            goto end;

        x509 = load_cert(certfile, FORMAT_PEM, "CA certificate");
        if (x509 == NULL)
            goto end;

        if (!X509_check_private_key(x509, pkey)) {
            BIO_printf(bio_err,
                       "CA certificate and CA private key do not match\n");
            goto end;
        }
    }
    if (!selfsign)
        x509p = x509;

    f = NCONF_get_string(conf, BASE_SECTION, ENV_PRESERVE);
    if (f == NULL)
        ERR_clear_error();
    if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
        preserve = 1;
    f = NCONF_get_string(conf, BASE_SECTION, ENV_MSIE_HACK);
    if (f == NULL)
        ERR_clear_error();
    if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
        msie_hack = 1;

    f = NCONF_get_string(conf, section, ENV_NAMEOPT);

    if (f) {
        if (!set_name_ex(&nameopt, f)) {
            BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f);
            goto end;
        }
        default_op = 0;
    } else {
        nameopt = XN_FLAG_ONELINE;
        ERR_clear_error();
    }

    f = NCONF_get_string(conf, section, ENV_CERTOPT);

    if (f) {
        if (!set_cert_ex(&certopt, f)) {
            BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f);
            goto end;
        }
        default_op = 0;
    } else
        ERR_clear_error();

    f = NCONF_get_string(conf, section, ENV_EXTCOPY);

    if (f) {
        if (!set_ext_copy(&ext_copy, f)) {
            BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f);
            goto end;
        }
    } else
        ERR_clear_error();

    /*****************************************************************/
    /* lookup where to write new certificates */
    if ((outdir == NULL) && (req)) {

        outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR);
        if (outdir == NULL) {
            BIO_printf(bio_err,
                       "there needs to be defined a directory for new certificate to be placed in\n");
            goto end;
        }
#ifndef OPENSSL_SYS_VMS
        /*
         * outdir is a directory spec, but access() for VMS demands a
         * filename.  We could use the DEC C routine to convert the
         * directory syntax to Unixly, and give that to app_isdir,
         * but for now the fopen will catch the error if it's not a
         * directory
         */
        if (app_isdir(outdir) <= 0) {
            BIO_printf(bio_err, "%s: %s is not a directory\n", prog, outdir);
            perror(outdir);
            goto end;
        }
#endif
    }

    /*****************************************************************/
    /* we need to load the database file */
    dbfile = lookup_conf(conf, section, ENV_DATABASE);
    if (dbfile == NULL)
        goto end;

    db = load_index(dbfile, &db_attr);
    if (db == NULL)
        goto end;

    /* Lets check some fields */
    for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
        pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
        if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) {
            BIO_printf(bio_err,
                       "entry %d: not revoked yet, but has a revocation date\n",
                       i + 1);
            goto end;
        }
        if ((pp[DB_type][0] == DB_TYPE_REV) &&
            !make_revoked(NULL, pp[DB_rev_date])) {
            BIO_printf(bio_err, " in entry %d\n", i + 1);
            goto end;
        }
        if (!check_time_format((char *)pp[DB_exp_date])) {
            BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1);
            goto end;
        }
        p = pp[DB_serial];
        j = strlen(p);
        if (*p == '-') {
            p++;
            j--;
        }
        if ((j & 1) || (j < 2)) {
            BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n",
                       i + 1, j);
            goto end;
        }
        for ( ; *p; p++) {
            if (!isxdigit(_UC(*p))) {
                BIO_printf(bio_err,
                           "entry %d: bad char 0%o '%c' in serial number\n",
                           i + 1, *p, *p);
                goto end;
            }
        }
    }
    if (verbose) {
        TXT_DB_write(bio_out, db->db);
        BIO_printf(bio_err, "%d entries loaded from the database\n",
                   sk_OPENSSL_PSTRING_num(db->db->data));
        BIO_printf(bio_err, "generating index\n");
    }

    if (!index_index(db))
        goto end;

    /*****************************************************************/
    /* Update the db file for expired certificates */
    if (doupdatedb) {
        if (verbose)
            BIO_printf(bio_err, "Updating %s ...\n", dbfile);

        i = do_updatedb(db);
        if (i == -1) {
            BIO_printf(bio_err, "Malloc failure\n");
            goto end;
        } else if (i == 0) {
            if (verbose)
                BIO_printf(bio_err, "No entries found to mark expired\n");
        } else {
            if (!save_index(dbfile, "new", db))
                goto end;

            if (!rotate_index(dbfile, "new", "old"))
                goto end;

            if (verbose)
                BIO_printf(bio_err,
                           "Done. %d entries marked as expired\n", i);
        }
    }

    /*****************************************************************/
    /* Read extensions config file                                   */
    if (extfile) {
        if ((extconf = app_load_config(extfile)) == NULL) {
            ret = 1;
            goto end;
        }

        if (verbose)
            BIO_printf(bio_err, "Successfully loaded extensions file %s\n",
                       extfile);

        /* We can have sections in the ext file */
        if (extensions == NULL) {
            extensions = NCONF_get_string(extconf, "default", "extensions");
            if (extensions == NULL)
                extensions = "default";
        }
    }

    /*****************************************************************/
    if (req || gencrl) {
        /* FIXME: Is it really always text? */
        Sout = bio_open_default(outfile, 'w', FORMAT_TEXT);
        if (Sout == NULL)
            goto end;
    }

    if (md == NULL
        && (md = lookup_conf(conf, section, ENV_DEFAULT_MD)) == NULL)
        goto end;

    if (strcmp(md, "default") == 0) {
        int def_nid;
        if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) <= 0) {
            BIO_puts(bio_err, "no default digest\n");
            goto end;
        }
        md = (char *)OBJ_nid2sn(def_nid);
    }

    if (!opt_md(md, &dgst)) {
        goto end;
    }

    if (req) {
        if (email_dn == 1) {
            char *tmp_email_dn = NULL;

            tmp_email_dn = NCONF_get_string(conf, section, ENV_DEFAULT_EMAIL_DN);
            if (tmp_email_dn != NULL && strcmp(tmp_email_dn, "no") == 0)
                email_dn = 0;
        }
        if (verbose)
            BIO_printf(bio_err, "message digest is %s\n",
                       OBJ_nid2ln(EVP_MD_type(dgst)));
        if (policy == NULL
            && (policy = lookup_conf(conf, section, ENV_POLICY)) == NULL)
            goto end;

        if (verbose)
            BIO_printf(bio_err, "policy is %s\n", policy);

        serialfile = lookup_conf(conf, section, ENV_SERIAL);
        if (serialfile == NULL)
            goto end;

        if (!extconf) {
            /*
             * no '-extfile' option, so we look for extensions in the main
             * configuration file
             */
            if (!extensions) {
                extensions = NCONF_get_string(conf, section, ENV_EXTENSIONS);
                if (!extensions)
                    ERR_clear_error();
            }
            if (extensions) {
                /* Check syntax of file */
                X509V3_CTX ctx;
                X509V3_set_ctx_test(&ctx);
                X509V3_set_nconf(&ctx, conf);
                if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) {
                    BIO_printf(bio_err,
                               "Error Loading extension section %s\n",
                               extensions);
                    ret = 1;
                    goto end;
                }
            }
        }

        if (startdate == NULL) {
            startdate = NCONF_get_string(conf, section,
                                         ENV_DEFAULT_STARTDATE);
            if (startdate == NULL)
                ERR_clear_error();
        }
        if (startdate && !ASN1_TIME_set_string(NULL, startdate)) {
            BIO_printf(bio_err,
                       "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
            goto end;
        }
        if (startdate == NULL)
            startdate = "today";

        if (enddate == NULL) {
            enddate = NCONF_get_string(conf, section, ENV_DEFAULT_ENDDATE);
            if (enddate == NULL)
                ERR_clear_error();
        }
        if (enddate && !ASN1_TIME_set_string(NULL, enddate)) {
            BIO_printf(bio_err,
                       "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
            goto end;
        }

        if (days == 0) {
            if (!NCONF_get_number(conf, section, ENV_DEFAULT_DAYS, &days))
                days = 0;
        }
        if (!enddate && (days == 0)) {
            BIO_printf(bio_err,
                       "cannot lookup how many days to certify for\n");
            goto end;
        }

        if ((serial = load_serial(serialfile, create_ser, NULL)) == NULL) {
            BIO_printf(bio_err, "error while loading serial number\n");
            goto end;
        }
        if (verbose) {
            if (BN_is_zero(serial))
                BIO_printf(bio_err, "next serial number is 00\n");
            else {
                if ((f = BN_bn2hex(serial)) == NULL)
                    goto end;
                BIO_printf(bio_err, "next serial number is %s\n", f);
                OPENSSL_free(f);
            }
        }

        if ((attribs = NCONF_get_section(conf, policy)) == NULL) {
            BIO_printf(bio_err, "unable to find 'section' for %s\n", policy);
            goto end;
        }

        if ((cert_sk = sk_X509_new_null()) == NULL) {
            BIO_printf(bio_err, "Memory allocation failure\n");
            goto end;
        }
        if (spkac_file != NULL) {
            total++;
            j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts,
                              attribs, db, serial, subj, chtype, multirdn,
                              email_dn, startdate, enddate, days, extensions,
                              conf, verbose, certopt, nameopt, default_op,
                              ext_copy);
            if (j < 0)
                goto end;
            if (j > 0) {
                total_done++;
                BIO_printf(bio_err, "\n");
                if (!BN_add_word(serial, 1))
                    goto end;
                if (!sk_X509_push(cert_sk, x)) {
                    BIO_printf(bio_err, "Memory allocation failure\n");
                    goto end;
                }
                if (outfile) {
                    output_der = 1;
                    batch = 1;
                }
            }
        }
        if (ss_cert_file != NULL) {
            total++;
            j = certify_cert(&x, ss_cert_file, pkey, x509, dgst, sigopts,
                             attribs,
                             db, serial, subj, chtype, multirdn, email_dn,
                             startdate, enddate, days, batch, extensions,
                             conf, verbose, certopt, nameopt, default_op,
                             ext_copy);
            if (j < 0)
                goto end;
            if (j > 0) {
                total_done++;
                BIO_printf(bio_err, "\n");
                if (!BN_add_word(serial, 1))
                    goto end;
                if (!sk_X509_push(cert_sk, x)) {
                    BIO_printf(bio_err, "Memory allocation failure\n");
                    goto end;
                }
            }
        }
        if (infile != NULL) {
            total++;
            j = certify(&x, infile, pkey, x509p, dgst, sigopts, attribs, db,
                        serial, subj, chtype, multirdn, email_dn, startdate,
                        enddate, days, batch, extensions, conf, verbose,
                        certopt, nameopt, default_op, ext_copy, selfsign);
            if (j < 0)
                goto end;
            if (j > 0) {
                total_done++;
                BIO_printf(bio_err, "\n");
                if (!BN_add_word(serial, 1))
                    goto end;
                if (!sk_X509_push(cert_sk, x)) {
                    BIO_printf(bio_err, "Memory allocation failure\n");
                    goto end;
                }
            }
        }
        for (i = 0; i < argc; i++) {
            total++;
            j = certify(&x, argv[i], pkey, x509p, dgst, sigopts, attribs, db,
                        serial, subj, chtype, multirdn, email_dn, startdate,
                        enddate, days, batch, extensions, conf, verbose,
                        certopt, nameopt, default_op, ext_copy, selfsign);
            if (j < 0)
                goto end;
            if (j > 0) {
                total_done++;
                BIO_printf(bio_err, "\n");
                if (!BN_add_word(serial, 1))
                    goto end;
                if (!sk_X509_push(cert_sk, x)) {
                    BIO_printf(bio_err, "Memory allocation failure\n");
                    goto end;
                }
            }
        }
        /*
         * we have a stack of newly certified certificates and a data base
         * and serial number that need updating
         */

        if (sk_X509_num(cert_sk) > 0) {
            if (!batch) {
                BIO_printf(bio_err,
                           "\n%d out of %d certificate requests certified, commit? [y/n]",
                           total_done, total);
                (void)BIO_flush(bio_err);
                tmp[0] = '\0';
                if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
                    BIO_printf(bio_err,
                               "CERTIFICATION CANCELED: I/O error\n");
                    ret = 0;
                    goto end;
                }
                if (tmp[0] != 'y' && tmp[0] != 'Y') {
                    BIO_printf(bio_err, "CERTIFICATION CANCELED\n");
                    ret = 0;
                    goto end;
                }
            }

            BIO_printf(bio_err, "Write out database with %d new entries\n",
                       sk_X509_num(cert_sk));

            if (!save_serial(serialfile, "new", serial, NULL))
                goto end;

            if (!save_index(dbfile, "new", db))
                goto end;
        }

        if (verbose)
            BIO_printf(bio_err, "writing new certificates\n");
        for (i = 0; i < sk_X509_num(cert_sk); i++) {
            BIO *Cout = NULL;
            X509 *xi = sk_X509_value(cert_sk, i);
            ASN1_INTEGER *serialNumber = X509_get_serialNumber(xi);
            int k;
            char *n;

            j = ASN1_STRING_length(serialNumber);
            p = (const char *)ASN1_STRING_get0_data(serialNumber);

            if (strlen(outdir) >= (size_t)(j ? CERT_MAX - j * 2 - 6 : CERT_MAX - 8)) {
                BIO_printf(bio_err, "certificate file name too long\n");
                goto end;
            }

            strcpy(new_cert, outdir);
#ifndef OPENSSL_SYS_VMS
            OPENSSL_strlcat(new_cert, "/", sizeof(new_cert));
#endif

            n = (char *)&(new_cert[strlen(new_cert)]);
            if (j > 0) {
                for (k = 0; k < j; k++) {
                    if (n >= &(new_cert[sizeof(new_cert)]))
                        break;
                    BIO_snprintf(n,
                                 &new_cert[0] + sizeof(new_cert) - n,
                                 "%02X", (unsigned char)*(p++));
                    n += 2;
                }
            } else {
                *(n++) = '0';
                *(n++) = '0';
            }
            *(n++) = '.';
            *(n++) = 'p';
            *(n++) = 'e';
            *(n++) = 'm';
            *n = '\0';
            if (verbose)
                BIO_printf(bio_err, "writing %s\n", new_cert);

            Cout = BIO_new_file(new_cert, "w");
            if (Cout == NULL) {
                perror(new_cert);
                goto end;
            }
            write_new_certificate(Cout, xi, 0, notext);
            write_new_certificate(Sout, xi, output_der, notext);
            BIO_free_all(Cout);
        }

        if (sk_X509_num(cert_sk)) {
            /* Rename the database and the serial file */
            if (!rotate_serial(serialfile, "new", "old"))
                goto end;

            if (!rotate_index(dbfile, "new", "old"))
                goto end;

            BIO_printf(bio_err, "Data Base Updated\n");
        }
    }

    /*****************************************************************/
    if (gencrl) {
        int crl_v2 = 0;
        if (!crl_ext) {
            crl_ext = NCONF_get_string(conf, section, ENV_CRLEXT);
            if (!crl_ext)
                ERR_clear_error();
        }
        if (crl_ext) {
            /* Check syntax of file */
            X509V3_CTX ctx;
            X509V3_set_ctx_test(&ctx);
            X509V3_set_nconf(&ctx, conf);
            if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) {
                BIO_printf(bio_err,
                           "Error Loading CRL extension section %s\n",
                           crl_ext);
                ret = 1;
                goto end;
            }
        }

        if ((crlnumberfile = NCONF_get_string(conf, section, ENV_CRLNUMBER))
            != NULL)
            if ((crlnumber = load_serial(crlnumberfile, 0, NULL)) == NULL) {
                BIO_printf(bio_err, "error while loading CRL number\n");
                goto end;
            }

        if (!crldays && !crlhours && !crlsec) {
            if (!NCONF_get_number(conf, section,
                                  ENV_DEFAULT_CRL_DAYS, &crldays))
                crldays = 0;
            if (!NCONF_get_number(conf, section,
                                  ENV_DEFAULT_CRL_HOURS, &crlhours))
                crlhours = 0;
            ERR_clear_error();
        }
        if ((crldays == 0) && (crlhours == 0) && (crlsec == 0)) {
            BIO_printf(bio_err,
                       "cannot lookup how long until the next CRL is issued\n");
            goto end;
        }

        if (verbose)
            BIO_printf(bio_err, "making CRL\n");
        if ((crl = X509_CRL_new()) == NULL)
            goto end;
        if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509)))
            goto end;

        tmptm = ASN1_TIME_new();
        if (tmptm == NULL)
            goto end;
        X509_gmtime_adj(tmptm, 0);
        X509_CRL_set1_lastUpdate(crl, tmptm);
        if (!X509_time_adj_ex(tmptm, crldays, crlhours * 60 * 60 + crlsec,
                              NULL)) {
            BIO_puts(bio_err, "error setting CRL nextUpdate\n");
            goto end;
        }
        X509_CRL_set1_nextUpdate(crl, tmptm);

        ASN1_TIME_free(tmptm);

        for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
            pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
            if (pp[DB_type][0] == DB_TYPE_REV) {
                if ((r = X509_REVOKED_new()) == NULL)
                    goto end;
                j = make_revoked(r, pp[DB_rev_date]);
                if (!j)
                    goto end;
                if (j == 2)
                    crl_v2 = 1;
                if (!BN_hex2bn(&serial, pp[DB_serial]))
                    goto end;
                tmpser = BN_to_ASN1_INTEGER(serial, NULL);
                BN_free(serial);
                serial = NULL;
                if (!tmpser)
                    goto end;
                X509_REVOKED_set_serialNumber(r, tmpser);
                ASN1_INTEGER_free(tmpser);
                X509_CRL_add0_revoked(crl, r);
            }
        }

        /*
         * sort the data so it will be written in serial number order
         */
        X509_CRL_sort(crl);

        /* we now have a CRL */
        if (verbose)
            BIO_printf(bio_err, "signing CRL\n");

        /* Add any extensions asked for */

        if (crl_ext || crlnumberfile != NULL) {
            X509V3_CTX crlctx;
            X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0);
            X509V3_set_nconf(&crlctx, conf);

            if (crl_ext)
                if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl))
                    goto end;
            if (crlnumberfile != NULL) {
                tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL);
                if (!tmpser)
                    goto end;
                X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0);
                ASN1_INTEGER_free(tmpser);
                crl_v2 = 1;
                if (!BN_add_word(crlnumber, 1))
                    goto end;
            }
        }
        if (crl_ext || crl_v2) {
            if (!X509_CRL_set_version(crl, 1))
                goto end;       /* version 2 CRL */
        }

        /* we have a CRL number that need updating */
        if (crlnumberfile != NULL)
            if (!save_serial(crlnumberfile, "new", crlnumber, NULL))
                goto end;

        BN_free(crlnumber);
        crlnumber = NULL;

        if (!do_X509_CRL_sign(crl, pkey, dgst, sigopts))
            goto end;

        PEM_write_bio_X509_CRL(Sout, crl);

        if (crlnumberfile != NULL) /* Rename the crlnumber file */
            if (!rotate_serial(crlnumberfile, "new", "old"))
                goto end;

    }
    /*****************************************************************/
    if (dorevoke) {
        if (infile == NULL) {