Fix handling of invalid characters in message headers and output (#1489032)