Libical — an implementation of iCalendar protocols and data formats

Github workflow Packaging status

About

Libical — an implementation of iCalendar protocols and data formats

Most of the code in here was written by Eric Busboom at the end of the last millennium with help from dozens of contributors. It is currently maintained by Allen Winter and the libical team at https://libical.github.io/libical.

Libical is an Open Source implementation of the iCalendar protocols and protocol data units. The iCalendar specification describes how calendar clients can communicate with calendar servers so users can store their calendar data and arrange meetings with other users.

Thanks to our contributors.

RFCs

See RFC calendar standards for list of RFCs supported by this library.

License

The code and datafiles in this distribution are licensed under the Mozilla Public License (MPL) v2.0. See https://www.mozilla.org/MPL for a copy of this license.

Alternately, you may use libical under the terms of the GNU Lesser General Public License (LGPL) v2.1. See https://www.gnu.org/licenses/lgpl-2.1.txt for a copy of this license.

This dual license ensures that the library can be incorporated into both proprietary code and GPL'd programs, and will benefit from improvements made by programmers in both realms. We (the libical developers) will only accept changes to this library if they are similarly dual-licensed.

Building

See the Building Libical instructions.

Documentation

For new releases please refer to our Change Log for a high-level overview of changes since the previous version.

See the C API documentation and glibc API documentation.

For a conceptual overview of the library, see Using Libical. There is other rudimentary, unfinished documentation in the docs/ directory of the source distribution, annotated examples in examples/ and the test code in src/test/.

For developers porting their code to libical version 4, please visit the Version 4 Migration Guide.

Acknowledgments

Portions of this distribution are (C) Copyright 1996 Apple Computer,Inc., AT&T Corp., International Business Machines Corporation and Siemens Rolm Communications Inc. See src/libicalvcal/README.TXT for details.

Libical Users

In no particular order:

Get Involved

Watch the github project at https://github.com/libical/libical

Follow discussions and announcements at https://github.com/libical/libical/discussions

Report bugs to our issue tracker at https://github.com/libical/libical/issues

Building Libical

Libical uses the CMake buildsystem

Please see the comments at the top of CMakeLists.txt for the available configuration options you can pass to cmake.

The installation directory defaults to /usr/local on UNIX and c:/Program Files on Windows. You can change this by passing -DCMAKE_INSTALL_PREFIX=/install/path to cmake.

To build a debug version pass -DCMAKE_BUILD_TYPE=Debug to cmake.

To build libical you will need:

  • a C99-compliant C compiler (let us know if the build fails with your C compiler)
  • a C11-compliant C compiler for libical-glib
  • a C++11 compliant compiler for C++ bindings
  • CMake version 3.20.0 or higher
  • Perl
  • libicu (not required but strongly recommended)

Building on Unix with gcc or clang:

% mkdir build
% cd build
% cmake ..
% make
% make install

Building on Windows with MicroSoft Visual Studio: From a command prompt for the version of MSVC you want to use

% mkdir build
% cd build
% cmake -G "NMake Makefiles" ..
% nmake
% nmake install

NOTE: Some MSVC 32bit compilers (like MSVC2005) use a 64bit version of time_t. In these cases you must pass -DUSE_32BIT_TIME_T=true to cmake to make sure the 32bit version of time_t is used instead.

Building on Windows with mingw: Make sure you have the path to the MinGW programs in %PATH% first, for example:

% set "PATH=c:\MinGW\mingw64\bin;%PATH%"
% mkdir build
% cd build
% cmake -G "MinGW Makefiles" ..
% mingw32-make
% mingw32-make install

Building on Windows under Cygwin:

% mkdir build
% cd build
% cmake ..
% make
% make install

Building on MSYS with mingw:

% mkdir build
% cd build
% cmake -G "MSYS Makefiles" ..
% nmake
% nmake install

To run the test suite, from inside the build directory run make test (or nmake test or mingw32-make test)

To run the test suite in verbose mode, pass ARGS="-V" to the make command For example: nmake test ARGS="-V"

By default, the buildsystem creates shared(dynamic) and static versions of the libraries, but that behavior can be modified at CMake time:

  • To build the static libraries only, pass -DSTATIC_ONLY=True to cmake.
  • To build the shared libraries only, pass -DSHARED_ONLY=True to cmake.

Building with Different Compilers

For example, say you want to use Clang to build on Linux. Then you can set the C and C++ compilers at CMake time, like so:

% CC=clang CXX=clang++ cmake ..

Building for OSX (Mac)

Homebrew

A couple of necessary dependencies do not have their headers and development libraries linked into /usr/local/{include,lib} due to possible contamination with the operating system versions of the same name. This is known to be the case with libffi and libxml2

Fix is to export PKG_CONFIG_PATH so CMake can find them, as in:

export PKG_CONFIG_PATH=/usr/local/opt/libffi/lib/pkgconfig:/usr/local/opt/libxml2/lib/pkgconfig

Building for Android

% mkdir build
% cd build
% export ANDROID_NDK=/path/to/android-ndk
% cmake -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
        -DCMAKE_INSTALL_PREFIX=/install/path .. \
        -DANDROID_ABI=[x86,x86_64,armeabi-v7a,arm64-v8a,...]
% make
% make install

For more information about building CMake projects on Android see https://developer.android.com/ndk/guides/cmake

