#include <curl/curl.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/ts.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>

#include <stdio.h>
#include <string.h>
#include <time.h>

#include "timestamp.h"

static size_t
receive_reply(char *data, size_t size, size_t count, void *arg)
{
	struct timestamp_reply *reply = arg;
	size_t n;

	if (size != 0 && count > (TIMESTAMP_MAX_REPLY - reply->size) / size)
		return 0;
	n = size * count;
	memcpy(reply->data + reply->size, data, n);
	reply->size += n;
	return n;
}

int
timestamp_fetch(const char *url, const char *ca_file, const char *tls_ca_file,
    const char *sha256, long timeout_ms, struct timestamp_reply *reply)
{
	TS_REQ *req = NULL;
	TS_RESP *resp = NULL;
	TS_MSG_IMPRINT *imprint = NULL;
	TS_VERIFY_CTX *verify = NULL;
	X509_ALGOR *algorithm = NULL, *digest;
	X509_STORE *store = NULL;
	STACK_OF(PKCS7_SIGNER_INFO) *signers;
	const ASN1_OBJECT *digest_oid;
	ASN1_INTEGER *nonce = NULL;
	BIGNUM *number = NULL;
	CURL *curl = NULL;
	struct curl_slist *headers = NULL, *added;
	unsigned char hash[32], random[16], *request = NULL;
	const unsigned char *cursor;
	struct tm tm;
	char pair[3];
	long status = 0;
	int n, i, rv = -1;

	memset(reply, 0, sizeof(*reply));
	reply->error = "request_failed";
	if (url == NULL || strncmp(url, "https://", 8) != 0 || ca_file == NULL ||
	    *ca_file == '\0' || sha256 == NULL || strlen(sha256) != 64 || timeout_ms <= 0)
		return -1;
	for (i = 0; i < 64; i++)
		if (strchr("0123456789abcdef", sha256[i]) == NULL)
			return -1;
	for (i = 0; i < 32; i++) {
		unsigned int byte;

		pair[0] = sha256[i * 2];
		pair[1] = sha256[i * 2 + 1];
		pair[2] = '\0';
		if (sscanf(pair, "%x", &byte) != 1)
			return -1;
		hash[i] = (unsigned char)byte;
	}
	if ((req = TS_REQ_new()) == NULL || (imprint = TS_MSG_IMPRINT_new()) == NULL ||
	    (algorithm = X509_ALGOR_new()) == NULL || RAND_bytes(random, sizeof(random)) != 1)
		goto out;
	X509_ALGOR_set0(algorithm, OBJ_nid2obj(NID_sha256), V_ASN1_NULL, NULL);
	number = BN_bin2bn(random, sizeof(random), NULL);
	if (number == NULL || (nonce = BN_to_ASN1_INTEGER(number, NULL)) == NULL ||
	    TS_REQ_set_version(req, 1) != 1 || TS_MSG_IMPRINT_set_algo(imprint, algorithm) != 1 ||
	    TS_MSG_IMPRINT_set_msg(imprint, hash, sizeof(hash)) != 1 ||
	    TS_REQ_set_msg_imprint(req, imprint) != 1 || TS_REQ_set_nonce(req, nonce) != 1 ||
	    TS_REQ_set_cert_req(req, 1) != 1 || (n = i2d_TS_REQ(req, &request)) <= 0)
		goto out;
	if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK)
		goto out;
	curl = curl_easy_init();
	headers = curl_slist_append(NULL, "Content-Type: application/timestamp-query");
	if (curl == NULL || headers == NULL)
		goto http_done;
	added = curl_slist_append(headers, "Accept: application/timestamp-reply");
	if (added == NULL)
		goto http_done;
	headers = added;
