2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
58 /* ====================================================================
59 * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
87 * 6. Redistributions of any form whatsoever must retain the following
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
112 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
114 * On VMS, you need to define this to get the declaration of fileno(). The
115 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
117 # define _POSIX_C_SOURCE 2
122 #include <sys/types.h>
126 #include <openssl/err.h>
127 #include <openssl/x509.h>
128 #include <openssl/x509v3.h>
129 #include <openssl/pem.h>
130 #include <openssl/pkcs12.h>
131 #include <openssl/ui.h>
132 #include <openssl/safestack.h>
133 #ifndef OPENSSL_NO_ENGINE
134 # include <openssl/engine.h>
136 #ifndef OPENSSL_NO_RSA
137 # include <openssl/rsa.h>
139 #include <openssl/bn.h>
140 #ifndef OPENSSL_NO_JPAKE
141 # include <openssl/jpake.h>
149 static int WIN32_rename(const char *from, const char *to);
150 # define rename(from,to) WIN32_rename((from),(to))
159 static UI_METHOD *ui_method = NULL;
161 static int set_table_opts(unsigned long *flags, const char *arg,
162 const NAME_EX_TBL * in_tbl);
163 static int set_multi_opts(unsigned long *flags, const char *arg,
164 const NAME_EX_TBL * in_tbl);
166 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
167 /* Looks like this stuff is worth moving into separate function */
168 static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
169 const char *key_descrip, int format);
172 int app_init(long mesgwin);
173 #ifdef undef /* never finished - probably never will be
175 int args_from_file(char *file, int *argc, char **argv[])
180 static char *buf = NULL;
181 static char **arg = NULL;
184 fp = fopen(file, "r");
188 if (fseek(fp, 0, SEEK_END) == 0)
189 len = ftell(fp), rewind(fp);
202 buf = (char *)OPENSSL_malloc(len + 1);
206 len = fread(buf, 1, len, fp);
212 for (p = buf; *p; p++)
217 arg = (char **)OPENSSL_malloc(sizeof(char *) * (i * 2));
225 if (*p == '#') { /* comment line */
226 while (*p && (*p != '\n'))
230 /* else we have a line */
233 while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
241 /* else it is a tab or space */
243 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
253 while (*p && (*p != '\n'))
257 /* else *p == '\n' */
269 if ((*s == 'D') || (*s == 'd'))
270 return (FORMAT_ASN1);
271 else if ((*s == 'T') || (*s == 't'))
272 return (FORMAT_TEXT);
273 else if ((*s == 'N') || (*s == 'n'))
274 return (FORMAT_NETSCAPE);
275 else if ((*s == 'S') || (*s == 's'))
276 return (FORMAT_SMIME);
277 else if ((*s == 'M') || (*s == 'm'))
278 return (FORMAT_MSBLOB);
280 || (strcmp(s, "PKCS12") == 0) || (strcmp(s, "pkcs12") == 0)
281 || (strcmp(s, "P12") == 0) || (strcmp(s, "p12") == 0))
282 return (FORMAT_PKCS12);
283 else if ((*s == 'E') || (*s == 'e'))
284 return (FORMAT_ENGINE);
285 else if ((*s == 'P') || (*s == 'p')) {
286 if (s[1] == 'V' || s[1] == 'v')
291 return (FORMAT_UNDEF);
294 #if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_NETWARE)
295 void program_name(char *in, char *out, int size)
301 /* find the last '/', '\' or ':' */
302 for (i = n - 1; i > 0; i--) {
303 if ((in[i] == '/') || (in[i] == '\\') || (in[i] == ':')) {
312 # if defined(OPENSSL_SYS_NETWARE)
313 /* strip off trailing .nlm if present. */
314 if ((n > 4) && (p[n - 4] == '.') &&
315 ((p[n - 3] == 'n') || (p[n - 3] == 'N')) &&
316 ((p[n - 2] == 'l') || (p[n - 2] == 'L')) &&
317 ((p[n - 1] == 'm') || (p[n - 1] == 'M')))
320 /* strip off trailing .exe if present. */
321 if ((n > 4) && (p[n - 4] == '.') &&
322 ((p[n - 3] == 'e') || (p[n - 3] == 'E')) &&
323 ((p[n - 2] == 'x') || (p[n - 2] == 'X')) &&
324 ((p[n - 1] == 'e') || (p[n - 1] == 'E')))
331 for (i = 0; i < n; i++) {
332 if ((p[i] >= 'A') && (p[i] <= 'Z'))
333 out[i] = p[i] - 'A' + 'a';
340 # ifdef OPENSSL_SYS_VMS
341 void program_name(char *in, char *out, int size)
346 while (*chars != '\0') {
347 q = strrchr(p, *chars);
356 strncpy(out, p, size - 1);
358 out[size - 1] = '\0';
364 void program_name(char *in, char *out, int size)
368 p = strrchr(in, '/');
373 BUF_strlcpy(out, p, size);
378 int chopup_args(ARGS *arg, char *buf, int *argc, char **argv[])
387 if (arg->count == 0) {
389 arg->data = (char **)OPENSSL_malloc(sizeof(char *) * arg->count);
390 if (arg->data == NULL)
393 for (i = 0; i < arg->count; i++)
399 /* first scan over white space */
402 while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\n')))
407 /* The start of something good :-) */
408 if (num >= arg->count) {
410 int tlen = arg->count + 20;
411 tmp_p = (char **)OPENSSL_realloc(arg->data,
412 sizeof(char *) * tlen);
417 /* initialize newly allocated data */
418 for (i = num; i < arg->count; i++)
421 arg->data[num++] = p;
423 /* now look for the end of this */
424 if ((*p == '\'') || (*p == '\"')) { /* scan for closing quote */
426 arg->data[num - 1]++; /* jump over quote */
427 while (*p && (*p != i))
431 while (*p && ((*p != ' ') && (*p != '\t') && (*p != '\n')))
447 int app_init(long mesgwin)
453 int dump_cert_text(BIO *out, X509 *x)
457 p = X509_NAME_oneline(X509_get_subject_name(x), NULL, 0);
458 BIO_puts(out, "subject=");
462 p = X509_NAME_oneline(X509_get_issuer_name(x), NULL, 0);
463 BIO_puts(out, "\nissuer=");
471 static int ui_open(UI *ui)
473 return UI_method_get_opener(UI_OpenSSL())(ui);
476 static int ui_read(UI *ui, UI_STRING *uis)
478 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
479 && UI_get0_user_data(ui)) {
480 switch (UI_get_string_type(uis)) {
484 const char *password =
485 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
486 if (password && password[0] != '\0') {
487 UI_set_result(ui, uis, password);
495 return UI_method_get_reader(UI_OpenSSL())(ui, uis);
498 static int ui_write(UI *ui, UI_STRING *uis)
500 if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD
501 && UI_get0_user_data(ui)) {
502 switch (UI_get_string_type(uis)) {
506 const char *password =
507 ((PW_CB_DATA *)UI_get0_user_data(ui))->password;
508 if (password && password[0] != '\0')
515 return UI_method_get_writer(UI_OpenSSL())(ui, uis);
518 static int ui_close(UI *ui)
520 return UI_method_get_closer(UI_OpenSSL())(ui);
523 int setup_ui_method(void)
525 ui_method = UI_create_method("OpenSSL application user interface");
526 UI_method_set_opener(ui_method, ui_open);
527 UI_method_set_reader(ui_method, ui_read);
528 UI_method_set_writer(ui_method, ui_write);
529 UI_method_set_closer(ui_method, ui_close);
533 void destroy_ui_method(void)
536 UI_destroy_method(ui_method);
541 int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
545 const char *prompt_info = NULL;
546 const char *password = NULL;
547 PW_CB_DATA *cb_data = (PW_CB_DATA *)cb_tmp;
550 if (cb_data->password)
551 password = cb_data->password;
552 if (cb_data->prompt_info)
553 prompt_info = cb_data->prompt_info;
557 res = strlen(password);
560 memcpy(buf, password, res);
564 ui = UI_new_method(ui_method);
571 prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
573 BIO_printf(bio_err, "Out of memory\n");
578 ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD;
579 UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0);
582 ok = UI_add_input_string(ui, prompt, ui_flags, buf,
583 PW_MIN_LENGTH, bufsiz - 1);
584 if (ok >= 0 && verify) {
585 buff = (char *)OPENSSL_malloc(bufsiz);
587 BIO_printf(bio_err, "Out of memory\n");
589 OPENSSL_free(prompt);
592 ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
593 PW_MIN_LENGTH, bufsiz - 1, buf);
599 while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0));
602 OPENSSL_cleanse(buff, (unsigned int)bufsiz);
609 BIO_printf(bio_err, "User interface error\n");
610 ERR_print_errors(bio_err);
611 OPENSSL_cleanse(buf, (unsigned int)bufsiz);
615 BIO_printf(bio_err, "aborted!\n");
616 OPENSSL_cleanse(buf, (unsigned int)bufsiz);
620 OPENSSL_free(prompt);
625 static char *app_get_pass(BIO *err, char *arg, int keepbio);
627 int app_passwd(BIO *err, char *arg1, char *arg2, char **pass1, char **pass2)
630 if (!arg2 || !arg1 || strcmp(arg1, arg2))
635 *pass1 = app_get_pass(err, arg1, same);
641 *pass2 = app_get_pass(err, arg2, same ? 2 : 0);
649 static char *app_get_pass(BIO *err, char *arg, int keepbio)
651 char *tmp, tpass[APP_PASS_LEN];
652 static BIO *pwdbio = NULL;
654 if (!strncmp(arg, "pass:", 5))
655 return BUF_strdup(arg + 5);
656 if (!strncmp(arg, "env:", 4)) {
657 tmp = getenv(arg + 4);
659 BIO_printf(err, "Can't read environment variable %s\n", arg + 4);
662 return BUF_strdup(tmp);
664 if (!keepbio || !pwdbio) {
665 if (!strncmp(arg, "file:", 5)) {
666 pwdbio = BIO_new_file(arg + 5, "r");
668 BIO_printf(err, "Can't open file %s\n", arg + 5);
673 * Under _WIN32, which covers even Win64 and CE, file
674 * descriptors referenced by BIO_s_fd are not inherited
675 * by child process and therefore below is not an option.
676 * It could have been an option if bss_fd.c was operating
677 * on real Windows descriptors, such as those obtained
680 } else if (!strncmp(arg, "fd:", 3)) {
684 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
685 if ((i < 0) || !pwdbio) {
686 BIO_printf(err, "Can't access file descriptor %s\n", arg + 3);
690 * Can't do BIO_gets on an fd BIO so add a buffering BIO
692 btmp = BIO_new(BIO_f_buffer());
693 pwdbio = BIO_push(btmp, pwdbio);
695 } else if (!strcmp(arg, "stdin")) {
696 pwdbio = BIO_new_fp(stdin, BIO_NOCLOSE);
698 BIO_printf(err, "Can't open BIO for stdin\n");
702 BIO_printf(err, "Invalid password argument \"%s\"\n", arg);
706 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
708 BIO_free_all(pwdbio);
712 BIO_printf(err, "Error reading password from BIO\n");
715 tmp = strchr(tpass, '\n');
718 return BUF_strdup(tpass);
721 int add_oid_section(BIO *err, CONF *conf)
724 STACK_OF(CONF_VALUE) *sktmp;
727 if (!(p = NCONF_get_string(conf, NULL, "oid_section"))) {
731 if (!(sktmp = NCONF_get_section(conf, p))) {
732 BIO_printf(err, "problem loading oid section %s\n", p);
735 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
736 cnf = sk_CONF_VALUE_value(sktmp, i);
737 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
738 BIO_printf(err, "problem creating object %s=%s\n",
739 cnf->name, cnf->value);
746 static int load_pkcs12(BIO *err, BIO *in, const char *desc,
747 pem_password_cb *pem_cb, void *cb_data,
748 EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca)
751 char tpass[PEM_BUFSIZE];
754 p12 = d2i_PKCS12_bio(in, NULL);
756 BIO_printf(err, "Error loading PKCS12 file for %s\n", desc);
759 /* See if an empty password will do */
760 if (PKCS12_verify_mac(p12, "", 0) || PKCS12_verify_mac(p12, NULL, 0))
764 pem_cb = (pem_password_cb *)password_callback;
765 len = pem_cb(tpass, PEM_BUFSIZE, 0, cb_data);
767 BIO_printf(err, "Passpharse callback error for %s\n", desc);
770 if (len < PEM_BUFSIZE)
772 if (!PKCS12_verify_mac(p12, tpass, len)) {
774 "Mac verify error (wrong password?) in PKCS12 file for %s\n",
780 ret = PKCS12_parse(p12, pass, pkey, cert, ca);
787 X509 *load_cert(BIO *err, const char *file, int format,
788 const char *pass, ENGINE *e, const char *cert_descrip)
793 if ((cert = BIO_new(BIO_s_file())) == NULL) {
794 ERR_print_errors(err);
800 # ifndef OPENSSL_NO_SETVBUF_IONBF
801 setvbuf(stdin, NULL, _IONBF, 0);
802 # endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
804 BIO_set_fp(cert, stdin, BIO_NOCLOSE);
806 if (BIO_read_filename(cert, file) <= 0) {
807 BIO_printf(err, "Error opening %s %s\n", cert_descrip, file);
808 ERR_print_errors(err);
813 if (format == FORMAT_ASN1)
814 x = d2i_X509_bio(cert, NULL);
815 else if (format == FORMAT_NETSCAPE) {
817 nx = ASN1_item_d2i_bio(ASN1_ITEM_rptr(NETSCAPE_X509), cert, NULL);
821 if ((strncmp(NETSCAPE_CERT_HDR, (char *)nx->header->data,
822 nx->header->length) != 0)) {
823 NETSCAPE_X509_free(nx);
824 BIO_printf(err, "Error reading header on certificate\n");
829 NETSCAPE_X509_free(nx);
830 } else if (format == FORMAT_PEM)
831 x = PEM_read_bio_X509_AUX(cert, NULL,
832 (pem_password_cb *)password_callback, NULL);
833 else if (format == FORMAT_PKCS12) {
834 if (!load_pkcs12(err, cert, cert_descrip, NULL, NULL, NULL, &x, NULL))
837 BIO_printf(err, "bad input format specified for %s\n", cert_descrip);
842 BIO_printf(err, "unable to load certificate\n");
843 ERR_print_errors(err);
850 EVP_PKEY *load_key(BIO *err, const char *file, int format, int maybe_stdin,
851 const char *pass, ENGINE *e, const char *key_descrip)
854 EVP_PKEY *pkey = NULL;
857 cb_data.password = pass;
858 cb_data.prompt_info = file;
860 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
861 BIO_printf(err, "no keyfile specified\n");
864 #ifndef OPENSSL_NO_ENGINE
865 if (format == FORMAT_ENGINE) {
867 BIO_printf(err, "no engine specified\n");
869 pkey = ENGINE_load_private_key(e, file, ui_method, &cb_data);
871 BIO_printf(err, "cannot load %s from engine\n", key_descrip);
872 ERR_print_errors(err);
878 key = BIO_new(BIO_s_file());
880 ERR_print_errors(err);
883 if (file == NULL && maybe_stdin) {
885 # ifndef OPENSSL_NO_SETVBUF_IONBF
886 setvbuf(stdin, NULL, _IONBF, 0);
887 # endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
889 BIO_set_fp(key, stdin, BIO_NOCLOSE);
890 } else if (BIO_read_filename(key, file) <= 0) {
891 BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
892 ERR_print_errors(err);
895 if (format == FORMAT_ASN1) {
896 pkey = d2i_PrivateKey_bio(key, NULL);
897 } else if (format == FORMAT_PEM) {
898 pkey = PEM_read_bio_PrivateKey(key, NULL,
899 (pem_password_cb *)password_callback,
902 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
903 else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
904 pkey = load_netscape_key(err, key, file, key_descrip, format);
906 else if (format == FORMAT_PKCS12) {
907 if (!load_pkcs12(err, key, key_descrip,
908 (pem_password_cb *)password_callback, &cb_data,
912 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA) && !defined (OPENSSL_NO_RC4)
913 else if (format == FORMAT_MSBLOB)
914 pkey = b2i_PrivateKey_bio(key);
915 else if (format == FORMAT_PVK)
916 pkey = b2i_PVK_bio(key, (pem_password_cb *)password_callback,
920 BIO_printf(err, "bad input format specified for key file\n");
927 BIO_printf(err, "unable to load %s\n", key_descrip);
928 ERR_print_errors(err);
933 EVP_PKEY *load_pubkey(BIO *err, const char *file, int format, int maybe_stdin,
934 const char *pass, ENGINE *e, const char *key_descrip)
937 EVP_PKEY *pkey = NULL;
940 cb_data.password = pass;
941 cb_data.prompt_info = file;
943 if (file == NULL && (!maybe_stdin || format == FORMAT_ENGINE)) {
944 BIO_printf(err, "no keyfile specified\n");
947 #ifndef OPENSSL_NO_ENGINE
948 if (format == FORMAT_ENGINE) {
950 BIO_printf(bio_err, "no engine specified\n");
952 pkey = ENGINE_load_public_key(e, file, ui_method, &cb_data);
956 key = BIO_new(BIO_s_file());
958 ERR_print_errors(err);
961 if (file == NULL && maybe_stdin) {
963 # ifndef OPENSSL_NO_SETVBUF_IONBF
964 setvbuf(stdin, NULL, _IONBF, 0);
965 # endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
967 BIO_set_fp(key, stdin, BIO_NOCLOSE);
968 } else if (BIO_read_filename(key, file) <= 0) {
969 BIO_printf(err, "Error opening %s %s\n", key_descrip, file);
970 ERR_print_errors(err);
973 if (format == FORMAT_ASN1) {
974 pkey = d2i_PUBKEY_bio(key, NULL);
976 #ifndef OPENSSL_NO_RSA
977 else if (format == FORMAT_ASN1RSA) {
979 rsa = d2i_RSAPublicKey_bio(key, NULL);
981 pkey = EVP_PKEY_new();
983 EVP_PKEY_set1_RSA(pkey, rsa);
987 } else if (format == FORMAT_PEMRSA) {
989 rsa = PEM_read_bio_RSAPublicKey(key, NULL,
990 (pem_password_cb *)password_callback,
993 pkey = EVP_PKEY_new();
995 EVP_PKEY_set1_RSA(pkey, rsa);
1001 else if (format == FORMAT_PEM) {
1002 pkey = PEM_read_bio_PUBKEY(key, NULL,
1003 (pem_password_cb *)password_callback,
1006 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
1007 else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
1008 pkey = load_netscape_key(err, key, file, key_descrip, format);
1010 #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
1011 else if (format == FORMAT_MSBLOB)
1012 pkey = b2i_PublicKey_bio(key);
1015 BIO_printf(err, "bad input format specified for key file\n");
1022 BIO_printf(err, "unable to load %s\n", key_descrip);
1026 #if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
1027 static EVP_PKEY *load_netscape_key(BIO *err, BIO *key, const char *file,
1028 const char *key_descrip, int format)
1033 const unsigned char *p;
1036 buf = BUF_MEM_new();
1037 pkey = EVP_PKEY_new();
1039 if (buf == NULL || pkey == NULL)
1042 if (!BUF_MEM_grow_clean(buf, size + 1024 * 10))
1044 i = BIO_read(key, &(buf->data[size]), 1024 * 10);
1049 BIO_printf(err, "Error reading %s %s", key_descrip, file);
1053 p = (unsigned char *)buf->data;
1054 rsa = d2i_RSA_NET(NULL, &p, (long)size, NULL,
1055 (format == FORMAT_IISSGC ? 1 : 0));
1059 EVP_PKEY_set1_RSA(pkey, rsa);
1063 EVP_PKEY_free(pkey);
1066 #endif /* ndef OPENSSL_NO_RC4 */
1068 static int load_certs_crls(BIO *err, const char *file, int format,
1069 const char *pass, ENGINE *e, const char *desc,
1070 STACK_OF(X509) **pcerts,
1071 STACK_OF(X509_CRL) **pcrls)
1075 STACK_OF(X509_INFO) *xis = NULL;
1080 cb_data.password = pass;
1081 cb_data.prompt_info = file;
1083 if (format != FORMAT_PEM) {
1084 BIO_printf(err, "bad input format specified for %s\n", desc);
1089 bio = BIO_new_fp(stdin, BIO_NOCLOSE);
1091 bio = BIO_new_file(file, "r");
1094 BIO_printf(err, "Error opening %s %s\n", desc, file ? file : "stdin");
1095 ERR_print_errors(err);
1099 xis = PEM_X509_INFO_read_bio(bio, NULL,
1100 (pem_password_cb *)password_callback,
1106 *pcerts = sk_X509_new_null();
1112 *pcrls = sk_X509_CRL_new_null();
1117 for (i = 0; i < sk_X509_INFO_num(xis); i++) {
1118 xi = sk_X509_INFO_value(xis, i);
1119 if (xi->x509 && pcerts) {
1120 if (!sk_X509_push(*pcerts, xi->x509))
1124 if (xi->crl && pcrls) {
1125 if (!sk_X509_CRL_push(*pcrls, xi->crl))
1131 if (pcerts && sk_X509_num(*pcerts) > 0)
1134 if (pcrls && sk_X509_CRL_num(*pcrls) > 0)
1140 sk_X509_INFO_pop_free(xis, X509_INFO_free);
1144 sk_X509_pop_free(*pcerts, X509_free);
1148 sk_X509_CRL_pop_free(*pcrls, X509_CRL_free);
1151 BIO_printf(err, "unable to load %s\n",
1152 pcerts ? "certificates" : "CRLs");
1153 ERR_print_errors(err);
1158 STACK_OF(X509) *load_certs(BIO *err, const char *file, int format,
1159 const char *pass, ENGINE *e, const char *desc)
1161 STACK_OF(X509) *certs;
1162 if (!load_certs_crls(err, file, format, pass, e, desc, &certs, NULL))
1167 STACK_OF(X509_CRL) *load_crls(BIO *err, const char *file, int format,
1168 const char *pass, ENGINE *e, const char *desc)
1170 STACK_OF(X509_CRL) *crls;
1171 if (!load_certs_crls(err, file, format, pass, e, desc, NULL, &crls))
1176 #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1177 /* Return error for unknown extensions */
1178 #define X509V3_EXT_DEFAULT 0
1179 /* Print error for unknown extensions */
1180 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
1181 /* ASN1 parse unknown extensions */
1182 #define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
1183 /* BIO_dump unknown extensions */
1184 #define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
1186 #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1187 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1189 int set_cert_ex(unsigned long *flags, const char *arg)
1191 static const NAME_EX_TBL cert_tbl[] = {
1192 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1193 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1194 {"no_header", X509_FLAG_NO_HEADER, 0},
1195 {"no_version", X509_FLAG_NO_VERSION, 0},
1196 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1197 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1198 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1199 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1200 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1201 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1202 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1203 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1204 {"no_aux", X509_FLAG_NO_AUX, 0},
1205 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1206 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1207 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1208 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1209 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1212 return set_multi_opts(flags, arg, cert_tbl);
1215 int set_name_ex(unsigned long *flags, const char *arg)
1217 static const NAME_EX_TBL ex_tbl[] = {
1218 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1219 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1220 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1221 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1222 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1223 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1224 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1225 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1226 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1227 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1228 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1229 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1230 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1231 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1232 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1233 {"dn_rev", XN_FLAG_DN_REV, 0},
1234 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1235 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1236 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1237 {"align", XN_FLAG_FN_ALIGN, 0},
1238 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1239 {"space_eq", XN_FLAG_SPC_EQ, 0},
1240 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1241 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1242 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1243 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1244 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1247 if (set_multi_opts(flags, arg, ex_tbl) == 0)
1249 if ((*flags & XN_FLAG_SEP_MASK) == 0)
1250 *flags |= XN_FLAG_SEP_CPLUS_SPC;
1254 int set_ext_copy(int *copy_type, const char *arg)
1256 if (!strcasecmp(arg, "none"))
1257 *copy_type = EXT_COPY_NONE;
1258 else if (!strcasecmp(arg, "copy"))
1259 *copy_type = EXT_COPY_ADD;
1260 else if (!strcasecmp(arg, "copyall"))
1261 *copy_type = EXT_COPY_ALL;
1267 int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1269 STACK_OF(X509_EXTENSION) *exts = NULL;
1270 X509_EXTENSION *ext, *tmpext;
1272 int i, idx, ret = 0;
1273 if (!x || !req || (copy_type == EXT_COPY_NONE))
1275 exts = X509_REQ_get_extensions(req);
1277 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1278 ext = sk_X509_EXTENSION_value(exts, i);
1279 obj = X509_EXTENSION_get_object(ext);
1280 idx = X509_get_ext_by_OBJ(x, obj, -1);
1281 /* Does extension exist? */
1283 /* If normal copy don't override existing extension */
1284 if (copy_type == EXT_COPY_ADD)
1286 /* Delete all extensions of same type */
1288 tmpext = X509_get_ext(x, idx);
1289 X509_delete_ext(x, idx);
1290 X509_EXTENSION_free(tmpext);
1291 idx = X509_get_ext_by_OBJ(x, obj, -1);
1292 } while (idx != -1);
1294 if (!X509_add_ext(x, ext, -1))
1302 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1307 static int set_multi_opts(unsigned long *flags, const char *arg,
1308 const NAME_EX_TBL * in_tbl)
1310 STACK_OF(CONF_VALUE) *vals;
1315 vals = X509V3_parse_list(arg);
1316 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1317 val = sk_CONF_VALUE_value(vals, i);
1318 if (!set_table_opts(flags, val->name, in_tbl))
1321 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1325 static int set_table_opts(unsigned long *flags, const char *arg,
1326 const NAME_EX_TBL * in_tbl)
1329 const NAME_EX_TBL *ptbl;
1335 } else if (c == '+') {
1341 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1342 if (!strcasecmp(arg, ptbl->name)) {
1343 *flags &= ~ptbl->mask;
1345 *flags |= ptbl->flag;
1347 *flags &= ~ptbl->flag;
1354 void print_name(BIO *out, const char *title, X509_NAME *nm,
1355 unsigned long lflags)
1362 BIO_puts(out, title);
1363 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1367 if (lflags == XN_FLAG_COMPAT) {
1368 buf = X509_NAME_oneline(nm, 0, 0);
1370 BIO_puts(out, "\n");
1374 BIO_puts(out, "\n");
1375 X509_NAME_print_ex(out, nm, indent, lflags);
1376 BIO_puts(out, "\n");
1380 X509_STORE *setup_verify(BIO *bp, char *CAfile, char *CApath)
1383 X509_LOOKUP *lookup;
1384 if (!(store = X509_STORE_new()))
1386 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1390 if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) {
1391 BIO_printf(bp, "Error loading file %s\n", CAfile);
1395 X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
1397 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1401 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1402 BIO_printf(bp, "Error loading directory %s\n", CApath);
1406 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1411 X509_STORE_free(store);
1415 #ifndef OPENSSL_NO_ENGINE
1416 /* Try to load an engine in a shareable library */
1417 static ENGINE *try_load_engine(BIO *err, const char *engine, int debug)
1419 ENGINE *e = ENGINE_by_id("dynamic");
1421 if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
1422 || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
1430 ENGINE *setup_engine(BIO *err, const char *engine, int debug)
1435 if (strcmp(engine, "auto") == 0) {
1436 BIO_printf(err, "enabling auto ENGINE support\n");
1437 ENGINE_register_all_complete();
1440 if ((e = ENGINE_by_id(engine)) == NULL
1441 && (e = try_load_engine(err, engine, debug)) == NULL) {
1442 BIO_printf(err, "invalid engine \"%s\"\n", engine);
1443 ERR_print_errors(err);
1447 ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, err, 0);
1449 ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
1450 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1451 BIO_printf(err, "can't use that engine\n");
1452 ERR_print_errors(err);
1457 BIO_printf(err, "engine \"%s\" set.\n", ENGINE_get_id(e));
1459 /* Free our "structural" reference. */
1466 int load_config(BIO *err, CONF *cnf)
1468 static int load_config_called = 0;
1469 if (load_config_called)
1471 load_config_called = 1;
1477 OPENSSL_load_builtin_modules();
1479 if (CONF_modules_load(cnf, NULL, 0) <= 0) {
1480 BIO_printf(err, "Error configuring OpenSSL\n");
1481 ERR_print_errors(err);
1487 char *make_config_name()
1489 const char *t = X509_get_default_cert_area();
1493 len = strlen(t) + strlen(OPENSSL_CONF) + 2;
1494 p = OPENSSL_malloc(len);
1497 BUF_strlcpy(p, t, len);
1498 #ifndef OPENSSL_SYS_VMS
1499 BUF_strlcat(p, "/", len);
1501 BUF_strlcat(p, OPENSSL_CONF, len);
1506 static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1513 return (lh_strhash(n));
1516 static int index_serial_cmp(const OPENSSL_CSTRING *a,
1517 const OPENSSL_CSTRING *b)
1519 const char *aa, *bb;
1521 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1522 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1523 return (strcmp(aa, bb));
1526 static int index_name_qual(char **a)
1528 return (a[0][0] == 'V');
1531 static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1533 return (lh_strhash(a[DB_name]));
1536 int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1538 return (strcmp(a[DB_name], b[DB_name]));
1541 static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1542 static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1543 static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1544 static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1547 BIGNUM *load_serial(char *serialfile, int create, ASN1_INTEGER **retai)
1551 MS_STATIC char buf[1024];
1552 ASN1_INTEGER *ai = NULL;
1554 ai = ASN1_INTEGER_new();
1558 if ((in = BIO_new(BIO_s_file())) == NULL) {
1559 ERR_print_errors(bio_err);
1563 if (BIO_read_filename(in, serialfile) <= 0) {
1569 if (ret == NULL || !rand_serial(ret, ai))
1570 BIO_printf(bio_err, "Out of memory\n");
1573 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1574 BIO_printf(bio_err, "unable to load number from %s\n",
1578 ret = ASN1_INTEGER_to_BN(ai, NULL);
1581 "error converting number from bin to BIGNUM\n");
1594 ASN1_INTEGER_free(ai);
1598 int save_serial(char *serialfile, char *suffix, BIGNUM *serial,
1599 ASN1_INTEGER **retai)
1604 ASN1_INTEGER *ai = NULL;
1608 j = strlen(serialfile);
1610 j = strlen(serialfile) + strlen(suffix) + 1;
1612 BIO_printf(bio_err, "file name too long\n");
1617 BUF_strlcpy(buf[0], serialfile, BSIZE);
1619 #ifndef OPENSSL_SYS_VMS
1620 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, suffix);
1622 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, suffix);
1626 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1628 out = BIO_new(BIO_s_file());
1630 ERR_print_errors(bio_err);
1633 if (BIO_write_filename(out, buf[0]) <= 0) {
1638 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1639 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1642 i2a_ASN1_INTEGER(out, ai);
1643 BIO_puts(out, "\n");
1653 ASN1_INTEGER_free(ai);
1657 int rotate_serial(char *serialfile, char *new_suffix, char *old_suffix)
1662 i = strlen(serialfile) + strlen(old_suffix);
1663 j = strlen(serialfile) + strlen(new_suffix);
1666 if (j + 1 >= BSIZE) {
1667 BIO_printf(bio_err, "file name too long\n");
1670 #ifndef OPENSSL_SYS_VMS
1671 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", serialfile, new_suffix);
1673 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", serialfile, new_suffix);
1675 #ifndef OPENSSL_SYS_VMS
1676 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", serialfile, old_suffix);
1678 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", serialfile, old_suffix);
1681 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1682 serialfile, buf[1]);
1684 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1690 "unable to rename %s to %s\n", serialfile, buf[1]);
1695 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n",
1696 buf[0], serialfile);
1698 if (rename(buf[0], serialfile) < 0) {
1700 "unable to rename %s to %s\n", buf[0], serialfile);
1702 rename(buf[1], serialfile);
1710 int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1722 if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
1724 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1737 CA_DB *load_index(char *dbfile, DB_ATTR *db_attr)
1739 CA_DB *retdb = NULL;
1740 TXT_DB *tmpdb = NULL;
1741 BIO *in = BIO_new(BIO_s_file());
1742 CONF *dbattr_conf = NULL;
1744 long errorline = -1;
1747 ERR_print_errors(bio_err);
1750 if (BIO_read_filename(in, dbfile) <= 0) {
1752 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1755 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1758 #ifndef OPENSSL_SYS_VMS
1759 BIO_snprintf(buf[0], sizeof buf[0], "%s.attr", dbfile);
1761 BIO_snprintf(buf[0], sizeof buf[0], "%s-attr", dbfile);
1763 dbattr_conf = NCONF_new(NULL);
1764 if (NCONF_load(dbattr_conf, buf[0], &errorline) <= 0) {
1765 if (errorline > 0) {
1767 "error on line %ld of db attribute file '%s'\n",
1771 NCONF_free(dbattr_conf);
1776 if ((retdb = OPENSSL_malloc(sizeof(CA_DB))) == NULL) {
1777 fprintf(stderr, "Out of memory\n");
1784 retdb->attributes = *db_attr;
1786 retdb->attributes.unique_subject = 1;
1790 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1794 "DEBUG[load_index]: unique_subject = \"%s\"\n", p);
1796 retdb->attributes.unique_subject = parse_yesno(p, 1);
1802 NCONF_free(dbattr_conf);
1810 int index_index(CA_DB *db)
1812 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1813 LHASH_HASH_FN(index_serial),
1814 LHASH_COMP_FN(index_serial))) {
1816 "error creating serial number index:(%ld,%ld,%ld)\n",
1817 db->db->error, db->db->arg1, db->db->arg2);
1821 if (db->attributes.unique_subject
1822 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1823 LHASH_HASH_FN(index_name),
1824 LHASH_COMP_FN(index_name))) {
1825 BIO_printf(bio_err, "error creating name index:(%ld,%ld,%ld)\n",
1826 db->db->error, db->db->arg1, db->db->arg2);
1832 int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1835 BIO *out = BIO_new(BIO_s_file());
1839 ERR_print_errors(bio_err);
1843 j = strlen(dbfile) + strlen(suffix);
1844 if (j + 6 >= BSIZE) {
1845 BIO_printf(bio_err, "file name too long\n");
1848 #ifndef OPENSSL_SYS_VMS
1849 j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr", dbfile);
1851 j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr", dbfile);
1853 #ifndef OPENSSL_SYS_VMS
1854 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.attr.%s", dbfile, suffix);
1856 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-attr-%s", dbfile, suffix);
1858 #ifndef OPENSSL_SYS_VMS
1859 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, suffix);
1861 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, suffix);
1864 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[0]);
1866 if (BIO_write_filename(out, buf[0]) <= 0) {
1868 BIO_printf(bio_err, "unable to open '%s'\n", dbfile);
1871 j = TXT_DB_write(out, db->db);
1877 out = BIO_new(BIO_s_file());
1879 BIO_printf(bio_err, "DEBUG: writing \"%s\"\n", buf[1]);
1881 if (BIO_write_filename(out, buf[1]) <= 0) {
1883 BIO_printf(bio_err, "unable to open '%s'\n", buf[2]);
1886 BIO_printf(out, "unique_subject = %s\n",
1887 db->attributes.unique_subject ? "yes" : "no");
1895 int rotate_index(const char *dbfile, const char *new_suffix,
1896 const char *old_suffix)
1901 i = strlen(dbfile) + strlen(old_suffix);
1902 j = strlen(dbfile) + strlen(new_suffix);
1905 if (j + 6 >= BSIZE) {
1906 BIO_printf(bio_err, "file name too long\n");
1909 #ifndef OPENSSL_SYS_VMS
1910 j = BIO_snprintf(buf[4], sizeof buf[4], "%s.attr", dbfile);
1912 j = BIO_snprintf(buf[4], sizeof buf[4], "%s-attr", dbfile);
1914 #ifndef OPENSSL_SYS_VMS
1915 j = BIO_snprintf(buf[2], sizeof buf[2], "%s.attr.%s", dbfile, new_suffix);
1917 j = BIO_snprintf(buf[2], sizeof buf[2], "%s-attr-%s", dbfile, new_suffix);
1919 #ifndef OPENSSL_SYS_VMS
1920 j = BIO_snprintf(buf[0], sizeof buf[0], "%s.%s", dbfile, new_suffix);
1922 j = BIO_snprintf(buf[0], sizeof buf[0], "%s-%s", dbfile, new_suffix);
1924 #ifndef OPENSSL_SYS_VMS
1925 j = BIO_snprintf(buf[1], sizeof buf[1], "%s.%s", dbfile, old_suffix);
1927 j = BIO_snprintf(buf[1], sizeof buf[1], "%s-%s", dbfile, old_suffix);
1929 #ifndef OPENSSL_SYS_VMS
1930 j = BIO_snprintf(buf[3], sizeof buf[3], "%s.attr.%s", dbfile, old_suffix);
1932 j = BIO_snprintf(buf[3], sizeof buf[3], "%s-attr-%s", dbfile, old_suffix);
1935 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", dbfile, buf[1]);
1937 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1942 BIO_printf(bio_err, "unable to rename %s to %s\n", dbfile, buf[1]);
1947 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[0], dbfile);
1949 if (rename(buf[0], dbfile) < 0) {
1950 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[0], dbfile);
1952 rename(buf[1], dbfile);
1956 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[4], buf[3]);
1958 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1963 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[4], buf[3]);
1965 rename(dbfile, buf[0]);
1966 rename(buf[1], dbfile);
1970 BIO_printf(bio_err, "DEBUG: renaming \"%s\" to \"%s\"\n", buf[2], buf[4]);
1972 if (rename(buf[2], buf[4]) < 0) {
1973 BIO_printf(bio_err, "unable to rename %s to %s\n", buf[2], buf[4]);
1975 rename(buf[3], buf[4]);
1976 rename(dbfile, buf[0]);
1977 rename(buf[1], dbfile);
1985 void free_index(CA_DB *db)
1989 TXT_DB_free(db->db);
1994 int parse_yesno(const char *str, int def)
1999 case 'f': /* false */
2000 case 'F': /* FALSE */
2006 case 't': /* true */
2007 case 'T': /* TRUE */
2022 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
2023 * where characters may be escaped by \
2025 X509_NAME *parse_name(char *subject, long chtype, int multirdn)
2027 size_t buflen = strlen(subject) + 1; /* to copy the types and values
2028 * into. due to escaping, the copy
2029 * can only become shorter */
2030 char *buf = OPENSSL_malloc(buflen);
2031 size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
2032 char **ne_types = OPENSSL_malloc(max_ne * sizeof(char *));
2033 char **ne_values = OPENSSL_malloc(max_ne * sizeof(char *));
2034 int *mval = OPENSSL_malloc(max_ne * sizeof(int));
2036 char *sp = subject, *bp = buf;
2039 X509_NAME *n = NULL;
2042 if (!buf || !ne_types || !ne_values || !mval) {
2043 BIO_printf(bio_err, "malloc error\n");
2047 if (*subject != '/') {
2048 BIO_printf(bio_err, "Subject does not start with '/'.\n");
2051 sp++; /* skip leading / */
2053 /* no multivalued RDN by default */
2058 ne_types[ne_num] = bp;
2060 if (*sp == '\\') { /* is there anything to escape in the
2066 "escape character at end of string\n");
2069 } else if (*sp == '=') {
2078 "end of string encountered while processing type of subject name element #%d\n",
2082 ne_values[ne_num] = bp;
2089 "escape character at end of string\n");
2092 } else if (*sp == '/') {
2094 /* no multivalued RDN by default */
2095 mval[ne_num + 1] = 0;
2097 } else if (*sp == '+' && multirdn) {
2099 * a not escaped + signals a mutlivalued RDN
2102 mval[ne_num + 1] = -1;
2111 if (!(n = X509_NAME_new()))
2114 for (i = 0; i < ne_num; i++) {
2115 if ((nid = OBJ_txt2nid(ne_types[i])) == NID_undef) {
2117 "Subject Attribute %s has no known NID, skipped\n",
2122 if (!*ne_values[i]) {
2124 "No value provided for Subject Attribute %s, skipped\n",
2129 if (!X509_NAME_add_entry_by_NID
2130 (n, nid, chtype, (unsigned char *)ne_values[i], -1, -1, mval[i]))
2134 OPENSSL_free(ne_values);
2135 OPENSSL_free(ne_types);
2143 OPENSSL_free(ne_values);
2145 OPENSSL_free(ne_types);
2153 int args_verify(char ***pargs, int *pargc,
2154 int *badarg, BIO *err, X509_VERIFY_PARAM **pm)
2156 ASN1_OBJECT *otmp = NULL;
2157 unsigned long flags = 0;
2159 int purpose = 0, depth = -1;
2160 char **oldargs = *pargs;
2161 char *arg = **pargs, *argn = (*pargs)[1];
2163 if (!strcmp(arg, "-policy")) {
2167 otmp = OBJ_txt2obj(argn, 0);
2169 BIO_printf(err, "Invalid Policy \"%s\"\n", argn);
2174 } else if (strcmp(arg, "-purpose") == 0) {
2175 X509_PURPOSE *xptmp;
2179 i = X509_PURPOSE_get_by_sname(argn);
2181 BIO_printf(err, "unrecognized purpose\n");
2184 xptmp = X509_PURPOSE_get0(i);
2185 purpose = X509_PURPOSE_get_id(xptmp);
2189 } else if (strcmp(arg, "-verify_depth") == 0) {
2195 BIO_printf(err, "invalid depth\n");
2200 } else if (strcmp(arg, "-attime") == 0) {
2206 * interpret the -attime argument as seconds since Epoch
2208 if (sscanf(argn, "%li", ×tamp) != 1) {
2209 BIO_printf(bio_err, "Error parsing timestamp %s\n", argn);
2212 /* on some platforms time_t may be a float */
2213 at_time = (time_t)timestamp;
2216 } else if (!strcmp(arg, "-ignore_critical"))
2217 flags |= X509_V_FLAG_IGNORE_CRITICAL;
2218 else if (!strcmp(arg, "-issuer_checks"))
2219 flags |= X509_V_FLAG_CB_ISSUER_CHECK;
2220 else if (!strcmp(arg, "-crl_check"))
2221 flags |= X509_V_FLAG_CRL_CHECK;
2222 else if (!strcmp(arg, "-crl_check_all"))
2223 flags |= X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL;
2224 else if (!strcmp(arg, "-policy_check"))
2225 flags |= X509_V_FLAG_POLICY_CHECK;
2226 else if (!strcmp(arg, "-explicit_policy"))
2227 flags |= X509_V_FLAG_EXPLICIT_POLICY;
2228 else if (!strcmp(arg, "-inhibit_any"))
2229 flags |= X509_V_FLAG_INHIBIT_ANY;
2230 else if (!strcmp(arg, "-inhibit_map"))
2231 flags |= X509_V_FLAG_INHIBIT_MAP;
2232 else if (!strcmp(arg, "-x509_strict"))
2233 flags |= X509_V_FLAG_X509_STRICT;
2234 else if (!strcmp(arg, "-extended_crl"))
2235 flags |= X509_V_FLAG_EXTENDED_CRL_SUPPORT;
2236 else if (!strcmp(arg, "-use_deltas"))
2237 flags |= X509_V_FLAG_USE_DELTAS;
2238 else if (!strcmp(arg, "-policy_print"))
2239 flags |= X509_V_FLAG_NOTIFY_POLICY;
2240 else if (!strcmp(arg, "-check_ss_sig"))
2241 flags |= X509_V_FLAG_CHECK_SS_SIGNATURE;
2242 else if (!strcmp(arg, "-no_alt_chains"))
2243 flags |= X509_V_FLAG_NO_ALT_CHAINS;
2244 else if (!strcmp(arg, "-allow_proxy_certs"))
2245 flags |= X509_V_FLAG_ALLOW_PROXY_CERTS;
2251 X509_VERIFY_PARAM_free(*pm);
2256 if (!*pm && !(*pm = X509_VERIFY_PARAM_new())) {
2262 X509_VERIFY_PARAM_add0_policy(*pm, otmp);
2264 X509_VERIFY_PARAM_set_flags(*pm, flags);
2267 X509_VERIFY_PARAM_set_purpose(*pm, purpose);
2270 X509_VERIFY_PARAM_set_depth(*pm, depth);
2273 X509_VERIFY_PARAM_set_time(*pm, at_time);
2280 *pargc -= *pargs - oldargs;
2287 * Read whole contents of a BIO into an allocated memory buffer and return
2291 int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
2295 unsigned char tbuf[1024];
2296 mem = BIO_new(BIO_s_mem());
2300 if ((maxlen != -1) && maxlen < 1024)
2304 len = BIO_read(in, tbuf, len);
2307 if (BIO_write(mem, tbuf, len) != len) {
2316 ret = BIO_get_mem_data(mem, (char **)out);
2317 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
2322 int pkey_ctrl_string(EVP_PKEY_CTX *ctx, char *value)
2325 char *stmp, *vtmp = NULL;
2326 stmp = BUF_strdup(value);
2329 vtmp = strchr(stmp, ':');
2334 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2339 static void nodes_print(BIO *out, const char *name,
2340 STACK_OF(X509_POLICY_NODE) *nodes)
2342 X509_POLICY_NODE *node;
2344 BIO_printf(out, "%s Policies:", name);
2346 BIO_puts(out, "\n");
2347 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2348 node = sk_X509_POLICY_NODE_value(nodes, i);
2349 X509_POLICY_NODE_print(out, node, 2);
2352 BIO_puts(out, " <empty>\n");
2355 void policies_print(BIO *out, X509_STORE_CTX *ctx)
2357 X509_POLICY_TREE *tree;
2358 int explicit_policy;
2361 out = BIO_new_fp(stderr, BIO_NOCLOSE);
2364 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2365 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2367 BIO_printf(out, "Require explicit Policy: %s\n",
2368 explicit_policy ? "True" : "False");
2370 nodes_print(out, "Authority", X509_policy_tree_get0_policies(tree));
2371 nodes_print(out, "User", X509_policy_tree_get0_user_policies(tree));
2376 #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK)
2378 static JPAKE_CTX *jpake_init(const char *us, const char *them,
2384 BIGNUM *bnsecret = BN_new();
2387 /* Use a safe prime for p (that we found earlier) */
2389 "F9E5B365665EA7A05A9C534502780FEE6F1AB5BD4F49947FD036DBD7E905269AF46EF28B0FC07487EE4F5D20FB3C0AF8E700F3A2FA3414970CBED44FEDFF80CE78D800F184BB82435D137AADA2C6C16523247930A63B85661D1FC817A51ACD96168E95898A1F83A79FFB529368AA7833ABD1B0C3AEDDB14D2E1A2F71D99F763F");
2395 BN_bin2bn((const unsigned char *)secret, strlen(secret), bnsecret);
2397 ctx = JPAKE_CTX_new(us, them, p, g, q, bnsecret);
2406 static void jpake_send_part(BIO *conn, const JPAKE_STEP_PART *p)
2408 BN_print(conn, p->gx);
2409 BIO_puts(conn, "\n");
2410 BN_print(conn, p->zkpx.gr);
2411 BIO_puts(conn, "\n");
2412 BN_print(conn, p->zkpx.b);
2413 BIO_puts(conn, "\n");
2416 static void jpake_send_step1(BIO *bconn, JPAKE_CTX *ctx)
2420 JPAKE_STEP1_init(&s1);
2421 JPAKE_STEP1_generate(&s1, ctx);
2422 jpake_send_part(bconn, &s1.p1);
2423 jpake_send_part(bconn, &s1.p2);
2424 (void)BIO_flush(bconn);
2425 JPAKE_STEP1_release(&s1);
2428 static void jpake_send_step2(BIO *bconn, JPAKE_CTX *ctx)
2432 JPAKE_STEP2_init(&s2);
2433 JPAKE_STEP2_generate(&s2, ctx);
2434 jpake_send_part(bconn, &s2);
2435 (void)BIO_flush(bconn);
2436 JPAKE_STEP2_release(&s2);
2439 static void jpake_send_step3a(BIO *bconn, JPAKE_CTX *ctx)
2443 JPAKE_STEP3A_init(&s3a);
2444 JPAKE_STEP3A_generate(&s3a, ctx);
2445 BIO_write(bconn, s3a.hhk, sizeof s3a.hhk);
2446 (void)BIO_flush(bconn);
2447 JPAKE_STEP3A_release(&s3a);
2450 static void jpake_send_step3b(BIO *bconn, JPAKE_CTX *ctx)
2454 JPAKE_STEP3B_init(&s3b);
2455 JPAKE_STEP3B_generate(&s3b, ctx);
2456 BIO_write(bconn, s3b.hk, sizeof s3b.hk);
2457 (void)BIO_flush(bconn);
2458 JPAKE_STEP3B_release(&s3b);
2461 static void readbn(BIGNUM **bn, BIO *bconn)
2466 l = BIO_gets(bconn, buf, sizeof buf);
2468 assert(buf[l - 1] == '\n');
2473 static void jpake_receive_part(JPAKE_STEP_PART *p, BIO *bconn)
2475 readbn(&p->gx, bconn);
2476 readbn(&p->zkpx.gr, bconn);
2477 readbn(&p->zkpx.b, bconn);
2480 static void jpake_receive_step1(JPAKE_CTX *ctx, BIO *bconn)
2484 JPAKE_STEP1_init(&s1);
2485 jpake_receive_part(&s1.p1, bconn);
2486 jpake_receive_part(&s1.p2, bconn);
2487 if (!JPAKE_STEP1_process(ctx, &s1)) {
2488 ERR_print_errors(bio_err);
2491 JPAKE_STEP1_release(&s1);
2494 static void jpake_receive_step2(JPAKE_CTX *ctx, BIO *bconn)
2498 JPAKE_STEP2_init(&s2);
2499 jpake_receive_part(&s2, bconn);
2500 if (!JPAKE_STEP2_process(ctx, &s2)) {
2501 ERR_print_errors(bio_err);
2504 JPAKE_STEP2_release(&s2);
2507 static void jpake_receive_step3a(JPAKE_CTX *ctx, BIO *bconn)
2512 JPAKE_STEP3A_init(&s3a);
2513 l = BIO_read(bconn, s3a.hhk, sizeof s3a.hhk);
2514 assert(l == sizeof s3a.hhk);
2515 if (!JPAKE_STEP3A_process(ctx, &s3a)) {
2516 ERR_print_errors(bio_err);
2519 JPAKE_STEP3A_release(&s3a);
2522 static void jpake_receive_step3b(JPAKE_CTX *ctx, BIO *bconn)
2527 JPAKE_STEP3B_init(&s3b);
2528 l = BIO_read(bconn, s3b.hk, sizeof s3b.hk);
2529 assert(l == sizeof s3b.hk);
2530 if (!JPAKE_STEP3B_process(ctx, &s3b)) {
2531 ERR_print_errors(bio_err);
2534 JPAKE_STEP3B_release(&s3b);
2537 void jpake_client_auth(BIO *out, BIO *conn, const char *secret)
2542 BIO_puts(out, "Authenticating with JPAKE\n");
2544 ctx = jpake_init("client", "server", secret);
2546 bconn = BIO_new(BIO_f_buffer());
2547 BIO_push(bconn, conn);
2549 jpake_send_step1(bconn, ctx);
2550 jpake_receive_step1(ctx, bconn);
2551 jpake_send_step2(bconn, ctx);
2552 jpake_receive_step2(ctx, bconn);
2553 jpake_send_step3a(bconn, ctx);
2554 jpake_receive_step3b(ctx, bconn);
2556 BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
2558 psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
2563 JPAKE_CTX_free(ctx);
2566 void jpake_server_auth(BIO *out, BIO *conn, const char *secret)
2571 BIO_puts(out, "Authenticating with JPAKE\n");
2573 ctx = jpake_init("server", "client", secret);
2575 bconn = BIO_new(BIO_f_buffer());
2576 BIO_push(bconn, conn);
2578 jpake_receive_step1(ctx, bconn);
2579 jpake_send_step1(bconn, ctx);
2580 jpake_receive_step2(ctx, bconn);
2581 jpake_send_step2(bconn, ctx);
2582 jpake_receive_step3a(ctx, bconn);
2583 jpake_send_step3b(bconn, ctx);
2585 BIO_puts(out, "JPAKE authentication succeeded, setting PSK\n");
2587 psk_key = BN_bn2hex(JPAKE_get_shared_key(ctx));
2592 JPAKE_CTX_free(ctx);
2597 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
2599 * next_protos_parse parses a comma separated list of strings into a string
2600 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2601 * outlen: (output) set to the length of the resulting buffer on success.
2602 * err: (maybe NULL) on failure, an error message line is written to this BIO.
2603 * in: a NUL termianted string like "abc,def,ghi"
2605 * returns: a malloced buffer or NULL on failure.
2607 unsigned char *next_protos_parse(unsigned short *outlen, const char *in)
2611 size_t i, start = 0;
2617 out = OPENSSL_malloc(strlen(in) + 1);
2621 for (i = 0; i <= len; ++i) {
2622 if (i == len || in[i] == ',') {
2623 if (i - start > 255) {
2627 out[start] = i - start;
2636 #endif /* !OPENSSL_NO_TLSEXT &&
2637 * !OPENSSL_NO_NEXTPROTONEG */
2640 * Platform-specific sections
2645 # define fileno(a) (int)_fileno(a)
2648 # include <windows.h>
2651 static int WIN32_rename(const char *from, const char *to)
2653 TCHAR *tfrom = NULL, *tto;
2657 if (sizeof(TCHAR) == 1) {
2658 tfrom = (TCHAR *)from;
2660 } else { /* UNICODE path */
2662 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2663 tfrom = (TCHAR *)malloc(sizeof(TCHAR) * (flen + tlen));
2667 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2668 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2670 for (i = 0; i < flen; i++)
2671 tfrom[i] = (TCHAR)from[i];
2672 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2673 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2675 for (i = 0; i < tlen; i++)
2676 tto[i] = (TCHAR)to[i];
2679 if (MoveFile(tfrom, tto))
2681 err = GetLastError();
2682 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2683 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2685 err = GetLastError();
2687 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2689 else if (err == ERROR_ACCESS_DENIED)
2692 errno = EINVAL; /* we could map more codes... */
2696 if (tfrom != NULL && tfrom != (TCHAR *)from)
2702 /* app_tminterval section */
2704 double app_tminterval(int stop, int usertime)
2708 static ULARGE_INTEGER tmstart;
2709 static int warning = 1;
2710 # ifdef _WIN32_WINNT
2711 static HANDLE proc = NULL;
2715 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2716 GetCurrentProcessId());
2718 proc = (HANDLE) - 1;
2721 if (usertime && proc != (HANDLE) - 1) {
2723 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2729 if (usertime && warning) {
2730 BIO_printf(bio_err, "To get meaningful results, run "
2731 "this program on idle system.\n");
2734 GetSystemTime(&systime);
2735 SystemTimeToFileTime(&systime, &now);
2738 if (stop == TM_START) {
2739 tmstart.u.LowPart = now.dwLowDateTime;
2740 tmstart.u.HighPart = now.dwHighDateTime;
2742 ULARGE_INTEGER tmstop;
2744 tmstop.u.LowPart = now.dwLowDateTime;
2745 tmstop.u.HighPart = now.dwHighDateTime;
2747 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2753 #elif defined(OPENSSL_SYS_NETWARE)
2756 double app_tminterval(int stop, int usertime)
2759 static clock_t tmstart;
2760 static int warning = 1;
2762 if (usertime && warning) {
2763 BIO_printf(bio_err, "To get meaningful results, run "
2764 "this program on idle system.\n");
2768 if (stop == TM_START)
2771 ret = (clock() - tmstart) / (double)CLOCKS_PER_SEC;
2776 #elif defined(OPENSSL_SYSTEM_VXWORKS)
2779 double app_tminterval(int stop, int usertime)
2782 # ifdef CLOCK_REALTIME
2783 static struct timespec tmstart;
2784 struct timespec now;
2786 static unsigned long tmstart;
2789 static int warning = 1;
2791 if (usertime && warning) {
2792 BIO_printf(bio_err, "To get meaningful results, run "
2793 "this program on idle system.\n");
2796 # ifdef CLOCK_REALTIME
2797 clock_gettime(CLOCK_REALTIME, &now);
2798 if (stop == TM_START)
2801 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2802 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2805 if (stop == TM_START)
2808 ret = (now - tmstart) / (double)sysClkRateGet();
2813 #elif defined(OPENSSL_SYSTEM_VMS)
2817 double app_tminterval(int stop, int usertime)
2819 static clock_t tmstart;
2827 now = rus.tms_utime;
2830 now = clock(); /* sum of user and kernel times */
2833 gettimeofday(&tv, NULL);
2834 now = (clock_t)((unsigned long long)tv.tv_sec * CLK_TCK +
2835 (unsigned long long)tv.tv_usec * (1000000 / CLK_TCK)
2839 if (stop == TM_START)
2842 ret = (now - tmstart) / (double)(CLK_TCK);
2847 #elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2848 # include <sys/times.h>
2850 double app_tminterval(int stop, int usertime)
2854 clock_t now = times(&rus);
2855 static clock_t tmstart;
2858 now = rus.tms_utime;
2860 if (stop == TM_START)
2863 long int tck = sysconf(_SC_CLK_TCK);
2864 ret = (now - tmstart) / (double)tck;
2871 # include <sys/time.h>
2872 # include <sys/resource.h>
2874 double app_tminterval(int stop, int usertime)
2879 static struct timeval tmstart;
2882 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2884 gettimeofday(&now, NULL);
2886 if (stop == TM_START)
2889 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2890 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2896 /* app_isdir section */
2898 int app_isdir(const char *name)
2901 WIN32_FIND_DATA FileData;
2902 # if defined(UNICODE) || defined(_UNICODE)
2903 size_t i, len_0 = strlen(name) + 1;
2905 if (len_0 > sizeof(FileData.cFileName) / sizeof(FileData.cFileName[0]))
2908 # if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2909 if (!MultiByteToWideChar
2910 (CP_ACP, 0, name, len_0, FileData.cFileName, len_0))
2912 for (i = 0; i < len_0; i++)
2913 FileData.cFileName[i] = (WCHAR)name[i];
2915 hList = FindFirstFile(FileData.cFileName, &FileData);
2917 hList = FindFirstFile(name, &FileData);
2919 if (hList == INVALID_HANDLE_VALUE)
2922 return ((FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
2925 # include <sys/stat.h>
2927 # if defined(_S_IFMT) && defined(_S_IFDIR)
2928 # define S_ISDIR(a) (((a) & _S_IFMT) == _S_IFDIR)
2930 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
2934 int app_isdir(const char *name)
2936 # if defined(S_ISDIR)
2939 if (stat(name, &st) == 0)
2940 return S_ISDIR(st.st_mode);
2949 /* raw_read|write section */
2950 #if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2951 int raw_read_stdin(void *buf, int siz)
2954 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2960 int raw_read_stdin(void *buf, int siz)
2962 return read(fileno(stdin), buf, siz);
2966 #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2967 int raw_write_stdout(const void *buf, int siz)
2970 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2976 int raw_write_stdout(const void *buf, int siz)
2978 return write(fileno(stdout), buf, siz);