MessagesLoader.java

/* ========================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyright 2009-2024, Arnaud Roques
 *
 * Project Info:  https://plantuml.com
 * 
 * If you like this project or if you find it useful, you can support us at:
 * 
 * https://plantuml.com/patreon (only 1$ per month!)
 * https://plantuml.com/paypal
 * 
 * This file is part of PlantUML.
 *
 * PlantUML 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, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PlantUML 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 library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 *
 * Original Author:  Arnaud Roques
 *
 */
package net.sourceforge.plantuml.error.messages;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.dedication.Dedication;
import net.sourceforge.plantuml.error.cron.CronExpression;
import net.sourceforge.plantuml.error.cron.CronSyntaxException;
import net.sourceforge.plantuml.klimt.color.HColorSet;
import net.sourceforge.plantuml.utils.Log;
import net.sourceforge.plantuml.yaml.parser.Monomorph;
import net.sourceforge.plantuml.yaml.parser.MonomorphType;
import net.sourceforge.plantuml.yaml.parser.YamlParser;
import net.sourceforge.plantuml.yaml.parser.YamlSyntaxException;

/**
 * Reads messages.yaml, the file that tells which message to show in an error
 * diagram and when. See {@code docs/MESSAGES_ERREUR.md}.
 *
 * Loading never fails: an invalid rule or message is ignored, and described in
 * {@link MessagesConfig#getProblems()}.
 */
public final class MessagesLoader {

	static final String RESOURCE_DIRECTORY = "/net/sourceforge/plantuml/error/";
	static final String RESOURCE = RESOURCE_DIRECTORY + "messages.yaml";

	static final int MAX_IMAGE_SIZE = 64 * 1024;
	static final int MAX_ID_LENGTH = 64;
	static final int MAX_QRCODE_LENGTH = 256;
	static final int MIN_FONT_SIZE = 6;
	static final int MAX_FONT_SIZE = 72;
	static final int MAX_QRCODE_SCALE = 10;

	private static final String RESOURCE_PREFIX = "resource:";
	private static final byte[] PNG_SIGNATURE = { (byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n' };

	private static final Set<String> ROOT_KEYS = keys("rules", "messages");
	private static final Set<String> RULE_KEYS = keys("id", "cron", "from", "until", "source-contains",
			"probability", "message", "position");
	private static final Set<String> MESSAGE_KEYS = keys("background", "font-size", "text", "qrcode", "qrcode-scale",
			"image", "image-position");

	private static Set<String> keys(String... keys) {
		return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(keys)));
	}

	/** Why one rule or one message is ignored. */
	private static class InvalidEntryException extends Exception {
		InvalidEntryException(String message) {
			super(message);
		}
	}

	private final List<String> problems = new ArrayList<>();
	private final Map<String, MessageDefinition> messages = new LinkedHashMap<>();
	// The messages of the file that are invalid, to say so when a rule uses one
	private final Set<String> invalidMessages = new HashSet<>();
	private final List<MessageRule> rules = new ArrayList<>();

	private MessagesLoader() {
	}

	/**
	 * Loads the messages.yaml embedded in PlantUML. Never fails; every problem is
	 * logged.
	 */
	public static MessagesConfig loadDefault() {
		MessagesConfig result;
		try (InputStream is = MessagesLoader.class.getResourceAsStream(RESOURCE)) {
			if (is == null)
				result = failure("resource " + RESOURCE + " not found");
			else
				result = fromBytes(readAll(is, Integer.MAX_VALUE));
		} catch (IOException | RuntimeException e) {
			result = failure("cannot read " + RESOURCE + ": " + e);
		}
		for (String problem : result.getProblems())
			Log.info(() -> "messages.yaml: " + problem);

		return result;
	}

