# Calendar server

`rpc.cmsd` serves calendars to Calendar Manager and other CSA clients over RPC. It can be started on demand by `inetd` or `xinetd` or run as a standalone systemd service (`rpc-cmsd.service`, `rpc.cmsd -s -u`). Starting as `root`, it initializes `/var/spool/calendar`, drops effective privileges to `daemon`, switches to the calendar owner's identity only for file-ownership updates, and handles requests. The request path is validated before data is used.

### Local `AF_UNIX` transport \& `SO_PEERCRED` (default)

In standalone mode, `rpc.cmsd` listens on `/run/rpc.cmsd/cmsd.sock` (or `-U <path>`) and verifies the caller's real kernel UID via `SO_PEERCRED` on Linux, rejecting any forged `AUTH_UNIX` UID with `AUTH_TOOWEAK`. Passing `-u` (the default in `rpc-cmsd.service`) runs strictly over `AF_UNIX` with **zero open TCP/UDP ports** and **no `rpcbind` dependency**. `libcsa` (`connection.c`) connects to `/run/rpc.cmsd/cmsd.sock` first for local calendars (overridable via `DTCM_UNIX_SOCK`), falling back to loopback TCP/UDP (`127.0.0.1`) only when speaking to a legacy daemon.

On Debian/Ubuntu, the `ck-core-cde` package installs `/lib/systemd/system/rpc-cmsd.service` with `RuntimeDirectory=rpc.cmsd`, `PrivateNetwork=yes`, `RestrictAddressFamilies=AF_UNIX`, `NoNewPrivileges=yes`, and `ProtectHome=read-only`, initializes `/var/spool/calendar`, and enables and starts `rpc-cmsd.service` automatically on `apt install`. Legacy loopback TCP/UDP (`-l`) and opt-in LAN (`-n`) modes remain available when explicitly configured.

### Encrypted calendar sharing: CalDAV (HTTPS) \& SSH socket forwarding
- **CalDAV (`File → CalDAV Sync...`)**: Calendar Manager (`caldav_client.c`, `caldav_ui.c`) reuses `ics_io.c` and `libcurl` to sync with standard HTTPS CalDAV servers (Nextcloud, Radicale, Baïkal, Fastmail, etc.) using `PROPFIND`, `GET`, and `PUT` with TLS certificate verification enabled by default. Network I/O runs asynchronously on a background `pthread` (signaling the Xt event loop via `XtAppAddInput`) so the UI remains responsive. Persistent `(UID, ETag)` sync state (`~/.dt/dtcm_caldav_state`, mode `0600`) enables two-way **Sync** without duplicating unchanged events; optional periodic auto-sync (`auto_sync_mins`) uses `XtAppAddTimeOut`. Profiles are saved to `~/.dt/dtcm_caldav.conf` (`0600`) without persisting plaintext passwords, and optional desktop keyring storage (`secret-tool` / `gnome-keyring`) stores and retrieves passwords over stdin without exposing them on argv. UID filenames are sanitized against path traversal.
- **Desktop alarm notifications (`notify_desktop.c`, `alarm.c`)**: Appointment popup reminders also dispatch a non-blocking `org.freedesktop.Notifications` toast via `notify-send` (`--app-name=Calendar --icon=office-calendar --`), working on both Wayland and X11 even when `dtcm` is minimized or on another workspace (disable with `DTCM_DESKTOP_NOTIFY=0`).
- **SSH Unix-socket forwarding (`lib/csa/ssh_tunnel.c`)**: For classic `user@remotehost` CDE-to-CDE calendars without opening LAN RPC ports, enable **Use SSH socket tunnel for remote calendars** in **View → Server \& Network Status...** (or set `DTCM_SSH_TUNNEL=1` / browse `user@ssh://remotehost`). `libcsa` opens an encrypted `ssh -N -T -L <private_sock>:/run/rpc.cmsd/cmsd.sock` tunnel (`0700` directory, `0600` socket, `BatchMode=yes`, strict hostname validation) and cleans it up on exit.
- **Live diagnostics (`View → Server & Network Status...`)**: Reports active calendar, CSA handle state, `AF_UNIX`/`SO_PEERCRED` status, any active TCP/UDP ports, systemd isolation policy, SSH tunnel toggle, and local spool status.

