src/lib/BasicASN1Reader.h
author František Kučera <franta-hg@frantovo.cz>
Sun, 20 Jun 2021 21:06:02 +0200
branchv_0
changeset 14 02725d301010
parent 13 d5e2cb9e31f1
child 15 95ca127ba816
permissions -rw-r--r--
somehow parse nested SEQUENCEs and SETs + support definite long form of lengths (multiple length octets)

/**
 * Relational pipes
 * Copyright © 2021 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once

#include <memory>
#include <vector>
#include <array>
#include <sstream>

#include "ASN1Reader.h"

namespace relpipe {
namespace in {
namespace asn1 {
namespace lib {

/**
 * Reads ASN.1 data encoded as BER (DER, CER).
 */
class BasicASN1Reader : public ASN1Reader {
private:

	bool started = false;

	enum class TagClass : uint8_t {
		Universal = 0,
		Application = 1,
		ContextSpecific = 2,
		Private = 3
	};

	enum class PC : uint8_t {
		Primitive = 0,
		Constructed = 1
	};

	class Header {
	public:
		TagClass tagClass;
		PC pc;
		uint64_t tag;
		bool definiteLength;
		size_t length;
	};

	class LevelMetadata {
	public:
		bool definiteLength;
		size_t length;
		size_t start;
	};

	std::vector<LevelMetadata> level;

	void checkRemainingItems() {
		if (level.size()) {
			LevelMetadata& l = level.back();
			if (l.definiteLength && l.length == getBytesRead() - l.start) {
				level.pop_back();
				handlers.writeCollectionEnd();
			}
		}
	}

	Header readHeader() {
		Header h;

		memset(&h, 0, sizeof (h)); // TODO: remove, not needed

		uint8_t tagByte;
		read(&tagByte, 1);

		h.tagClass = (TagClass) (tagByte >> 6);
		h.pc = (PC) ((tagByte >> 5) & 1);
		h.tag = tagByte & (0xFF >> 3);
		if (h.tag > 30) throw relpipe::writer::RelpipeWriterException(L"not yet implemented, ASN.1 tag > 30"); // FIXME: higher tag values → read more bytes

		uint8_t lengthByte;
		read(&lengthByte, 1);

		if (lengthByte >> 7 == 0) {
			// definite short
			h.definiteLength = true;
			h.length = lengthByte;
		} else if (lengthByte == 0b10000000) {
			// indefinite
			h.definiteLength = false;
			h.length = 0;
		} else if (lengthByte == 0xFF) {
			throw relpipe::writer::RelpipeWriterException(L"ASN.1 lengthByte == 0xFF (reserved value)"); // TODO: better exception
		} else {
			// definite long
			h.definiteLength = true;
			h.length = 0;
			std::vector<uint8_t> lengthBytes(lengthByte & 0b01111111, 0);
			read(lengthBytes.data(), lengthBytes.size());
			for (uint8_t l : lengthBytes) h.length = (h.length << 8) + l;
		}

		return h;
	}

	void readNext() {
		checkRemainingItems();
		Header typeHeader = readHeader();
		// commit(); // TODO: commit here and recover later instead of rollback?

		if (!started) {
			handlers.writeStreamStart();
			started = true;
		}
		
		// TODO: check tagClass and pc

		// TODO: constants, more types
		if (typeHeader.tag == 0) handlers.writeCollectionEnd();
		else if (typeHeader.tag == 16) {
			level.push_back({typeHeader.definiteLength, typeHeader.length, getBytesRead()}); // TODO: transaction
			handlers.writeCollectionStart(ASN1ContentHandler::CollectionType::Sequence);
		} else if (typeHeader.tag == 17) {
			level.push_back({typeHeader.definiteLength, typeHeader.length, getBytesRead()}); // TODO: transaction
			handlers.writeCollectionStart(ASN1ContentHandler::CollectionType::Set);
		} else if (typeHeader.tag == 5 && typeHeader.length == 0) {
			handlers.writeNull();
		} else if (typeHeader.tag == 1) {
			bool value;
			read((uint8_t*) & value, 1);
			handlers.writeBoolean(value);
		} else {
			// TODO: do not skip, parse
			std::vector<uint8_t> temp(typeHeader.length, 0);
			read(temp.data(), typeHeader.length);
			// TODO: recover transaction?

			std::stringstream description;
			description << "value:"
					<< " tag = " << typeHeader.tag
					<< " tagClass = " << (int) typeHeader.tagClass
					<< " pc = " << (int) typeHeader.pc
					<< " length = " << typeHeader.length
					<< " definite = " << (typeHeader.definiteLength ? "true" : "false");

			handlers.writeString(ASN1ContentHandler::StringType::UTF8String, description.str());
		}

		commit();


		// TODO: remove debug/demo output:
		return;
		handlers.writeCollectionStart(ASN1ContentHandler::CollectionType::Sequence);
		handlers.writeNull();
		handlers.writeBoolean(true);

		handlers.writeString(ASN1ContentHandler::StringType::UTF8String, "tagClass:");
		handlers.writeInteger((int64_t) typeHeader.tagClass);
		handlers.writeString(ASN1ContentHandler::StringType::UTF8String, "pc:");
		handlers.writeInteger((int64_t) typeHeader.pc);
		handlers.writeString(ASN1ContentHandler::StringType::UTF8String, "tag:");
		handlers.writeInteger((int64_t) typeHeader.tag);
		handlers.writeString(ASN1ContentHandler::StringType::UTF8String, "definiteLength:");
		handlers.writeBoolean(typeHeader.definiteLength);
		handlers.writeString(ASN1ContentHandler::StringType::UTF8String, "length:");
		handlers.writeInteger((int64_t) typeHeader.length);

		handlers.writeString(ASN1ContentHandler::StringType::UTF8String, "relational pipes");
		handlers.writeCollectionEnd();
	}

protected:

	void update() override {
		while (true) readNext();
	}

public:

	void close() override {
		// TODO: check the bytes remaining in the buffer
		//if (started) handlers.writeStreamEnd();
	}

};

}
}
}
}