	/**
	 * Loads the content of a messages.yaml file, signed with the key of
	 * {@link Dedication}. This is the single entry point for the raw bytes: without
	 * a valid signature, nothing is loaded, so no message is shown.
	 */
	public static MessagesConfig fromBytes(byte[] data) {
		return fromBytes(data, Dedication.E, Dedication.N);
	}

	/** Same as {@link #fromBytes(byte[])}, with another public key (for the tests). */
	static MessagesConfig fromBytes(byte[] data, BigInteger e, BigInteger n) {
		final String content = MessagesSignature.verify(data, e, n);
		if (content == null)
			return failure("missing or invalid signature: nothing loaded");

		return load(Arrays.asList(content.split("\n", -1)));
	}

	static MessagesConfig load(List<String> lines) {
		final MessagesLoader loader = new MessagesLoader();
		loader.loadAll(lines);
		return new MessagesConfig(loader.rules, loader.messages, loader.problems);
	}

	private static MessagesConfig failure(String problem) {
		return new MessagesConfig(Collections.<MessageRule>emptyList(),
				Collections.<String, MessageDefinition>emptyMap(), Collections.singletonList(problem));
	}

	private void loadAll(List<String> lines) {
		final Monomorph root;
		try {
			root = new YamlParser().parse(lines);
		} catch (YamlSyntaxException e) {
			problems.add("invalid YAML: " + e.getMessage());
			return;
		}
		if (root.getType() != MonomorphType.MAP) {
			problems.add("the file must be a map with the keys rules and messages");
			return;
		}
		for (String key : root.keys())
			if (ROOT_KEYS.contains(key) == false)
				problems.add("unknown key '" + key + "' at the root, ignored");

		// The messages first: the rules refer to them, whatever the order of the file
		final Monomorph messagesNode = root.getMapValue("messages");
		if (isEmpty(messagesNode) == false) {
			if (messagesNode.getType() == MonomorphType.MAP)
				for (String id : messagesNode.keys())
					loadMessage(id, messagesNode.getMapValue(id));
			else
				problems.add("'messages' must be a map: no message loaded");
		}

		final Monomorph rulesNode = root.getMapValue("rules");
		if (isEmpty(rulesNode) == false) {
			if (rulesNode.getType() == MonomorphType.LIST)
				for (int i = 0; i < rulesNode.size(); i++)
					loadRule(i + 1, rulesNode.getElementAt(i));
			else
				problems.add("'rules' must be a list: no rule loaded");
		}
	}

	// "key:" alone is an empty scalar
	private static boolean isEmpty(Monomorph node) {
		return node == null || (node.getType() == MonomorphType.SCALAR && node.getValue().length() == 0);
	}

	// ----- Messages

	private void loadMessage(String id, Monomorph node) {
		try {
			checkId(id);
			messages.put(id, parseMessage(id, node));
		} catch (InvalidEntryException e) {
			invalidMessages.add(id);
			problems.add("message '" + id + "' ignored: " + e.getMessage());
		}
	}