Optional Dependencies

  • libicu "International Components for Unicode" development libraries. Highly recommended for RSCALE support. libicu can be found at http://www.icu-project.org

    If CMake doesn't locate your libicu installation try setting the ICU_ROOT or ICU_BASE environment variables to the top folder where libicu is installed and run cmake again.

  • Berkeley DB storage. Optional for the Berkeley Database storage support. The development toolkit can be found at https://www.oracle.com/database/berkeley-db

    This code path has not been fully tested. Don't be surprised if there are bugs. Do NOT use for production code.

  • GObject Introspection. To generate GObject introspection "typelib" files pass the -DGOBJECT_INTROSPECTION=True option to cmake. You'll need to have the GObject Introspection development package v0.6.7 or higher installed beforehand.

    Requires the GObject Introspection development package:

    • Ubuntu: apt-get install gobject-introspection
    • Fedora: dnf install gobject-introspection
    • Mac: brew install gobject-introspection pygobject3
    • Windows: vcpkg install gobject-introspection (see [using vcpkg](#Using vcpkg to install dependencies).

You can also force CMake to ignore any of the optional dependencies by passing the option -DCMAKE_DISABLE_FIND_PACKAGE_=True. For instance:

  % cmake -DCMAKE_DISABLE_FIND_PACKAGE_ICU=True # tell cmake to ignore ICU

Language Bindings

This C library can be built with bindings for these other languages:

  • C++. If a C++ compiler is found the buildsystem will create and install the C++ bindings API. Turn this off by passing -DWITH_CXX_BINDINGS=False option to cmake. Don't mix ABI from C and C++ compilers.

  • Python bindings are built using gobject-introspection, which is enabled by passing -DGOBJECT_INTROSPECTION=True to cmake.

    Requires the GObject Introspection development package (see above).

    Don't forget to set (or append to, as needed) the GI_TYPELIB_PATH environment variable to $PREFIX/lib/girepository-1.0 (or $PREFIX/lib64/girepository-1.0).

Tweaking the Library Behavior

Use these CMake options to adjust the library behavior as follows:

  • ICAL_ERRORS_ARE_FATAL=[true|false] Set to make icalerror_* calls abort instead of internally signaling an error. Default=false

  • ICAL_ALLOW_EMPTY_PROPERTIES=[true|false] Set to prevent empty properties from being replaced with X-LIC-ERROR properties. Default=false

  • USE_BUILTIN_TZDATA=[true|false] Set to build using our own (instead of the system's) timezone data. Default=false (use the system timezone data on non-Windows systems) ALWAYS true on Windows systems

Tweaking the Installation Directories

By default, the installation layout is according to the GNU standard installation directories.

You can override various installation folders by passing the following variables to cmake:

  • CMAKE_INSTALL_LIBDIR = The fullpath where you want the put the installed libraries
  • CMAKE_INSTALL_INCLUDEDIR = The fullpath where you want to put the installed include files
  • CMAKE_INSTALL_DATAROOTDIR = The fullpath where to want to put the shared files

for example: cmake -DCMAKE_INSTALL_PREFIX=/opt -DCMAKE_INSTALL_LIBDIR=/opt/lib32 ..

Build the documentation

Run make docs to build the API documentation and reference.

Disable the docs make target by running cmake with -DICAL_BUILD_DOCS=False option. Disable the libical-glib developer documentation by running cmake with -DICAL_GLIB_BUILD_DOCS=False.

Using vcpkg to install dependencies

If you want to use vcpkg (in $VCPKG_ROOT) to build the dependencies as part of the project you can also tell CMake the vcpkg toolchain file with: "-DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake"

for example: if you have vcpkg installed in $HOME/vcpkg, then run cmake -DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake ..

Windows note: MSVC comes with vcpkg pre-installed and sets %VCPKG_ROOT% for you. However, the only way to update that vcpkg version is by upgrading MSVC itself; which may not be what you want and may be too old. Consider installing your own vcpkg instead of relying on the MSVC vcpkg.

Non-Windows note: You'll need to pre-install autoconf, automake and autoconf-archive for icu. See %VCPKG_ROOT%/p rts/icu/portfile.cmake for more info.

Dependencies

Required

  • CMake version 3.20 or above
  • A fully C99 standards complaint C compiler
  • Perl

For the C++ bindings a fully C++11 standards compliant C++ compiler

For RSCALE support the libicu development package is needed.

GLib Bindings

  • pkgconfig
  • gobject-introspection (-devel)
  • libxml2 (-devel)
  • python3

and to build the associated GLib bindings documentation you'll need;

  • gi-docgen

in addition, to build the Vala support you'll also need:

  • vala (valac, the Vala compiler)

Optional dependencies

  • berkeleydb (-devel) for Berkeley DB storage support in libicalss

Using Libical

Author: Eric Busboom eric@civicknowledge.com

Date: January 2001

1 Introduction

Libical is an Open Source implementation of the iCalendar protocols and protocol data units. The iCalendar specification describes how calendar clients can communicate with calendar servers so users can store their calendar data and arrange meetings with other users.

Libical implements multiple RFC calendar standards.

This documentation assumes that you are familiar with the iCalendar standards RFC5545 and RFC5546. These specifications are available at the IETF Tools website:

1.1 The libical project

This code is under active development. If you would like to contribute to the project, visit https://libical.github.io/libical/.

1.2 License

The code and datafiles in this distribution are licensed under the Mozilla Public License version 2.0. See https://www.mozilla.org/MPL for a copy of the license. Alternately, you may use libical under the terms of the GNU Lesser General Public License, version 2.1. See https://www.gnu.org/licenses/lgpl-2.1.html for a copy of the LGPL.

This dual license ensures that the library can be incorporated into both proprietary code and GPL'd programs, and will benefit from improvements made by programmers in both realms. We (the libical developers) will only accept changes to this library if they are similarly dual-licensed.

1.3 Example Code

A lot of the documentation for this library is in the form of example code. These examples are in the examples/ directory of the distribution. Also look in src/test/ for additional annotated examples.

2 Building the Library

Libical uses CMake to generate makefiles. It should build with no adjustments on Linux, MacOS and Windows using gcc, clang and Microsoft Visual. Please report build problems to the Libical issue tracker.

For a more complete guide to building the library, see the Building Libical instructions.

3 Structure

The iCalendar data model is based on four types of objects: components, properties, values and parameters.

Properties are the fundamental unit of information in iCalendar, and they work a bit like a hash entry, with a constant key and a variable value. Properties may also have modifiers, called parameters. In the iCal content line

ORGANIZER;ROLE=CHAIR:MAILTO:mrbig@host.com

The property name is ORGANIZER, the value of the property is mrbig@host.com and the ROLE parameter specifies that Mr Big is the chair of the meetings associated with this property.

Components are groups of properties that represent the core objects of a calendar system, such as events or timezones. Components are delimited by BEGIN and END tags.

When a component is sent across a network, if it is un-encrypted, it will look something like:

BEGIN:VCALENDAR
METHOD:REQUEST
PRODID: -//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
DTSTAMP:19980309T231000Z
UID:guid-1.host1.com
ORGANIZER;ROLE=CHAIR:MAILTO:mrbig@host.com
ATTENDEE;RSVP=TRUE;ROLE=REQ-PARTICIPANT;CUTYPE=GROUP:
  MAILTO:employee-A@host.com
DESCRIPTION:Project XYZ Review Meeting
CATEGORIES:MEETING
CLASS:PUBLIC
CREATED:19980309T130000Z
SUMMARY:XYZ Project Review
DTSTART;TZID=US-Eastern:19980312T083000
DTEND;TZID=US-Eastern:19980312T093000
LOCATION:1CP Conference Room 4350
END:VEVENT
END:VCALENDAR

Note that components can be nested; this example has both a VCALENDAR and a VEVENT component, one nested inside the other.

3.1 Core iCal classes

Libical is an object-based, data-oriented library. Nearly all of the routines in the library are associated with an opaque data types and perform some operation on that data type. Although the library does not actually have classes, we will use those terms since the behavior of these associations of data and routines is very similar to a class.

3.1.1 Properties

Properties are represented with the icalproperty class and its many "derived" classes with one "derived" class per property type in RFC5545. Again, there is no actual inheritance relations, but there are clusters of routines that make this term useful. A property is a container for a single value and a set of parameters.

3.1.2 Components

In libical, components are represented with the icalcomponent class. icalcomponent is a container for a set of other components and properties.

3.1.3 Values

Values are represented in a similar way to properties; a base class and many "derived " classes. A value is essentially an abstract handle on a single fundamental type, a structure or a union.

3.1.4 Parameters

Parameters are represented in a similar way to properties, except that they contain only one value.

3.2 Other elements of libical

In addition to the core iCal classes, libical has many other types, structures, and classes that aid in creating and using iCal components.

3.2.1 Enumerations and types

Libical is strongly typed, so every component, property, parameter, and value type has an enumeration, and some have an associated structure or union.

3.2.2 The parser

The libical parser offers a variety of ways to convert RFC5545 text into a libical internal component structure. The parser can parse blocks of text as a string, or it can parse line-by-line.

3.2.3 Error objects

Libical has a substantial error reporting system for both programming errors and component usage errors.

3.2.4 Memory Management

Since many of libical's interfaces return strings, the library has its own memory management system to eliminate the need to free every string returned from the library. See Memory Management.

3.2.5 Storage classes

The library also offers several classes to store components to files, memory or databases.

4 Differences From RFCs

Libical has been designed to follow the standards as closely as possible, so that the key objects in the standards are also key objects in the library. However, there are a few areas where the specifications are (arguably) irregular, and following them exactly would result in an unfriendly interface. These deviations make libical easier to use by maintaining a self-similar interface.

4.1 Pseudo Components

Libical defines components for groups of properties that look and act like components, but are not defined as components in the specification. XDAYLIGHT and XSTANDARD are notable examples. These pseudo components group properties within the VTIMEZONE components. For instance, the timezone properties associated with daylight savings time starts with BEGIN:DAYLIGHT and ends with END:DAYLIGHT, just like other components, but is not defined as a component in RFC5545 (see section 3.6.5) In libical, this grouping is represented by the XDAYLIGHT component. Standard iCal components all start with the letter "V," while pseudo components start with "X."

There are also pseudo components that are conceptually derived classes of VALARM. RFC5546 defines what properties may be included in each component, and for VALARM, the set of properties it may have depends on the value of the ACTION property.

For instance, if a VALARM component has an ACTION property with the value of AUDIO, the component must also have an ATTACH property. However, if the ACTION value is DISPLAY, the component must have a DESCRIPTION property.

To handle these various, complex restrictions, libical has pseudo components for each type of alarm: XAUDIOALARM, XDISPLAYALARM, XEMAILALARM and XPROCEDUREALARM.

4.2 Combined Values

Many values can take more than one type. TRIGGER, for instance, can have a value type of with DURATION or of DATE-TIME. These multiple types make it difficult to create routines to return the value associated with a property.

It is natural to have interfaces that would return the value of a property, but it is cumbersome for a single routine to return multiple types. So, in libical, properties that can have multiple types are given a single type that is the union of their RFC5545 types. For instance, in libical, the value of the TRIGGER property resolves to struct icaltriggertype. This type is a union of a DURATION and a DATE-TIME.

4.3 Multi-Valued Properties

Some properties, such as CATEGORIES have only one value type, but each CATEGORIES property can have multiple value instances. This also results in a cumbersome interface -- CATEGORIES accessors would have to return a list while all other accessors returned a single value. In libical, all properties have a single value, and multi-valued properties are broken down into multiple single valued properties during parsing. That is, an input line like,

CATEGORIES: work, home

becomes in libical's internal representation

CATEGORIES: work
CATEGORIES: home

Oddly, RFC5545 allows some multi-valued properties (like FREEBUSY) to exist as both a multi-values property and as multiple single value properties, while others (like CATEGORIES) can only exist as single multi-valued properties. This makes the internal representation for CATEGORIES illegal. However when you convert a component to a string, the library will collect all of the CATEGORIES properties into one.

5 Using libical

5.1 Creating Components

There are three ways to create components in Libical:

  1. creating individual objects and assembling them,
  2. building entire objects in massive vargs calls,
  3. parsing a text file containing iCalendar data.

5.1.1 Constructor Interfaces

Using constructor interfaces, you create each of the objects separately and then assemble them in to components:

icalcomponent *event;
icalproperty *prop;
icalparameter *param;
struct icaltimetype atime;

// create new VEVENT component
event = icalcomponent_new(ICAL_VEVENT_COMPONENT);

// add DTSTAMP property to the event
prop = icalproperty_new_dtstamp(atime);
icalcomponent_add_property(event, prop);

// add UID property to the event
prop = icalproperty_new_uid("guid-1.example.com");
icalcomponent_add_property(event, prop);

// add ORGANIZER (with ROLE=CHAIR) to the event
prop = icalproperty_new_organizer("mrbig@example.com");
param = icalparameter_new_role(ICAL_ROLE_CHAIR);
icalproperty_add_parameter(prop, param);
icalcomponent_add_property(event, prop);

Notice that libical uses a semi-object-oriented style of interface. Most things you work with are objects, that are instantiated with a constructor that has "new" in the name. Also note that, other than the object reference, most structure data is passed in to libical routines by value. Libical has some complex but very regular memory handling rules. These are detailed in section Memory Management.

If any of the constructors fail, they will return 0. If you try to insert 0 into a property or component, or use a zero-valued object reference, libical will either silently ignore the error or will abort with an error message. This behavior is controlled by a compile time flag (ICAL_ERRORS_ARE_FATAL), and will abort by default.

5.1.2 varargs Constructors

There is another way to create complex components, which is arguably more elegant, if you are not horrified by varargs. The varargs constructor interface allows you to create intricate components in a single block of code. Here is the previous examples in the vaargs style.

icalcomponent *calendar;
struct icaltimetype atime;

calendar =
    icalcomponent_vanew(
        ICAL_VCALENDAR_COMPONENT,
        icalproperty_new_version("2.0"),
        icalproperty_new_prodid(
             "-//RDU Software//NONSGML HandCal//EN"),
        icalcomponent_vanew(
            ICAL_VEVENT_COMPONENT,
            icalproperty_new_dtstamp(atime),
            icalproperty_new_uid("guid-1.host1.com"),
            icalproperty_vanew_organizer(
                "mrbig@host.com",
                icalparameter_new_role(ICAL_ROLE_CHAIR),
                (void *)0),
            icalproperty_vanew_attendee(
                "employee-A@host.com",
                icalparameter_new_role(
                    ICAL_ROLE_REQPARTICIPANT),
                icalparameter_new_rsvp(1),
                icalparameter_new_cutype(ICAL_CUTYPE_GROUP),
                (void *)0),
            icalproperty_new_location(
               "1CP Conference Room 4350"),
            (void *)0),
        (void *)0);

This form is similar to the constructor form, except that the constructors have vanew instead of new in the name. The arguments are similar too, except that the component constructor can have a list of properties, and the property constructor can have a list of parameters.

Be sure to terminate every list with a NULL (or a (void 0), or your code will crash, if you are lucky. The reason you can't use 0 itself is that depending on what platform you are on, sizeof(int) ≠ sizeof(void *).

5.1.3 Parsing Text Files

The final way to create components will probably be the most common; you can create components from RFC5545 compliant text. If you have the string in memory, use

icalcomponent* icalparser_parse_string(char* str);

If the string contains only one component, the parser will return the component in libical form. If the string contains multiple components, the multiple components will be returned as the children of an ICAL_XROOT_COMPONENT component.

Parsing a whole string may seem wasteful if you want to pull a large component off of the network or from a file; you may prefer to parse the component line by line. This is possible too by using:

icalparser* icalparser_new();

void icalparser_free(
    icalparser* parser);

icalparser_get_line(
    icalparser *parser,
    char* (*read_stream)(char *s, size_t size,  void *d));

icalparser_add_line(
    icalparser *parser,
    char *line);

icalparser_set_gen_data(
    icalparser *parser,
    void *data);

These routines will construct a parser object to which you can add lines of input and retrieve any components that the parser creates from the input. These routines work by specifying an adaptor routine to get string data from a source. For example:

char* read_stream(char *s, size_t size, void *d)
{
    return fgets(s, size, (FILE*)d);
}

int main(int argc, char *argv[])
{
    char *line;
    icalcomponent *component;
    icalparser *parser = icalparser_new();

    // open file (first command-line argument)
    FILE* stream = fopen(argv[1], "r");

    // associate the FILE with the parser so that read_stream
    // will have access to it
    icalparser_set_gen_data(parser, stream);

    do {
        // read the file, line-by-line, and parse the data
        line = icalparser_get_line(parser, read_stream);
        component = icalparser_add_line(parser, line);

        // if icalparser has finished parsing a component,
        // it will return it
        if (component != 0) {
            // print the parsed component
            printf("%s", icalcomponent_as_ical_string(component));
            icalparser_clean(parser);

            printf("\n---------------\n");

            icalcomponent_free(component);
        }
    } while (line != 0);

    return 0;
}

The parser object parametrizes the routine used to get input lines with icalparser_set_gen_data()and icalparser_get_line(). In this example, the routine read_stream() will fetch the next line from a stream, with the stream passed in as the void* parameter d. The parser calls read_stream() from icalparser_get_line(), but it also needs to know what stream to use. This is set by the call to icalparser_set_gen_data(). By using a different routine for read_stream() or passing in different data with icalparser_set_gen_data(), you can connect to any data source.

Using the same mechanism, other implementations could read from memory buffers, sockets or other interfaces.

Since the example code is a very common way to use the parser, there is a convenience routine;

icalcomponent* icalparser_parse(
    icalparser *parser,
    char* (*line_gen_func)(char *s, size_t size,  void *d));

To use this routine, you still must construct the parser object and pass in a reference to a line reading routine. If the parser can create a single component from the input, it will return a pointer to the newly constructed component. If the parser can construct multiple components from the input, it will return a reference to an XROOT component (of type ICAL_XROOT_COMPONENT.) This XROOT component will hold all of the components constructed from the input as children.

char* read_stream(char *s, size_t size, void *d)
{
    return fgets(s, size, (FILE*)d);
}

int main(int argc, char *argv[])
{
    char* line;
    icalcomponent *component;
    icalparser *parser = icalparser_new();

    // open file (first command-line argument)
    FILE* stream = fopen(argv[1], "r");

    // associate the FILE with the parser so that read_stream
    // will have access to it
    icalparser_set_gen_data(parser, stream);

    // parse the opened file
    component = icalparser_parse(parser, read_stream);

    if (component != 0) {
        // print the parsed component
        printf("%s", icalcomponent_as_ical_string(component));
        icalcomponent_free(component);
    }

    icalparser_free(parser);

    return 0;
}

5.2 Accessing Components

Given a reference to a component, you probably will want to access the properties, parameters and values inside. Libical interfaces let you find sub-component, add and remove sub-components, and do the same three operations on properties.

5.2.1 Finding Components

To find a sub-component of a component, use:

icalcomponent* icalcomponent_get_first_component(
    icalcomponent* component,
    icalcomponent_kind kind);

This routine will return a reference to the first component of the type kind. The key kind values, listed in icalenums.h are:

  • ICAL_ANY_COMPONENT
  • ICAL_VEVENT_COMPONENT
  • ICAL_VTODO_COMPONENT
  • ICAL_VJOURNAL_COMPONENT
  • ICAL_VCALENDAR_COMPONENT
  • ICAL_VFREEBUSY_COMPONENT
  • ICAL_VALARM_COMPONENT

These are only the most common components; there are many more listed in icalenums.h.

As you might guess, if there is more than one subcomponent of the type you have chosen, this routine will return only the first. to get at the others, you need to iterate through the component.

5.2.2 Iterating Through Components

Iteration requires a second routine to get the next subcomponent after the first:

icalcomponent* icalcomponent_get_next_component(
    icalcomponent* component,
    icalcomponent_kind kind);

With the 'first' and 'next' routines, you can create a for loop to iterate through all of a components subcomponents

icalcomponent *c;

for(c = icalcomponent_get_first_component(comp, ICAL_ANY_COMPONENT);
    c != 0;
    c = icalcomponent_get_next_component(comp, ICAL_ANY_COMPONENT))
{
      do_something(c);
}

This code bit will iterate through all of the subcomponents in comp but you can select a specific type of component by changing ICAL_ANY_COMPONENT to another component type.

5.2.3 Using Component Iterators

The iteration model in the previous section requires the component to keep the state of the iteration. So, you could not use this model to perform a sorting operations, since you'd need two iterators and there is only space for one. If you ever call icalcomponent_get_first_component() when an iteration is in progress, the pointer will be reset to the beginning.

To solve this problem, there are also external iterators for components. The routines associated with these external iterators are:

icalcompiter icalcomponent_begin_component(
    icalcomponent* component,
    icalcomponent_kind kind);

icalcompiter icalcomponent_end_component(
    icalcomponent* component,
    icalcomponent_kind kind);

icalcomponent* icalcompiter_next(
    icalcompiter* i);

icalcomponent* icalcompiter_prior(
    icalcompiter* i);

icalcomponent* icalcompiter_deref(
    icalcompiter* i);

The *_begin_*() and *_end_*() routines return a new iterator that points to the beginning and end of the list of subcomponent for the given component, and the kind argument works like the kind argument for internal iterators.

After creating an iterators, use *_next() and *_prior() to step forward and backward through the list and get the component that the iterator points to, and use _deref() to return the component that the iterator points to without moving the iterator. All routines will return 0 when they move to point off the end of the list.

Here is an example of a loop using these routines:

for(i = icalcomponent_begin_component(impl->cluster, ICAL_ANY_COMPONENT);
    icalcompiter_deref(&i)!= 0;
    icalcompiter_next(&i))
{
    icalcomponent *this = icalcompiter_deref(&i);
}

5.2.4 Removing Components

Removing an element from a list while iterating through the list with the internal iterators can cause problems, since you will probably be removing the element that the internal iterator points to. The _remove() routine will keep the iterator valid by moving it to the next component, but in a normal loop, this will result in two advances per iteration, and you will remove only every other component. To avoid the problem, you will need to step the iterator ahead of the element you are going to remove, like this:

for(c = icalcomponent_get_first_component(parent_comp, ICAL_ANY_COMPONENT);
    c != 0;
    c = next)
{
    next = icalcomponent_get_next_component(parent_comp, ICAL_ANY_COMPONENT);
    icalcomponent_remove_component(parent_comp,c);
}

Another way to remove components is to rely on the side effect of icalcomponent_remove_component(): if component iterator in the parent component is pointing to the child that will be removed, it will move the iterator to the component after the child. The following code will exploit this behavior:

icalcomponent_get_first_component(parent_comp,ICAL_VEVENT_COMPONENT);

while((c=icalcomponent_get_current_component(c)) != 0){
   if(icalcomponent_isa(c) == ICAL_VEVENT_COMPONENT){
      icalcomponent_remove_component(parent_comp,inner);
   } else {
      icalcomponent_get_next_component(parent_comp,ICAL_VEVENT_COMPONENT);
   }
}

5.2.5 Working with properties and parameters

Finding, iterating and removing properties works the same as it does for components, using the property-specific or parameter-specific interfaces:

icalproperty* icalcomponent_get_first_property(
    icalcomponent* component,
    icalproperty_kind kind);

icalproperty* icalcomponent_get_next_property(
    icalcomponent* component,
    icalproperty_kind kind);

void icalcomponent_add_property(
    icalcomponent* component,
    icalproperty* property);

void icalcomponent_remove_property(
    icalcomponent* component,
    icalproperty* property);

For parameters:

icalparameter* icalproperty_get_first_parameter(
     icalproperty* prop,
     icalparameter_kind kind);

icalparameter* icalproperty_get_next_parameter(
     icalproperty* prop,
     icalparameter_kind kind);

void icalproperty_add_parameter(
     icalproperty* prop,
     icalparameter* parameter);

void icalproperty_remove_parameter_by_kind(
     icalproperty* prop,
     icalparameter_kind kind);

Note that since there should be only one parameter of each type in a property, you will rarely need to use icalparameter_get_next_parameter().

5.2.6 Working with values

Values are typically part of a property, although they can exist on their own. You can manipulate them either as part of the property or independently.

The most common way to work with values to is to manipulate them from the properties that contain them. This involves fewer routine calls and intermediate variables than working with them independently, and it is type-safe.

For each property, there are a _get_() and a _set_() routine that accesses the internal value. For instanace, for the UID property, the routines are:

void icalproperty_set_uid(
    icalproperty* prop,
    const char* v);

const char* icalproperty_get_uid(
    icalproperty* prop);

For multi-valued properties, like ATTACH, the value type is usually a struct or union that holds both possible types.

If you want to work with the underlying value object, you can get and set it with:

icalvalue* icalproperty_get_value(
    icalproperty* prop);

void icalproperty_set_value(
    icalproperty* prop,
    icalvalue* value);

icalproperty_get_value() will return a reference that you can manipulate with other icalvalue routines. Most of the time, you will have to know what the type of the value is. For instance, if you know that the value is a DATETIME type, you can manipulate it with:

struct icaltimetype icalvalue_get_datetime(
    icalvalue* value);

void icalvalue_set_datetime(
    icalvalue* value,
    struct icaltimetype v);

Some complex value types, such as ATTACH and RECUR, are passed by reference rather than by value. For example, when using icalvalue_get_recur(), you receive a reference to the internal state of the value object. Conversely, when setting these values, the value object retains a reference to the original object instead of creating a copy.

Caution: Manipulating this referenced object will also modify the owning value object.

Be mindful of the memory management for these objects, which is managed through reference counting. For more details, see Memory Management.

When working with an extension property or value (and X-PROPERTY or a property that has the parameter VALUE=x-name), the value type is always a string. To get and set the value, use:

void icalproperty_set_x(
    icalproperty* prop,
    char* v);

char* icalproperty_get_x(
    icalproperty* prop);

All X properties have the type of ICAL_X_PROPERTY, so you will need these routines to get and set the name of the property:

char* icalproperty_get_x_name(
    icalproperty* prop)

void icalproperty_set_x_name(
    icalproperty* prop,
    char* name);

5.2.7 Checking Component Validity

RFC5546 defines rules for what properties must exist in a component to be used for transferring scheduling data. Most of these rules relate to the existence of properties relative to the METHOD property, which declares what operation a remote receiver should use to process a component. For instance, if the METHOD is REQUEST and the component is a VEVENT, the sender is probably asking the receiver to join in a meeting. In this case, RFC5546 says that the component must specify a start time (DTSTART) and list the receiver as an attendee (ATTENDEE).

Libical can check these restrictions with the routine:

int icalrestriction_check(icalcomponent* comp);

This routine returns 0 if the component does not pass RFC5546 restrictions, or if the component is malformed. The component you pass in must be a VCALENDAR, with one or more children, like the examples in RFC5546.

When this routine runs, it will insert new properties into the component to indicate any errors it finds. See section 6.5.3, X-LIC-ERROR for more information about these error properties.

5.2.8 Converting Components to Text

To create an RFC5545 compliant text representation of an object, use one of the *_as_ical_string() routines:

char* icalcomponent_as_ical_string(icalcomponent* component)

char* icalproperty_as_ical_string(icalproperty* property)

char* icalparameter_as_ical_string(icalparameter* parameter)

char* icalvalue_as_ical_string(icalvalue* value)

In most cases, you will only use icalcomponent_as_ical_string(), since it will cascade and convert all of the parameters, properties and values that are attached to the root component.

Remember that the string returned by these routines is owned by the library, and will eventually be re-written. You should copy it if you want to preserve it.

5.3 Time

5.3.1 Time structure

Libical defines its own time structure for storing all dates and times. It would have been nice to reuse the C library's struct tm, but that structure does not differentiate between dates and times, and between local time and UTC. The libical structure is:

struct icaltimetype {
  int year;
  int month;
  int day;
  int hour;
  int minute;
  int second;
  int is_utc; /* 1-> time is in UTC timezone */
  int is_date; /* 1 -> interpret this as date. */
};

The year, month, day, hour, minute and second fields hold the broken-out time values. The is_utc field distinguishes between times in UTC and a local time zone. The is_date field indicates if the time should be interpreted only as a date. If it is a date, the hour, minute and second fields are assumed to be zero, regardless of their actual values.

5.3.2 Creating time structures

There are several ways to create a new icaltimetype structure:

struct icaltimetype icaltime_from_string(
    const char* str);

struct icaltimetype icaltime_from_timet_with_zone(
    icaltime_t v,
    int is_date,
    icaltimezone* zone);

icaltime_from_string() takes any RFC5545 compliant time string:

struct icaltimetype tt = icaltime_from_string("19970101T103000");

icaltime_from_timet_with_zone() takes a icaltime_t value, representing seconds past the POSIX epoch, a flag to indicate if the time is a date, and a time zone. Dates have an identical structure to a time, but the time portion (hours, minutes and seconds) is always 00:00:00. Dates act differently in sorting and comparison, and they have a different string representation in RFC5545.

5.3.3 Time manipulating routines

The null time value is used to indicate that the data in the structure is not a valid time.

struct icaltimetype icaltime_null_time(void);

int icaltime_is_null_time(struct icaltimetype t);

It is sensible for the broken-out time fields to contain values that are not permitted in an ISO compliant time string. For instance, the seconds field can hold values greater than 59, and the hours field can hold values larger than 24. The excessive values will be rolled over into the next larger field when the structure is normalized.

struct icaltimetype icaltime_normalize(struct icaltimetype t);

Normalizing allows you to do arithmetic operations on time values.

struct icaltimetype tt = icaltime_from_string("19970101T103000");

tt.days +=3
tt.second += 70;

tt = icaltime_normalize(tt);

There are several routines to get the day of the week or month, etc, from a time structure.

short icaltime_day_of_year(
    struct icaltimetype t);

struct icaltimetype icaltime_from_day_of_year(
    short doy,
    short year);

short icaltime_day_of_week(
    struct icaltimetype t);

short icaltime_start_doy_week(
    struct icaltimetype t,
    int fdow);

short icaltime_week_number(
    short day_of_month,
    short month,
    short year);

short icaltime_days_in_month(
    short month,
    short year);

Two routines convert time structures to and from the number of seconds since the POSIX epoch. The is_date field indicates whether or not the hour, minute and second fields should be used in the conversion.

struct icaltimetype icaltime_from_timet_with_zone(
    icaltime_t v,
    int is_date,
    icaltimezone* zone);

icaltime_t icaltime_as_timet(
    struct icaltimetype);

The compare routine works exactly like strcmp(), but on time structures.

int icaltime_compare(
    struct icaltimetype a,
    struct icaltimetype b);

The following routines convert between UTC and a named timezone. The tzid field must be a timezone name from the Olsen database, such as America/Los_Angeles.

The utc_offset routine returns the offset of the named time zone from UTC, in seconds.

The tt parameter in the following routines indicates the date on which the conversion should be made. The parameter is necessary because timezones have many different rules for when daylight savings time is used, and these rules can change over time. So, for a single timezone one year may have daylight savings time on March 15, but for other years March 15 may be standard time, and some years may have standard time all year.

int icaltime_utc_offset(
    struct icaltimetype tt,
    char* tzid);

int icaltime_local_utc_offset();

struct icaltimetype icaltime_as_utc(
    struct icaltimetype tt,
    char* tzid);

struct icaltimetype icaltime_as_zone(
    struct icaltimetype tt,
    char* tzid);

struct icaltimetype icaltime_as_local(
    struct icaltimetype tt);

5.4 Storing Objects

The libical distribution includes a separate library, libicalss, that allows you to store iCal component data to disk in a variety of ways.

The file storage routines are organized in an inheritance hierarchy that is rooted in icalset, with the derived class icalfileset and icaldirset. Icalfileset stores components to a file, while icaldirset stores components to multiple files, one per month based on DTSTAMP. Other storages classes, for storage to a heap or a mysql database for example, could be added in the future.

All of the icalset derived classes have the same interface:

icaldirset* icaldirset_new(
    const char* path);

void icaldirset_free(
    icaldirset* store);

const char* icaldirset_path(
    icaldirset* store);

void icaldirset_mark(
    icaldirset* store);

icalerrorenum icaldirset_commit(
    icaldirset* store);

icalerrorenum icaldirset_add_component(
    icaldirset* store,
    icalcomponent* comp);

icalerrorenum icaldirset_remove_component(
    icaldirset* store,
    icalcomponent* comp);

int icaldirset_count_components(
    icaldirset* store,
    icalcomponent_kind kind);

icalerrorenum icaldirset_select(
    icaldirset* store,
    icalcomponent* gauge);

void icaldirset_clear(
    icaldirset* store);

icalcomponent* icaldirset_fetch(
    icaldirset* store,
    const char* uid);

int icaldirset_has_uid(
    icaldirset* store,
    const char* uid);

icalcomponent* icaldirset_fetch_match(
    icaldirset* set,
    icalcomponent *c);

icalerrorenum icaldirset_modify(
    icaldirset* store,
    icalcomponent *oldc,
    icalcomponent *newc);

icalcomponent* icaldirset_get_current_component(
    icaldirset* store);

icalcomponent* icaldirset_get_first_component(
    icaldirset* store);

icalcomponent* icaldirset_get_next_component(
    icaldirset* store);

5.4.1 Creating a new set

You can create a new set from either the base class or the direved class. From the base class use one of:

icalset* icalset_new_file(const char* path);

icalset* icalset_new_dir(const char* path);

icalset* icalset_new_heap(void);

icalset* icalset_new_mysql(const char* path);

You can also create a new set based on the derived class, For instance, with icalfileset:

icalfileset* icalfileset_new(
    const char* path);

icalfileset* icalfileset_new_open(
    const char* path,
    int flags,
    int mode);

icalset_new_file() is identical to icalfileset_new(). Both routines will open an existing file for reading and writing, or create a new file if it does not exist. icalfileset_new_open() takes the same arguments as the open() system routine and behaves in the same way.

The icalset and icalfileset objects are somewhat interchangeable -- you can use an icalfileset* as an argument to any of the icalset routines.

The following examples will all use icalfileset routines; using the other icalset derived classes will be similar.

5.4.2 Adding, Finding and Removing Components

To add components to a set, use:

icalerrorenum icalfileset_add_component(
    icalfileset* cluster,
    icalcomponent* child);

The fileset keeps an in-memory copy of the components, and this set must be written back to the file occasionally. There are two routines to manage this:

void icalfileset_mark(icalfileset* cluster);

icalerrorenum icalfileset_commit(icalfileset* cluster);

icalfileset_mark() indicates that the in-memory components have changed. Calling the _add_component() routine will call _mark() automatically, but you may need to call it yourself if you have made a change to an existing component. The _commit() routine writes the data base to disk, but only if it is marked. The _commit() routine is called automatically when the icalfileset is freed.

To iterate through the components in a set, use:

icalcomponent* icalfileset_get_first_component(icalfileset* cluster);

icalcomponent* icalfileset_get_next_component(icalfileset* cluster);

icalcomponent* icalfileset_get_current_component (icalfileset* cluster);

These routines work like the corresponding routines from icalcomponent, except that their output is filtered through a gauge. A gauge is a test for the properties within a components; only components that pass the test are returned. A gauge can be constructed from a MINSQL string with:

icalgauge* icalgauge_new_from_sql(const char* sql);

Then, you can add the gauge to the set with :

icalerrorenum icalfileset_select(
    icalfileset* store,
    icalgauge* gauge);

Here is an example that puts all of these routines together:

void test_fileset()
{
    icalfileset *fs;
    icalcomponent *c;
    int i;
    char *path = "test_fileset.ics";

    icalgauge  *g = icalgauge_new_from_sql(
        "SELECT * FROM VEVENT WHERE DTSTART > '20000103T120000Z' AND
DTSTART <= '20000106T120000Z'");

    fs = icalfileset_new(path);

    for (i = 0; i!= 10; i++){
        c = make_component(i); /* Make a new component where DTSTART has month of i */
        icalfileset_add_component(fs,c);
    }

    icalfileset_commit(fs); /* Write to disk */
    icalfileset_select(fs,g); /* Set the gauge to filter components */

    for (c = icalfileset_get_first_component(fs);
         c != 0;
         c = icalfileset_get_next_component(fs))
    {
        struct icaltimetype t = icalcomponent_get_dtstart(c);
        printf("%s\n",icaltime_as_ctime(t));

    }

    icalfileset_free(fs);
}

5.4.3 Other routines

There are several other routines in the icalset interface, but they not fully implemented yet.

5.5 Memory Management

Libical relies heavily on dynamic allocation for both the core objects and for the strings used to hold values. Some of this memory the library caller owns and must free, and some of the memory is managed by the library. Here is a summary of the memory rules.

  1. If the function name has "new" in it (such as icalcomponent_new(), or icalproperty_new_from_string()), the caller gets control of the memory. The caller also gets control over an object that is cloned via a function that ends with "_clone" (like icalcomponent_clone())

  2. If you got the memory from a routine with "clone" or "new" in it, you must call the corresponding *_free() routine to free the memory, for example use icalcomponent_free() to free objects created with icalcomponent_new() or icalcomponent_clone(). The only exception to this rule are objects that implement reference counting (i.e. icalattach and icalrecurrencetype), which are deallocated via *_unref() functions. Learn more in the next section.

  3. If the function name has "add" in it, the caller is transferring control of the memory to the routine, for example the function icalproperty_add_parameter()

  4. If the function name has "remove" in it, the caller passes in a pointer to an object and after the call returns, the caller owns the object. So, before you call icalcomponent_remove_property(comp, foo), you do not own "foo" and after the call returns, you do.

  5. If the routine returns a string and its name does NOT end in _r, libical owns the memory and will put it on a ring buffer to reclaim later. For example, icalcomponent_as_ical_string(). You better strdup() it if you want to keep it, and you don't have to delete it.

  6. If the routine returns a string and its name does end in _r, the caller gets control of the memory and is responsible for freeing it. For example, icalcomponent_as_ical_string_r() does the same thing as icalcomponent_as_ical_string(), except you now have control of the string buffer it returns.

5.5.1 Reference Counting

Some special types are managed using reference counting, in particular:

  • icalattach
  • struct icalrecurrencetype

Just as any other object they are allocated using any of the *_new*() functions, e.g.

  • icalrecurrencetype_new_from_string()
  • icalattach_new_from_data()

When an object is returned by one of these constructor functions, its reference counter is set to 1.

The reference counter can be modified using:

  • *_ref() – to increase the counter.
  • *_unref() – to decrease the counter.

The object is automatically deallocated when the reference counter reaches 0. No explicit *_free() functions exist for these types.

When such objects are passed to functions as arguments, it is the task of the function being called to manage the reference counter, not of the caller. If a pointer to an object is returned by a function other than the constructor functions, it is the task of the calling function rather than of the returning function to manage the reference counter.

5.6 Error Handling

Libical has several error handling mechanisms for the various types of programming, semantic and syntactic errors you may encounter.

5.6.1 Return values

Many library routines signal errors through their return values. All routines that return a pointer, such as icalcomponent_new(), will return 0 (zero) on a fatal error. Some routines will return a value of enum icalerrorenum.

5.6.2 icalerrno

Most routines will set the global error value icalerrno on errors. This variable is an enumeration; permissible values can be found in libical/icalerror.h. If the routine returns an enum icalerrorenum, then the return value will be the same as icalerrno. You can use icalerror_strerror() to get a string that describes the error. The enumerations are:

  • ICAL_BADARG_ERROR: One of the arguments to a routine was bad. Typically for a null pointer.

  • ICAL_NEWFAILED_ERROR: A new() or malloc() failed.

  • ICAL_MALFORMEDDATA_ERROR: An input string was not in the correct format

  • ICAL_PARSE_ERROR: The parser failed to parse an incoming component

  • ICAL_INTERNAL_ERROR: Largely equivalent to an assert

  • ICAL_FILE_ERROR: A file operation failed. Check errno for more detail.

  • ICAL_ALLOCATION_ERROR: ?

  • ICAL_USAGE_ERROR: ?

  • ICAL_NO_ERROR: No error

  • ICAL_MULTIPLEINCLUSION_ERROR: ?

  • ICAL_TIMEDOUT_ERROR: For CSTP and acquiring locks

  • ICAL_UNKNOWN_ERROR: ?

5.6.3 X-LIC-ERROR and X-LIC-INVALID-COMPONENT

The library handles semantic and syntactic errors in components by inserting errors properties into the components. If the parser cannot parse incoming text (a syntactic error) or if the icalrestriction_check() routine indicates that the component does not meet the requirements of RFC5546 (a semantic error) the library will insert properties of the type X-LIC-ERROR to describe the error. Here is an example of the error property:

X-LIC-ERROR;X-LIC-ERRORTYPE=INVALID_ITIP :Failed iTIP restrictions
for property DTSTART.

Expected 1 instances of the property and got 0

This error resulted from a call to icalrestriction_check(), which discovered that the component does not have a DTSTART property, as required by RFC5545.

There are a few routines to manipulate error properties:

RoutinePurpose
void icalrestriction_check()Check a component against RFC5546 and insert error properties to indicate non compliance
int icalcomponent_count_errors()Return the number of error properties in a component
void icalcomponent_strip_errors()Remove all error properties in a component
void icalcomponent_convert_errors()Convert some error properties into REQUESTS-STATUS properties to indicate the inability to process the component as an iTIP request

The types of errors are listed in icalerror.h. They are:

  • ICAL_XLICERRORTYPE_COMPONENTPARSEERROR
  • ICAL_XLICERRORTYPE_PARAMETERVALUEPARSEERROR
  • ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR
  • ICAL_XLICERRORTYPE_PROPERTYPARSEERROR
  • ICAL_XLICERRORTYPE_VALUEPARSEERROR
  • ICAL_XLICERRORTYPE_UNKVCALPROP
  • ICAL_XLICERRORTYPE_INVALIDITIP

The libical parser will generate the error that end in PARSEERROR when it encounters garbage in the input steam. ICAL_XLICERRORTYPE_INVALIDITIP is inserted by icalrestriction_check(), and ICAL_XLICERRORTYPE_UNKVCALPROP is generated by icalvcal_convert() when it encounters a vCal property that it cannot convert or does not know about.

icalcomponent_convert_errors() converts some of the error properties in a component into REQUEST-STATUS properties that indicate a failure. As of libical version 0.18, this routine only converts PARSEERROR errors and it always generates a 3.x (failure) code. This makes it more of a good idea than a really useful bit of code.

5.6.4 ICAL_ERRORS_ARE_FATAL and icalerror_errors_are_fatal

If icalerror_get_errors_are_fatal() returns 1, then any error condition will cause the program to abort. The abort occurs in icalerror_set_errno(), and is done with an assert(0) if NDEBUG is undefined, and with icalerror_crash_here() if NDEBUG is defined. Initially, icalerror_get_errors_are_fatal() is 1 when ICAL_ERRORS_ARE_FATAL is defined, and 0 otherwise. Since ICAL_ERRORS_ARE_FATAL is defined by default, icalerror_get_errors_are_fatal() is also set to 1 by default.

You can change the compiled-in ICAL_ERRORS_ARE_FATAL behavior at runtime by calling icalerror_set_errors_are_fatal(0) (i.e, errors are not fatal) or icalerror_set_errors_are_fatal(1) (i.e, errors are fatal).

5.7 Naming Standard

Structures that you access with the "struct" keyword, such as struct icaltimetype are things that you are allowed to see inside and poke at.

Structures that you access though a typedef, such as icalcomponent are things where all of the data is hidden.

Component names that start with "V" are part of RFC5545 or another iCal standard. Component names that start with "X" are also part of the spec, but they are not actually components in the spec. However, they look and act like components, so they are components in libical. Names that start with XLIC or X-LIC are not part of any iCal spec. They are used internally by libical.

Enums that identify a component, property, value or parameter end with _COMPONENT, _PROPERTY, _VALUE, or _PARAMETER"

Enums that identify a parameter value have the name of the parameter as the second word. For instance: ICAL_ROLE_REQPARTICIPANT or ICAL_PARTSTAT_ACCEPTED.

The enums for the parts of a recurrence rule and request statuses are irregular.

6 Hacks and Bugs

There are a lot of hacks in the library -- bits of code that I am not proud of and should probably be changed. These are marked with the comment string "HACK."

7 Library Reference

7.1 Manipulating struct icaltimetype

7.1.1 Struct icaltimetype

struct icaltimetype

{
    int year;
    int month;
    int day;
    int hour;
    int minute;
    int second;
    int is_utc;
    int is_date;
    const char* zone;
};

Migrating to version 4

A guide to help developers port their code from libical v3.x to libical 4.0.

Conditional compilation

To continue supporting the 3.0 version you can use conditional compilation, like so:

     #if ICAL_CHECK_VERSION(4,0,0)
     <...new code for the libical 4.0 version ...>
     #else
     <...old code for the libical 3.0 version ...>
     #endif

you can handle code that no longer exists in 4.0 with:

     #if !ICAL_CHECK_VERSION(4,0,0)
     <...old code for the libical 3.0 version ...>
     #endif

C library

Modified functions

  • icalrecurrencetype_from_string() was replaced by icalrecurrencetype_new_from_string(), which returns a struct icalrecurrencetype * rather than a struct icalrecurrencetype.

  • The following functions now take arguments of type struct icalrecurrencetype * rather than struct icalrecurrencetype:

    • icalproperty_new_rrule()
    • icalproperty_get_rrule()
    • icalproperty_set_rrule()
    • icalproperty_vanew_rrule()
    • icalproperty_new_exrule()
    • icalproperty_set_exrule()
    • icalproperty_get_exrule()
    • icalproperty_vanew_exrule()
    • icalrecur_iterator_new()
    • icalvalue_new_recur()
    • icalvalue_set_recur()
    • icalvalue_get_recur()
  • The following functions now return a value of type struct icalrecurrencetype * rather than struct icalrecurrencetype:

    • icalproperty_get_rrule()
    • icalproperty_get_exrule()
    • icalvalue_get_recur()

New functions

The following functions have been added:

  • icalrecurrencetype_new()
  • icalrecurrencetype_ref()
  • icalrecurrencetype_unref()
  • icalrecurrencetype_clone()
  • icalrecurrencetype_encode_day()
  • icalrecurrencetype_encode_month()
  • icaltzutil_set_zone_directory()
  • icalcomponent_clone()
  • icalproperty_clone()
  • icalparameter_clone()
  • icalvalue_clone()
  • icalcluster_clone()
  • icalrecur_iterator_prev()
  • icalrecur_resize_by()
  • icalrecurrencetype_new()
  • icalrecurrencetype_ref()
  • icalrecurrencetype_unref()
  • icalrecurrencetype_clone()
  • icalrecurrencetype_from_string()
  • icalcomponent_set_x_name()
  • icalcomponent_get_x_name()
  • icalcomponent_get_component_name()
  • icalcomponent_get_component_name_r()
  • ical_set_invalid_rrule_handling_setting()
  • ical_get_invalid_rrule_handling_setting()
  • icalparser_get_ctrl()
  • icalparser_set_ctrl()

Removed functions

  • icalrecurrencetype_clear() has been removed.

  • These deprecated functions have been removed:

    • caldat()
    • juldat()
    • icalcomponent_new_clone()
    • icalparameter_new_clone()
    • icalproperty_new_clone()
    • icalvalue_new_clone()
    • icalcluster_new_clone()
  • No longer publicly visible functions:

    • icaltzutil_fetch_timezone()
    • icalrecurrencetype_clear()

Removed data types

  • These data structures have been removed (as they were never used):
    • struct icaltimezonetype
    • struct icaltimezonephase

Migrating from 3.0 to 4.0

bool return values

A number of function signatures have been changed to use 'bool' rather than 'int' types.

This is implemented using the C99 standards compliant <stdbool.h> header.

Clone functions

Replace all ical*_new_clone() function calls with ical*_clone() . ie, use icalcomponent_clone() rather then icalcomponent_new_clone().

icalrecurrencetype now passed by reference

The way struct icalrecurrencetype is passed between functions has been changed. While it was usually passed by value in 3.0, it is now passed by reference. A reference counting mechanism is applied that takes care of de-allocating an instance as soon as the reference counter goes to 0.

Code like this in libical 3.0:

    struct icalrecurrencetype recur;

    icalrecurrencetype_clear(&recur);

    // Work with the object

changes to this in libical 4.0:

    struct icalrecurrencetype *recur;

    // allocate
    recur = icalrecurrencetype_new();
    if (recur) {

        // Work with the object

        // deallocate
        icalrecurrencetype_unref(recur);
    } else {
        // out of memory error handling
    }

icalgeotype now uses character strings rather than doubles

The members of struct icalgeotype for latitude ('lat) and longitude ('lon) have been changed to use ICAL_GEO_LEN long character strings rather than the double type.

This means that simple assignments in 3.0 must be replaced by string copies.

     geo.lat = 0.0;
     geo.lon = 10.0;

becomes

     strncpy(geo.lat, "0.0", ICAL_GEO_LEN-1);
     strncpy(geo.lon, "10.0", ICAL_GEO_LEN-1);

and

    double lat = geo.lat;
    double lon = geo.lon;

becomes

    double lat, lon;
    sscanf(geo.lat, "%lf", &lat);
    sscanf(geo.lon, "%lf", &lon);

Working with icalvalue and icalproperty

Code like this in libical 3.0:

    icalvalue *recur_value = ...;
    struct icalrecurrencetype recur = icalvalue_get_recur(recur_value);

    // Work with the object

changes to this in libical 4.0:

    icalvalue *recur_value = ...;
    struct icalrecurrencetype *recur = icalvalue_get_recur(recur_value);

    // Work with the object
    // No need to unref

C++ library

Modified methods

  • The following methods now take arguments of type struct icalrecurrencetype * rather than const struct icalrecurrencetype &:

    • ICalValue.set_recur()
    • ICalProperty.set_exrule()
    • ICalProperty.set_rrule()
  • The following methods now returns a value of type struct icalrecurrencetype * rather than struct icalrecurrencetype:

    • ICalValue.get_recur()
    • ICalProperty.get_exrule()
    • ICalProperty.get_rrule()

icalrecurrencetype.by_xxx static arrays replaced by dynamically allocated ones

I.e. memory short by_hour[ICAL_BY_DAY_SIZE] etc. are replaced by

typedef struct
{
  short *data;
  short size;
} icalrecurrence_by_data;

struct icalrecurrencetype {
  ...
  icalrecurrence_by_data by[ICAL_BY_NUM_PARTS];
}

Memory is allocated in the required size using the new icalrecur_resize_by() function. It is automatically freed together with the containing icalrecurrencetype. As the size of the array is stored explicitly, no termination of the array with special value ICAL_RECURRENCE_ARRAY_MAX is required anymore. The array is iterated by comparing the iterator to the size member value.

Migrating icalrecurrencetype.by_xxx static arrays usage from 3.0 to 4.0

Code like this in libical 3.0:

    icalrecurrencetype recur;
    ...
    recur.by_hour[0] = 12;
    recur.by_hour[1] = ICAL_RECURRENCE_ARRAY_MAX;

changes to something like this in libical 4.0:

    icalrecurrencetype *recur;
    ...
    if (!icalrecur_resize_by(&recur->by[ICAL_BY_HOUR], 1)) {
      // allocation failed
      // error handling
    } else {
      recur.by[ICAL_BY_HOUR].data[0] = 12;
    }

GLib/Python bindings - changed ICalGLib.Recurrence.*_by_* methods

i_cal_recurrence_*_by_xxx* methods have been replaced by more generic versions that take the 'by' type (day, month, ...) as a parameter.

Migrating ICalGLib.Recurrence.*_by_* methods from 3.0 to 4.0

Code like this in libical 3.0:

    recurrence.set_by_second(0,
    recurrence.get_by_second(0) + 1)

changes to something like this in libical 4.0:

    recurrence.set_by(ICalGLib.RecurrenceByRule.BY_SECOND, 0,
    recurrence.get_by(ICalGLib.RecurrenceByRule.BY_SECOND, 0) + 1)

Known Limitations

List where libical doesn't fully support all the features described in the RFCs.

Contributions to help us fix these limitations are welcome.

RFC 5545

Recurrence Rule section 3.3.10

Recurrence Rule sections 3.8.5.3, DURATION 3.3.6

  • The lib (e.g. icalcomponent_foreach_recurrence(), icalcomponent_get_dtend()) does not differentiate between nominal and exact durations. According to the RFC, when a component's duration is specified using the DURATION property rather than DTEND, the nominal duration must be used to calculate each recurrence's duration. However, the current implementation always uses the exact duration, which can cause discrepancies if a recurrence spans a daylight saving time transition.

    ref: https://github.com/libical/libical/issues/630

Libical RFC calendar standards support

Libical implements the RFCS:

  • RFC5545 Internet Calendaring and Scheduling Core Object Specification (iCalendar)
  • RFC5546 iCalendar Transport-Independent Interoperability Protocol (iTIP)
  • RFC7529 Non-Gregorian Recurrence Rules in the Internet Calendaring and Scheduling Core Object Specification (iCalendar)

as well as iCalendar extensions described in:

  • RFC7986 New Properties for iCalendar
  • RFC9073 Event Publishing Extensions to iCalendar
  • RFC9074 "VALARM" Extensions for iCalendar
  • RFC9253 Support for iCalendar Relationships

Plus:

  • RFC6047 iCalendar Message-Based Interoperability Protocol (iMIP)
  • RFC6638 Scheduling Extensions to CalDAV

Contributors

The Libical project was founded in 1999 (or perhaps earlier) by Eric Busboom eric@clarinova.com.

We use the term "Contributors to the Libical project" to indicate the current active developers, to include and not limited to:

There are now far too many Libical contributors to list here. See the commit history for the complete list.

From pre-2015 (the first 15 years) we recognize these people who contributed by means outside of a version control system:

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[4.0.0] - Unreleased

This is a major release and is not source or binary compatible with version 3.x.

Please see Version 4 Migration Guide for details about API changes since libical 3.x.

Added

  • REUSE compliant licensing
  • Brand new icalvcard library that follows the libical API.
  • draft-ietf-calext-eventpub-extensions-19 (RFC 9073) support added
  • draft-ietf-calext-valarm-extensions-07 (RFC 9074) support added
  • Added support for Event Publishing (RFC 9073) and VALARM (RFC 9074) Extensions
  • New CMake option "LIBICAL_ENABLE_64BIT_ICALTIME_T" to use 64-bit time_t implementations on 32-bit systems (where available and supported. Windows-only so far)
  • GEO property has arbitrary precision (values are internally stored as strings, not doubles)
  • Allow previous recurrence iteration
  • icalparser_ctrl setting defines how to handle invalid CONTROL characters during parsing

Changed

  • Requires MSVC 2013 or higher (when building on Windows with MSVC)
  • Requires CMake v3.20.0 or higher
  • For the C++ bindings, requires a C++11 compliant C++ compiler
  • libical-glib requires glib 2.38 or higher
  • libical-glib requires a C11 compliant C compiler
  • Replace gtk-doc with gi-docgen to produce libical-glib developer documentation
  • libical-glib API is considered stable; no longer need to define LIBICAL_GLIB_UNSTABLE_API=1 before including <libical-glib/libical-glib.h>
  • CMake option -DGOBJECT_INTROSPECTION=True by default.
  • icaltzutil_get_zone_directory() can use the TZDIR environment to find system zoneinfo

Deprecated

  • The icalvcal library is deprecated and will be removed sometime in the 4.x series. Please port your icalvcal code to use icalvcard instead.

Removed

  • The old src/python code is removed in favor of the glib-introspection generated Python bindings. Requires building with -DGOBJECT_INTROSPECTION=True

Fixed

  • Fixed icalcomponent_get_duration() to account for DTEND/DUE TZID
  • Improved performance of recurrence iterators

[3.0.21] - Unreleased

  • Fix some scenarios with RRULEs and EXRULE (#754)

[3.0.20] - 2025-05-10

  • Clean up the byte-swapping macros
  • Fix a testcase in libical-glib when using 64-bit on a 32-bit system
  • Fix regression introduced in v3.0.19 ignoring non-empty REQUEST-STATUS extdata
  • Fix regression introduced in v3.0.19 error reporting for END before BEGIN
  • Fix a CMake problem in libical-glib

[3.0.19] - 2024-12-23

  • Fix for changes to the libicu 75 API
  • Add vcpkg manifest-mode support
  • Improved berkeley-db discovery on Mac with homebrew
  • Improved libicu discrovery on Mac with homebrew
  • Properly set DYLD_LIBRARY_PATH on Mac for libical-ical tests
  • Resolved known limitation: Negative values are now also supported for BYMONTHDAY and BYYEARDAY.
  • Add support for RDATE;VALUE=PERIOD
  • Fix time conversion to time_t for times before epoch
  • Allow icalcomponent_foreach_recurrence to receive DATE-only start and end params.
  • Fix the calculation of an event's duration if DTSTART is a DATE-only value.
  • Fix icaltime_span_new() - ignore the case where DTEND is unset and require it to be set by the caller instead.
  • Various fixes for fuzzer issues

[3.0.18] - 2024-03-24

  • Requires CMake v3.5.0 or higher
  • Escape ^ (U+005E) character in parameter values according to RFC 6868
  • New CMake option LIBICAL_BUILD_EXAMPLES to disable building the examples
  • Should be able to use the project as a submodule
  • Built-in timezones updated to tzdata2024a

[3.0.17] - 2023-10-14

  • Improved Android support
  • Escape commas in x-property TEXT values
  • Built-in timezones updated to tzdata2023c
  • icalparser_ctrl setting defines how to handle invalid CONTROL characters during parsing
  • New publicly available functions:
    • get_zone_directory
    • icalparser_get_ctrl
    • icalparser_set_ctrl

[3.0.16] - 2022-10-17

  • Fix regressions in 3.0.15 due to improperly tested fuzz fixes
  • Fix argument guards in icaltime_as_timet to match documentation and tests

[3.0.15] - 2022-10-06

  • Add missing property parameters into libical-glib
  • Fix CMake option USE_32BIT_TIME_T actually uses a 32-bit time_t value
  • Fix icaltime_as_timet, which returned incorrect results for years >= 2100, to work properly between years 1902 and 10k.
  • Fix x-property comma handling and escaping
  • Built-in timezones updated to tzdata2022d (now with a VTIMEZONE for each time zone alias)
  • Fix a fuzzer issue
  • Handle unreachable-code compile warnings with clang
  • Ensure all vanew_foo() calls finish with (void*)0 (not 0)

[3.0.14] - 2022-02-15

  • icalvalue: Reset non-UTC icaltimetype::zone on set
  • Fix icalcomponent_set_due not removing TZID when necessary

[3.0.13] - 2022-01-17

  • icalcomponent_get_dtend() returns icaltime_null_time() unless called on VEVENT, VAVAILABILITY or VFREEBUSY
  • icalcomponent_get_duration() for VTODO calculate with DUE instead of DTEND
  • Replace CMake FindBDB with FindBerleyDB (https://github.com/sum01/FindBerkeleyDB)
  • Fix finding ICU and BerkeleyDB on Mac (look for homebrew installs first)

[3.0.12] - 2021-12-08

  • Fix a libicalval crash in cleanVObject
  • METHOD:DECLINECOUNTER must have DTEND or DURATION
  • Handle if DTEND and DURATION are both missing
  • Improved FindICU (copied from official CMake. see files in cmake/Kitware)
  • Buildsystem fixes (especially for the Ninja generator)
  • Built-in timezones updated to tzdata2021e

[3.0.11] - 2021-10-09

  • Fix icalrecur_iterator_set_start() for hourly, minutely, and secondly recurrences
  • Fix build for Berkeley DB version greater than 5
  • Fix vcal for some architectures (like aarch64, ppc64le and s390x)
  • Fix memory leaks in vcal
  • Prevent crash when looking for tzid in initialize_rscale
  • Adjust libdir and includedir in generated pkgconfig files
  • Built-in timezones updated to tzdata2021c

[3.0.10] - 2021-04-17

  • Fix building -DSTATIC_ONLY=True with Ninja
  • Fix generating wrong recurrence rules (#478)
  • Fix a bug computing transitions in tzfiles
  • Fix reading TZif files to use TZ string in the footer as the last (non-terminating) transitions
  • Fix reading TZif files to use more RRULEs and/or RDATEs whevever possible
  • Built-in timezones updated to tzdata2021a

[3.0.9] - 2021-01-16

  • Add support for empty parameters, e.g. CN=""
  • Accept VTIMEZONE with more than one X- property
  • Several fixes for recurrences containing BYWEEKNO
  • icalrecurrencetype_from_string() will reject any RRULE that contains a rule-part that occurs more than once
  • Improve thread safety
  • Fix compiled-in path for the built-in timezone data
  • Fix reading TZif files with empty v1 data (use v2+ whenever possible)
  • Add backwards compatibility for previous TZIDs
  • Built-in timezones updated to tzdata2020d
  • icalrecurrencetype_from_string() will reject any RRULE that contains a rule-part that occurs more than once
  • Fix build with newer libicu
  • Fix cross-compile support in libical-glib

[3.0.8] - 2020-03-07

  • Fix for icalattach_new_from_data() and the 'free_fn' argument
  • Fix if recurrencetype contains both COUNT and UNTIL (only output UNTIL in the RRULE)

[3.0.7] - 2019-12-15

  • libical-glib: Fix ICalAttach handling of the icalattach native structure
  • Let icalattach_new_from_data() use the 'free_fn' argument again
  • Fix memory leaks in attachment handling and elsewhere
  • Fix a multithreading race condition
  • More fuzzification fixes

[3.0.6] - 2019-09-14

  • Handle both COUNT and UNTIL in RRULEs
  • Fix RRULE BYDAY with INTERVAL=2 conflict
  • Various fuzzification fixes
  • New publicly available function:
    • icaltimezone_truncate_vtimezone
  • Add option to disable building the test suite
  • Built-in timezones updated to tzdata2019c

[3.0.5] - 2019-05-14

  • New publicly available function:
    • icalproperty_get_datetime_with_component
  • Allow reset DATE/DATE-TIME VALUE parameter for all-day events
  • icalproperty_get_datetime_with_component() will use location as TZID fallback.
  • New CMake option ENABLE_GTK_DOC for disabling the libical-glib developer documentation
  • GObject Introspection - use $MAJOR-0 versioning
  • libical-glib API is considered unstable, define LIBICAL_GLIB_UNSTABLE_API=1 before including <libical-glib/libical-glib.h> to be able to use it.
  • Built-in timezones updated to tzdata2019a
  • De-fuzzifications and Coverity fixes

[3.0.4] - 2018-08-14

  • Silently fail RSCALE recurrence clauses when RSCALE is disabled
  • Fixed icalcomponent_set_comment() and icalcomponent_set_uid()
  • fix FREQ=MONTHLY;BYMONTH
  • Skip UTF-8 marker when parsing
  • Fix parsing ? in VCF files produced by Outlook
  • Fix TZID on DATE-TIME value can override time specified in UTC
  • CMake discovery module for ICU uses pkg-config now
  • New publicly available function:
    • icalparameter_kind_is_valid
  • Built-in timezones updated to tzdata2018e

[3.0.3] - 2018-02-27

  • VTODO COMPLETED property can be a DATE-TIME or DATE (for backward compatibility)
  • Improved recurrence iteration

[3.0.2] - 2018-02-17

  • No longer attempt to detect the need for -DUSE_32BIT_TIME_T with MSVC
  • New CMake option ICAL_BUILD_DOCS which can be used to disable the docs target
  • Fix threading hang in BSD type systems (OpenBSD, MacOS,...)
  • Build with Ninja improvements

[3.0.1] - 2017-11-18

  • Built-in timezones updated to tzdata2017c
  • Fix a multi-threaded deadlock in icaltimezone_load_builtin_timezone()
  • Fix a CMake problem with parallel builds

[3.0.0] - 2017-10-28

  • Relicense from MPL 1.0 to MPL 2.0 (keep dual license for LGPL v2.1)
  • Requires CMake v3.1.0 or higher along with various CMake and buildsystem fixes
  • Added a 'make uninstall'
  • Fixed use-after-free issues and some memory leaks
  • Built-in timezones updated to tzdata2017b
  • More accurate VTIMEZONE generation when using the system time zone data (when USE_BUILTIN_TZDATA=False)
  • icalvalue_as_ical_string() returns "TRUE" (non-zero) or "FALSE" (zero) values only.
  • New icalvalue.h convenience macros: ICAL_BOOLEAN_TRUE and ICAL_BOOLEAN_FALSE
  • Better value type checking of property values when parsing
  • icalvalue_new/set_date and icalvalue_new/set_datetime now enforce DATE and DATE-TIME values respectively
  • draft-ietf-calext-extensions (RFC 7986) support added
  • Parameter values are now en/decoded per RFC 6868
  • Removed is_utc from icaltimetype struct
    • Set icaltimetype.zone to icaltimezone_get_utc_timezone() to change a time to UTC
    • Use icaltime_is_utc() to check if a time is in UTC
  • Added support for VPATCH component
  • New publicly available functions:
    • icalproperty_set_parent (icalproperty_get_parent was already public)
    • icalvalue_get_parent (icalvalue_set_parent was already public)
    • icalparameter_set_parent
    • icalparameter_get_parent
    • icalvalue_new_datetimedate (DATE or DATE-TIME)
    • icalvalue_set_datetimedate
    • icalvalue_get_datetimedate
    • icalrecur_iterator_set_start
    • icalcomponent_normalize
    • icalproperty_normalize
  • Removed deprecated functions:
    • icaltime_from_timet (use icaltime_from_timet_with_zone)
    • icaltime_start_day_of_week (use icaltime_start_day_week)
    • icalproperty_remove_parameter (use icalproperty_remove_parameter_by_kind)
    • icalproperty_string_to_enum (use icalproperty_kind_and_string_to_enum)
  • Signature changed for functions:
    • Parse_MIME_FromFileName
    • icalgauge *icalgauge_new_from_sql
    • const char *icallangbind_property_eval_string
    • const char *icallangbind_property_eval_string_r
    • void set_zone_directory
    • icalcalendar *icalcalendar_new
    • int icalrecur_expand_recurrence

[2.0.0] - 2015-12-28

  • WARNING: Version 2 IS NOT Binary Compatible with Older Versions
  • Version 2 is Source Compatible with Older Versions
  • Lots of source code scrubbing
  • [New] RSCALE support (requires libicu from http://www.icu-project.org)
  • [New] CalDAV attachment support (draft-ietf-calext-caldav-attachments)
  • [New] Resurrect the Berkeley DB storage support
  • [Bug] issue83: Incorrect recurrence generation for weekly pattern
  • Handle RRULEs better
  • Handle threading better

[1.0.1] - 2014-10-11

  • [Bug] issue74: Do not escape double quote character
  • [Bug] issue80,issue92: fix crashes using icaltimezone_load_builtin_timezone() recursively
  • [Bug] Fix icalcomponent_foreach_recurrence() and large durations between recurrences (e.g. FREQ=YEARLY)
  • [Bug] Properly handle UTCOFFSETs of the form +/-00mmss
  • [Bug] Properly skip bogus dates (e.g. 2/30, 4/31) in RRULE:FREQ=MONTHLY
  • [Bug] Properly handle RRULE:FREQ=MONTHLY;BYDAY;BYMONTHDAY when DTSTART isn't on BYDAY
  • [Bug] Fix RRULE:FREQ=YEARLY;BYDAY;BYWEEKNO - MUST use ISO weeks
  • [Bug] Properly skip bogus dates (e.g. 2/29) in RRULE:FREQ=YEARLY[;BYMONTH][;BYMONTHDAY]

  • [New] Update tzdata to version 2014g

  • [New] Support added for schedule params: agent, status, force-send

  • [New] Added a UID to the VFREEBUSY component

  • [New] Allow dates > 2038 if sizeof(time_t) > 4

  • [New] Add properties from draft-ietf-tzdist-service

  • [New] Add support for RRULE:FREQ=YEARLY;BYDAY;BYYEARDAY

  • [New] Fixed RRULE:FREQ=YEARLY;BYYEARDAY for negative days

  • [Build] Autotools build system is removed

  • [Build] CMake version 2.8.9 (or higher) is required (was CMake version 2.4.0)

  • [Build] Add new -DSHARED_ONLY and -DSTATIC_ONLY CMake options

  • [Build] Remove -DSTATIC_LIBRARY CMake option

  • [Build] MSYS2 builds (fixed instructions)

  • [Build/Doc] Now can build api documentation with make docs

  • [Quality] More regression tests added, in particular for recurrence

  • [Quality] Almost all compile warnings silenced

  • [Quality] A bunch of Coverity Scan warnings silenced

[1.0.0] - 2014-06-28

  • Reborn