## Requests
- A lookup, archive or restore request carries an attribute count and an array of operators. The two counts must agree; a request whose counts differ is refused instead of being decoded into an array of the wrong size.
- Attribute numbers sent by a client are not used as indexes. The server finds the attribute by its name and keeps the index within the calendar's or the entry's attribute array. An entry has no value for an attribute that was added to the calendar after the entry was stored.
- A calendar name is copied without a fixed-size buffer. An empty name or a name containing `/` is refused, so a name cannot select a file outside the calendar directory.
- Creating a calendar that already exists neither adds an access list to it nor removes it, and creating one that fails does not remove a file it did not create. Deleting several appointments in one request walks its list of keys within the list.
- The size and the check of a calendar, and the registration of a callback in either protocol version, are for those who may look at the calendar: a user without rights to it gets neither the number of its entries nor its updates. The procedure that discarded the appointments of a calendar in memory when the daemon ran in debug mode does nothing now.
- The text of a recurrence rule that is rebuilt to compare two rules is built in a buffer that grows with the rule, so a rule with hundreds of days no longer overruns a fixed buffer, and rules whose text cannot be built are not taken for the same rule.
- A calendar whose file cannot be set up for the extensible format because memory ran out is reported as a failure instead of being freed twice, and the temporary log of a garbage collection that fails is closed.
- An attribute of an update request that has no value and a name the calendar does not know is skipped instead of being read for its type; an attribute that exists loses its value, as before.
- A date criterion that is not a date, a Classification or Type attribute without a value, an unterminated reference identifier and an offset beyond the range of a calendar date are handled instead of dereferenced.

## Protocol limits

The XDR routines of the calendar protocols (versions 2 to 5 and the callback protocol) read the length of a string or the number of elements from the message and allocate that much before they read the contents. Every string, byte string, array and list in them is therefore bounded, by the constants of `lib/csa/cmlimits.h`, on both the request and the reply side:

| Constant | Limit | What it bounds |
| --- | --- | --- |
| `_DtCM_LIMIT_NAME` | 512 | calendar and user names (`user@host`) |
| `_DtCM_LIMIT_ATTR_NAME` | 256 | attribute names |
| `_DtCM_LIMIT_CHARSET`, `_DtCM_LIMIT_ENTRY_ID` | 64, 256 | character set names, entry identifiers |
| `_DtCM_LIMIT_DATE_TIME` | 128 | dates, date ranges, durations, lead times |
| `_DtCM_LIMIT_TEXT` | 65,536 | string attribute values, appointment text, opaque data |
| `_DtCM_LIMIT_ARCHIVE` | 64 MiB | the text of an archived calendar |
| `_DtCM_LIMIT_ATTRIBUTES` | 1,024 | attributes or attribute names of an entry, a calendar or a request; reminders of an appointment |
| `_DtCM_LIMIT_ENTRIES`, `_DtCM_LIMIT_KEYS` | 1,048,576, 65,536 | entries, appointments, reminders in a list; keys in a request |
| `_DtCM_LIMIT_CALENDARS` | 65,536 | calendar names in a list |
| `_DtCM_LIMIT_ACCESS_ENTRIES`, `_DtCM_LIMIT_ITEMS` | 65,536 | access list and date list entries; instances, ranges and exceptions of a request |
| `_DtCM_LIMIT_TAGS`, `_DtCM_LIMIT_REGISTRATIONS` | 16 | tags of an appointment, registrations in a request |

A message that exceeds a limit is refused (the server answers that it could not decode the arguments) and a reply that would exceed one is not sent. The values of enumerations of the older protocols and the type of an attribute value are checked on decoding; an unknown value refuses the message. A string that is not there is sent as the empty string.

Linked lists are coded in a loop with the bytes of the recursive routines that rpcgen generates, so a list of a million nodes no longer nests a million calls deep when it is read, written or freed. The XDR routines of versions 2 to 4 are kept in `rtable2_xdr.c`, `rtable3_xdr.c` and `rtable4_xdr.c` instead of being generated, and the list coding is in `cmxdrlist.c`.

## Calendar files

A calendar is stored as a log of records. The writers build every record, entry table and attribute list in a buffer that grows with the data, and escape every string with the rules the log already used for some fields: a newline, a backslash and a double quote are written with a leading backslash. A string without those characters is stored exactly as before. The reader's token buffer is sized by the file, and an unterminated string at the end of a file ends the token, so what the writers store can be read back.

## Privileges

