/*
 *  Copyright 2014-2023 The GmSSL Project. All Rights Reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the License); you may
 *  not use this file except in compliance with the License.
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 */


#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/hex.h>
#include <gmssl/pem.h>
#include <gmssl/x509.h>
#include <gmssl/x509_ext.h>
#include <gmssl/x509_crl.h>
#include <gmssl/file.h>
#include <gmssl/error.h>


static const char *usage =
	" -in revoked_certs"
	" -cacert pem -key pem -pass pass [-sm2_id str | -sm2_id_hex hex]"
	" [-next_update time] "
	" [-gen_authority_key_id]"
	" [-crl_num num]"
	" [-delta_crl_indicator num]"
	" [-ca_issuers_uri uri]"
	" [-ocsp_uri uri]"
	" [-out der]\n";

static const char *options =
"Options\n"
"\n"
"    -in revoked_certs      To be revoked certificate list\n"
"                           This input file format is DER-encoding of SEQUENCE OF RevokedCertificate\n"
"                           revoked_certs.der can be generated by `gmssl certrevoke`\n"
"    -cacert pem            The issuer certificate\n"
"    -key pem               The issuer private key\n"
"    -pass pass             Password for decrypting private key file\n"
"    -sm2_id str            Authority's ID in SM2 signature algorithm\n"
"    -sm2_id_hex hex        Authority's ID in hex format\n"
"                           When `-sm2_id` or `-sm2_id_hex` is specified,\n"
"                             must use the same ID in other commands explicitly.\n"
"                           If neither `-sm2_id` nor `-sm2_id_hex` is specified,\n"
"                             the default string '1234567812345678' is used\n"
"    -next_update time      Optional CRL attribute\n"
"    -out der | stdout      Output CRL in DER-encoding\n"
"\n"
"Examples\n"
"\n"
"    gmssl crlgen -in revoked_certs.der -cacert cacert.pem -key cakey.pem -pass P@ssw0rd -gen_authority_key_id -crl_num 1\n"
"    gmssl crlgen -in revoked_certs.der -cacert cacert.pem -key cakey.pem -pass P@ssw0rd -gen_authority_key_id -crl_num 2\n"
"\n";

