Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions docs/how-to/parse-errors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,38 @@ When you access a property descriptor like :attr:`event.DTSTART <icalendar.cal.e
Original error: Expected datetime, date, or time. Got: 'INVALID-DATE'

:class:`~icalendar.error.BrokenCalendarProperty` is a subclass of :class:`~icalendar.error.InvalidCalendar`, so existing ``except InvalidCalendar`` handlers will still catch it.


Parse calendars that are not UTF-8
----------------------------------

:rfc:`5545#section-3.1.4` sets the default character set encoding of iCalendar data to UTF-8.
Some applications still export calendars in other encodings, such as ``cp1252``.
If the data is not valid UTF-8, :meth:`Calendar.from_ical <icalendar.cal.calendar.Calendar.from_ical>` raises an :class:`~icalendar.error.ICalDecodeError`.

.. code-block:: pycon

>>> from icalendar import ICalDecodeError
>>> data = b"BEGIN:VCALENDAR\r\nPRODID:R\xe9union\r\nEND:VCALENDAR\r\n"
>>> try:
... Calendar.from_ical(data)
... except ICalDecodeError as e:
... print(f"Line {e.line_number}: {e.value!r}")
Line 2: b'\xe9'

icalendar does not guess the encoding, because a wrong guess silently turns the text into different characters.
If you know the encoding of the data, decode it yourself and pass the string.

.. code-block:: pycon

>>> calendar = Calendar.from_ical(data.decode("cp1252"))
>>> print(calendar["PRODID"])
Réunion

If you prefer the behavior of earlier versions of icalendar, which replaced the invalid bytes with the replacement character ``�``, decode the data with ``errors="replace"``.

.. code-block:: pycon

>>> calendar = Calendar.from_ical(data.decode("utf-8", errors="replace"))
>>> print(calendar["PRODID"])
R�union
27 changes: 24 additions & 3 deletions docs/how-to/upgrade.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,11 @@ The example below shows how to correctly access binary data:
>>> v_binary.bytes[:4] # correct access for PNG image data
b'\x89PNG'

For backward compatibility, if corrupt data is acceptable and you need to get the bytes as a Unicode string, use :meth:`~icalendar.parser_tools.to_unicode` as shown in the following code:
For backward compatibility, if corrupt data is acceptable and you need to get the bytes as a Unicode string, decode them with ``errors="replace"`` as shown in the following code:

.. code-block:: pycon

>>> from icalendar.parser_tools import to_unicode
>>> string = to_unicode(v_binary.bytes) # corrupts data
>>> string = v_binary.bytes.decode("utf-8", errors="replace") # corrupts data

.. _removed-from-icalendar-parser-string:

Expand All @@ -86,6 +85,28 @@ These functions have been removed from :mod:`icalendar.parser.string`:
* ``unescape_char``
* ``unescape_string``

.. _from-ical-not-utf-8:

``Component.from_ical`` raises an error for data that is not UTF-8
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

:meth:`Component.from_ical <icalendar.cal.component.Component.from_ical>` used to replace bytes that are not valid UTF-8 with ``�``, which silently corrupted the text.
It now raises an :class:`~icalendar.error.ICalDecodeError` instead.

If you know the encoding of the data, decode it yourself and pass the string:

.. code-block:: python

calendar = Calendar.from_ical(data.decode("cp1252"))

If you want the previous behavior, decode the data with ``errors="replace"``:

.. code-block:: python

calendar = Calendar.from_ical(data.decode("utf-8", errors="replace"))

See :doc:`parse-errors` for more information.


.. _upgrade-8.0.0-prek:

Expand Down
1 change: 1 addition & 0 deletions news/1793.breaking
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Changed :meth:`Calendar.from_ical <icalendar.cal.calendar.Calendar.from_ical>` to raise :class:`~icalendar.error.ICalDecodeError` when the data is not valid UTF-8. Previously, it silently replaced the invalid bytes with ``�``. If you know the encoding of the data, decode it yourself before parsing, as described in :ref:`from-ical-not-utf-8`. I used AI to assist me with this change. :user:`Hrittik20`
4 changes: 4 additions & 0 deletions src/icalendar/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,12 @@
)
from icalendar.error import (
BrokenCalendarProperty,
CalendarDecodeError,
ComponentEndMissing,
ComponentStartMissing,
FeatureWillBeRemovedInFutureVersion,
GloballyUniqueTZIDGuessed,
ICalDecodeError,
ICalParsingError,
IncompleteAlarmInformation,
IncompleteComponent,
Expand Down Expand Up @@ -126,6 +128,7 @@
"Available",
"BrokenCalendarProperty",
"Calendar",
"CalendarDecodeError",
"Component",
"ComponentEndMissing",
"ComponentFactory",
Expand All @@ -135,6 +138,7 @@
"FeatureWillBeRemovedInFutureVersion",
"FreeBusy",
"GloballyUniqueTZIDGuessed",
"ICalDecodeError",
"ICalParsingError",
"Image",
"IncompleteAlarmInformation",
Expand Down
65 changes: 65 additions & 0 deletions src/icalendar/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,69 @@ def __init__(
super().__init__(full_message)


class CalendarDecodeError(InvalidCalendar):
"""The calendar data could not be decoded.

:rfc:`5545#section-3.1.4` sets the default character set encoding
of iCalendar data to UTF-8.
icalendar does not guess another encoding,
because a wrong guess silently turns the text into different characters.

If you know the encoding of the data, decode it yourself and pass the string
to :meth:`Calendar.from_ical <icalendar.cal.calendar.Calendar.from_ical>`.
See :doc:`/how-to/parse-errors` for examples.
If you get such calendars from a well-known application,
open an issue related to :issue:`1793`.

The original :class:`UnicodeDecodeError` is chained as ``__cause__``.

.. versionadded:: 0.0.0

Parameters:
error: The error raised while decoding the data.
"""

encoding: str
"""The encoding that was used to decode the data."""

value: bytes
"""The bytes that could not be decoded."""

start: int
"""The position of the first byte that could not be decoded."""

line_number: int
"""The line of the bytes that could not be decoded, starting at 1."""

def __init__(self, error: UnicodeDecodeError) -> None:
value = error.object[error.start : error.end]
line_number = error.object.count(b"\n", 0, error.start) + 1
super().__init__(
f"Could not decode {value!r} at position {error.start} (line "
f"{line_number}) as {error.encoding}. RFC 5545 sets the default "
"encoding of iCalendar data to UTF-8. To find out how to proceed, see "
"https://icalendar.readthedocs.io/en/stable/reference/api/"
"icalendar.error.html#icalendar.error.CalendarDecodeError "
"and https://github.com/collective/icalendar/issues/1793"
)
self.encoding = error.encoding
self.value = value
self.start = error.start
self.line_number = line_number


class ICalDecodeError(CalendarDecodeError, ICalParsingError):
"""The iCalendar data could not be decoded.

:meth:`Component.from_ical <icalendar.cal.component.Component.from_ical>`
raises this error, so you can catch it as either
:class:`~icalendar.error.CalendarDecodeError` or
:class:`~icalendar.error.ICalParsingError`.

.. versionadded:: 0.0.0
"""


class BrokenCalendarProperty(InvalidCalendar):
"""A property could not be parsed and its value is broken.

Expand Down Expand Up @@ -403,9 +466,11 @@ def __init__(

__all__ = [
"BrokenCalendarProperty",
"CalendarDecodeError",
"ComponentEndMissing",
"ComponentStartMissing",
"FeatureWillBeRemovedInFutureVersion",
"ICalDecodeError",
"ICalParsingError",
"IncompleteAlarmInformation",
"IncompleteComponent",
Expand Down
18 changes: 12 additions & 6 deletions src/icalendar/parser/ical/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@

from typing import TYPE_CHECKING, ClassVar

from icalendar.error import ICalParsingError, InvalidToken
from icalendar.error import (
CalendarDecodeError,
ICalDecodeError,
ICalParsingError,
InvalidToken,
)
from icalendar.parser.content_line import Contentline, Contentlines
from icalendar.parser.property import split_on_unescaped_comma
from icalendar.prop import vBroken
Expand Down Expand Up @@ -78,11 +83,12 @@ def contains_uid(self, uid: str) -> bool:
def initialize_parsing(self):
self._stack: list[Component] = []
self._components: list[Component] = []
self._data = self._content_lines = (
self._data
if isinstance(self._data, list)
else Contentlines.from_ical(self._data)
)
if not isinstance(self._data, list):
try:
self._data = Contentlines.from_ical(self._data)
except CalendarDecodeError as error:
raise ICalDecodeError(error.__cause__) from error.__cause__
self._content_lines = self._data
self._content_lines_iterator = iter(self._content_lines)

def handle_line_parse_error(self, exception: Exception):
Expand Down
15 changes: 12 additions & 3 deletions src/icalendar/parser_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

from icalendar.error import CalendarDecodeError

#: The supported sequence types.
SEQUENCE_TYPES = (list, tuple)
#: The default encoding to use when encoding or decoding iCalendar data.
Expand Down Expand Up @@ -35,16 +37,23 @@ def to_unicode(value: ICAL_TYPE, encoding: str = "utf-8-sig") -> str:
"""Converts a value to Unicode, even if it is already a Unicode string.

Parameters:
value: The value to convert.
value: Required. The value to convert.
encoding: The encoding to use in the conversion.

Raises:
~icalendar.error.CalendarDecodeError: If ``value`` cannot be decoded.

.. versionchanged:: 0.0.0
Raise :class:`~icalendar.error.CalendarDecodeError` instead of
replacing bytes that cannot be decoded.
"""
if isinstance(value, str):
return value
if isinstance(value, bytes):
try:
return value.decode(encoding)
except UnicodeDecodeError:
return value.decode("utf-8-sig", "replace")
except UnicodeDecodeError as error:
raise CalendarDecodeError(error) from error
else:
return value

Expand Down
11 changes: 4 additions & 7 deletions src/icalendar/tests/prop/test_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import pytest

from icalendar.error import CalendarDecodeError
from icalendar.parser import Parameters
from icalendar.prop.factory import TypesFactory

Expand Down Expand Up @@ -228,13 +229,9 @@ def test_prop_vText(self):
).parts()
assert vText.from_ical(value) == "A string with; some\\ characters in\\it"

# We are forgiving to utf-8 encoding errors:
# We intentionally use a string with unexpected encoding
#
assert vText.from_ical(b"Ol\xe9") == "Ol�"

# Notice how accented E character, encoded with latin-1, got replaced
# with the official U+FFFD REPLACEMENT CHARACTER.
# Bytes with an unexpected encoding are not replaced, see issue 1793.
with pytest.raises(CalendarDecodeError):
vText.from_ical(b"Ol\xe9")

def test_prop_vTime(self):
from icalendar.prop import vTime
Expand Down
54 changes: 54 additions & 0 deletions src/icalendar/tests/test_issue_1793_invalid_utf8.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Calendar data that is not valid UTF-8 raises an error instead of being corrupted.

See https://github.com/collective/icalendar/issues/1793
"""

import pytest

from icalendar import (
Calendar,
CalendarDecodeError,
ICalDecodeError,
ICalParsingError,
LazyCalendar,
)

# \xe9 is "é" in cp1252, but not valid UTF-8
CP1252_CALENDAR = (
b"BEGIN:VCALENDAR\r\n"
b"VERSION:2.0\r\n"
b"BEGIN:VEVENT\r\n"
b"SUMMARY:R\xe9union\r\n"
b"END:VEVENT\r\n"
b"END:VCALENDAR\r\n"
)


@pytest.mark.parametrize("calendar_class", [Calendar, LazyCalendar])
def test_from_ical_raises_for_invalid_utf8(calendar_class):
with pytest.raises(ICalDecodeError):
calendar_class.from_ical(CP1252_CALENDAR)


def test_error_can_be_caught_as_parsing_or_decode_error():
with pytest.raises(ICalParsingError):
Calendar.from_ical(CP1252_CALENDAR)
with pytest.raises(CalendarDecodeError):
Calendar.from_ical(CP1252_CALENDAR)


def test_error_information():
with pytest.raises(ICalDecodeError) as exc_info:
Calendar.from_ical(CP1252_CALENDAR)
error = exc_info.value
assert error.encoding == "utf-8"
assert error.value == b"\xe9"
assert error.start == CP1252_CALENDAR.index(b"\xe9")
assert error.line_number == 4
assert isinstance(error.__cause__, UnicodeDecodeError)
assert "issues/1793" in str(error)


def test_decode_with_known_encoding():
calendar = Calendar.from_ical(CP1252_CALENDAR.decode("cp1252"))
assert calendar.events[0]["SUMMARY"] == "Réunion"
4 changes: 3 additions & 1 deletion src/icalendar/tests/test_unit_parser_tools.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import unittest

from icalendar.error import CalendarDecodeError
from icalendar.parser_tools import data_encode, from_unicode, to_unicode


Expand All @@ -10,7 +11,8 @@ def test_parser_tools_to_unicode(self):
assert to_unicode(b"spam") == "spam"
assert to_unicode(b"\xc6\xb5") == "Ƶ"
assert to_unicode(b"\xc6\xb5") == "Ƶ"
assert to_unicode(b"\xc6\xb5", encoding="ascii") == "Ƶ"
with self.assertRaises(CalendarDecodeError):
to_unicode(b"\xc6\xb5", encoding="ascii")
assert to_unicode(1) == 1
assert to_unicode(None) is None

Expand Down