#define OPTION(key, value) do { if (curl_easy_setopt(curl, key, value) != CURLE_OK) goto http_done; } while (0)
	OPTION(CURLOPT_URL, url);
	OPTION(CURLOPT_PROTOCOLS_STR, "https");
	OPTION(CURLOPT_FOLLOWLOCATION, 0L);
	OPTION(CURLOPT_PROXY, "");
	OPTION(CURLOPT_NOSIGNAL, 1L);
	OPTION(CURLOPT_SSL_VERIFYPEER, 1L);
	OPTION(CURLOPT_SSL_VERIFYHOST, 2L);
	OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
	OPTION(CURLOPT_CONNECTTIMEOUT_MS, timeout_ms < 3000 ? timeout_ms : 3000L);
	OPTION(CURLOPT_TIMEOUT_MS, timeout_ms);
	OPTION(CURLOPT_POST, 1L);
	OPTION(CURLOPT_POSTFIELDS, request);
	OPTION(CURLOPT_POSTFIELDSIZE, (long)n);
	OPTION(CURLOPT_HTTPHEADER, headers);
	OPTION(CURLOPT_WRITEFUNCTION, receive_reply);
	OPTION(CURLOPT_WRITEDATA, reply);
	if (tls_ca_file != NULL && *tls_ca_file != '\0')
		OPTION(CURLOPT_CAINFO, tls_ca_file);
	reply->error = "transport_failed";
	if (curl_easy_perform(curl) != CURLE_OK ||
	    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status) != CURLE_OK || status != 200)
		goto http_done;
	reply->error = "invalid_response";
	cursor = reply->data;
	resp = d2i_TS_RESP(NULL, &cursor, (long)reply->size);
	if (resp == NULL || cursor != reply->data + reply->size)
		goto http_done;
	store = X509_STORE_new();
	verify = TS_REQ_to_TS_VERIFY_CTX(req, NULL);
	if (store == NULL || verify == NULL || X509_STORE_load_locations(store, ca_file, NULL) != 1)
		goto http_done;
	X509_VERIFY_PARAM_set_auth_level(X509_STORE_get0_param(store), 2);
	/* This context already checks the requested imprint, version and nonce.
	 * Signature verification additionally checks the explicit trust and TSA EKU. */
#if OPENSSL_VERSION_NUMBER >= 0x30400000L
	if (TS_VERIFY_CTX_set0_store(verify, store) != 1)
		goto http_done;
#else
	TS_VERIFY_CTX_set_store(verify, store);
#endif
	store = NULL;
	TS_VERIFY_CTX_add_flags(verify, TS_VFY_SIGNATURE);
	reply->error = "untrusted_response";
	/* libcrypto also accepts legacy CMS digests; require SHA-2 evidence. */
	if (TS_RESP_get_token(resp) == NULL ||
	    (signers = PKCS7_get_signer_info(TS_RESP_get_token(resp))) == NULL ||
	    sk_PKCS7_SIGNER_INFO_num(signers) != 1)
		goto http_done;
	PKCS7_SIGNER_INFO_get0_algs(sk_PKCS7_SIGNER_INFO_value(signers, 0), NULL, &digest, NULL);
	if (digest == NULL)
		goto http_done;
	X509_ALGOR_get0(&digest_oid, NULL, NULL, digest);
	n = OBJ_obj2nid(digest_oid);
	if (n != NID_sha256 && n != NID_sha384 && n != NID_sha512)
		goto http_done;
	if (TS_RESP_verify_response(verify, resp) != 1)
		goto http_done;
	if (ASN1_TIME_to_tm((const ASN1_TIME *)TS_TST_INFO_get_time(TS_RESP_get_tst_info(resp)), &tm) != 1 ||
	    tm.tm_year < 70 || tm.tm_year > 8099)
		goto http_done;
	snprintf(reply->at, sizeof(reply->at), "%04d-%02d-%02dT%02d:%02d:%02dZ",
	    tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
	reply->error = NULL;
	rv = 0;
http_done:
	curl_slist_free_all(headers);
	curl_easy_cleanup(curl);
	curl_global_cleanup();
out:
	TS_VERIFY_CTX_free(verify);
	X509_STORE_free(store);
	TS_RESP_free(resp);
	OPENSSL_free(request);
	ASN1_INTEGER_free(nonce);
	BN_free(number);
	X509_ALGOR_free(algorithm);
	TS_MSG_IMPRINT_free(imprint);
	TS_REQ_free(req);
	ERR_clear_error();
	return rv;
#undef OPTION
}