	private MessageDefinition parseMessage(String id, Monomorph node) throws InvalidEntryException {
		if (node.getType() != MonomorphType.MAP)
			throw new InvalidEntryException("a message must be a map");

		checkKeys(node, MESSAGE_KEYS);

		final String background = optionalScalar(node, "background");
		if (background != null && HColorSet.instance().getColorOrNull(background) == null)
			throw new InvalidEntryException(
					"invalid background '" + background + "' (a color starting with # must be quoted)");

		final int fontSize = optionalInt(node, "font-size", MIN_FONT_SIZE, MAX_FONT_SIZE,
				MessageDefinition.DEFAULT_FONT_SIZE);

		String text = optionalScalar(node, "text");
		if (text != null) {
			while (text.endsWith("\n"))
				text = text.substring(0, text.length() - 1);
			if (text.trim().length() == 0)
				throw new InvalidEntryException("empty text");
		}

		final String qrcode = optionalScalar(node, "qrcode");
		if (qrcode != null && qrcode.length() > MAX_QRCODE_LENGTH)
			throw new InvalidEntryException("qrcode longer than " + MAX_QRCODE_LENGTH + " characters");

		final int qrcodeScale = optionalInt(node, "qrcode-scale", 1, MAX_QRCODE_SCALE,
				MessageDefinition.DEFAULT_QRCODE_SCALE);

		final String imageValue = optionalScalar(node, "image");
		final byte[] image = imageValue == null ? null : parseImage(imageValue);

		ImagePosition imagePosition = ImagePosition.RIGHT;
		final String imagePositionValue = optionalScalar(node, "image-position");
		if (imagePositionValue != null) {
			imagePosition = ImagePosition.fromYaml(imagePositionValue);
			if (imagePosition == null)
				throw new InvalidEntryException("unknown image-position '" + imagePositionValue + "'");
		}

		if (text == null && qrcode == null && image == null)
			throw new InvalidEntryException("a message needs text, image or qrcode");

		return new MessageDefinition(id, background, fontSize, text, qrcode, qrcodeScale, image, imagePosition);
	}

	private byte[] parseImage(String value) throws InvalidEntryException {
		final byte[] result;
		if (value.startsWith(RESOURCE_PREFIX))
			result = readImageResource(value.substring(RESOURCE_PREFIX.length()).trim());
		else
			result = decodeBase64(value);

		if (result.length > MAX_IMAGE_SIZE)
			throw new InvalidEntryException("image larger than " + MAX_IMAGE_SIZE + " bytes");

		if (startsWithPngSignature(result) == false)
			throw new InvalidEntryException("the image is not a PNG");

		return result;
	}

	private static byte[] readImageResource(String name) throws InvalidEntryException {
		if (isValidResourceName(name) == false)
			throw new InvalidEntryException("invalid resource name '" + name + "'");

		try (InputStream is = MessagesLoader.class.getResourceAsStream(RESOURCE_DIRECTORY + name)) {
			if (is == null)
				throw new InvalidEntryException("resource '" + name + "' not found");

			return readAll(is, MAX_IMAGE_SIZE + 1);
		} catch (IOException e) {
			throw new InvalidEntryException("cannot read resource '" + name + "': " + e);
		}
	}

	// Only a plain file name next to messages.yaml: no directory, no ".."
	private static boolean isValidResourceName(String name) {
		if (name.endsWith(".png") == false || name.length() == ".png".length() || name.startsWith("."))
			return false;

		for (int i = 0; i < name.length(); i++) {
			final char c = name.charAt(i);
			final boolean ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'
					|| c == '-' || c == '.';
			if (ok == false)
				return false;
		}
		return true;
	}

	private static byte[] decodeBase64(String value) throws InvalidEntryException {
		final StringBuilder sb = new StringBuilder(value.length());
		for (int i = 0; i < value.length(); i++) {
			final char c = value.charAt(i);
			if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
				sb.append(c);
		}
		// Refused before decoding, so that a huge text is never decoded
		if (sb.length() > (MAX_IMAGE_SIZE + 2) / 3 * 4)
			throw new InvalidEntryException("image larger than " + MAX_IMAGE_SIZE + " bytes");

		try {
			return Base64.getDecoder().decode(sb.toString());
		} catch (IllegalArgumentException e) {
			throw new InvalidEntryException("invalid base64 image");
		}
	}

	private static boolean startsWithPngSignature(byte[] data) {
		if (data.length < PNG_SIGNATURE.length)
			return false;

		for (int i = 0; i < PNG_SIGNATURE.length; i++)
			if (data[i] != PNG_SIGNATURE[i])
				return false;

		return true;
	}

	// ----- Rules