`rpc.cmsd` changes its effective user and group to the daemon's at start-up and stops if it cannot. When it changes the owner or mode of a calendar file it switches to the file owner and back; if the chmod or chown fails, or the switch back fails, the daemon stops instead of continuing as `root`.

## Signals

`SIGALRM` and `SIGUSR1` start the daily garbage collection (the check of the registered clients, the reminders and the rewriting of the logs), `SIGUSR2` switches the debug output and `SIGHUP` makes the daemon give way to a newer one. The handlers only note that the signal arrived. The daemon blocks the four signals, serves its requests in its own loop (`cmsloop.c`) and lets the signals through only while it waits for the next request, so the work they ask for is done between two requests and never inside a handler, where it could interrupt the allocator or a request that is half processed. A request that is processed when `SIGHUP` arrives is finished and answered first. The daemon ignores `SIGPIPE`, so a client that goes away before it gets its reply cannot end it.

## Tests

`programs/dtcm/server/tests` holds request-level regression tests. The test program includes the production `log.c` and `cmsfunc.c`, compiles the other sources it exercises with AddressSanitizer and UndefinedBehaviorSanitizer and links the built `rpc.cmsd` and `libcsa`. Each case runs in its own process:

```sh
make -C programs/dtcm/server check
```

The cases cover the request decoders, calendar names and attribute handling, the log writers and reader with strings of all sizes, creating, updating and deleting entries and calendars, and the privilege changes. Run against the code from before the first of these changes, the same test source fails 27 of its 29 cases; the other two check results that did not change. Five more cases check the rebuilt text of a long recurrence rule, the size, check, flush and registration requests of a user who has no rights to a calendar, the closing of the temporary log of a failed dump and attributes without a value; all five fail on the previous sources.

`tests/loop-test.c` runs the service loop with a UDP service on the loopback interface while another process sends it the four signals: the work they ask for never runs during a request or with a signal open, every request is answered, a signal that arrives while the loop waits is not lost, and a request that is processed when `SIGHUP` arrives is finished first. With handlers that do the work themselves, two of its five cases fail, and a third fails when the daemon does not ignore `SIGPIPE`.

`lib/csa/tests` tests the XDR routines with hand-made messages: strings and arrays at and beyond their limits, counts of two and four billion, lists of 300,000 nodes, enumeration values and attribute types that do not exist, messages cut off in the middle of a list, and the bytes of lists whose `next` member is first, in the middle and last. The cases run under AddressSanitizer and UndefinedBehaviorSanitizer with leak detection and a limit on a single allocation:

```sh
make -C lib/csa check
```

Run against the XDR routines from before these changes, 14 of the 17 cases fail; the other three check the bytes of lists and the release of cut-off messages, which did not change. A live `rpc.cmsd` that is sent one request with a list of two million nodes crashes in the previous code and refuses the request now.

## iCalendar (`.ics`) import and export in `dtcm`

