static STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
				   long length)
	{
	ASN1_OCTET_STRING *oct = NULL;
	STACK_OF(SCT) *sk = NULL;
	SCT *sct;
	unsigned char *p, *p2;
	unsigned short listlen, sctlen = 0, fieldlen;

	if (d2i_ASN1_OCTET_STRING(&oct, pp, length) == NULL)
		return NULL;
	if (oct->length < 2)
		goto done;
	p = oct->data;
	n2s(p, listlen);
	if (listlen != oct->length - 2)
		goto done;

	if ((sk=sk_SCT_new_null()) == NULL)
		goto done;

	while (listlen > 0)
		{
		if (listlen < 2)
			goto err;
		n2s(p, sctlen);
		listlen -= 2;

		if ((sctlen < 1) || (sctlen > listlen))
			goto err;
		listlen -= sctlen;

		sct = OPENSSL_malloc(sizeof(SCT));
		if (!sct)
			goto err;
		if (!sk_SCT_push(sk, sct))
			{
			OPENSSL_free(sct);
			goto err;
			}

		sct->sct = OPENSSL_malloc(sctlen);
		if (!sct->sct)
			goto err;
		memcpy(sct->sct, p, sctlen);
		sct->sctlen = sctlen;
		p += sctlen;
		p2 = sct->sct;

		sct->version = *p2++;
		if (sct->version == 0)		/* SCT v1 */
			{
			/* Fixed-length header:
			 *		struct {
			 * (1 byte)	  Version sct_version;
			 * (32 bytes)	  LogID id;
			 * (8 bytes)	  uint64 timestamp;
			 * (2 bytes + ?)  CtExtensions extensions;
			 */
			if (sctlen < 43)
				goto err;
			sctlen -= 43;

			sct->logid = p2;
			sct->logidlen = 32;
			p2 += 32;

			n2l8(p2, sct->timestamp);

			n2s(p2, fieldlen);
			if (sctlen < fieldlen)
				goto err;
			sct->ext = p2;
			sct->extlen = fieldlen;
			p2 += fieldlen;
			sctlen -= fieldlen;

			/* digitally-signed struct header:
			 * (1 byte)       Hash algorithm
			 * (1 byte)       Signature algorithm
			 * (2 bytes + ?)  Signature
			 */
			if (sctlen < 4)
				goto err;
			sctlen -= 4;

			sct->hash_alg = *p2++;
			sct->sig_alg = *p2++;
			n2s(p2, fieldlen);
			if (sctlen != fieldlen)
				goto err;
			sct->sig = p2;
			sct->siglen = fieldlen;
			}
		}

	done:
	ASN1_OCTET_STRING_free(oct);
	return sk;

	err:
	SCT_LIST_free(sk);
	sk = NULL;
	goto done;
	}