	private void loadRule(int number, Monomorph node) {
		String id = null;
		try {
			if (node.getType() != MonomorphType.MAP)
				throw new InvalidEntryException("a rule must be a map");

			id = optionalScalar(node, "id");
			if (id == null)
				throw new InvalidEntryException("missing id");

			checkId(id);
			if (findRule(id) != null)
				throw new InvalidEntryException("duplicate id");

			rules.add(parseRule(id, node));
		} catch (InvalidEntryException e) {
			problems.add("rule #" + number + (id == null ? "" : " '" + id + "'") + " ignored: " + e.getMessage());
		}
	}

	private MessageRule findRule(String id) {
		for (MessageRule rule : rules)
			if (rule.getId().equals(id))
				return rule;

		return null;
	}

	private MessageRule parseRule(String id, Monomorph node) throws InvalidEntryException {
		checkKeys(node, RULE_KEYS);

		final List<CronExpression> crons = parseCrons(node.getMapValue("cron"));

		final String fromValue = optionalScalar(node, "from");
		final int from = fromValue == null ? 0 : parseDate("from", fromValue);
		final String untilValue = optionalScalar(node, "until");
		final int until = untilValue == null ? 0 : parseDate("until", untilValue);
		if (from != 0 && until != 0 && from > until)
			throw new InvalidEntryException("'from' is after 'until'");

		String sourceContains = optionalScalar(node, "source-contains");
		if (sourceContains != null) {
			if (sourceContains.length() == 0)
				throw new InvalidEntryException("empty source-contains");
			sourceContains = StringUtils.goLowerCase(sourceContains);
		}

		final String probabilityValue = optionalScalar(node, "probability");
		final double probability = probabilityValue == null ? 1.0 : parseProbability(probabilityValue);

		final MessageDefinition message = parseRuleMessage(id, node.getMapValue("message"));

		MessagePosition position = MessagePosition.TOP;
		final String positionValue = optionalScalar(node, "position");
		if (positionValue != null) {
			position = MessagePosition.fromYaml(positionValue);
			if (position == null)
				throw new InvalidEntryException("unknown position '" + positionValue + "'");
		}

		return new MessageRule(id, crons, from, until, sourceContains, probability, message, position);
	}

	private static List<CronExpression> parseCrons(Monomorph node) throws InvalidEntryException {
		final List<CronExpression> result = new ArrayList<>();
		if (node == null)
			return result;

		try {
			if (node.getType() == MonomorphType.SCALAR) {
				result.add(parseCron(node.getValue()));
			} else if (node.getType() == MonomorphType.LIST) {
				if (node.size() == 0)
					throw new InvalidEntryException("empty cron");
				for (int i = 0; i < node.size(); i++) {
					final Monomorph element = node.getElementAt(i);
					if (element.getType() != MonomorphType.SCALAR)
						throw new InvalidEntryException("a cron list must only hold strings");
					result.add(parseCron(element.getValue()));
				}
			} else {
				throw new InvalidEntryException("cron must be a string or a list of strings");
			}
		} catch (CronSyntaxException e) {
			throw new InvalidEntryException(e.getMessage());
		}
		return result;
	}

	// "cron:" alone is an empty value, and "cron: []" a list holding one empty value
	private static CronExpression parseCron(String value) throws InvalidEntryException, CronSyntaxException {
		if (value.trim().length() == 0)
			throw new InvalidEntryException("empty cron");

		return CronExpression.parse(value);
	}

	private MessageDefinition parseRuleMessage(String ruleId, Monomorph node) throws InvalidEntryException {
		if (node == null)
			throw new InvalidEntryException("missing message");

		if (node.getType() == MonomorphType.MAP)
			return parseMessage(ruleId, node);

		if (node.getType() != MonomorphType.SCALAR || node.getValue().length() == 0)
			throw new InvalidEntryException("missing message");

		final String reference = node.getValue();
		final MessageDefinition result = messages.get(reference);
		if (result != null)
			return result;

		if (invalidMessages.contains(reference))
			throw new InvalidEntryException("message '" + reference + "' is invalid");

		throw new InvalidEntryException("unknown message '" + reference + "'");
	}