Calendar Manager (`programs/dtcm/dtcm/`) supports RFC 5545 iCalendar (`.ics`) exchange via **File → Import iCalendar (.ics)...** and **File → Export iCalendar (.ics)...**:
- Parses folded RFC 5545 lines, escaped text (`\n`, `\,`, `\;`, ``\\`), UTC and local ``DTSTART`/`DTEND`timestamps, IANA and common Windows`TZID`parameters (resolved via`/usr/share/zoneinfo`with exact DST rules),`VALUE=DATE`all-day events, ISO 8601`DURATION` values (`PT45M`, `P1D`), `SUMMARY`, `LOCATION`, `DESCRIPTION`, and `RRULE` recurrences (`DAILY`, `WEEKLY`, `MONTHLY`, `YEARLY`, `INTERVAL`, `COUNT\`).
- Maps imported events into CSA (`rpc.cmsd`) appointments (`csa_add_entry` with data-version recurrence rules) and deduplicates expanded CSA recurrence occurrences by `CSA_ENTRY_ATTR_REFERENCE_IDENTIFIER` during `.ics` export, with an automatic in-memory fallback when `dtcm` runs without a local `rpc.cmsd` daemon.
- `programs/dtcm/dtcm/ics_io.c` is verified standalone under AddressSanitizer and UndefinedBehaviorSanitizer by `programs/dtcm/dtcm/tests/check-ics-io.py`.

## Calendar Manager (`dtcm`) visual \& interaction UX improvements

Calendar Manager (`programs/dtcm/dtcm/`) includes everyday usability upgrades while preserving the classic Motif look and 100% CSA storage compatibility:
- **Visual clarity**: persistent Today accent highlight across Month, Week, and Day views; live current-time horizontal indicator line (updated every 60 seconds) in Day and Week views; subtle weekend column shading (Sunday and Saturday) and ISO 8601 week numbers (`W01`–`W53`) in Month view; color-coded category bars (`Work`, `Personal`, `Important`, `Travel`); hover preview of the full appointment summary, location, and category in the bottom status bar; and a right-aligned connection/sync status badge (`Local AF_UNIX` or `CalDAV: synced HH:MM`).
- **Navigation \& context menu**: mouse-wheel (`Button4`/`Button5`) paging, keyboard navigation (`Left`/`Right`/`Up`/`Down`, `Home`/`T` for Today, `Enter` and `Ctrl+N` for New Appointment), and a right-click (`Button3`) context menu on day cells and appointments (*New Appointment...*, *New To Do...*, *Switch to Day View*, *Jump to Today*, plus *Edit Appointment...* and *Delete Appointment* when clicking an appointment).
- **Appointment Editor**: quick duration chips (`15m`, `30m`, `1h`, `All Day`), a dedicated `Location:` field, and a `Category:` dropdown (`None`, `Work`, `Personal`, `Important`, `Travel`) mapped to RFC 5545 `LOCATION:` and `CATEGORIES:` while remaining backward-compatible with CSA `what` text.
- **Drag-and-drop**: drop `.ics` files directly onto the `dtcm` window to import events via `dtcm_import_ics_file()`, and drag appointments between day cells in Month view to reschedule them with DST-preserving day shifts.
- **Proportional Day-view cards \& direct manipulation**: timed appointments in Day view render as proportional pastel-tinted cards with a 4px left category accent bar and side-by-side overlap layout (`dtcm_layout_day_events()`). Dragging an empty time range creates a pre-filled appointment in 15-minute increments; dragging a card moves it; dragging its bottom edge resizes its duration.
- **Agenda view \& inline Quick Filter**: a 5th **Agenda** view displays upcoming events chronologically (14 / 30 / 90 days) with double-click to edit, and a collapsible inline filter bar (`/` or `Ctrl+F`) filters live by text and category.
- **Undo \& Reminder Snooze**: a 10-entry Undo ring buffer (`Ctrl+Z` or **Edit → Undo**) restores deleted appointments and reverts drag-moves/resizes (`tests/check-undo-stack.py`); alarm popups include a **Snooze 10m** action.
- **Multi-day spanning bars**: events spanning multiple days render as continuous horizontal pastel-tinted bars with category accent caps across week rows in Month view (`dtcm_compute_multiday_spans()`), reserving top lanes so single-day entries appear cleanly below.
- **Multiple overlaid calendars**: subscribe to read-only `.ics` / `webcal://` feeds or remote calendars via **View → Overlaid Calendars...** and toggle visibility from the **View → Calendars Sidebar** (`Ctrl+B`) checklist strip. Overlay sources are persisted in `~/.dt/dtcm_overlays` (`0600`), refreshed asynchronously on a background thread (`overlay_store.c`, `overlay_ui.c`), and merged into Month, Day, and Agenda views (`tests/check-overlay-store.py`).
- **Extended `RRULE` \& single-occurrence delete**: `ics_io.c` supports `BYDAY` weekday lists, `UNTIL`, `EXDATE` exclusions, and occurrence expansion (`dtcm_ics_expand_occurrences()`); deleting a recurring appointment via the context menu prompts for **This Occurrence** (`CSA_SCOPE_ONE`) vs **All Occurrences** (`CSA_SCOPE_ALL`).
- **iTIP / iMIP meeting invitations**: importing or dropping an RFC 5546 `METHOD:REQUEST` `.ics` file opens a **Meeting Invitation** dialog displaying the meeting summary, time, location, organizer, and attendees, with **Accept**, **Tentative**, and **Decline** actions that add accepted or tentative meetings to the primary calendar and deliver a `METHOD:REPLY` via either **Send Reply via Mail** (`submit_mail`) or **Save Reply `.ics`...** (`itip_ui.c`, `ics_io.c`, `tests/ics-io-test.c`).
- Pure calendar/category/hit-test helpers (`ux_helpers.c`) are verified under ASan/UBSan by `programs/dtcm/dtcm/tests/check-ux-helpers.py`.

## Limits
- The request-level tests call the handlers directly; the live checks of the daemon are kept outside the tree.