int crlgen_main(int argc, char **argv)
{
	int ret = 1;
	char *prog = argv[0];
	char *str;

	uint8_t *revoked_certs = NULL;
	size_t revoked_certs_len = 0;

	char *outfile = NULL;
	FILE *outfp = stdout;
	uint8_t *outbuf = NULL;
	uint8_t *out;
	size_t outlen = 0;

	uint8_t *cacert = NULL;
	size_t cacert_len = 0;
	FILE *keyfp = NULL;
	char *pass = NULL;
	SM2_KEY sign_key;
	char signer_id[SM2_MAX_ID_LENGTH + 1] = {0};
	size_t signer_id_len = 0;

	const uint8_t *issuer;
	size_t issuer_len;
	time_t this_update = time(NULL);
	time_t next_update = -1;

	uint8_t exts[512];
	size_t extslen = 0;
	int gen_authority_key_id = 0;
	int crl_num = -1;
	int delta_crl_indicator = -1;
	char *http_uri = NULL;
	char *ldap_uri = NULL;
	char *ca_issuers_uri = NULL;
	char *ocsp_uri = NULL;


	argc--;
	argv++;

	while (argc > 0) {
		if (!strcmp(*argv, "-help")) {
			printf("usage: %s %s\n\n", prog, usage);
			printf("%s\n", options);
			ret = 0;
			goto end;
		} else if (!strcmp(*argv, "-in")) {
			if (--argc < 1) goto bad;
			str = *(++argv);
			if (file_read_all(str, &revoked_certs, &revoked_certs_len) != 1) {
				fprintf(stderr, "%s: read input file '%s' failed\n", prog, str);
				goto end;
			}
		} else if (!strcmp(*argv, "-out")) {
			if (--argc < 1) goto bad;
			outfile = *(++argv);
			if (!(outfp = fopen(outfile, "wb"))) {
				fprintf(stderr, "%s: open '%s' failure : %s\n", prog, outfile, strerror(errno));
				goto end;
			}

		} else if (!strcmp(*argv, "-cacert")) {
			if (--argc < 1) goto bad;
			str = *(++argv);
			if (x509_cert_new_from_file(&cacert, &cacert_len, str) != 1) {
				fprintf(stderr, "%s: open certificate '%s' failure\n", prog, str);
				goto end;
			}

		} else if (!strcmp(*argv, "-key")) {
			if (--argc < 1) goto bad;
			str = *(++argv);
			if (!(keyfp = fopen(str, "rb"))) {
				fprintf(stderr, "%s: open '%s' failure : %s\n", prog, str, strerror(errno));
				goto end;
			}
		} else if (!strcmp(*argv, "-pass")) {
			if (--argc < 1) goto bad;
			pass = *(++argv);
		} else if (!strcmp(*argv, "-sm2_id")) {
			if (--argc < 1) goto bad;
			str = *(++argv);
			if (strlen(str) > sizeof(signer_id) - 1) {
				fprintf(stderr, "%s: invalid `-sm2_id` length\n", prog);
				goto end;
			}
			strncpy(signer_id, str, sizeof(signer_id));
			signer_id_len = strlen(str);
		} else if (!strcmp(*argv, "-sm2_id_hex")) {
			if (--argc < 1) goto bad;
			str = *(++argv);
			if (strlen(str) > (sizeof(signer_id) - 1) * 2) {
				fprintf(stderr, "%s: invalid `-sm2_id_hex` length\n", prog);
				goto end;
			}
			if (hex_to_bytes(str, strlen(str), (uint8_t *)signer_id, &signer_id_len) != 1) {
				fprintf(stderr, "%s: invalid `-sm2_id_hex` value\n", prog);
				goto end;
			}

		} else if (!strcmp(*argv, "-next_update")) {
			if (--argc < 1) goto bad;
			str = *(++argv);
			if (asn1_time_from_str(0, &next_update, str) != 1) {
				fprintf(stderr, "%s: invalid time '%s' for `-next_update`\n", prog, str);
				goto bad;
			}
		} else if (!strcmp(*argv, "-gen_authority_key_id")) {
			gen_authority_key_id = 1;
		} else if (!strcmp(*argv, "-crl_num")) {
			if (--argc < 1) goto bad;
			crl_num = atoi(*(++argv));
		} else if (!strcmp(*argv, "-delta_crl_indicator")) {
			if (--argc < 1) goto bad;
			delta_crl_indicator = atoi(*(++argv));
		} else if (!strcmp(*argv, "-http_uri")) {
			if (--argc < 1) goto bad;
			http_uri = *(++argv);
		} else if (!strcmp(*argv, "-ldap_uri")) {
			if (--argc < 1) goto bad;
			ldap_uri = *(++argv);
		} else if (!strcmp(*argv, "-ca_issuers_uri")) {
			ca_issuers_uri = *(++argv);
		} else if (!strcmp(*argv, "-ocsp_uri")) {
			if (--argc < 1) goto bad;
			ocsp_uri = *(++argv);
		} else {
			fprintf(stderr, "%s: illegal option `%s`\n", prog, *argv);
			goto end;
bad:
			fprintf(stderr, "%s: `%s` option value missing\n", prog, *argv);
			goto end;
		}

		argc--;
		argv++;
	}

	if (!revoked_certs) {
		fprintf(stderr, "%s: `-in` option required\n", prog);
		fprintf(stderr, "usage: gmssl %s %s\n", prog, usage);
		goto end;
	} else {
		const uint8_t *d = revoked_certs;
		size_t dlen = revoked_certs_len;
		const uint8_t *serial;
		size_t serial_len;
		time_t revoke_date;
		const uint8_t *exts;
		size_t exts_len;

		while (dlen) {
			if (x509_revoked_cert_from_der(&serial, &serial_len, &revoke_date, &exts, &exts_len, &d, &dlen) != 1) {
				fprintf(stderr, "%s: invalid input\n", prog);
				goto end;
			}
			format_bytes(stderr, 0, 4, "Revoked Certificate SN", serial, serial_len);
		}
	}

	if (!cacert) {
		fprintf(stderr, "%s: `-cacert` option required\n", prog);
		fprintf(stderr, "usage: gmssl %s %s\n", prog, usage);
		goto end;
	}

	if (!keyfp) {
		fprintf(stderr, "%s: `-key` option required\n", prog);
		fprintf(stderr, "usage: gmssl %s %s\n", prog, usage);
		goto end;
	}
	if (!pass) {
		fprintf(stderr, "usage: gmssl %s %s\n", prog, usage);
		fprintf(stderr, "%s: `-pass` option required\n", prog);
		goto end;
	}
	if (sm2_private_key_info_decrypt_from_pem(&sign_key, pass, keyfp) != 1) {
		fprintf(stderr, "%s: load private key failure\n", prog);
		goto end;
	}
	if (!signer_id_len) {
		strcpy(signer_id, SM2_DEFAULT_ID);
		signer_id_len = strlen(SM2_DEFAULT_ID);
	}

	if (x509_cert_get_subject(cacert, cacert_len, &issuer, &issuer_len) != 1) {
		fprintf(stderr, "%s: parse CA certificate failure\n", prog);
		goto end;
	}

	// Extensions
	if (gen_authority_key_id) {
		if (x509_crl_exts_add_default_authority_key_identifier(exts, &extslen, sizeof(exts), &sign_key) != 1) {
			fprintf(stderr, "%s: inner error\n", prog);
			goto end;
		}
	}
	if (x509_crl_exts_add_crl_number(exts, &extslen, sizeof(exts), -1, crl_num) < 0) {
		fprintf(stderr, "%s: add CRLNumber error\n", prog);
		goto end;
	}
	if (x509_crl_exts_add_delta_crl_indicator(exts, &extslen, sizeof(exts), X509_critical, delta_crl_indicator) < 0) {
		fprintf(stderr, "%s: add DeltaCRLIndicator error\n", prog);
		goto end;
	}
	if (ca_issuers_uri || ocsp_uri) {
		if (x509_crl_exts_add_authority_info_acess(exts, &extslen, sizeof(exts), -1,
			ca_issuers_uri, ca_issuers_uri ? strlen(ca_issuers_uri) : 0,
			ocsp_uri, ocsp_uri ? strlen(ocsp_uri) : 0) != 1) {
			fprintf(stderr, "%s: add AuthorityInfoAccess error\n", prog);
			goto end;
		}
	}
	if (http_uri || ldap_uri) {
		if (x509_crl_exts_add_freshest_crl(exts, &extslen, sizeof(exts), -1,
			http_uri, http_uri ? strlen(http_uri) : 0,
			ldap_uri, ldap_uri ? strlen(ldap_uri) : 0) != 1) {
			fprintf(stderr, "%s: add FreshestCRL error\n", prog);
			goto end;
		}
	}

	if (x509_crl_sign_to_der(
		X509_version_v2,
		OID_sm2sign_with_sm3,
		issuer, issuer_len,
		this_update, next_update,
		revoked_certs, revoked_certs_len,
		extslen ? exts : NULL, extslen,
		&sign_key, signer_id, signer_id_len,
		NULL, &outlen) != 1) {
		fprintf(stderr, "%s: inner error\n", prog);
		goto end;
	}
	if (!(outbuf = malloc(outlen))) {
		fprintf(stderr, "%s: malloc failure\n", prog);
		goto end;
	}
	out = outbuf;
	outlen = 0;
	if (x509_crl_sign_to_der(
		X509_version_v2,
		OID_sm2sign_with_sm3,
		issuer, issuer_len,
		this_update, next_update,
		revoked_certs, revoked_certs_len,
		extslen ? exts : NULL, extslen,
		&sign_key, signer_id, signer_id_len,
		&out, &outlen) != 1) {
		fprintf(stderr, "%s: inner error\n", prog);
		goto end;
	}
	if (fwrite(outbuf, 1, outlen, outfp) != outlen) {
		fprintf(stderr, "%s: output failure\n", prog);
		return -1;
	}
	ret = 0;

end:
	if (revoked_certs) free(revoked_certs);
	if (keyfp) fclose(keyfp);
	if (cacert) free(cacert);
	if (outfile && outfp) fclose(outfp);
	if (outbuf) free(outbuf);
	return ret;
}