	/** "2027-01-15" as 20270115. */
	static int parseDate(String key, String value) throws InvalidEntryException {
		final String error = "invalid " + key + " '" + value + "', expected YYYY-MM-DD";
		if (value.length() != 10 || value.charAt(4) != '-' || value.charAt(7) != '-')
			throw new InvalidEntryException(error);

		final int year = parseDigits(value.substring(0, 4));
		final int month = parseDigits(value.substring(5, 7));
		final int day = parseDigits(value.substring(8, 10));
		if (year == -1 || month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month))
			throw new InvalidEntryException(error);

		return year * 10000 + month * 100 + day;
	}

	private static int daysInMonth(int year, int month) {
		switch (month) {
		case 2:
			final boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
			return leap ? 29 : 28;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		default:
			return 31;
		}
	}

	/** "0.3", "1" or "1.0", between 0 and 1. */
	private static double parseProbability(String value) throws InvalidEntryException {
		final String error = "invalid probability '" + value + "', expected a number between 0.0 and 1.0";
		final int dot = value.indexOf('.');
		final String integerPart = dot == -1 ? value : value.substring(0, dot);
		final String decimalPart = dot == -1 ? "0" : value.substring(dot + 1);
		if (integerPart.length() > 1 || parseDigits(integerPart) == -1 || decimalPart.length() > 6
				|| parseDigits(decimalPart) == -1)
			throw new InvalidEntryException(error);

		final double result = Double.parseDouble(value);
		if (result < 0.0 || result > 1.0)
			throw new InvalidEntryException(error);

		return result;
	}

	// ----- Helpers

	// Letters, digits, '-' and '_': the id appears in logs and tests
	private static void checkId(String id) throws InvalidEntryException {
		if (id.length() == 0 || id.length() > MAX_ID_LENGTH)
			throw new InvalidEntryException("invalid id '" + id + "'");

		for (int i = 0; i < id.length(); i++) {
			final char c = id.charAt(i);
			final boolean ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'
					|| c == '-';
			if (ok == false)
				throw new InvalidEntryException("invalid id '" + id + "'");
		}
	}

	private static void checkKeys(Monomorph node, Set<String> allowed) throws InvalidEntryException {
		for (String key : node.keys())
			if (allowed.contains(key) == false)
				throw new InvalidEntryException("unknown key '" + key + "'");
	}

	/** The value of a scalar key, or null when the key is missing. */
	private static String optionalScalar(Monomorph node, String key) throws InvalidEntryException {
		final Monomorph value = node.getMapValue(key);
		if (value == null)
			return null;

		if (value.getType() != MonomorphType.SCALAR)
			throw new InvalidEntryException("'" + key + "' must be a single value");

		return value.getValue();
	}

	private static int optionalInt(Monomorph node, String key, int min, int max, int defaultValue)
			throws InvalidEntryException {
		final String value = optionalScalar(node, key);
		if (value == null)
			return defaultValue;

		final int result = parseDigits(value);
		if (result < min || result > max)
			throw new InvalidEntryException("invalid " + key + " '" + value + "', expected " + min + "-" + max);

		return result;
	}

	/** A small unsigned decimal number, or -1. */
	private static int parseDigits(String s) {
		if (s.length() == 0 || s.length() > 6)
			return -1;

		int result = 0;
		for (int i = 0; i < s.length(); i++) {
			final char c = s.charAt(i);
			if (c < '0' || c > '9')
				return -1;

			result = result * 10 + (c - '0');
		}
		return result;
	}

	private static byte[] readAll(InputStream is, int limit) throws IOException {
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		final byte[] buffer = new byte[4096];
		int read;
		while ((read = is.read(buffer)) != -1) {
			baos.write(buffer, 0, read);
			if (baos.size() >= limit)
				break;
		}
		return baos.toByteArray();
	}

}