mirror of
https://github.com/stalwartlabs/stalwart.git
synced 2026-11-26 23:29:52 +00:00
v1.2.0
This commit is contained in:
parent
3adead91f3
commit
b2d3df9a9b
1025 changed files with 233382 additions and 5660 deletions
23
.github/workflows/ci.yml
vendored
23
.github/workflows/ci.yml
vendored
|
|
@ -277,7 +277,6 @@ jobs:
|
|||
uses: docker/bake-action@v7
|
||||
env:
|
||||
DOCKER_BUILD_RECORD_UPLOAD: false
|
||||
GITHUB_TOKEN: ${{github.token}}
|
||||
TARGET: ${{matrix.target}}
|
||||
GHCR_REPO: ghcr.io/${{github.repository}}
|
||||
BUILD_ENV: ${{matrix.build_env}}
|
||||
|
|
@ -358,7 +357,7 @@ jobs:
|
|||
- name: Build
|
||||
run: |
|
||||
rustup target add ${{matrix.target}}
|
||||
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis keep azure nats enterprise"
|
||||
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks foundationdb s3 redis keep azure nats enterprise exchange"
|
||||
mkdir -p artifacts
|
||||
mv ./target/${{matrix.target}}/release/stalwart.exe ./artifacts/stalwart.exe
|
||||
|
||||
|
|
@ -386,24 +385,10 @@ jobs:
|
|||
with:
|
||||
disable_annotations: true
|
||||
|
||||
#- name: Build FoundationDB Edition
|
||||
# env:
|
||||
# GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# run: |
|
||||
# rustup target add ${{matrix.target}}
|
||||
# # Pin FoundationDB 7.4.x (Apple publishes these as prereleases)
|
||||
# curl --retry 5 -Lso foundationdb.pkg "$(gh api -X GET /repos/apple/foundationdb/releases --jq '[.[] | select(.tag_name | startswith("7.4."))] | sort_by(.tag_name | split(".") | map(tonumber)) | reverse | .[0].assets[] | select(.name | test("${{startsWith(matrix.target, 'x86') && 'x86_64' || 'arm64'}}" + ".pkg$")) | .browser_download_url')"
|
||||
# echo "=== Package contents ==="
|
||||
# pkgutil --payload-files foundationdb.pkg || true
|
||||
# sudo installer -allowUntrusted -verbose -dumplog -pkg foundationdb.pkg -target /
|
||||
# cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "foundationdb s3 redis keep nats enterprise"
|
||||
# mkdir -p artifacts
|
||||
# mv ./target/${{matrix.target}}/release/stalwart ./artifacts/stalwart-foundationdb
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
rustup target add ${{matrix.target}}
|
||||
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis keep azure nats enterprise"
|
||||
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks foundationdb s3 redis keep azure nats enterprise exchange"
|
||||
mkdir -p artifacts
|
||||
mv ./target/${{matrix.target}}/release/stalwart ./artifacts/stalwart
|
||||
|
||||
|
|
@ -452,14 +437,14 @@ jobs:
|
|||
pkg update -f
|
||||
env ASSUME_ALWAYS_YES=yes pkg bootstrap -f
|
||||
pkg update -f
|
||||
pkg install -y rust gmake llvm rocksdb
|
||||
pkg install -y rust gmake cmake rust-bindgen-cli llvm rocksdb
|
||||
rustc --version
|
||||
run: |
|
||||
set -e
|
||||
export CARGO_TARGET_DIR=/tmp/target
|
||||
export CARGO_TERM_COLOR=always
|
||||
export CARGO_NET_RETRY=10
|
||||
cargo build --release -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis keep azure nats enterprise"
|
||||
cargo build --release -p stalwart --no-default-features --features "sqlite postgres mysql rocks foundationdb s3 redis keep azure nats enterprise exchange"
|
||||
mkdir -p artifacts
|
||||
cp /tmp/target/release/stalwart artifacts/stalwart
|
||||
|
||||
|
|
|
|||
131
CHANGELOG.md
131
CHANGELOG.md
|
|
@ -2,6 +2,135 @@
|
|||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [1.2.0] - 2026-11-23
|
||||
|
||||
Upgrade instructions:
|
||||
|
||||
- **Add the new permissions to the default roles.** Mail rules, junk e-mail lists, calendar settings and Exchange need new permissions, which default roles created by an earlier version do not include:
|
||||
- User, group and administrator roles: `sysMailRule*`, `sysBlockedSender*`, `sysSafeSender*` and `sysCalendarSettings*`.
|
||||
- Administrator role: `sysExchangeGet` and `sysExchangeUpdate`.
|
||||
|
||||
Add these permissions manually using the recovery administrator or restart the server once with the environment variable `STALWART_UPDATE_ROLE_PERMISSIONS=true` to add them, then remove the variable. See [Default roles on upgraded servers](https://stalw.art/docs/auth/authorization/permissions#default-roles-on-upgraded-servers) for details.
|
||||
- **Upgrade the WebUI to version 2.1.1.**
|
||||
|
||||
## Added
|
||||
- **Microsoft Exchange** protocols for Outlook, Apple Mail, Calendar and Contacts, and ActiveSync devices (disabled by default):
|
||||
- Exchange Web Services (EWS): mail, calendar, contacts, tasks, folders, sharing and delegates, free/busy, inbox rules, out of office, reminders, name resolution and distribution lists, streaming and pull notifications; schema versions Exchange 2010 SP2 to Exchange 2016 (`ewsVersion`).
|
||||
- MAPI over HTTP (EMSMDB and NSPI) for Outlook for Windows in online and cached mode: incremental change synchronization, offline address book, delegate access, rules and junk e-mail settings, reminders, search folders and read receipts.
|
||||
- Exchange ActiveSync 14.1 and 16.1: mail, calendar, contacts, tasks and notes, folder sync, Ping, SendMail, SmartReply, SmartForward, ItemOperations, MeetingResponse, ResolveRecipients, Search, Settings and out of office.
|
||||
- Autodiscover (POX, SOAP and JSON v2) for EWS, MAPI over HTTP and ActiveSync.
|
||||
- New `x:Exchange` object (`enable`, `ewsVersion`, `maxRequestSize`, `maxDevices`, `maxHeartbeat`, `maxObjectSize`; permissions `sysExchangeGet` and `sysExchangeUpdate`) and a new `exchange` cache size setting.
|
||||
- Exchange clients share data with IMAP, JMAP, CalDAV and CardDAV: Exchange-only item properties are kept, categories are shared account-wide, and Outlook and EWS rules are stored as `x:MailRule` rules.
|
||||
- Basic and OAuth authentication; NTLM and Kerberos are not supported.
|
||||
- New `exchange` Cargo feature (enabled by default) to build without the Exchange protocols.
|
||||
- **Message Disposition Notifications**:
|
||||
- [RFC 8098 - Message Disposition Notification](https://datatracker.ietf.org/doc/html/rfc8098)
|
||||
- [RFC 9007 - Handling MDN with JMAP](https://datatracker.ietf.org/doc/html/rfc9007): `MDN/send` and `MDN/parse` methods, capability `urn:ietf:params:jmap:mdn`.
|
||||
- **Calendar Availability**:
|
||||
- Per-account working hours in the new `x:CalendarSettings` object (permissions `sysCalendarSettings*`).
|
||||
- Managed in the WebUI, over JMAP or through the CalDAV `calendar-availability` property (RFC 7953), which generates and accepts `VAVAILABILITY`.
|
||||
- Time outside working hours appears as `BUSY-UNAVAILABLE` in iTIP free/busy and as unavailable periods in JMAP `Principal/getAvailability`.
|
||||
- New `shareFreeBusy` calendar setting that lets users see each other's free/busy time without an explicit share, within the same tenant or across the whole server when tenants are not used. Applies to CalDAV scheduling, JMAP availability and EWS.
|
||||
- **Resource accounts** for rooms and equipment:
|
||||
- Capacity and location
|
||||
- Delegates who manage the resource's calendar
|
||||
- Automatic or manual booking of invitations
|
||||
- **Mail rules**:
|
||||
- Server-side rules in the new `x:MailRule` object (permissions `sysMailRule*`), compiled together with the vacation response into one read-only Sieve script named `managed`.
|
||||
- Conditions: sender and recipient addresses, addressed to me, subject, body, subject or body, any header, header exists, size, attachments and attachment name or type, importance, sensitivity, message type (meeting, delivery report, read receipt, automatic reply, signed, encrypted), mailing list, recipient address and plus-address, spam score, authenticated sender, received date range and a weekly schedule with an optional time zone.
|
||||
- Actions: move, copy, Trash, Junk, not junk, mark as read, keywords, redirect or forward, set importance, reply with a template, reject (authenticated senders only) and discard.
|
||||
- Junk e-mail lists: blocked senders, safe senders and safe recipients, plus delegation of meeting requests.
|
||||
- **FoundationDB** Rust native client:
|
||||
- Native asynchronous Rust client replaces `libfdb_c`.
|
||||
- Supports FoundationDB 7.1 to 8.0 and TLS, needs no client library installed on the host. Included in the standard build and Docker image.
|
||||
- Compared with the previous `libfdb_c` client: 4.5x to 6.9x the throughput on point reads at 256 concurrent clients and 2.1x on key scans, 5x to 7x lower median latency, about 3x lower p99 latency at equal load, and roughly half the client CPU and a quarter of the client memory per point read.
|
||||
- The `libfdb_c` backend remains available with the `foundationdb-c` feature.
|
||||
|
||||
## Changed
|
||||
- FoundationDB: the separate `stalwart-foundationdb` build, its Docker image and the `install.sh --fdb` option are removed; the standard `stalwart` binary connects to FoundationDB.
|
||||
- OAuth: dynamically registered clients may use the device authorization grant and request the full access scope; they remain unverified and always require the user's consent.
|
||||
- MTA: every message stored in a local mailbox gets a `Return-Path` header from the envelope sender, whatever port or protocol it was submitted on.
|
||||
- Sieve:
|
||||
- Vacation response is no longer replied to messages classified as spam, and the untrusted interpreter enforces `maxReceivedHeaders` itself.
|
||||
- `:zone` also accepts IANA time zone names (non-standard extension), evaluated with daylight saving time at run time.
|
||||
- Spam filter: IMAP `APPEND` trains the classifier only on `$Junk`/`$NotJunk` or an upload to Junk, like JMAP `Email/import`, so migrations no longer flood it with ham.
|
||||
- DKIM2: updated to [draft-ietf-dkim-dkim2-spec-09](https://datatracker.ietf.org/doc/html/draft-ietf-dkim-dkim2-spec-09) and [draft-ietf-dkim-dkim2-dns-03](https://datatracker.ietf.org/doc/html/draft-ietf-dkim-dkim2-dns-03) (`mail-auth` 0.16).
|
||||
|
||||
## Fixed
|
||||
- OAuth: successful bearer authentication now emits `auth.success`.
|
||||
- MySQL: a counter update whose result is exactly zero (such as a queue quota counter that had drifted to -1) no longer fails with "LAST_INSERT_ID() did not return a value", which blocked all incoming mail.
|
||||
- SPF: unknown modifiers containing `/` no longer cause a permerror.
|
||||
- DNS: cached TXT lookups used for one purpose no longer make a domain's DMARC policy, DKIM keys or DKIM2 Domain Policy Record look missing.
|
||||
- MTA:
|
||||
- RCPT TO for an empty mailing list no longer fails at DATA with 503.
|
||||
- Expanding large mailing lists no longer takes quadratic time.
|
||||
- Stricter validation of ENVID, ORCPT, AUTH during a transaction and repeated EHLO.
|
||||
- SMTP, IMAP, POP3 and ManageSieve writes time out when the client stops reading.
|
||||
- The Delivery Test now handles TLS and DANE like real deliveries.
|
||||
- `RCPT TO:<Postmaster>` without a domain is accepted (RFC 5321 4.5.1).
|
||||
- IMAP:
|
||||
- Messages arriving during a command are announced before its tagged reply, so clients no longer skip them.
|
||||
- `STATUS` notifications during `IDLE` include `HIGHESTMODSEQ`, so Apple Mail syncs changes right away.
|
||||
- A failed `SELECT` or `EXAMINE` closes the previously selected mailbox, so a following `CLOSE` or `EXPUNGE` no longer affects it (Reported by Hebin Lv (吕贺彬), Beijing University of Posts and Telecommunications).
|
||||
- Limits on FETCH items, SEARCH criteria, sequence sets, flags and header field names per command.
|
||||
- Concurrent creates and renames of the same mailbox name no longer leave duplicates.
|
||||
- JMAP:
|
||||
- Draft saves, copies and imports no longer trigger new-mail pushes.
|
||||
- `EmailSubmission` no longer drops recipients on non-public TLDs such as `.internal`.
|
||||
- `Email/query` text searches containing symbol-only words no longer return nothing.
|
||||
- `ContactCard/parse` returns every vCard in a blob.
|
||||
- `ContactCard/set` generates a `uid` when the client omits it.
|
||||
- Unknown capabilities are answered with `unknownCapability`, and WebSocket `RequestError` frames carry the `requestId`.
|
||||
- `SieveScript/set` activation reports state changes correctly and uses the `sieveIsActive` error.
|
||||
- Oversized WebSocket messages are refused while reading.
|
||||
- `Identity/set` and `EmailSubmission/set` return `oldState`/`newState` and honour `ifInState`.
|
||||
- Invalid JSON bodies are answered with `notJSON`, and empty `createdIds` is echoed.
|
||||
- Push subscriptions whose endpoint answers 404 or 410 are destroyed.
|
||||
- Sieve:
|
||||
- `vacation`, `enclose` and `notify` strip CR/LF from header values taken from the message or script.
|
||||
- `enclose` and redirect loops stop at the hop limit.
|
||||
- `:addrbook:default` and named address books work in `:list` tests.
|
||||
- `redirect` copies to local accounts keep the spam verdict computed at DATA, so spam is filed in the target's Junk.
|
||||
- Calendar:
|
||||
- Meeting updates and acceptances refresh the Microsoft busy status.
|
||||
- Truncating a recurring series to a past end date notifies attendees.
|
||||
- Destroying an account removes its pending alarms.
|
||||
- Limits on generated time zone definitions and iMIP parts per message.
|
||||
- `CalendarEvent/set` rejects non-IANA time zone names instead of storing a floating event.
|
||||
- Invitation and alarm e-mails keep the line breaks of the event description.
|
||||
- CalDAV follows the default calendar set through JMAP.
|
||||
- Calendar scheduling:
|
||||
- New exceptions to recurring events reach attendees who already replied.
|
||||
- Attendees with `RSVP=FALSE` receive invitations, updates and cancellations.
|
||||
- Contacts: online services with a user name and no URI are no longer lost.
|
||||
- DKIM: automatic key rotation keeps the settings of the replaced key.
|
||||
- ACME: editing the contacts of an existing provider no longer fails with "Invalid email address".
|
||||
- OAuth:
|
||||
- The device authorization verification page is reachable in bootstrap and recovery mode.
|
||||
- In a cluster, access tokens are accepted immediately on all nodes.
|
||||
- Directories:
|
||||
- An unavailable directory no longer blocks settings reloads.
|
||||
- Accounts and groups created from external directories respect tenant quotas.
|
||||
- Security:
|
||||
- Auto-ban and rate limits apply per IPv6 /64, and blocked networks added at runtime are enforced without a reload.
|
||||
- Failed logins tripping only the per-login counter ban just the source address.
|
||||
- Role managers can no longer grant themselves permissions through parent roles.
|
||||
- Open IMAP, POP3, ManageSieve, WebSocket and EventSource sessions end when the account's permissions or password change.
|
||||
- Push delivery reads at most 1 KiB of an endpoint's error response.
|
||||
- Spam filter: cluster nodes load the updated classifier model after training on another node.
|
||||
- Cluster: nodes that miss coordinator events reload their state instead of keeping stale settings until a restart.
|
||||
- HTTP: stalled connections are closed after 60 seconds, POST /jmap buffering is limited, cross-site requests no longer trigger scan bans, and EventSource streams end on token revocation.
|
||||
- Search index:
|
||||
- Destroying an account during indexing no longer leaves index entries behind.
|
||||
- Busy accounts no longer hold an indexing slot indefinitely.
|
||||
- `x:IndexQueueStatus/query` accepts a numeric `partition`.
|
||||
- Storage:
|
||||
- PostgreSQL: requests on idle pooled connections and pool waits are bounded by `responseTimeout`.
|
||||
- Elasticsearch: searches return more than 10,000 matches and rejected bulk documents are reported.
|
||||
- Archiving: restoring items of a deleted account is refused.
|
||||
- Log viewer: only files written by the log tracer are read.
|
||||
- Recovery and bootstrap mode: new `STALWART_RECOVERY_MODE_BIND` environment variable sets the setup listener address, and an invalid bind address stops startup.
|
||||
|
||||
## [1.1.1] - 2026-11-16
|
||||
|
||||
## Added
|
||||
|
|
@ -20,7 +149,7 @@ All notable changes to this project will be documented in this file. This projec
|
|||
- `Principal/query` `text` and `name` filters now match a full address and whole words of the name and description; `name` was an exact address match and `text` never matched an address.
|
||||
- The `ClassifySpam` and `TroubleshootDmarc` actions accept `mailFrom: null` for the null reverse-path (`MAIL FROM:<>`), and the `ClassifySpam` `mailFromParameters` value `bit8Mime` is spelled correctly and no longer swapped with `binaryMime`.
|
||||
- IMAP:
|
||||
- Every token of a request, including empty quoted strings, now counts toward the request size limit at its in-memory size; floods of `""` before login or of `(` after it could exhaust server memory.
|
||||
- Every token of a request, including empty quoted strings, now counts toward the request size limit at its in-memory size; floods of `""` before login or of `(` after it could exhaust server memory (Reported by Jan Kahmen (turingpoint)).
|
||||
- FETCH, SEARCH, STORE, THREAD, UIDBATCHES, COPY and MOVE now send `EXISTS` for messages delivered since the last update before their responses refer to them (RFC 9051 §5.2); clients could record the new UID without the message and skip it for good.
|
||||
- Email:
|
||||
- An incoming or appended message is no longer dropped as a duplicate when the only stored message with the same `Message-ID` in the target mailbox is a draft.
|
||||
|
|
|
|||
627
Cargo.lock
generated
627
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -14,6 +14,8 @@ members = [
|
|||
"crates/managesieve",
|
||||
"crates/pop3",
|
||||
"crates/dav-proto",
|
||||
"crates/exchange-proto",
|
||||
"crates/exchange",
|
||||
"crates/scim-proto",
|
||||
"crates/scim",
|
||||
"crates/dav",
|
||||
|
|
@ -37,6 +39,7 @@ members = [
|
|||
"crates/jmap-tools",
|
||||
"crates/s3",
|
||||
"crates/crypto",
|
||||
"crates/fdb",
|
||||
]
|
||||
default-members = [
|
||||
"crates/main",
|
||||
|
|
@ -52,6 +55,8 @@ default-members = [
|
|||
"crates/managesieve",
|
||||
"crates/pop3",
|
||||
"crates/dav-proto",
|
||||
"crates/exchange-proto",
|
||||
"crates/exchange",
|
||||
"crates/scim-proto",
|
||||
"crates/scim",
|
||||
"crates/dav",
|
||||
|
|
|
|||
|
|
@ -19,9 +19,9 @@ RUN export DEBIAN_FRONTEND=noninteractive && \
|
|||
g++-x86-64-linux-gnu binutils-x86-64-linux-gnu
|
||||
RUN rustup target add "$(cat /target.txt)"
|
||||
COPY --from=planner /recipe.json /recipe.json
|
||||
RUN RUSTFLAGS="$(cat /flags.txt)" cargo chef cook --target "$(cat /target.txt)" --release --no-default-features --features "sqlite postgres mysql rocks s3 redis keep azure nats enterprise" --recipe-path /recipe.json
|
||||
RUN RUSTFLAGS="$(cat /flags.txt)" cargo chef cook --target "$(cat /target.txt)" --release --no-default-features --features "sqlite postgres mysql rocks foundationdb s3 redis keep azure nats enterprise exchange" --recipe-path /recipe.json
|
||||
COPY . .
|
||||
RUN RUSTFLAGS="$(cat /flags.txt)" cargo build --target "$(cat /target.txt)" --release -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis keep azure nats enterprise"
|
||||
RUN RUSTFLAGS="$(cat /flags.txt)" cargo build --target "$(cat /target.txt)" --release -p stalwart --no-default-features --features "sqlite postgres mysql rocks foundationdb s3 redis keep azure nats enterprise exchange"
|
||||
RUN mv "/build/target/$(cat /target.txt)/release" "/output"
|
||||
|
||||
FROM docker.io/debian:trixie-slim
|
||||
|
|
|
|||
|
|
@ -16,14 +16,14 @@ ENV DEBIAN_FRONTEND="noninteractive" \
|
|||
TERM=xterm-256color \
|
||||
AWS_LC_SYS_PREBUILT_NASM=1
|
||||
# With zig, we only need libclang and make. ca-certificates is required for curl
|
||||
# to verify HTTPS downloads (zig tarballs, FoundationDB debs, crates.io, etc).
|
||||
# to verify HTTPS downloads (zig tarballs, crates.io, etc).
|
||||
RUN \
|
||||
--mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt,sharing=locked \
|
||||
rm -f /etc/apt/apt.conf.d/docker-clean && \
|
||||
echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' >/etc/apt/apt.conf.d/keep-cache && \
|
||||
apt-get update && \
|
||||
apt-get install -yq --no-install-recommends ca-certificates curl git jq xz-utils make libclang-19-dev
|
||||
apt-get install -yq --no-install-recommends ca-certificates curl git xz-utils make libclang-19-dev
|
||||
RUN \
|
||||
ZIG_VERSION=0.17.0 && \
|
||||
case "$(uname -m)" in \
|
||||
|
|
@ -94,41 +94,6 @@ RUN \
|
|||
[ -n "${includes}" ] && \
|
||||
target_var="${TARGET//-/_}" && \
|
||||
echo "export BINDGEN_EXTRA_CLANG_ARGS_${target_var}='${includes}'" >> /env-cargo; \
|
||||
fi && \
|
||||
if [[ "${TARGET}" == *gnu ]]; then \
|
||||
base_arch="${TARGET%%-*}"; \
|
||||
case "$base_arch" in \
|
||||
x86_64) \
|
||||
echo "export FDB_ARCH=amd64" >> /env-cargo; \
|
||||
;; \
|
||||
aarch64) \
|
||||
echo "export FDB_ARCH=aarch64" >> /env-cargo; \
|
||||
;; \
|
||||
*) \
|
||||
exit 1; \
|
||||
;; \
|
||||
esac; \
|
||||
target_var="${TARGET^^}"; \
|
||||
echo "export FDB_RUSTFLAGS_VAR=CARGO_TARGET_${target_var//-/_}_RUSTFLAGS" >> /env-cargo; \
|
||||
fi
|
||||
# Install FoundationDB (pinned to latest 7.4.x; Apple publishes 7.4 as
|
||||
# prereleases on GitHub, so the release list is fetched without the
|
||||
# prerelease filter and narrowed by tag name).
|
||||
ARG FDB_VERSION_RANGE="7.4"
|
||||
RUN \
|
||||
--mount=type=secret,id=GITHUB_TOKEN,env=GITHUB_TOKEN \
|
||||
source /env-cargo && \
|
||||
if [ ! -z "${FDB_ARCH}" ]; then \
|
||||
auth=() && \
|
||||
if [ -n "${GITHUB_TOKEN}" ]; then auth=(-H "Authorization: Bearer ${GITHUB_TOKEN}"); fi && \
|
||||
fdb_url="$(curl --retry 5 -fLs "${auth[@]}" 'https://api.github.com/repos/apple/foundationdb/releases?per_page=100' | jq --arg FDB_ARCH "$FDB_ARCH" --arg RANGE "${FDB_VERSION_RANGE}" -r '[.[] | select(.tag_name | startswith($RANGE + "."))] | sort_by(.tag_name | split(".") | map(tonumber)) | reverse | .[0].assets[] | select(.name | test("foundationdb-clients.*" + $FDB_ARCH + ".deb$")) | .browser_download_url')" && \
|
||||
[ -n "${fdb_url}" ] && \
|
||||
curl --retry 5 -fLso fdb-client.deb "${fdb_url}" && \
|
||||
mkdir -p /fdb && \
|
||||
dpkg -x fdb-client.deb /fdb && \
|
||||
mv /fdb/usr/include/foundationdb /usr/include && \
|
||||
mv /fdb/usr/lib/libfdb_c.so /usr/lib && \
|
||||
rm -rf fdb-client.deb /fdb; \
|
||||
fi
|
||||
# Cargo-chef Cache layer
|
||||
RUN \
|
||||
|
|
@ -137,31 +102,11 @@ RUN \
|
|||
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,target=/usr/local/cargo/git \
|
||||
source /env-cargo && \
|
||||
if [ ! -z "${FDB_ARCH}" ]; then \
|
||||
env "${FDB_RUSTFLAGS_VAR}=-L /usr/lib" cargo chef cook --recipe-path recipe.json --zigbuild --release --target ${BUILD_TARGET} -p stalwart --no-default-features --features "foundationdb s3 redis keep nats enterprise"; \
|
||||
fi
|
||||
RUN \
|
||||
--mount=type=secret,id=ACTIONS_RESULTS_URL,env=ACTIONS_RESULTS_URL \
|
||||
--mount=type=secret,id=ACTIONS_RUNTIME_TOKEN,env=ACTIONS_RUNTIME_TOKEN \
|
||||
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,target=/usr/local/cargo/git \
|
||||
source /env-cargo && \
|
||||
cargo chef cook --recipe-path recipe.json --zigbuild --release --target ${BUILD_TARGET} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis keep azure nats enterprise"
|
||||
cargo chef cook --recipe-path recipe.json --zigbuild --release --target ${BUILD_TARGET} -p stalwart --no-default-features --features "sqlite postgres mysql rocks foundationdb s3 redis keep azure nats enterprise exchange"
|
||||
# Copy the source code
|
||||
COPY . .
|
||||
ENV RUSTC_WRAPPER="sccache" \
|
||||
SCCACHE_GHA_ENABLED=true
|
||||
# Build FoundationDB version
|
||||
RUN \
|
||||
--mount=type=secret,id=ACTIONS_RESULTS_URL,env=ACTIONS_RESULTS_URL \
|
||||
--mount=type=secret,id=ACTIONS_RUNTIME_TOKEN,env=ACTIONS_RUNTIME_TOKEN \
|
||||
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,target=/usr/local/cargo/git \
|
||||
source /env-cargo && \
|
||||
if [ ! -z "${FDB_ARCH}" ]; then \
|
||||
env "${FDB_RUSTFLAGS_VAR}=-L /usr/lib" cargo zigbuild --release --target ${BUILD_TARGET} -p stalwart --no-default-features --features "foundationdb s3 redis keep nats enterprise" && \
|
||||
mv /app/target/${TARGET}/release/stalwart /app/artifact/stalwart-foundationdb; \
|
||||
fi
|
||||
# Build generic version
|
||||
RUN \
|
||||
--mount=type=secret,id=ACTIONS_RESULTS_URL,env=ACTIONS_RESULTS_URL \
|
||||
|
|
@ -169,7 +114,7 @@ RUN \
|
|||
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||
--mount=type=cache,target=/usr/local/cargo/git \
|
||||
source /env-cargo && \
|
||||
cargo zigbuild --release --target ${BUILD_TARGET} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis keep azure nats enterprise" && \
|
||||
cargo zigbuild --release --target ${BUILD_TARGET} -p stalwart --no-default-features --features "sqlite postgres mysql rocks foundationdb s3 redis keep azure nats enterprise exchange" && \
|
||||
mv /app/target/${TARGET}/release/stalwart /app/artifact/stalwart
|
||||
|
||||
# *****************
|
||||
|
|
|
|||
|
|
@ -1,78 +0,0 @@
|
|||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM debian:trixie-slim AS chef
|
||||
ARG TARGETARCH
|
||||
ARG FDB_VERSION_RANGE="7.4"
|
||||
RUN apt-get update && \
|
||||
export DEBIAN_FRONTEND=noninteractive && \
|
||||
apt-get install -yq --no-install-recommends \
|
||||
build-essential \
|
||||
ca-certificates \
|
||||
cmake \
|
||||
clang \
|
||||
curl \
|
||||
jq \
|
||||
protobuf-compiler
|
||||
ENV RUSTUP_HOME=/opt/rust/rustup \
|
||||
PATH=/home/root/.cargo/bin:/opt/rust/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
RUN curl https://sh.rustup.rs -sSf | \
|
||||
env CARGO_HOME=/opt/rust/cargo \
|
||||
sh -s -- -y --default-toolchain stable --profile minimal --no-modify-path && \
|
||||
env CARGO_HOME=/opt/rust/cargo \
|
||||
rustup component add rustfmt
|
||||
RUN \
|
||||
ARCH="${TARGETARCH:-$(dpkg --print-architecture)}" && \
|
||||
case "$ARCH" in \
|
||||
amd64) FDB_ARCH=amd64 ;; \
|
||||
arm64) FDB_ARCH=aarch64 ;; \
|
||||
*) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;; \
|
||||
esac && \
|
||||
curl --retry 5 -fLso fdb-client.deb "$(curl --retry 5 -fLs 'https://api.github.com/repos/apple/foundationdb/releases?per_page=100' | jq --arg FDB_ARCH "$FDB_ARCH" --arg RANGE "${FDB_VERSION_RANGE}" -r '[.[] | select(.tag_name | startswith($RANGE + "."))] | sort_by(.tag_name | split(".") | map(tonumber)) | reverse | .[0].assets[] | select(.name | test("foundationdb-clients.*" + $FDB_ARCH + ".deb$")) | .browser_download_url')" && \
|
||||
mkdir -p /fdb && \
|
||||
dpkg -x fdb-client.deb /fdb && \
|
||||
mv /fdb/usr/include/foundationdb /usr/include && \
|
||||
mv /fdb/usr/lib/libfdb_c.so /usr/lib && \
|
||||
rm -rf fdb-client.deb /fdb
|
||||
RUN env CARGO_HOME=/opt/rust/cargo cargo install cargo-chef && \
|
||||
rm -rf /opt/rust/cargo/registry/
|
||||
WORKDIR /app
|
||||
|
||||
FROM chef AS planner
|
||||
COPY Cargo.toml .
|
||||
COPY Cargo.lock .
|
||||
COPY crates/ crates/
|
||||
COPY resources/ resources/
|
||||
RUN cargo chef prepare --recipe-path recipe.json
|
||||
|
||||
FROM chef AS builder
|
||||
COPY --from=planner /app/recipe.json recipe.json
|
||||
RUN cargo chef cook --release --recipe-path recipe.json
|
||||
COPY Cargo.toml .
|
||||
COPY Cargo.lock .
|
||||
COPY crates/ crates/
|
||||
COPY resources/ resources/
|
||||
RUN cargo build -p stalwart --no-default-features --features "foundationdb s3 redis keep azure nats enterprise" --release
|
||||
|
||||
FROM debian:trixie-slim AS runtime
|
||||
|
||||
COPY --from=builder --chmod=0755 /app/target/release/stalwart /usr/local/bin/stalwart
|
||||
COPY --from=builder /usr/lib/libfdb_c.so /usr/lib/libfdb_c.so
|
||||
RUN export DEBIAN_FRONTEND=noninteractive && \
|
||||
apt-get update && \
|
||||
apt-get install -yq --no-install-recommends ca-certificates curl libcap2-bin && \
|
||||
rm -rf /var/lib/apt/lists/* && \
|
||||
groupadd -r -g 2000 stalwart && \
|
||||
useradd -r -u 2000 -g 2000 -s /usr/sbin/nologin -M stalwart && \
|
||||
mkdir -p /etc/stalwart /var/lib/stalwart && \
|
||||
chown stalwart:stalwart /etc/stalwart /var/lib/stalwart && \
|
||||
setcap 'cap_net_bind_service=+ep' /usr/local/bin/stalwart
|
||||
|
||||
USER stalwart
|
||||
WORKDIR /var/lib/stalwart
|
||||
VOLUME ["/etc/stalwart", "/var/lib/stalwart"]
|
||||
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
||||
ENV STALWART_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
||||
CMD curl -fsSk "$STALWART_HEALTHCHECK_URL" || curl -fsS http://127.0.0.1:8080/healthz/live || exit 1
|
||||
ENTRYPOINT ["/usr/local/bin/stalwart"]
|
||||
CMD ["--config", "/etc/stalwart/config.json"]
|
||||
11
README.md
11
README.md
|
|
@ -5,7 +5,7 @@
|
|||
</p>
|
||||
|
||||
<h3 align="center">
|
||||
Secure, scalable mail & collaboration server with comprehensive protocol support 🛡️ <br/>(IMAP, JMAP, SMTP, CalDAV, CardDAV, WebDAV)
|
||||
Secure, scalable mail & collaboration server with comprehensive protocol support 🛡️ <br/>(IMAP, JMAP, SMTP, CalDAV, CardDAV, WebDAV, Microsoft Exchange)
|
||||
</h3>
|
||||
|
||||
<br>
|
||||
|
|
@ -30,7 +30,7 @@
|
|||
|
||||
## Features
|
||||
|
||||
**Stalwart** is an open-source mail & collaboration server with JMAP, IMAP4, POP3, SMTP, CalDAV, CardDAV and WebDAV support and a wide range of modern features. It is written in Rust and designed to be secure, fast, robust and scalable.
|
||||
**Stalwart** is an open-source mail & collaboration server with JMAP, IMAP4, POP3, SMTP, CalDAV, CardDAV, WebDAV and Microsoft Exchange support and a wide range of modern features. It is written in Rust and designed to be secure, fast, robust and scalable.
|
||||
|
||||
Key features:
|
||||
|
||||
|
|
@ -54,6 +54,11 @@ Key features:
|
|||
* Inbound throttling and filtering with granular configuration rules, sieve scripting, MTA hooks and milter integration.
|
||||
* Distributed virtual queues with delayed delivery, priority delivery, quotas, routing rules and throttling support.
|
||||
* Envelope rewriting and message modification.
|
||||
- Microsoft Exchange (drop-in replacement for Outlook and ActiveSync clients):
|
||||
* [MAPI over HTTP](https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmapihttp/d502edcf-0b22-42f2-8500-019f00d60245) for classic Outlook for Windows, in cached and online mode.
|
||||
* Exchange Web Services (EWS) for Outlook for Mac and Apple Mail, Calendar and Contacts.
|
||||
* [Exchange ActiveSync](https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-ashttp/4cbf28dc-2876-41c6-9d87-ba9db86cd40d) 14.1 and 16.1 for phones and tablets.
|
||||
* Autodiscover, global address list and offline address book.
|
||||
- **Collaboration** server:
|
||||
- Calendaring and scheduling:
|
||||
- [CalDAV](https://datatracker.ietf.org/doc/html/rfc4791) and [CalDAV Scheduling](https://datatracker.ietf.org/doc/html/rfc6638) support.
|
||||
|
|
@ -85,7 +90,7 @@ Key features:
|
|||
- Sieve scripting language with support for all [registered extensions](https://www.iana.org/assignments/sieve-extensions/sieve-extensions.xhtml).
|
||||
- Email aliases, mailing lists, subaddressing and catch-all addresses support.
|
||||
- Automated DNS management.
|
||||
- Automatic account configuration and discovery with [PACC](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-pacc/), [autoconfig](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-autoconfig/) and [autodiscover](https://learn.microsoft.com/en-us/exchange/architecture/client-access/autodiscover?view=exchserver-2019).
|
||||
- Automatic account configuration and discovery with [PACC](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-pacc/), [autoconfig](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-autoconfig/) and [autodiscover](https://learn.microsoft.com/en-us/exchange/architecture/client-access/autodiscover?view=exchserver-2019) for Exchange and Outlook clients.
|
||||
- Multi-tenancy support with domain and tenant isolation.
|
||||
- Disk quotas per user and tenant.
|
||||
- **Encryption** with **OpenPGP** and **S/MIME**:
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "calcard"
|
||||
description = "iCalendar/JSCalendar and vCard/JSContact parsing, building and conversion library"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -53,6 +53,21 @@ impl Tz {
|
|||
tz.time_zone().is_some().then_some(tz)
|
||||
}
|
||||
|
||||
pub fn from_iana_id(id: u16) -> Option<Self> {
|
||||
tzdb::id_to_name(id).map(|_| Self::Iana(id))
|
||||
}
|
||||
|
||||
pub fn iana_name(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Iana(id) => tzdb::id_to_name(*id),
|
||||
Self::Fixed(_) | Self::Floating => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn offset_at_unix(&self, seconds: i64) -> i32 {
|
||||
Timestamp::from_second(seconds).map_or(0, |timestamp| self.offset_at(timestamp).seconds())
|
||||
}
|
||||
|
||||
/// Resolves a named zone, caching it for the lifetime of the process.
|
||||
///
|
||||
/// Returns `None` for floating and fixed zones, and for a name the time
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ use crate::{
|
|||
},
|
||||
icalendar::ICalendarParameterName,
|
||||
};
|
||||
use ahash::AHashSet;
|
||||
use jiff::{
|
||||
Timestamp,
|
||||
civil::{self, Date, Weekday},
|
||||
|
|
@ -146,6 +147,7 @@ const TZ_MAX_FUTURE_YEARS: i32 = 100;
|
|||
const TZ_RANGE_MARGIN: i64 = 86400;
|
||||
const TZ_RULE_ACTIVE_SECONDS: i64 = 366 * 86400;
|
||||
const MAX_OBSERVANCES: usize = 4096;
|
||||
const MAX_ADDED_TIMEZONES: usize = 32;
|
||||
|
||||
impl ICalendar {
|
||||
pub fn add_timezone(&mut self, tz_id: &str, from: i64, to: i64) -> Option<u32> {
|
||||
|
|
@ -202,16 +204,15 @@ impl ICalendar {
|
|||
}
|
||||
|
||||
pub fn add_missing_timezones(&mut self) -> usize {
|
||||
let mut defined: Vec<&str> = Vec::new();
|
||||
for component in self.timezones() {
|
||||
for entry in &component.entries {
|
||||
if entry.name == ICalendarProperty::Tzid
|
||||
&& let Some(ICalendarValue::Text(tz_id)) = entry.values.first()
|
||||
{
|
||||
defined.push(tz_id.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
let defined: AHashSet<&str> = self
|
||||
.timezones()
|
||||
.flat_map(|component| &component.entries)
|
||||
.filter(|entry| entry.name == ICalendarProperty::Tzid)
|
||||
.filter_map(|entry| match entry.values.first() {
|
||||
Some(ICalendarValue::Text(tz_id)) => Some(tz_id.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut referenced: Vec<String> = Vec::new();
|
||||
let mut range: Option<(i64, i64)> = None;
|
||||
|
|
@ -231,8 +232,9 @@ impl ICalendar {
|
|||
for entry in &component.entries {
|
||||
for param in &entry.params {
|
||||
if param.name == ICalendarParameterName::Tzid
|
||||
&& referenced.len() < MAX_ADDED_TIMEZONES
|
||||
&& let Some(tz_id) = param.value.as_text()
|
||||
&& !defined.contains(&tz_id)
|
||||
&& !defined.contains(tz_id)
|
||||
&& !referenced.iter().any(|id| id == tz_id)
|
||||
{
|
||||
referenced.push(tz_id.to_string());
|
||||
|
|
|
|||
|
|
@ -1563,6 +1563,7 @@ where
|
|||
JSContactProperty::OnlineServices => {
|
||||
for (name, value) in value.into_expanded_object() {
|
||||
let mut entry = VCardEntry::new(VCardProperty::Socialprofile);
|
||||
let mut user = None;
|
||||
|
||||
for (sub_property, value) in value.into_expanded_object() {
|
||||
match sub_property {
|
||||
|
|
@ -1581,9 +1582,7 @@ where
|
|||
}
|
||||
Key::Property(JSContactProperty::User) => {
|
||||
if let Some(username) = value.into_string() {
|
||||
entry.add_param(VCardParameter::username(
|
||||
username.into_owned(),
|
||||
));
|
||||
user = Some(username.into_owned());
|
||||
}
|
||||
}
|
||||
Key::Property(JSContactProperty::Contexts) => {
|
||||
|
|
@ -1625,6 +1624,15 @@ where
|
|||
}
|
||||
}
|
||||
|
||||
if let Some(user) = user {
|
||||
if entry.values.is_empty() {
|
||||
entry.values = smallvec![VCardValue::Text(user)];
|
||||
entry.add_param(VCardParameter::value(VCardValueType::Text));
|
||||
} else {
|
||||
entry.add_param(VCardParameter::username(user));
|
||||
}
|
||||
}
|
||||
|
||||
state.insert_vcard(
|
||||
&[JSContactProperty::OnlineServices],
|
||||
entry.with_param(VCardParameter::prop_id(name.into_string())),
|
||||
|
|
|
|||
|
|
@ -1074,18 +1074,33 @@ impl VCard {
|
|||
}
|
||||
}
|
||||
VCardProperty::Socialprofile => {
|
||||
let is_text = entry.take_text_value_type() || entry.move_username_to_value();
|
||||
state.map_named_entry(
|
||||
&mut entry,
|
||||
&[
|
||||
VCardParameterName::Type,
|
||||
VCardParameterName::Pref,
|
||||
VCardParameterName::PropId,
|
||||
VCardParameterName::Label,
|
||||
VCardParameterName::ServiceType,
|
||||
VCardParameterName::Username,
|
||||
],
|
||||
if is_text {
|
||||
&[
|
||||
VCardParameterName::Type,
|
||||
VCardParameterName::Pref,
|
||||
VCardParameterName::PropId,
|
||||
VCardParameterName::Label,
|
||||
VCardParameterName::ServiceType,
|
||||
]
|
||||
} else {
|
||||
&[
|
||||
VCardParameterName::Type,
|
||||
VCardParameterName::Pref,
|
||||
VCardParameterName::PropId,
|
||||
VCardParameterName::Label,
|
||||
VCardParameterName::ServiceType,
|
||||
VCardParameterName::Username,
|
||||
]
|
||||
},
|
||||
JSContactProperty::OnlineServices,
|
||||
JSContactProperty::Uri,
|
||||
if is_text {
|
||||
JSContactProperty::User
|
||||
} else {
|
||||
JSContactProperty::Uri
|
||||
},
|
||||
[None, None],
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ use crate::{
|
|||
},
|
||||
};
|
||||
use jmap_tools::{Key, Map, Value};
|
||||
use smallvec::smallvec;
|
||||
use std::borrow::Cow;
|
||||
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
|
|
@ -103,6 +104,39 @@ impl EntryState {
|
|||
);
|
||||
}
|
||||
|
||||
pub(super) fn take_text_value_type(&mut self) -> bool {
|
||||
let len = self.entry.params.len();
|
||||
self.entry.params.retain(|param| {
|
||||
param.name != VCardParameterName::Value
|
||||
|| !param.value.as_value_type().is_some_and(|value_type| {
|
||||
value_type.is_iana_and(|v| *v == &VCardValueType::Text)
|
||||
})
|
||||
});
|
||||
self.entry.params.len() != len
|
||||
}
|
||||
|
||||
pub(super) fn move_username_to_value(&mut self) -> bool {
|
||||
if !self
|
||||
.entry
|
||||
.values
|
||||
.iter()
|
||||
.all(|value| matches!(value, VCardValue::Text(text) if text.is_empty()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(position) = self
|
||||
.entry
|
||||
.params
|
||||
.iter()
|
||||
.position(|param| param.name == VCardParameterName::Username)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let param = self.entry.params.remove(position);
|
||||
self.entry.values = smallvec![VCardValue::Text(param.value.into_text().into_owned())];
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn set_map_name(&mut self) {
|
||||
self.map_name = true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "common"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
build = "build.rs"
|
||||
|
||||
|
|
@ -19,10 +19,10 @@ jmap_proto = { path = "../jmap-proto" }
|
|||
sieve-rs = { path = "../sieve", features = ["serde"] }
|
||||
mail-parser = { version = "1.0", features = ["full_encoding"] }
|
||||
mail-builder = { version = "2.0" }
|
||||
mail-auth = { version = "0.15.1", features = ["generate", "arc"] }
|
||||
mail-auth = { version = "0.16.0", features = ["generate", "arc"] }
|
||||
smtp-report = { path = "../smtp-report" }
|
||||
smtp-proto = { path = "../smtp-proto", features = ["rkyv"] }
|
||||
dns-update = { version = "0.6.2" }
|
||||
dns-update = { version = "0.6.3" }
|
||||
calcard = { path = "../calcard", features = ["rkyv"] }
|
||||
ahash = { version = "0.8.12", features = ["serde"] }
|
||||
parking_lot = "0.13.0"
|
||||
|
|
@ -56,7 +56,6 @@ decancer = "4.0.0"
|
|||
unicode-security = "0.1.2"
|
||||
infer = "0.22"
|
||||
bincode = { version = "2.0.1", features = ["serde"] }
|
||||
hostname = "0.4.2"
|
||||
zip = "9.1"
|
||||
xxhash-rust = { version = "0.8.19", features = ["xxh3"] }
|
||||
psl = "2"
|
||||
|
|
@ -93,10 +92,11 @@ libc = "0.2.191"
|
|||
sd-notify = "0.5"
|
||||
|
||||
[target.'cfg(stalwart_tests)'.dependencies]
|
||||
dns-update = { version = "0.6.2", features = ["test_provider"] }
|
||||
dns-update = { version = "0.6.3", features = ["test_provider"] }
|
||||
|
||||
[features]
|
||||
dev_mode = []
|
||||
exchange = ["store/exchange"]
|
||||
enterprise = ["store/enterprise", "utils/enterprise", "trc/enterprise", "telemetry/enterprise", "directory/enterprise", "coordinator/enterprise", "registry/enterprise", "jmap_proto/enterprise"]
|
||||
foundation = []
|
||||
redis = ["store/redis"]
|
||||
|
|
|
|||
|
|
@ -10,7 +10,10 @@ use crate::{
|
|||
auth::{
|
||||
AccessScope, AccessTo, AccessTokenInner, AccountCache, ChangedBy, Permissions,
|
||||
RECOVERY_ADMIN_ID, TokenScope,
|
||||
oauth::scope::{OAuthScopes, scope_data_types},
|
||||
oauth::{
|
||||
scope::{OAuthScopes, scope_data_types},
|
||||
token::assert_credential_version,
|
||||
},
|
||||
permissions::{BuildPermissions, PermissionsListBuilder},
|
||||
},
|
||||
network::limiter::{AccountLimit, AccountLimits, AccountRate, LimiterResult, RateCounter},
|
||||
|
|
@ -20,7 +23,7 @@ use compact_str::format_compact;
|
|||
use registry::{
|
||||
schema::{
|
||||
enums::Permission,
|
||||
structs::{self, Account, Roles, UserRoles},
|
||||
structs::{self, Account, GroupAccount, ResourceAccount, Roles, UserRoles},
|
||||
},
|
||||
types::{EnumImpl, ipmask::IpAddrOrMask},
|
||||
};
|
||||
|
|
@ -185,25 +188,43 @@ impl Server {
|
|||
}
|
||||
.update_size())
|
||||
}
|
||||
Account::Group(account) => {
|
||||
let role_ids = account
|
||||
.roles
|
||||
Account::Group(GroupAccount {
|
||||
roles,
|
||||
permissions,
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
member_tenant_id,
|
||||
// SPDX-SnippetEnd
|
||||
..
|
||||
})
|
||||
| Account::Resource(ResourceAccount {
|
||||
roles,
|
||||
permissions,
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
member_tenant_id,
|
||||
// SPDX-SnippetEnd
|
||||
..
|
||||
}) => {
|
||||
let role_ids = roles
|
||||
.role_ids()
|
||||
.unwrap_or(self.core.network.security.default_role_ids_group.as_slice());
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
let tenant_id = account.member_tenant_id.map(|t| t.id() as u32);
|
||||
let tenant_id = member_tenant_id.map(|t| t.id() as u32);
|
||||
#[cfg(feature = "enterprise")]
|
||||
let permissions = self
|
||||
.effective_permissions(&account.permissions, role_ids, tenant_id)
|
||||
.effective_permissions(&permissions, role_ids, tenant_id)
|
||||
.await?;
|
||||
// SPDX-SnippetEnd
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let permissions = self
|
||||
.effective_permissions(&account.permissions, role_ids)
|
||||
.await?;
|
||||
let permissions = self.effective_permissions(&permissions, role_ids).await?;
|
||||
|
||||
Ok(AccessTokenInner {
|
||||
limits: self.account_limits(),
|
||||
|
|
@ -300,6 +321,14 @@ impl Server {
|
|||
Ok(items)
|
||||
}
|
||||
|
||||
pub fn is_access_token_current(&self, access_token: &AccessToken) -> bool {
|
||||
self.inner
|
||||
.cache
|
||||
.access_tokens
|
||||
.get(&access_token.account_id())
|
||||
.is_some_and(|inner| access_token.is_built_from(&inner))
|
||||
}
|
||||
|
||||
pub async fn access_token(&self, account_id: u32) -> trc::Result<Arc<AccessTokenInner>> {
|
||||
match self
|
||||
.inner
|
||||
|
|
@ -473,6 +502,19 @@ impl AccessToken {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn renew_session(
|
||||
&self,
|
||||
inner: Arc<AccessTokenInner>,
|
||||
token_scope: Option<TokenScope>,
|
||||
remote_ip: IpAddr,
|
||||
) -> trc::Result<Self> {
|
||||
if self.scope_idx == 0 {
|
||||
assert_credential_version(self.inner.credential_version, inner.credential_version)?;
|
||||
}
|
||||
Self::renew(inner, self.credential_id(), token_scope, remote_ip)?
|
||||
.assert_has_permission(Permission::Authenticate)
|
||||
}
|
||||
|
||||
pub fn is_built_from(&self, inner: &Arc<AccessTokenInner>) -> bool {
|
||||
Arc::ptr_eq(&self.inner, inner)
|
||||
}
|
||||
|
|
@ -1147,20 +1189,41 @@ fn hash_account(account: &Account) -> u64 {
|
|||
group_id.hash(&mut s);
|
||||
}
|
||||
}
|
||||
Account::Group(account) => {
|
||||
Account::Group(GroupAccount {
|
||||
roles,
|
||||
permissions,
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
account.member_tenant_id.hash(&mut s);
|
||||
member_tenant_id,
|
||||
// SPDX-SnippetEnd
|
||||
match &account.roles {
|
||||
..
|
||||
})
|
||||
| Account::Resource(ResourceAccount {
|
||||
roles,
|
||||
permissions,
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
member_tenant_id,
|
||||
// SPDX-SnippetEnd
|
||||
..
|
||||
}) => {
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
member_tenant_id.hash(&mut s);
|
||||
// SPDX-SnippetEnd
|
||||
match roles {
|
||||
Roles::Default => {}
|
||||
Roles::Custom(custom_roles) => {
|
||||
custom_roles.role_ids.as_slice().hash(&mut s);
|
||||
}
|
||||
}
|
||||
hash_permissions(&mut s, &account.permissions);
|
||||
hash_permissions(&mut s, permissions);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -398,7 +398,7 @@ impl Server {
|
|||
}
|
||||
|
||||
if token.starts_with(TOKEN_HEADER) {
|
||||
return self.authenticate_oauth_token(token, req.remote_ip).await;
|
||||
return self.authenticate_oauth_token(req, token).await;
|
||||
}
|
||||
|
||||
// Obtain external directory, if any. When no username is supplied
|
||||
|
|
@ -422,13 +422,21 @@ impl Server {
|
|||
}),
|
||||
};
|
||||
let expires_in = external.expires_at.map(|exp| exp.saturating_sub(now()));
|
||||
return self
|
||||
let account_name = CompactString::from(external.account.email.as_str());
|
||||
let access_token = self
|
||||
.build_directory_token(external.account, req.remote_ip)
|
||||
.await
|
||||
.map(|access_token| Authenticated {
|
||||
access_token: access_token.with_token_scope(token_scope),
|
||||
expires_in,
|
||||
});
|
||||
.await?;
|
||||
trc::event!(
|
||||
Auth(trc::AuthEvent::Success),
|
||||
AccountName = account_name,
|
||||
AccountId = access_token.account_id(),
|
||||
SpanId = req.session_id,
|
||||
Details = "Authenticated with external OAuth token",
|
||||
);
|
||||
return Ok(Authenticated {
|
||||
access_token: access_token.with_token_scope(token_scope),
|
||||
expires_in,
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
external_error = Some(err);
|
||||
|
|
@ -437,7 +445,7 @@ impl Server {
|
|||
}
|
||||
|
||||
// Internal OAuth
|
||||
match self.authenticate_oauth_token(token, req.remote_ip).await {
|
||||
match self.authenticate_oauth_token(req, token).await {
|
||||
Ok(authenticated) => Ok(authenticated),
|
||||
Err(err) => {
|
||||
if let Some(external_error) = external_error {
|
||||
|
|
@ -504,8 +512,8 @@ impl Server {
|
|||
|
||||
async fn authenticate_oauth_token(
|
||||
&self,
|
||||
req: &AuthRequest,
|
||||
token: &str,
|
||||
remote_ip: IpAddr,
|
||||
) -> trc::Result<Authenticated> {
|
||||
let token_info = self
|
||||
.decode_access_token(GrantType::AccessToken.into(), token)
|
||||
|
|
@ -527,15 +535,21 @@ impl Server {
|
|||
.oauth_grant_scope(grant.id, token_info.account_id)
|
||||
.await?;
|
||||
|
||||
AccessToken::renew(inner, None, Some(token_scope), remote_ip).map(|access_token| {
|
||||
Authenticated {
|
||||
access_token,
|
||||
expires_in: Some(token_info.expires_in),
|
||||
}
|
||||
let access_token = AccessToken::renew(inner, None, Some(token_scope), req.remote_ip)?;
|
||||
trc::event!(
|
||||
Auth(trc::AuthEvent::Success),
|
||||
AccountId = token_info.account_id,
|
||||
Id = grant.id,
|
||||
SpanId = req.session_id,
|
||||
Details = "Authenticated with OAuth token",
|
||||
);
|
||||
Ok(Authenticated {
|
||||
access_token,
|
||||
expires_in: Some(token_info.expires_in),
|
||||
})
|
||||
}
|
||||
|
||||
async fn impersonated_account_id(&self, username: &Username) -> trc::Result<Option<u32>> {
|
||||
pub async fn impersonated_account_id(&self, username: &Username) -> trc::Result<Option<u32>> {
|
||||
let address = username.address();
|
||||
|
||||
if let Some(account_id) = self.account_id_from_email(address, false).await? {
|
||||
|
|
|
|||
|
|
@ -86,6 +86,8 @@ pub struct DomainCache {
|
|||
|
||||
pub const DOMAIN_FLAG_RELAY: u8 = 1;
|
||||
pub const DOMAIN_FLAG_SUB_ADDRESSING: u8 = 1 << 1;
|
||||
pub const DOMAIN_FLAG_DKIM2_STRICT: u8 = 1 << 3;
|
||||
pub const DOMAIN_FLAG_DNS_MANAGED: u8 = 1 << 4;
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
|
|
@ -136,6 +138,9 @@ impl AccountStorage {
|
|||
}
|
||||
|
||||
pub const ACCOUNT_IS_USER: u64 = 1;
|
||||
pub const ACCOUNT_IS_ROOM: u64 = 1 << 1;
|
||||
pub const ACCOUNT_IS_EQUIPMENT: u64 = 1 << 2;
|
||||
pub(crate) const ACCOUNT_TYPE_MASK: u64 = ACCOUNT_IS_USER | ACCOUNT_IS_ROOM | ACCOUNT_IS_EQUIPMENT;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RoleCache {
|
||||
|
|
|
|||
|
|
@ -429,15 +429,17 @@ impl ResolvedClient {
|
|||
return None;
|
||||
}
|
||||
ResolvedClient::Stateless(meta) => meta.scopes,
|
||||
ResolvedClient::Registered(client) => OAuthScopes::from_registry(client.scopes.iter()),
|
||||
ResolvedClient::Cimd(Some(client)) => client.scopes,
|
||||
ResolvedClient::Registered(client) => {
|
||||
let scopes = OAuthScopes::from_registry(client.scopes.iter());
|
||||
if self.is_verified() {
|
||||
scopes
|
||||
} else {
|
||||
scopes.without(OAuthScopes::FULL)
|
||||
}
|
||||
}
|
||||
ResolvedClient::Cimd(Some(client)) => client.scopes.without(OAuthScopes::FULL),
|
||||
ResolvedClient::Cimd(None) => OAuthScopes::NONE,
|
||||
};
|
||||
let scopes = if self.is_verified() {
|
||||
scopes
|
||||
} else {
|
||||
scopes.without(OAuthScopes::FULL)
|
||||
};
|
||||
Some(scopes | OAuthScopes::ALWAYS_ALLOWED)
|
||||
}
|
||||
|
||||
|
|
@ -459,9 +461,10 @@ impl ResolvedClient {
|
|||
ResolvedClient::Registered(client) | ResolvedClient::RegisteredApplication(client) => {
|
||||
client.grant_types.contains(&grant)
|
||||
}
|
||||
ResolvedClient::Stateless(_)
|
||||
| ResolvedClient::Application(_)
|
||||
| ResolvedClient::Cimd(_) => grant != OAuthGrantType::DeviceCode,
|
||||
ResolvedClient::Stateless(_) => true,
|
||||
ResolvedClient::Application(_) | ResolvedClient::Cimd(_) => {
|
||||
grant != OAuthGrantType::DeviceCode
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,6 +64,17 @@ pub enum GrantRotation {
|
|||
}
|
||||
|
||||
impl StoredOAuthGrant {
|
||||
fn from_object(id: u64, object: Option<Object>) -> Option<Self> {
|
||||
object.and_then(|object| match object.inner {
|
||||
ObjectInner::OAuthGrant(grant) => Some(StoredOAuthGrant {
|
||||
id,
|
||||
revision: object.revision,
|
||||
grant,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn account_id(&self) -> u32 {
|
||||
self.grant.account_id.document_id()
|
||||
}
|
||||
|
|
@ -158,20 +169,19 @@ enum RotationStep {
|
|||
|
||||
impl Server {
|
||||
pub async fn oauth_grant(&self, grant_id: u64) -> trc::Result<Option<StoredOAuthGrant>> {
|
||||
self.registry()
|
||||
.get_fresh(ObjectId::new(ObjectType::OAuthGrant, Id::new(grant_id)))
|
||||
.await
|
||||
.caused_by(trc::location!())
|
||||
.map(|object| StoredOAuthGrant::from_object(grant_id, object))
|
||||
}
|
||||
|
||||
async fn oauth_grant_cached(&self, grant_id: u64) -> trc::Result<Option<StoredOAuthGrant>> {
|
||||
self.registry()
|
||||
.get(ObjectId::new(ObjectType::OAuthGrant, Id::new(grant_id)))
|
||||
.await
|
||||
.caused_by(trc::location!())
|
||||
.map(|object| {
|
||||
object.and_then(|object| match object.inner {
|
||||
ObjectInner::OAuthGrant(grant) => Some(StoredOAuthGrant {
|
||||
id: grant_id,
|
||||
revision: object.revision,
|
||||
grant,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.map(|object| StoredOAuthGrant::from_object(grant_id, object))
|
||||
}
|
||||
|
||||
pub async fn oauth_grant_scope(
|
||||
|
|
@ -179,16 +189,16 @@ impl Server {
|
|||
grant_id: u64,
|
||||
account_id: u32,
|
||||
) -> trc::Result<TokenScope> {
|
||||
if account_id == RECOVERY_ADMIN_ID && grant_id == RECOVERY_ADMIN_GRANT_ID {
|
||||
return Ok(TokenScope::Grant {
|
||||
grant_id,
|
||||
scopes: OAuthScopes::ALL,
|
||||
});
|
||||
}
|
||||
match self.oauth_grant(grant_id).await? {
|
||||
Some(stored) if stored.account_id() == account_id => {
|
||||
Ok(TokenScope::from_grant(grant_id, &stored.grant))
|
||||
}
|
||||
None if account_id == RECOVERY_ADMIN_ID && grant_id == RECOVERY_ADMIN_GRANT_ID => {
|
||||
Ok(TokenScope::Grant {
|
||||
grant_id,
|
||||
scopes: OAuthScopes::ALL,
|
||||
})
|
||||
}
|
||||
_ => Err(trc::AuthEvent::TokenExpired
|
||||
.into_err()
|
||||
.account_id(account_id)
|
||||
|
|
@ -210,7 +220,7 @@ impl Server {
|
|||
}
|
||||
token_scope => token_scope,
|
||||
};
|
||||
AccessToken::renew(inner, access_token.credential_id(), token_scope, remote_ip)
|
||||
access_token.renew_session(inner, token_scope, remote_ip)
|
||||
}
|
||||
|
||||
pub async fn refresh_access_token(
|
||||
|
|
@ -222,13 +232,34 @@ impl Server {
|
|||
if access_token.is_built_from(&inner) {
|
||||
Ok(None)
|
||||
} else {
|
||||
AccessToken::renew(
|
||||
inner,
|
||||
access_token.credential_id(),
|
||||
access_token.token_scope(),
|
||||
remote_ip,
|
||||
)
|
||||
.map(Some)
|
||||
access_token
|
||||
.renew_session(inner, access_token.token_scope(), remote_ip)
|
||||
.map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn assert_session_access(
|
||||
&self,
|
||||
access_token: &AccessToken,
|
||||
remote_ip: StdIpAddr,
|
||||
) -> trc::Result<()> {
|
||||
match self.refresh_access_token(access_token, remote_ip).await {
|
||||
Ok(Some(renewed))
|
||||
if renewed.effective_permissions() != access_token.effective_permissions() =>
|
||||
{
|
||||
Err(trc::SecurityEvent::Unauthorized
|
||||
.into_err()
|
||||
.account_id(access_token.account_id())
|
||||
.reason("Account permissions changed"))
|
||||
}
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) if matches!(err.as_ref(), trc::EventType::Auth(_)) => {
|
||||
Err(trc::SecurityEvent::Unauthorized
|
||||
.into_err()
|
||||
.account_id(access_token.account_id())
|
||||
.caused_by(err))
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -290,7 +321,7 @@ impl Server {
|
|||
|
||||
let mut grants = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
if let Some(stored) = self.oauth_grant(id.id()).await? {
|
||||
if let Some(stored) = self.oauth_grant_cached(id.id()).await? {
|
||||
grants.push(stored);
|
||||
}
|
||||
}
|
||||
|
|
@ -333,13 +364,17 @@ impl Server {
|
|||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
if self.oauth_grant(id.id()).await?.is_some_and(|stored| {
|
||||
let grant = &stored.grant;
|
||||
grant.client_id == client_id
|
||||
&& grant.client_kind == client_kind
|
||||
&& grant.last_used_at.timestamp() > idle_since
|
||||
&& OAuthScopes::from_registry(grant.scopes.iter()).contains(scopes)
|
||||
}) {
|
||||
if self
|
||||
.oauth_grant_cached(id.id())
|
||||
.await?
|
||||
.is_some_and(|stored| {
|
||||
let grant = &stored.grant;
|
||||
grant.client_id == client_id
|
||||
&& grant.client_kind == client_kind
|
||||
&& grant.last_used_at.timestamp() > idle_since
|
||||
&& OAuthScopes::from_registry(grant.scopes.iter()).contains(scopes)
|
||||
})
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -357,7 +392,7 @@ impl Server {
|
|||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
if let Some(stored) = self.oauth_grant(id.id()).await? {
|
||||
if let Some(stored) = self.oauth_grant_cached(id.id()).await? {
|
||||
self.delete_oauth_grant(stored, GrantDeletion::Unconditional, invalidator)
|
||||
.await?;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -412,16 +412,6 @@ pub fn validate_public_client_metadata(
|
|||
));
|
||||
}
|
||||
}
|
||||
if request
|
||||
.grant_types
|
||||
.iter()
|
||||
.any(|grant| grant == GRANT_TYPE_DEVICE_CODE)
|
||||
{
|
||||
return Err(ClientRegistrationError::invalid_client_metadata(
|
||||
"The device_code grant is not available to dynamically registered clients.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -334,6 +334,19 @@ permission_scopes!(
|
|||
SysSpamTrainingSampleCreate,
|
||||
SysSpamTrainingSampleDestroy,
|
||||
SysSpamTrainingSampleQuery,
|
||||
SysMailRuleGet,
|
||||
SysMailRuleCreate,
|
||||
SysMailRuleUpdate,
|
||||
SysMailRuleDestroy,
|
||||
SysMailRuleQuery,
|
||||
SysBlockedSenderGet,
|
||||
SysBlockedSenderCreate,
|
||||
SysBlockedSenderDestroy,
|
||||
SysBlockedSenderQuery,
|
||||
SysSafeSenderGet,
|
||||
SysSafeSenderCreate,
|
||||
SysSafeSenderDestroy,
|
||||
SysSafeSenderQuery,
|
||||
],
|
||||
OAuthScopes::CALENDARS => [
|
||||
CalendarAlarmsSend,
|
||||
|
|
@ -491,6 +504,8 @@ permission_scopes!(
|
|||
OAuthScopes::SETTINGS => [
|
||||
SysAccountSettingsGet,
|
||||
SysAccountSettingsUpdate,
|
||||
SysCalendarSettingsGet,
|
||||
SysCalendarSettingsUpdate,
|
||||
SysPublicKeyGet,
|
||||
SysPublicKeyCreate,
|
||||
SysPublicKeyUpdate,
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ use ahash::AHashSet;
|
|||
use registry::{
|
||||
schema::{
|
||||
enums::Permission,
|
||||
structs::{self, Account, PermissionsList, UserRoles},
|
||||
structs::{self, Account, GroupAccount, PermissionsList, ResourceAccount, UserRoles},
|
||||
},
|
||||
types::EnumImpl,
|
||||
};
|
||||
|
|
@ -136,10 +136,14 @@ impl Server {
|
|||
UserRoles::Custom(custom_roles) => custom_roles.role_ids.as_slice(),
|
||||
},
|
||||
),
|
||||
Account::Group(account) => (
|
||||
&account.permissions,
|
||||
account
|
||||
.roles
|
||||
Account::Group(GroupAccount {
|
||||
permissions, roles, ..
|
||||
})
|
||||
| Account::Resource(ResourceAccount {
|
||||
permissions, roles, ..
|
||||
}) => (
|
||||
permissions,
|
||||
roles
|
||||
.role_ids()
|
||||
.unwrap_or(self.core.network.security.default_role_ids_group.as_slice()),
|
||||
),
|
||||
|
|
@ -152,6 +156,7 @@ impl Server {
|
|||
let tenant_id = match account {
|
||||
Account::User(account) => account.member_tenant_id.map(|t| t.document_id()),
|
||||
Account::Group(account) => account.member_tenant_id.map(|t| t.document_id()),
|
||||
Account::Resource(account) => account.member_tenant_id.map(|t| t.document_id()),
|
||||
};
|
||||
#[cfg(feature = "enterprise")]
|
||||
let permissions = self
|
||||
|
|
@ -332,7 +337,11 @@ impl Default for DefaultPermissions {
|
|||
} else if name.starts_with("sysMaskedEmail")
|
||||
|| name.starts_with("sysArchivedItem")
|
||||
|| name.starts_with("sysAccountSettings")
|
||||
|| name.starts_with("sysCalendarSettings")
|
||||
|| name.starts_with("sysPublicKey")
|
||||
|| name.starts_with("sysMailRule")
|
||||
|| name.starts_with("sysBlockedSender")
|
||||
|| name.starts_with("sysSafeSender")
|
||||
|| (name.starts_with("sysSpamTrainingSample") && !name.contains("Create"))
|
||||
{
|
||||
default.user.push(permission);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
*/
|
||||
|
||||
use crate::auth::AccessToken;
|
||||
use crate::network::ip_to_bytes;
|
||||
use crate::network::ip_rate_key;
|
||||
use crate::network::limiter::{
|
||||
AccountLimits, AccountRate, InFlight, LimiterResult, RateCounter, RateHit,
|
||||
};
|
||||
|
|
@ -141,7 +141,7 @@ impl Server {
|
|||
.core
|
||||
.storage
|
||||
.memory
|
||||
.is_rate_allowed(KV_RATE_LIMIT_HTTP_ANONYMOUS, &ip_to_bytes(&addr), rate)
|
||||
.is_rate_allowed(KV_RATE_LIMIT_HTTP_ANONYMOUS, &ip_rate_key(&addr), rate)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
|
|
|
|||
72
crates/common/src/cache/directory.rs
vendored
72
crates/common/src/cache/directory.rs
vendored
|
|
@ -18,6 +18,12 @@ use registry::{
|
|||
};
|
||||
use std::sync::Arc;
|
||||
use store::registry::write::{RegistryWrite, RegistryWriteResult};
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
use registry::schema::enums::TenantStorageQuota;
|
||||
// SPDX-SnippetEnd
|
||||
use trc::AddContext;
|
||||
use types::id::Id;
|
||||
|
||||
|
|
@ -213,6 +219,9 @@ impl Server {
|
|||
))
|
||||
.ctx(trc::Key::Domain, CompactString::from(domain.name())));
|
||||
}
|
||||
#[cfg(feature = "enterprise")]
|
||||
self.assert_can_provision(&domain, TenantStorageQuota::MaxAccounts)
|
||||
.await?;
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
let mut aliases = Vec::with_capacity(account.email_aliases.len());
|
||||
|
|
@ -268,17 +277,6 @@ impl Server {
|
|||
..Default::default()
|
||||
}));
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
if self.core.is_enterprise_edition() && !self.can_create_account().await? {
|
||||
return Err(trc::AuthEvent::Error.into_err().details(
|
||||
"Account creation not possible: license key account limit reached",
|
||||
));
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
match self
|
||||
.registry()
|
||||
.write(RegistryWrite::insert(&account))
|
||||
|
|
@ -321,7 +319,7 @@ impl Server {
|
|||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
Some(account) if !account.is_user_account() => Ok(account_id),
|
||||
Some(account) if account.is_group_account() => Ok(account_id),
|
||||
Some(_) => Err(trc::AuthEvent::Error
|
||||
.into_err()
|
||||
.details("Account ID from directory does not correspond to a group account")
|
||||
|
|
@ -450,6 +448,9 @@ impl Server {
|
|||
))
|
||||
.ctx(trc::Key::Domain, CompactString::from(domain.name())));
|
||||
}
|
||||
#[cfg(feature = "enterprise")]
|
||||
self.assert_can_provision(&domain, TenantStorageQuota::MaxGroups)
|
||||
.await?;
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
let mut aliases = Vec::with_capacity(group.email_aliases.len());
|
||||
|
|
@ -486,17 +487,6 @@ impl Server {
|
|||
..Default::default()
|
||||
}));
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
if self.core.is_enterprise_edition() && !self.can_create_account().await? {
|
||||
return Err(trc::AuthEvent::Error.into_err().details(
|
||||
"Account creation not possible: license key account limit reached",
|
||||
));
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
match self
|
||||
.registry()
|
||||
.write(RegistryWrite::insert(&account))
|
||||
|
|
@ -522,6 +512,42 @@ impl Server {
|
|||
}
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
async fn assert_can_provision(
|
||||
&self,
|
||||
domain: &DomainCache,
|
||||
quota: TenantStorageQuota,
|
||||
) -> trc::Result<()> {
|
||||
if !self.core.is_enterprise_edition() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.can_create_account().await? {
|
||||
return Err(trc::AuthEvent::Error
|
||||
.into_err()
|
||||
.details("Account creation not possible: license key account limit reached"));
|
||||
}
|
||||
if let Some(tenant_id) = domain.id_tenant
|
||||
&& let Some(reached) = self
|
||||
.tenant_quota_reached(tenant_id, quota)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
return Err(trc::AuthEvent::Error
|
||||
.into_err()
|
||||
.details(format!(
|
||||
"Account creation not possible: tenant quota of {} {} reached",
|
||||
reached.limit, reached.objects
|
||||
))
|
||||
.ctx(trc::Key::Domain, CompactString::from(domain.name()))
|
||||
.ctx(trc::Key::Limit, reached.limit));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
async fn validate_address<'x>(
|
||||
&self,
|
||||
email: &'x str,
|
||||
|
|
|
|||
350
crates/common/src/cache/exchange.rs
vendored
Normal file
350
crates/common/src/cache/exchange.rs
vendored
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{UpdateLock, Verification};
|
||||
use ahash::AHashMap;
|
||||
use arc_swap::ArcSwapOption;
|
||||
use std::sync::Arc;
|
||||
use store::{roaring::RoaringBitmap, write::metadata::ExchangeFolder};
|
||||
use types::collection::Collection;
|
||||
use utils::cache::CacheItemWeight;
|
||||
|
||||
pub const EXCHANGE_GROUPS: usize = 4;
|
||||
const CONTAINER_META_WEIGHT: u64 = 64;
|
||||
const CONTAINER_ENTRY_WEIGHT: u64 = 48;
|
||||
const CATEGORY_WEIGHT: u64 = 32;
|
||||
pub const MAX_FOREIGN_REPLICAS: usize = 1024;
|
||||
pub const FIRST_FOREIGN_REPLID: u16 = 2;
|
||||
|
||||
pub fn foreign_replica_id(replicas: &[[u8; 16]], guid: &[u8; 16]) -> Option<u16> {
|
||||
replicas
|
||||
.iter()
|
||||
.position(|known| known == guid)
|
||||
.and_then(foreign_replid)
|
||||
}
|
||||
|
||||
pub fn foreign_replid(index: usize) -> Option<u16> {
|
||||
u16::try_from(index).ok()?.checked_add(FIRST_FOREIGN_REPLID)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Placement {
|
||||
pub container: u32,
|
||||
pub item: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct FolderKey {
|
||||
pub kind: u8,
|
||||
pub id: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct GroupwareDocument {
|
||||
kind: u8,
|
||||
document_id: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct GroupwarePlacement {
|
||||
pub folder: FolderKey,
|
||||
pub item: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct GroupwareAliases {
|
||||
placements: AHashMap<GroupwareDocument, GroupwarePlacement>,
|
||||
documents: AHashMap<GroupwarePlacement, u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExchangeDevice {
|
||||
pub slot: u16,
|
||||
pub device_id: Box<str>,
|
||||
pub device_type: Box<str>,
|
||||
pub policy_key: u32,
|
||||
pub wipe: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct NamedPropertyTable {
|
||||
pub names: Vec<Box<[u8]>>,
|
||||
pub ids: AHashMap<Box<[u8]>, u16>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct CategoryTable {
|
||||
entries: Box<[(Box<str>, Box<str>)]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExchangeAccountCache {
|
||||
pub store_instance: u64,
|
||||
pub objects_epoch: u64,
|
||||
pub objects: Arc<[(Collection, RoaringBitmap)]>,
|
||||
pub aliases: Arc<AHashMap<u32, Placement>>,
|
||||
pub aliased: Arc<AHashMap<Placement, u32>>,
|
||||
pub groupware_aliases: Arc<GroupwareAliases>,
|
||||
pub folder_aliases: Arc<AHashMap<FolderKey, u32>>,
|
||||
pub folder_aliased: Arc<AHashMap<u32, FolderKey>>,
|
||||
pub replicas: Arc<[[u8; 16]]>,
|
||||
pub named: Arc<NamedPropertyTable>,
|
||||
pub categories_version: u32,
|
||||
pub categories: Arc<CategoryTable>,
|
||||
pub devices: Arc<[ExchangeDevice]>,
|
||||
pub folder_change_ids: Arc<AHashMap<FolderKey, u64>>,
|
||||
pub folder_base: [u64; EXCHANGE_GROUPS],
|
||||
pub change_ids: [u64; EXCHANGE_GROUPS],
|
||||
pub exchange_change: u64,
|
||||
pub revision: u64,
|
||||
pub verification: Verification,
|
||||
pub update_lock: Arc<UpdateLock>,
|
||||
pub containers: Arc<ArcSwapOption<ContainerMeta>>,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ContainerMeta {
|
||||
pub calendar_change_id: u64,
|
||||
pub address_book_change_id: u64,
|
||||
pub entries: Box<[ContainerEntry]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContainerEntry {
|
||||
pub kind: u8,
|
||||
pub id: u32,
|
||||
pub components: u8,
|
||||
pub parent: ExchangeFolder,
|
||||
pub name: Box<str>,
|
||||
}
|
||||
|
||||
impl ContainerMeta {
|
||||
pub fn size(&self) -> u64 {
|
||||
self.entries
|
||||
.iter()
|
||||
.map(|entry| entry.name.len() as u64 + CONTAINER_ENTRY_WEIGHT)
|
||||
.sum::<u64>()
|
||||
+ CONTAINER_META_WEIGHT
|
||||
}
|
||||
}
|
||||
|
||||
impl NamedPropertyTable {
|
||||
pub fn from_names(names: &[Vec<u8>]) -> Self {
|
||||
let mut table = NamedPropertyTable {
|
||||
names: Vec::with_capacity(names.len()),
|
||||
ids: AHashMap::with_capacity(names.len()),
|
||||
};
|
||||
for name in names {
|
||||
table.push(name.as_slice().into());
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
pub fn push(&mut self, name: Box<[u8]>) {
|
||||
if let Ok(index) = u16::try_from(self.names.len()) {
|
||||
self.ids.insert(name.clone(), index);
|
||||
self.names.push(name);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(&self) -> u64 {
|
||||
self.names
|
||||
.iter()
|
||||
.map(|name| (name.len() as u64 * 2) + 48)
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
|
||||
impl GroupwareAliases {
|
||||
pub fn insert(&mut self, document_id: u32, placement: GroupwarePlacement) {
|
||||
let document = GroupwareDocument {
|
||||
kind: placement.folder.kind,
|
||||
document_id,
|
||||
};
|
||||
if let Some(previous) = self.placements.insert(document, placement) {
|
||||
self.forget(previous, document_id);
|
||||
}
|
||||
self.documents.insert(placement, document_id);
|
||||
}
|
||||
|
||||
pub fn document(&self, placement: GroupwarePlacement) -> Option<u32> {
|
||||
self.documents.get(&placement).copied()
|
||||
}
|
||||
|
||||
pub fn placement(&self, kind: u8, document_id: u32) -> Option<GroupwarePlacement> {
|
||||
self.placements
|
||||
.get(&GroupwareDocument { kind, document_id })
|
||||
.copied()
|
||||
}
|
||||
|
||||
pub fn holds_any(&self, kind: u8, document_ids: &RoaringBitmap) -> bool {
|
||||
!self.placements.is_empty()
|
||||
&& document_ids
|
||||
.iter()
|
||||
.any(|document_id| self.placement(kind, document_id).is_some())
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, kind: u8, document_ids: &RoaringBitmap) {
|
||||
for document_id in document_ids {
|
||||
if let Some(placement) = self
|
||||
.placements
|
||||
.remove(&GroupwareDocument { kind, document_id })
|
||||
{
|
||||
self.forget(placement, document_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn forget(&mut self, placement: GroupwarePlacement, document_id: u32) {
|
||||
if self.documents.get(&placement) == Some(&document_id) {
|
||||
self.documents.remove(&placement);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.placements.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.placements.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl CategoryTable {
|
||||
pub fn new(entries: impl IntoIterator<Item = (Box<str>, Box<str>)>) -> Self {
|
||||
let mut entries = entries.into_iter().collect::<Vec<_>>();
|
||||
entries.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
|
||||
entries.dedup_by(|(a, _), (b, _)| a == b);
|
||||
CategoryTable {
|
||||
entries: entries.into_boxed_slice(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spelling(&self, keyword: &str) -> Option<&str> {
|
||||
self.entries
|
||||
.binary_search_by(|(entry, _)| (**entry).cmp(keyword))
|
||||
.ok()
|
||||
.and_then(|index| self.entries.get(index))
|
||||
.map(|(_, name)| &**name)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
pub fn size(&self) -> u64 {
|
||||
self.entries
|
||||
.iter()
|
||||
.map(|(keyword, name)| (keyword.len() + name.len()) as u64 + CATEGORY_WEIGHT)
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExchangeAccountCache {
|
||||
pub fn objects(&self, collection: Collection) -> Option<&RoaringBitmap> {
|
||||
self.objects
|
||||
.iter()
|
||||
.find(|(c, _)| *c == collection)
|
||||
.map(|(_, ids)| ids)
|
||||
}
|
||||
|
||||
pub fn has_object(&self, collection: Collection, document_id: u32) -> bool {
|
||||
self.objects(collection)
|
||||
.is_some_and(|ids| ids.contains(document_id))
|
||||
}
|
||||
|
||||
pub fn alias_of(&self, document_id: u32) -> Option<Placement> {
|
||||
self.aliases.get(&document_id).copied()
|
||||
}
|
||||
|
||||
pub fn resolve_alias(&self, placement: Placement) -> Option<u32> {
|
||||
self.aliased.get(&placement).copied()
|
||||
}
|
||||
|
||||
pub fn email_document(&self, container: u32, item: u32) -> u32 {
|
||||
if self.aliased.is_empty() {
|
||||
item
|
||||
} else {
|
||||
self.resolve_alias(Placement { container, item })
|
||||
.unwrap_or(item)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn email_item(&self, container: u32, document_id: u32) -> u32 {
|
||||
if self.aliases.is_empty() {
|
||||
document_id
|
||||
} else {
|
||||
self.alias_of(document_id)
|
||||
.filter(|placement| placement.container == container)
|
||||
.map_or(document_id, |placement| placement.item)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn groupware_document(&self, folder: FolderKey, item: u32) -> Option<u32> {
|
||||
self.groupware_aliases
|
||||
.document(GroupwarePlacement { folder, item })
|
||||
}
|
||||
|
||||
pub fn groupware_item(&self, folder: FolderKey, document_id: u32) -> Option<u32> {
|
||||
self.groupware_aliases
|
||||
.placement(folder.kind, document_id)
|
||||
.filter(|placement| placement.folder == folder)
|
||||
.map(|placement| placement.item)
|
||||
}
|
||||
|
||||
pub fn folder_client_key(&self, folder: FolderKey) -> Option<u32> {
|
||||
self.folder_aliases.get(&folder).copied()
|
||||
}
|
||||
|
||||
pub fn resolve_folder_key(&self, client_key: u32) -> Option<FolderKey> {
|
||||
self.folder_aliased.get(&client_key).copied()
|
||||
}
|
||||
|
||||
pub fn replica_id(&self, guid: &[u8; 16]) -> Option<u16> {
|
||||
foreign_replica_id(&self.replicas, guid)
|
||||
}
|
||||
|
||||
pub fn replica_guid(&self, replid: u16) -> Option<&[u8; 16]> {
|
||||
replid
|
||||
.checked_sub(FIRST_FOREIGN_REPLID)
|
||||
.and_then(|index| self.replicas.get(usize::from(index)))
|
||||
}
|
||||
|
||||
pub fn device(&self, device_id: &str) -> Option<&ExchangeDevice> {
|
||||
self.devices
|
||||
.iter()
|
||||
.find(|device| &*device.device_id == device_id)
|
||||
}
|
||||
|
||||
pub fn containers(
|
||||
&self,
|
||||
calendar_change_id: u64,
|
||||
address_book_change_id: u64,
|
||||
) -> Option<Arc<ContainerMeta>> {
|
||||
self.containers.load_full().filter(|meta| {
|
||||
meta.calendar_change_id == calendar_change_id
|
||||
&& meta.address_book_change_id == address_book_change_id
|
||||
})
|
||||
}
|
||||
|
||||
pub fn publish_containers(&self, meta: Arc<ContainerMeta>) {
|
||||
self.containers.store(Some(meta));
|
||||
}
|
||||
|
||||
pub fn folder_change_id(&self, folder: FolderKey) -> Option<u64> {
|
||||
self.folder_change_ids
|
||||
.get(&folder)
|
||||
.or_else(|| self.folder_base.get(usize::from(folder.kind)))
|
||||
.copied()
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheItemWeight for ExchangeAccountCache {
|
||||
fn weight(&self) -> u64 {
|
||||
self.size
|
||||
}
|
||||
}
|
||||
266
crates/common/src/cache/exchange_sessions.rs
vendored
Normal file
266
crates/common/src/cache/exchange_sessions.rs
vendored
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use ahash::AHashMap;
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
mem,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use store::write::now;
|
||||
|
||||
pub const EXCHANGE_SESSIONS_MAX: usize = 16_384;
|
||||
pub const EXCHANGE_SESSIONS_MAX_PER_KIND: usize = 32;
|
||||
const SWEEP_INTERVAL: u64 = 60;
|
||||
|
||||
pub type ExchangeSessionValue = Arc<dyn Any + Send + Sync>;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ExchangeSessionLimit {
|
||||
Node,
|
||||
Account,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Overflow {
|
||||
Refuse,
|
||||
EvictEarliest,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ExchangeSessions(Mutex<SessionTable>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct SessionTable {
|
||||
accounts: AHashMap<u32, Vec<SessionEntry>>,
|
||||
len: usize,
|
||||
swept_at: u64,
|
||||
}
|
||||
|
||||
struct SessionEntry {
|
||||
id: u128,
|
||||
kind: TypeId,
|
||||
value: ExchangeSessionValue,
|
||||
expires: u64,
|
||||
ttl: u64,
|
||||
}
|
||||
|
||||
impl ExchangeSessions {
|
||||
pub fn insert(
|
||||
&self,
|
||||
account_id: u32,
|
||||
id: u128,
|
||||
value: ExchangeSessionValue,
|
||||
ttl: Duration,
|
||||
) -> Result<(), ExchangeSessionLimit> {
|
||||
let mut evicted = Vec::new();
|
||||
let result =
|
||||
self.0
|
||||
.lock()
|
||||
.insert(account_id, id, value, ttl_secs(ttl), now(), &mut evicted);
|
||||
drop(evicted);
|
||||
result
|
||||
}
|
||||
|
||||
pub fn insert_evicting(
|
||||
&self,
|
||||
account_id: u32,
|
||||
id: u128,
|
||||
value: ExchangeSessionValue,
|
||||
ttl: Duration,
|
||||
) -> Result<(), ExchangeSessionLimit> {
|
||||
let mut evicted = Vec::new();
|
||||
let result = self.0.lock().insert_evicting(
|
||||
account_id,
|
||||
id,
|
||||
value,
|
||||
ttl_secs(ttl),
|
||||
now(),
|
||||
&mut evicted,
|
||||
);
|
||||
drop(evicted);
|
||||
result
|
||||
}
|
||||
|
||||
pub fn get<T: Any + Send + Sync>(&self, account_id: u32, id: u128) -> Option<Arc<T>> {
|
||||
let mut evicted = Vec::new();
|
||||
let result = self.0.lock().get(account_id, id, now(), &mut evicted);
|
||||
drop(evicted);
|
||||
result
|
||||
}
|
||||
|
||||
pub fn remove<T: Any + Send + Sync>(
|
||||
&self,
|
||||
account_id: u32,
|
||||
id: u128,
|
||||
) -> Option<ExchangeSessionValue> {
|
||||
self.0.lock().take(account_id, id, TypeId::of::<T>())
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionTable {
|
||||
fn insert(
|
||||
&mut self,
|
||||
account_id: u32,
|
||||
id: u128,
|
||||
value: ExchangeSessionValue,
|
||||
ttl: u64,
|
||||
now: u64,
|
||||
evicted: &mut Vec<ExchangeSessionValue>,
|
||||
) -> Result<(), ExchangeSessionLimit> {
|
||||
let entry = SessionEntry::new(id, value, ttl, now);
|
||||
self.store(account_id, entry, now, Overflow::Refuse, evicted)
|
||||
}
|
||||
|
||||
fn insert_evicting(
|
||||
&mut self,
|
||||
account_id: u32,
|
||||
id: u128,
|
||||
value: ExchangeSessionValue,
|
||||
ttl: u64,
|
||||
now: u64,
|
||||
evicted: &mut Vec<ExchangeSessionValue>,
|
||||
) -> Result<(), ExchangeSessionLimit> {
|
||||
let entry = SessionEntry::new(id, value, ttl, now);
|
||||
self.store(account_id, entry, now, Overflow::EvictEarliest, evicted)
|
||||
}
|
||||
|
||||
fn store(
|
||||
&mut self,
|
||||
account_id: u32,
|
||||
entry: SessionEntry,
|
||||
now: u64,
|
||||
overflow: Overflow,
|
||||
evicted: &mut Vec<ExchangeSessionValue>,
|
||||
) -> Result<(), ExchangeSessionLimit> {
|
||||
let sweep_at = self.swept_at.saturating_add(SWEEP_INTERVAL);
|
||||
if now >= sweep_at || (self.len >= EXCHANGE_SESSIONS_MAX && now > self.swept_at) {
|
||||
self.sweep(now, evicted);
|
||||
}
|
||||
|
||||
let (id, kind) = (entry.id, entry.kind);
|
||||
if let Some(entries) = self.accounts.get_mut(&account_id) {
|
||||
if let Some(existing) = entries
|
||||
.iter_mut()
|
||||
.find(|entry| entry.id == id && entry.kind == kind)
|
||||
{
|
||||
evicted.push(mem::replace(existing, entry).value);
|
||||
return Ok(());
|
||||
}
|
||||
if kind_count(entries, kind) >= EXCHANGE_SESSIONS_MAX_PER_KIND {
|
||||
let before = evicted.len();
|
||||
evicted.extend(
|
||||
entries
|
||||
.extract_if(.., |entry| entry.expires <= now)
|
||||
.map(|entry| entry.value),
|
||||
);
|
||||
self.len -= evicted.len() - before;
|
||||
if kind_count(entries, kind) >= EXCHANGE_SESSIONS_MAX_PER_KIND {
|
||||
let earliest = match overflow {
|
||||
Overflow::Refuse => None,
|
||||
Overflow::EvictEarliest => entries
|
||||
.iter_mut()
|
||||
.filter(|entry| entry.kind == kind)
|
||||
.min_by_key(|entry| entry.expires),
|
||||
};
|
||||
let Some(earliest) = earliest else {
|
||||
evicted.push(entry.value);
|
||||
return Err(ExchangeSessionLimit::Account);
|
||||
};
|
||||
evicted.push(mem::replace(earliest, entry).value);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.len >= EXCHANGE_SESSIONS_MAX {
|
||||
evicted.push(entry.value);
|
||||
return Err(ExchangeSessionLimit::Node);
|
||||
}
|
||||
|
||||
self.accounts.entry(account_id).or_default().push(entry);
|
||||
self.len += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get<T: Any + Send + Sync>(
|
||||
&mut self,
|
||||
account_id: u32,
|
||||
id: u128,
|
||||
now: u64,
|
||||
evicted: &mut Vec<ExchangeSessionValue>,
|
||||
) -> Option<Arc<T>> {
|
||||
let kind = TypeId::of::<T>();
|
||||
let entry = self
|
||||
.accounts
|
||||
.get_mut(&account_id)?
|
||||
.iter_mut()
|
||||
.find(|entry| entry.id == id && entry.kind == kind)?;
|
||||
if entry.expires > now {
|
||||
let value = entry.value.clone().downcast::<T>().ok()?;
|
||||
entry.expires = now.saturating_add(entry.ttl);
|
||||
return Some(value);
|
||||
}
|
||||
evicted.extend(self.take(account_id, id, kind));
|
||||
None
|
||||
}
|
||||
|
||||
fn take(&mut self, account_id: u32, id: u128, kind: TypeId) -> Option<ExchangeSessionValue> {
|
||||
let entries = self.accounts.get_mut(&account_id)?;
|
||||
let position = entries
|
||||
.iter()
|
||||
.position(|entry| entry.id == id && entry.kind == kind)?;
|
||||
let entry = entries.swap_remove(position);
|
||||
if entries.is_empty() {
|
||||
self.accounts.remove(&account_id);
|
||||
}
|
||||
self.len -= 1;
|
||||
Some(entry.value)
|
||||
}
|
||||
|
||||
fn sweep(&mut self, now: u64, evicted: &mut Vec<ExchangeSessionValue>) {
|
||||
let mut len = 0;
|
||||
self.accounts.retain(|_, entries| {
|
||||
evicted.extend(
|
||||
entries
|
||||
.extract_if(.., |entry| entry.expires <= now)
|
||||
.map(|entry| entry.value),
|
||||
);
|
||||
len += entries.len();
|
||||
!entries.is_empty()
|
||||
});
|
||||
self.len = len;
|
||||
self.swept_at = now;
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionEntry {
|
||||
fn new(id: u128, value: ExchangeSessionValue, ttl: u64, now: u64) -> Self {
|
||||
SessionEntry {
|
||||
id,
|
||||
kind: Any::type_id(value.as_ref()),
|
||||
value,
|
||||
expires: now.saturating_add(ttl),
|
||||
ttl,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ttl_secs(ttl: Duration) -> u64 {
|
||||
ttl.as_secs()
|
||||
.saturating_add(u64::from(ttl.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
}
|
||||
|
||||
fn kind_count(entries: &[SessionEntry], kind: TypeId) -> usize {
|
||||
entries.iter().filter(|entry| entry.kind == kind).count()
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/common/src/cache/exchange_sessions/tests.rs"]
|
||||
mod tests;
|
||||
52
crates/common/src/cache/invalidate.rs
vendored
52
crates/common/src/cache/invalidate.rs
vendored
|
|
@ -14,7 +14,7 @@ use ahash::AHashSet;
|
|||
use registry::{
|
||||
schema::{
|
||||
prelude::{Object, ObjectInner, ObjectType, Property},
|
||||
structs::{Account, Credential, EmailAlias},
|
||||
structs::{Account, Credential, DnsManagement, EmailAlias},
|
||||
},
|
||||
types::{id::ObjectId, list::List},
|
||||
};
|
||||
|
|
@ -193,6 +193,49 @@ impl CacheInvalidationBuilder {
|
|||
}
|
||||
}
|
||||
|
||||
(ObjectInner::Account(current), ObjectInner::Account(new))
|
||||
if let (Account::Resource(current), Account::Resource(new)) =
|
||||
(current.as_ref(), new.as_ref()) =>
|
||||
{
|
||||
let was_renamed =
|
||||
(current.name != new.name) || (current.domain_id != new.domain_id);
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
let tenant_changed = current.member_tenant_id != new.member_tenant_id;
|
||||
// SPDX-SnippetEnd
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let tenant_changed = false;
|
||||
let aliases_changed = current.aliases != new.aliases;
|
||||
|
||||
if was_renamed
|
||||
|| aliases_changed
|
||||
|| tenant_changed
|
||||
|| current.kind != new.kind
|
||||
|| current.quotas != new.quotas
|
||||
|| current.locale != new.locale
|
||||
|| current.description != new.description
|
||||
{
|
||||
self.invalidate(CacheInvalidation::Account(id));
|
||||
}
|
||||
|
||||
if was_renamed || aliases_changed {
|
||||
self.invalidate_negative_email(&new_object.inner);
|
||||
}
|
||||
|
||||
if tenant_changed
|
||||
|| current.roles != new.roles
|
||||
|| current.permissions != new.permissions
|
||||
{
|
||||
self.invalidate(CacheInvalidation::AccessToken(id));
|
||||
}
|
||||
|
||||
if was_renamed {
|
||||
self.invalidate(CacheInvalidation::GroupwareResources(id));
|
||||
}
|
||||
}
|
||||
|
||||
(ObjectInner::Domain(current), ObjectInner::Domain(new)) => {
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
|
|
@ -210,6 +253,10 @@ impl CacheInvalidationBuilder {
|
|||
|| (current.catch_all_address != new.catch_all_address)
|
||||
|| (current.sub_addressing != new.sub_addressing)
|
||||
|| (current.allow_relaying != new.allow_relaying)
|
||||
|| (current.dns_management.allows_subdomain_signing()
|
||||
!= new.dns_management.allows_subdomain_signing())
|
||||
|| (matches!(current.dns_management, DnsManagement::Automatic(_))
|
||||
!= matches!(new.dns_management, DnsManagement::Automatic(_)))
|
||||
|| (current.enable != new.enable)
|
||||
{
|
||||
self.invalidate(CacheInvalidation::Domain(id));
|
||||
|
|
@ -383,6 +430,7 @@ impl CacheInvalidationBuilder {
|
|||
ObjectInner::Account(account) => match account.as_ref() {
|
||||
Account::User(account) => (&account.name, account.domain_id, &account.aliases),
|
||||
Account::Group(account) => (&account.name, account.domain_id, &account.aliases),
|
||||
Account::Resource(account) => (&account.name, account.domain_id, &account.aliases),
|
||||
},
|
||||
ObjectInner::MailingList(list) => (&list.name, list.domain_id, &list.aliases),
|
||||
_ => return,
|
||||
|
|
@ -431,7 +479,7 @@ impl Server {
|
|||
) {
|
||||
changes.invalidate(CacheInvalidation::AccessToken(grantee_id));
|
||||
let result = match self.try_account(grantee_id).await {
|
||||
Ok(Some(grantee)) if !grantee.is_user_account() => self
|
||||
Ok(Some(grantee)) if grantee.is_group_account() => self
|
||||
.registry()
|
||||
.query::<RoaringBitmap>(
|
||||
RegistryQuery::new(ObjectType::Account)
|
||||
|
|
|
|||
8
crates/common/src/cache/mod.rs
vendored
8
crates/common/src/cache/mod.rs
vendored
|
|
@ -18,6 +18,10 @@ use utils::cache::CacheItemWeight;
|
|||
|
||||
pub mod directory;
|
||||
pub mod email;
|
||||
#[cfg(feature = "exchange")]
|
||||
pub mod exchange;
|
||||
#[cfg(feature = "exchange")]
|
||||
pub mod exchange_sessions;
|
||||
pub mod http_auth;
|
||||
pub mod invalidate;
|
||||
pub mod large;
|
||||
|
|
@ -122,6 +126,10 @@ impl Verification {
|
|||
pub fn is_verified_since(&self, epoch: u64, revalidate: &RevalidateInterval) -> bool {
|
||||
self.epoch >= epoch && revalidate.is_within(self.verified_at)
|
||||
}
|
||||
|
||||
pub fn is_verified_after(&self, verified_at: u64) -> bool {
|
||||
self.verified_at > verified_at
|
||||
}
|
||||
}
|
||||
|
||||
impl MessageStoreCache {
|
||||
|
|
|
|||
234
crates/common/src/cache/principals.rs
vendored
234
crates/common/src/cache/principals.rs
vendored
|
|
@ -7,9 +7,10 @@
|
|||
use crate::{
|
||||
Server,
|
||||
auth::{
|
||||
ACCOUNT_IS_USER, AccountCache, AccountInfo, AccountStorage, ChangedBy, DOMAIN_FLAG_RELAY,
|
||||
DOMAIN_FLAG_SUB_ADDRESSING, DomainCache, EmailAddress, EmailAddressRef, EmailCache,
|
||||
MailingListCache, PermissionsGroup, RECOVERY_ADMIN_ID, RoleCache,
|
||||
ACCOUNT_IS_EQUIPMENT, ACCOUNT_IS_ROOM, ACCOUNT_IS_USER, ACCOUNT_TYPE_MASK, AccountCache,
|
||||
AccountInfo, AccountStorage, ChangedBy, DOMAIN_FLAG_DKIM2_STRICT, DOMAIN_FLAG_DNS_MANAGED,
|
||||
DOMAIN_FLAG_RELAY, DOMAIN_FLAG_SUB_ADDRESSING, DomainCache, EmailAddress, EmailAddressRef,
|
||||
EmailCache, MailingListCache, PermissionsGroup, RECOVERY_ADMIN_ID, RoleCache,
|
||||
permissions::BuildPermissions,
|
||||
},
|
||||
config::smtp::auth::DkimSigners,
|
||||
|
|
@ -34,14 +35,14 @@ use registry::schema::{
|
|||
use compact_str::{CompactString, ToCompactString};
|
||||
use registry::{
|
||||
schema::{
|
||||
enums::{DkimRotationStage, Locale, StorageQuota},
|
||||
enums::{DkimRotationStage, Locale, ResourceKind, StorageQuota},
|
||||
prelude::{ObjectType, Property},
|
||||
structs::{
|
||||
Account, DkimSignature, Domain, EncryptionAtRest, EncryptionSettings, MailingList,
|
||||
MaskedEmail, PublicKey, Role, SubAddressing,
|
||||
Account, DkimSignature, DnsManagement, Domain, EmailAlias, EncryptionAtRest,
|
||||
EncryptionSettings, MailingList, MaskedEmail, PublicKey, Role, SubAddressing,
|
||||
},
|
||||
},
|
||||
types::id::ObjectId,
|
||||
types::{id::ObjectId, list::List},
|
||||
};
|
||||
use std::{borrow::Cow, sync::Arc};
|
||||
use store::{
|
||||
|
|
@ -51,7 +52,7 @@ use store::{
|
|||
};
|
||||
use trc::{AddContext, CacheEvent};
|
||||
use types::id::Id;
|
||||
use utils::DomainPart;
|
||||
use utils::{DomainPart, map::vec_map::VecMap};
|
||||
|
||||
impl Server {
|
||||
pub async fn domain(&self, domain: &str) -> trc::Result<Option<Arc<DomainCache>>> {
|
||||
|
|
@ -151,6 +152,12 @@ impl Server {
|
|||
if domain.allow_relaying {
|
||||
flags |= DOMAIN_FLAG_RELAY;
|
||||
}
|
||||
if !domain.dns_management.allows_subdomain_signing() {
|
||||
flags |= DOMAIN_FLAG_DKIM2_STRICT;
|
||||
}
|
||||
if matches!(domain.dns_management, DnsManagement::Automatic(_)) {
|
||||
flags |= DOMAIN_FLAG_DNS_MANAGED;
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
|
|
@ -469,68 +476,46 @@ impl Server {
|
|||
}
|
||||
}
|
||||
Account::Group(account) => {
|
||||
let domain = self
|
||||
.domain_by_id(account.domain_id.document_id())
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
trc::AuthEvent::Error
|
||||
.into_err()
|
||||
.details("Domain not found for group account.")
|
||||
.ctx(trc::Key::AccountId, account_id)
|
||||
.ctx(trc::Key::Id, account.domain_id.document_id())
|
||||
.caused_by(trc::location!())
|
||||
})?;
|
||||
let mut name =
|
||||
String::with_capacity(domain.names[0].len() + account.name.len() + 1);
|
||||
name.push_str(account.name.as_ref());
|
||||
name.push('@');
|
||||
name.push_str(domain.names[0].as_ref());
|
||||
|
||||
let mut quota_objects: Option<ObjectQuota> = None;
|
||||
let mut quota_disk = 0;
|
||||
for (resource, limit) in account.quotas {
|
||||
if resource == StorageQuota::MaxDiskQuota {
|
||||
quota_disk = limit;
|
||||
} else {
|
||||
quota_objects
|
||||
.get_or_insert_with(|| self.core.email.max_objects.clone())
|
||||
.set(resource, limit as u32);
|
||||
}
|
||||
}
|
||||
|
||||
AccountCache {
|
||||
id: account_id,
|
||||
name: name.into_boxed_str(),
|
||||
addresses: [EmailAddress {
|
||||
local_part: account.name.into(),
|
||||
domain_id: account.domain_id.document_id(),
|
||||
}]
|
||||
.into_iter()
|
||||
.chain(
|
||||
account
|
||||
.aliases
|
||||
.into_iter()
|
||||
.filter(|alias| alias.enable)
|
||||
.map(|alias| EmailAddress {
|
||||
local_part: alias.name.into(),
|
||||
domain_id: alias.domain_id.document_id(),
|
||||
}),
|
||||
)
|
||||
.collect(),
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
id_tenant: account.member_tenant_id.map(|id| id.document_id()),
|
||||
// SPDX-SnippetEnd
|
||||
id_member_of: Default::default(),
|
||||
quota_disk,
|
||||
description: account.description.map(Into::into),
|
||||
storage: AccountStorage::boxed(quota_objects, None),
|
||||
locale: account.locale,
|
||||
flags: 0,
|
||||
active_script: Default::default(),
|
||||
}
|
||||
self.build_shared_account_cache(
|
||||
account_id,
|
||||
SharedAccount {
|
||||
name: account.name,
|
||||
domain_id: account.domain_id,
|
||||
aliases: account.aliases,
|
||||
quotas: account.quotas,
|
||||
description: account.description,
|
||||
locale: account.locale,
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
member_tenant_id: account.member_tenant_id,
|
||||
// SPDX-SnippetEnd
|
||||
flags: 0,
|
||||
},
|
||||
)
|
||||
.await?
|
||||
}
|
||||
Account::Resource(account) => {
|
||||
self.build_shared_account_cache(
|
||||
account_id,
|
||||
SharedAccount {
|
||||
name: account.name,
|
||||
domain_id: account.domain_id,
|
||||
aliases: account.aliases,
|
||||
quotas: account.quotas,
|
||||
description: account.description,
|
||||
locale: account.locale,
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
member_tenant_id: account.member_tenant_id,
|
||||
// SPDX-SnippetEnd
|
||||
flags: AccountCache::resource_flags(account.kind),
|
||||
},
|
||||
)
|
||||
.await?
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -970,6 +955,29 @@ impl AccountCache {
|
|||
self.flags & ACCOUNT_IS_USER != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_group_account(&self) -> bool {
|
||||
self.flags & ACCOUNT_TYPE_MASK == 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn resource_kind(&self) -> Option<ResourceKind> {
|
||||
if self.flags & ACCOUNT_IS_ROOM != 0 {
|
||||
Some(ResourceKind::Room)
|
||||
} else if self.flags & ACCOUNT_IS_EQUIPMENT != 0 {
|
||||
Some(ResourceKind::Equipment)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resource_flags(kind: ResourceKind) -> u64 {
|
||||
match kind {
|
||||
ResourceKind::Room => ACCOUNT_IS_ROOM,
|
||||
ResourceKind::Equipment => ACCOUNT_IS_EQUIPMENT,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn disk_quota(&self) -> u64 {
|
||||
self.quota_disk
|
||||
|
|
@ -1026,3 +1034,89 @@ impl Server {
|
|||
Ok(encryption)
|
||||
}
|
||||
}
|
||||
|
||||
struct SharedAccount {
|
||||
name: String,
|
||||
domain_id: Id,
|
||||
aliases: List<EmailAlias>,
|
||||
quotas: VecMap<StorageQuota, u64>,
|
||||
description: Option<String>,
|
||||
locale: Locale,
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
member_tenant_id: Option<Id>,
|
||||
// SPDX-SnippetEnd
|
||||
flags: u64,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
async fn build_shared_account_cache(
|
||||
&self,
|
||||
account_id: u32,
|
||||
account: SharedAccount,
|
||||
) -> trc::Result<AccountCache> {
|
||||
let domain = self
|
||||
.domain_by_id(account.domain_id.document_id())
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
trc::AuthEvent::Error
|
||||
.into_err()
|
||||
.details("Domain not found for account.")
|
||||
.ctx(trc::Key::AccountId, account_id)
|
||||
.ctx(trc::Key::Id, account.domain_id.document_id())
|
||||
.caused_by(trc::location!())
|
||||
})?;
|
||||
let mut name = String::with_capacity(domain.names[0].len() + account.name.len() + 1);
|
||||
name.push_str(account.name.as_ref());
|
||||
name.push('@');
|
||||
name.push_str(domain.names[0].as_ref());
|
||||
|
||||
let mut quota_objects: Option<ObjectQuota> = None;
|
||||
let mut quota_disk = 0;
|
||||
for (resource, limit) in account.quotas {
|
||||
if resource == StorageQuota::MaxDiskQuota {
|
||||
quota_disk = limit;
|
||||
} else {
|
||||
quota_objects
|
||||
.get_or_insert_with(|| self.core.email.max_objects.clone())
|
||||
.set(resource, limit as u32);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(AccountCache {
|
||||
id: account_id,
|
||||
name: name.into_boxed_str(),
|
||||
addresses: [EmailAddress {
|
||||
local_part: account.name.into(),
|
||||
domain_id: account.domain_id.document_id(),
|
||||
}]
|
||||
.into_iter()
|
||||
.chain(
|
||||
account
|
||||
.aliases
|
||||
.into_iter()
|
||||
.filter(|alias| alias.enable)
|
||||
.map(|alias| EmailAddress {
|
||||
local_part: alias.name.into(),
|
||||
domain_id: alias.domain_id.document_id(),
|
||||
}),
|
||||
)
|
||||
.collect(),
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
id_tenant: account.member_tenant_id.map(|id| id.document_id()),
|
||||
// SPDX-SnippetEnd
|
||||
id_member_of: Default::default(),
|
||||
quota_disk,
|
||||
description: account.description.map(Into::into),
|
||||
storage: AccountStorage::boxed(quota_objects, None),
|
||||
locale: account.locale,
|
||||
flags: account.flags,
|
||||
active_script: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
26
crates/common/src/cache/reload.rs
vendored
26
crates/common/src/cache/reload.rs
vendored
|
|
@ -5,14 +5,14 @@
|
|||
*/
|
||||
|
||||
use crate::{
|
||||
Core, Server,
|
||||
BuildServer, Core, Server,
|
||||
config::{
|
||||
server::{Listeners, tls::parse_certificates},
|
||||
storage::Storage,
|
||||
telemetry::Telemetry,
|
||||
},
|
||||
ipc::{QueueEvent, RegistryChange},
|
||||
network::security::{BlockedIps, IpWithTtl},
|
||||
network::security::BlockedIps,
|
||||
};
|
||||
use ahash::AHashMap;
|
||||
use directory::Directories;
|
||||
|
|
@ -34,7 +34,13 @@ pub struct ReloadResult {
|
|||
|
||||
impl Server {
|
||||
pub async fn reload_registry(&self, change: RegistryChange) -> trc::Result<ReloadResult> {
|
||||
Box::pin(self.reload(change)).await
|
||||
let result = Box::pin(self.reload(change)).await;
|
||||
if change.object() == ObjectType::SpamClassifier
|
||||
&& let Err(err) = self.inner.build_server().spam_model_reload().await
|
||||
{
|
||||
trc::error!(err.details("Failed to reload spam classifier model"));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn reload(&self, change: RegistryChange) -> trc::Result<ReloadResult> {
|
||||
|
|
@ -50,13 +56,11 @@ impl Server {
|
|||
.unwrap_or(u64::MAX);
|
||||
|
||||
if expires_at > now() {
|
||||
let mut ips = self.inner.data.blocked_ips.write();
|
||||
if let Some(ip) = ip.address.try_to_ip() {
|
||||
ips.block(ip, expires_at);
|
||||
} else {
|
||||
ips.blocked_ip_networks
|
||||
.push(IpWithTtl::new(ip.address, expires_at));
|
||||
}
|
||||
self.inner
|
||||
.data
|
||||
.blocked_ips
|
||||
.write()
|
||||
.block(ip.address, expires_at);
|
||||
}
|
||||
}
|
||||
return Ok(bootstrap.into());
|
||||
|
|
@ -184,6 +188,7 @@ impl Server {
|
|||
.await
|
||||
.ok();
|
||||
|
||||
bootstrap.log_notices();
|
||||
return Ok(ReloadResult {
|
||||
errors: bootstrap.errors,
|
||||
warnings: bootstrap.warnings,
|
||||
|
|
@ -195,6 +200,7 @@ impl Server {
|
|||
}
|
||||
}
|
||||
|
||||
bootstrap.log_notices();
|
||||
Ok(bootstrap.into())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
60
crates/common/src/config/exchange.rs
Normal file
60
crates/common/src/config/exchange.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use registry::schema::{enums::EwsVersion, structs::Exchange};
|
||||
use std::time::Duration;
|
||||
use store::registry::bootstrap::Bootstrap;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ExchangeEndpoint {
|
||||
Ews,
|
||||
ActiveSync,
|
||||
Mapi,
|
||||
OfflineAddressBook,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExchangeConfig {
|
||||
pub enabled: bool,
|
||||
pub ews_version: EwsVersion,
|
||||
pub max_request_size: usize,
|
||||
pub max_devices: usize,
|
||||
pub max_heartbeat: Duration,
|
||||
pub max_object_size: usize,
|
||||
}
|
||||
|
||||
impl ExchangeConfig {
|
||||
pub async fn parse(bp: &mut Bootstrap) -> Self {
|
||||
Self::from(bp.setting_infallible::<Exchange>().await)
|
||||
}
|
||||
|
||||
pub fn endpoint(&self, segment: &str) -> Option<ExchangeEndpoint> {
|
||||
if self.enabled {
|
||||
hashify::map_ignore_case!(segment.as_bytes(), ExchangeEndpoint,
|
||||
"ews" => ExchangeEndpoint::Ews,
|
||||
"microsoft-server-activesync" => ExchangeEndpoint::ActiveSync,
|
||||
"mapi" => ExchangeEndpoint::Mapi,
|
||||
"oab" => ExchangeEndpoint::OfflineAddressBook,
|
||||
)
|
||||
.copied()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Exchange> for ExchangeConfig {
|
||||
fn from(exchange: Exchange) -> Self {
|
||||
ExchangeConfig {
|
||||
enabled: exchange.enable,
|
||||
ews_version: exchange.ews_version,
|
||||
max_request_size: usize::try_from(exchange.max_request_size).unwrap_or(usize::MAX),
|
||||
max_devices: usize::try_from(exchange.max_devices).unwrap_or(usize::MAX),
|
||||
max_heartbeat: exchange.max_heartbeat.into_inner(),
|
||||
max_object_size: usize::try_from(exchange.max_object_size).unwrap_or(usize::MAX),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -34,6 +34,7 @@ pub struct GroupwareConfig {
|
|||
pub max_calendars_per_event: usize,
|
||||
pub max_expanded_query_duration: u64,
|
||||
pub max_availability_duration: u64,
|
||||
pub share_free_busy: bool,
|
||||
pub availability_rate: Option<Rate>,
|
||||
pub max_attachments_size: usize,
|
||||
pub default_calendar_name: Option<String>,
|
||||
|
|
@ -135,6 +136,7 @@ impl GroupwareConfig {
|
|||
.into_inner()
|
||||
.as_secs(),
|
||||
max_availability_duration: calendar.max_availability_duration.into_inner().as_secs(),
|
||||
share_free_busy: calendar.share_free_busy,
|
||||
availability_rate: calendar.availability_rate_limit,
|
||||
max_attachments_size: calendar.max_attachments_size as usize,
|
||||
max_vcard_size: book.max_v_card_size as usize,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@
|
|||
*/
|
||||
|
||||
use super::server::tls::build_self_signed_cert;
|
||||
#[cfg(feature = "exchange")]
|
||||
use crate::cache::exchange::ExchangeAccountCache;
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
|
|
@ -52,6 +54,8 @@ use utils::{
|
|||
tls::build_tls_connector,
|
||||
};
|
||||
|
||||
#[cfg(feature = "exchange")]
|
||||
const EXCHANGE_CACHE_ESTIMATE: u64 = (std::mem::size_of::<ExchangeAccountCache>() + 4096) as u64;
|
||||
const MAX_HARVEST_TASKS: usize = 8;
|
||||
|
||||
impl Data {
|
||||
|
|
@ -111,6 +115,8 @@ impl Data {
|
|||
logos: Default::default(),
|
||||
smtp_connectors: TlsConnectors::try_new().failed("Failed to build TLS connectors"),
|
||||
memory_budget: Default::default(),
|
||||
#[cfg(feature = "exchange")]
|
||||
exchange_sessions: Default::default(),
|
||||
harvest_tasks: Arc::new(Semaphore::new(MAX_HARVEST_TASKS)),
|
||||
asn_geo_data: Default::default(),
|
||||
password_verifier: Default::default(),
|
||||
|
|
@ -179,6 +185,8 @@ impl Caches {
|
|||
)
|
||||
.with_name("scheduling"),
|
||||
metadata_viewers: MetadataViewerCache::new(cache.access_tokens / 4),
|
||||
#[cfg(feature = "exchange")]
|
||||
exchange: Cache::new(cache.exchange, EXCHANGE_CACHE_ESTIMATE).with_name("exchange"),
|
||||
emails: Cache::new(cache.email_addresses, 255u64).with_name("emailAddresses"),
|
||||
emails_negative: CacheWithTtl::new(
|
||||
cache.email_addresses_negative,
|
||||
|
|
@ -308,6 +316,8 @@ impl Default for Data {
|
|||
logos: Default::default(),
|
||||
smtp_connectors: TlsConnectors::try_new().unwrap(),
|
||||
memory_budget: Default::default(),
|
||||
#[cfg(feature = "exchange")]
|
||||
exchange_sessions: Default::default(),
|
||||
harvest_tasks: Arc::new(Semaphore::new(MAX_HARVEST_TASKS)),
|
||||
asn_geo_data: Default::default(),
|
||||
password_verifier: Default::default(),
|
||||
|
|
|
|||
|
|
@ -243,6 +243,15 @@ impl JmapConfig {
|
|||
}),
|
||||
);
|
||||
|
||||
self.capabilities.session.append(
|
||||
Capability::Mdn,
|
||||
Capabilities::Empty(EmptyCapabilities::default()),
|
||||
);
|
||||
self.capabilities.account.insert(
|
||||
Capability::Mdn,
|
||||
Capabilities::Empty(EmptyCapabilities::default()),
|
||||
);
|
||||
|
||||
// Add vacation response capabilities
|
||||
self.capabilities.session.append(
|
||||
Capability::VacationResponse,
|
||||
|
|
|
|||
|
|
@ -81,7 +81,7 @@ impl Scripting {
|
|||
.with_cpu_limit(untrusted.max_cpu_cycles as usize)
|
||||
.with_max_variable_size(untrusted.max_var_size as usize)
|
||||
.with_max_redirects(untrusted.max_redirects as usize)
|
||||
.with_max_received_headers(usize::MAX) // This is set to usize::MAX here, but the actual limit is enforced during ingestion.
|
||||
.with_max_received_headers(untrusted.max_received_headers as usize)
|
||||
.with_max_header_size(untrusted.max_header_size as usize)
|
||||
.with_max_out_messages(untrusted.max_out_messages as usize)
|
||||
.with_max_header_count(limits.header_count)
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ use crate::{
|
|||
};
|
||||
use arc_swap::ArcSwap;
|
||||
use blob::BlobConfig;
|
||||
#[cfg(feature = "exchange")]
|
||||
use exchange::ExchangeConfig;
|
||||
use groupware::GroupwareConfig;
|
||||
use hyper::HeaderMap;
|
||||
use p256::elliptic_curve::sec1::ToSec1Point;
|
||||
|
|
@ -32,6 +34,8 @@ use store::registry::bootstrap::Bootstrap;
|
|||
use telemetry::Metrics;
|
||||
|
||||
pub mod blob;
|
||||
#[cfg(feature = "exchange")]
|
||||
pub mod exchange;
|
||||
pub mod groupware;
|
||||
pub mod inner;
|
||||
pub mod mailstore;
|
||||
|
|
@ -130,6 +134,8 @@ impl Core {
|
|||
spam: SpamFilterConfig::parse(bp).await,
|
||||
email,
|
||||
groupware: GroupwareConfig::parse(bp).await,
|
||||
#[cfg(feature = "exchange")]
|
||||
exchange: ExchangeConfig::parse(bp).await,
|
||||
metadata,
|
||||
blob,
|
||||
storage,
|
||||
|
|
|
|||
|
|
@ -25,23 +25,41 @@ use rustls::{
|
|||
crypto::aws_lc_rs::{ALL_CIPHER_SUITES, cipher_suite::*, default_provider},
|
||||
};
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr as StdSocketAddr},
|
||||
str::FromStr,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr as StdSocketAddr},
|
||||
sync::Arc,
|
||||
};
|
||||
use store::registry::{RegistryObject, bootstrap::Bootstrap};
|
||||
use tokio::net::TcpSocket;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use types::id::Id;
|
||||
use utils::snowflake::SnowflakeIdGenerator;
|
||||
use utils::{failed, snowflake::SnowflakeIdGenerator};
|
||||
|
||||
const DEFAULT_RECOVERY_MODE_PORT: u16 = 8080;
|
||||
|
||||
pub fn recovery_mode_port() -> u16 {
|
||||
std::env::var("STALWART_RECOVERY_MODE_PORT")
|
||||
pub fn recovery_mode_addr() -> StdSocketAddr {
|
||||
let ip = match std::env::var("STALWART_RECOVERY_MODE_BIND")
|
||||
.ok()
|
||||
.and_then(|port| port.parse().ok())
|
||||
.unwrap_or(DEFAULT_RECOVERY_MODE_PORT)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
Some(ip) => ip.trim().parse().unwrap_or_else(|_| {
|
||||
failed(&format!(
|
||||
"Invalid STALWART_RECOVERY_MODE_BIND value {ip:?}: expected an IP address."
|
||||
))
|
||||
}),
|
||||
None => IpAddr::V6(Ipv6Addr::UNSPECIFIED),
|
||||
};
|
||||
let port = match std::env::var("STALWART_RECOVERY_MODE_PORT")
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
Some(port) => port.trim().parse().unwrap_or_else(|_| {
|
||||
failed(&format!(
|
||||
"Invalid STALWART_RECOVERY_MODE_PORT value {port:?}: expected a port number."
|
||||
))
|
||||
}),
|
||||
None => DEFAULT_RECOVERY_MODE_PORT,
|
||||
};
|
||||
StdSocketAddr::new(ip, port)
|
||||
}
|
||||
|
||||
impl Listeners {
|
||||
|
|
@ -75,10 +93,7 @@ impl Listeners {
|
|||
RegistryObject {
|
||||
id: ObjectId::new(ObjectType::NetworkListener, Id::singleton()),
|
||||
object: NetworkListener {
|
||||
bind: Map::new(vec![
|
||||
SocketAddr::from_str(&format!("[::]:{}", recovery_mode_port()))
|
||||
.unwrap(),
|
||||
]),
|
||||
bind: Map::new(vec![SocketAddr(recovery_mode_addr())]),
|
||||
name: "http-recovery".to_string(),
|
||||
protocol: NetworkListenerProtocol::Http,
|
||||
implicit_tls: false,
|
||||
|
|
|
|||
|
|
@ -212,7 +212,8 @@ impl DkimSigners {
|
|||
None => (
|
||||
Dkim2Signer::from_key(key)
|
||||
.domain(domain)
|
||||
.selector(signature.selector),
|
||||
.selector(signature.selector)
|
||||
.allow_from_subdomain(),
|
||||
Vec::with_capacity(2),
|
||||
),
|
||||
Some(signers) => (
|
||||
|
|
|
|||
|
|
@ -143,7 +143,13 @@ pub struct Tracers {
|
|||
pub struct Metrics {
|
||||
pub prometheus: Option<PrometheusMetrics>,
|
||||
pub otel: Option<Arc<OtelMetrics>>,
|
||||
pub log_path: Option<String>,
|
||||
pub log_files: Option<Arc<LogFiles>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LogFiles {
|
||||
pub path: String,
|
||||
pub prefix: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
|
@ -803,7 +809,7 @@ impl Metrics {
|
|||
None => None,
|
||||
}
|
||||
},
|
||||
log_path: bp
|
||||
log_files: bp
|
||||
.list_infallible::<Tracer>()
|
||||
.await
|
||||
.into_iter()
|
||||
|
|
@ -811,7 +817,10 @@ impl Metrics {
|
|||
if let Tracer::Log(log_tracer) = tracer.object
|
||||
&& log_tracer.enable
|
||||
{
|
||||
Some(log_tracer.path)
|
||||
Some(Arc::new(LogFiles {
|
||||
path: log_tracer.path,
|
||||
prefix: log_tracer.prefix,
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,13 +27,27 @@ use license::LicenseKey;
|
|||
use logo::{LogoLoadError, LogoSource};
|
||||
use mail_parser::DateTime;
|
||||
use registry::{
|
||||
schema::structs::{Domain, Tenant},
|
||||
types::id::ObjectId,
|
||||
schema::{
|
||||
enums::{AccountType, TenantStorageQuota},
|
||||
prelude::{ObjectType, Property},
|
||||
structs::{Domain, Tenant},
|
||||
},
|
||||
types::{EnumImpl, id::ObjectId},
|
||||
};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use store::{
|
||||
registry::{RegistryObjectCounter, RegistryQuery},
|
||||
roaring::RoaringBitmap,
|
||||
};
|
||||
use trc::{AddContext, MetricType};
|
||||
use utils::{cron::SimpleCron, outbound::OutboundPolicy, template::Template};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct TenantQuotaReached {
|
||||
pub limit: u32,
|
||||
pub objects: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Enterprise {
|
||||
pub license: LicenseKey,
|
||||
|
|
@ -296,6 +310,75 @@ impl Server {
|
|||
Ok(true)
|
||||
}
|
||||
|
||||
pub async fn tenant_quota_reached(
|
||||
&self,
|
||||
tenant_id: u32,
|
||||
quota: TenantStorageQuota,
|
||||
) -> trc::Result<Option<TenantQuotaReached>> {
|
||||
let (object_type, type_filter, objects) = match quota {
|
||||
TenantStorageQuota::MaxAccounts => (
|
||||
ObjectType::Account,
|
||||
&[AccountType::User, AccountType::Resource][..],
|
||||
"accounts",
|
||||
),
|
||||
TenantStorageQuota::MaxGroups => {
|
||||
(ObjectType::Account, &[AccountType::Group][..], "groups")
|
||||
}
|
||||
TenantStorageQuota::MaxDomains => (ObjectType::Domain, &[][..], "domains"),
|
||||
TenantStorageQuota::MaxMailingLists => {
|
||||
(ObjectType::MailingList, &[][..], "mailing lists")
|
||||
}
|
||||
TenantStorageQuota::MaxRoles => (ObjectType::Role, &[][..], "roles"),
|
||||
TenantStorageQuota::MaxOauthClients => {
|
||||
(ObjectType::OAuthClient, &[][..], "OAuth clients")
|
||||
}
|
||||
TenantStorageQuota::MaxDkimKeys => (ObjectType::DkimSignature, &[][..], "DKIM keys"),
|
||||
TenantStorageQuota::MaxDnsServers => (ObjectType::DnsServer, &[][..], "DNS servers"),
|
||||
TenantStorageQuota::MaxDirectories => (ObjectType::Directory, &[][..], "directories"),
|
||||
TenantStorageQuota::MaxAcmeProviders => {
|
||||
(ObjectType::AcmeProvider, &[][..], "ACME providers")
|
||||
}
|
||||
TenantStorageQuota::MaxDiskQuota => return Ok(None),
|
||||
};
|
||||
|
||||
let tenant = self.tenant(tenant_id).await.caused_by(trc::location!())?;
|
||||
let Some(limit) = tenant
|
||||
.quota_objects
|
||||
.as_ref()
|
||||
.map(|quotas| quotas.get(quota))
|
||||
.filter(|limit| *limit != u32::MAX)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let count = if type_filter.is_empty() {
|
||||
self.registry()
|
||||
.query::<RegistryObjectCounter>(
|
||||
RegistryQuery::new(object_type).with_tenant(tenant_id.into()),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.0 as u64
|
||||
} else {
|
||||
let mut count = 0;
|
||||
for account_type in type_filter {
|
||||
count += self
|
||||
.registry()
|
||||
.query::<RoaringBitmap>(
|
||||
RegistryQuery::new(object_type)
|
||||
.with_tenant(tenant_id.into())
|
||||
.equal(Property::Type, account_type.to_id()),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.len();
|
||||
}
|
||||
count
|
||||
};
|
||||
|
||||
Ok((count >= u64::from(limit)).then_some(TenantQuotaReached { limit, objects }))
|
||||
}
|
||||
|
||||
pub async fn logo_resource(&self, domain: &str) -> trc::Result<Option<Resource<Bytes>>> {
|
||||
if !self.is_enterprise_edition() {
|
||||
return Ok(None);
|
||||
|
|
|
|||
|
|
@ -326,6 +326,15 @@ impl BroadcastEvent {
|
|||
}
|
||||
}
|
||||
|
||||
impl RegistryChange {
|
||||
pub fn object(&self) -> ObjectType {
|
||||
match self {
|
||||
RegistryChange::Insert(id) | RegistryChange::Delete(id) => id.object(),
|
||||
RegistryChange::Reload(object) => *object,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ToHash {
|
||||
fn to_hash(&self) -> u64;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,6 +37,11 @@ use crate::{
|
|||
network::security::BlockedIps,
|
||||
storage::metadata::MetadataViewerCache,
|
||||
};
|
||||
#[cfg(feature = "exchange")]
|
||||
use crate::{
|
||||
cache::{exchange::ExchangeAccountCache, exchange_sessions::ExchangeSessions},
|
||||
config::exchange::ExchangeConfig,
|
||||
};
|
||||
use ahash::AHashMap;
|
||||
use arc_swap::ArcSwap;
|
||||
use auth::oauth::config::OAuthConfig;
|
||||
|
|
@ -165,6 +170,16 @@ pub const KV_LOCK_SEARCH_INDEX: u8 = 17;
|
|||
pub const KV_OAUTH_CIMD: u8 = 18;
|
||||
pub const KV_RATE_LIMIT_CIMD: u8 = 19;
|
||||
pub const KV_KEY_LOOKUP: u8 = 20;
|
||||
pub const KV_LOCK_RESOURCE_BOOKING: u8 = 21;
|
||||
pub const KV_LOCK_CREATE: u8 = 22;
|
||||
#[cfg(feature = "exchange")]
|
||||
pub const KV_EXCHANGE_SESSION: u8 = 23;
|
||||
#[cfg(feature = "exchange")]
|
||||
pub const KV_LOCK_EXCHANGE_SESSION: u8 = 24;
|
||||
#[cfg(feature = "exchange")]
|
||||
pub const KV_EXCHANGE_SUBMIT: u8 = 25;
|
||||
#[cfg(feature = "exchange")]
|
||||
pub const KV_LOCK_EXCHANGE_SUBMIT: u8 = 26;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Server {
|
||||
|
|
@ -203,6 +218,8 @@ pub struct Data {
|
|||
|
||||
pub smtp_connectors: TlsConnectors,
|
||||
pub memory_budget: MemoryBudget,
|
||||
#[cfg(feature = "exchange")]
|
||||
pub exchange_sessions: ExchangeSessions,
|
||||
|
||||
pub harvest_tasks: Arc<Semaphore>,
|
||||
}
|
||||
|
|
@ -236,6 +253,8 @@ pub struct Caches {
|
|||
pub events: Cache<u32, Arc<GroupwareResources>, SwapEviction>,
|
||||
pub scheduling: Cache<u32, Arc<GroupwareResources>, SwapEviction>,
|
||||
pub metadata_viewers: MetadataViewerCache,
|
||||
#[cfg(feature = "exchange")]
|
||||
pub exchange: Cache<u32, Arc<ExchangeAccountCache>>,
|
||||
|
||||
pub emails: Cache<EmailAddress, EmailCache>,
|
||||
pub emails_negative: CacheWithTtl<EmailAddress, ()>,
|
||||
|
|
@ -639,6 +658,8 @@ pub struct Core {
|
|||
pub smtp: SmtpConfig,
|
||||
pub spam: SpamFilterConfig,
|
||||
pub groupware: GroupwareConfig,
|
||||
#[cfg(feature = "exchange")]
|
||||
pub exchange: ExchangeConfig,
|
||||
pub metadata: MetadataConfig,
|
||||
pub metrics: Metrics,
|
||||
pub blob: BlobConfig,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ use crate::{
|
|||
BuildServer, Caches, Core, Data, IPC_CHANNEL_BUFFER, Inner, Ipc,
|
||||
config::{
|
||||
network::AsnGeoLookupConfig,
|
||||
server::{Listeners, listener::recovery_mode_port},
|
||||
server::{Listeners, listener::recovery_mode_addr},
|
||||
storage::Storage,
|
||||
telemetry::Telemetry,
|
||||
},
|
||||
|
|
@ -133,6 +133,7 @@ impl BootManager {
|
|||
.await
|
||||
.failed("⚠️ Startup failed");
|
||||
let mut bootstrap = Bootstrap::new(registry).await;
|
||||
bootstrap.data_store.clone().report_cluster(&mut bootstrap);
|
||||
|
||||
// Add safe defaults if missing
|
||||
if import_export == StoreOp::None {
|
||||
|
|
@ -175,7 +176,7 @@ impl BootManager {
|
|||
Hostname = CompactString::from(bootstrap.registry.local_hostname()),
|
||||
Details = format!(
|
||||
"No configuration file was found. Port {} is open for initial setup.",
|
||||
recovery_mode_port()
|
||||
recovery_mode_addr().port()
|
||||
),
|
||||
Version = env!("CARGO_PKG_VERSION"),
|
||||
);
|
||||
|
|
@ -184,7 +185,7 @@ impl BootManager {
|
|||
Server(trc::ServerEvent::RecoveryMode),
|
||||
Details = format!(
|
||||
"Port {} is open for troubleshooting and recovery.",
|
||||
recovery_mode_port()
|
||||
recovery_mode_addr().port()
|
||||
),
|
||||
Hostname = CompactString::from(bootstrap.registry.local_hostname()),
|
||||
Version = env!("CARGO_PKG_VERSION"),
|
||||
|
|
|
|||
|
|
@ -43,10 +43,12 @@ pub async fn acme_create_account(
|
|||
));
|
||||
}
|
||||
|
||||
let mut contact_urls = Vec::with_capacity(provider.contact.len());
|
||||
for contact in provider.contact.iter_mut() {
|
||||
let email = sanitize_email(contact.trim().strip_prefix("mailto:").unwrap_or(contact))
|
||||
.ok_or_else(|| AcmeError::Invalid(format!("Invalid contact email: {}", contact)))?;
|
||||
*contact = format!("mailto:{}", email);
|
||||
contact_urls.push(format!("mailto:{email}"));
|
||||
*contact = email;
|
||||
}
|
||||
|
||||
let client = acme_client(provider);
|
||||
|
|
@ -65,7 +67,7 @@ pub async fn acme_create_account(
|
|||
|
||||
let payload = serde_json::to_string(&NewAccountPayload {
|
||||
tos_agreed: true,
|
||||
contact: provider.contact.as_slice(),
|
||||
contact: &contact_urls,
|
||||
eab,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
|
|
|||
|
|
@ -100,6 +100,19 @@ impl Server {
|
|||
record: DnsRecord::TXT("v=spf1 mx -all".to_string()),
|
||||
});
|
||||
}
|
||||
DnsRecordType::Dkim2Policy => {
|
||||
records.push(NamedDnsRecord {
|
||||
name: format!("_domainkey.{domain_name}."),
|
||||
record: DnsRecord::TXT(
|
||||
if domain.dns_management.allows_subdomain_signing() {
|
||||
"v=DKIM1"
|
||||
} else {
|
||||
"v=DKIM1; f=strict"
|
||||
}
|
||||
.to_string(),
|
||||
),
|
||||
});
|
||||
}
|
||||
DnsRecordType::Dmarc => {
|
||||
if let Some(uri) = &domain.report_address_uri {
|
||||
let contents = if uri.starts_with("mailto:") && !uri.contains('@') {
|
||||
|
|
@ -393,26 +406,16 @@ impl Server {
|
|||
domain_id: Id,
|
||||
domain: &Domain,
|
||||
) -> trc::Result<String> {
|
||||
self.build_dns_records(
|
||||
domain_id,
|
||||
domain,
|
||||
&[
|
||||
DnsRecordType::Dkim,
|
||||
DnsRecordType::Tlsa,
|
||||
DnsRecordType::Spf,
|
||||
DnsRecordType::Mx,
|
||||
DnsRecordType::Dmarc,
|
||||
DnsRecordType::Srv,
|
||||
DnsRecordType::MtaSts,
|
||||
DnsRecordType::TlsRpt,
|
||||
DnsRecordType::Caa,
|
||||
DnsRecordType::AutoConfig,
|
||||
DnsRecordType::AutoConfigLegacy,
|
||||
DnsRecordType::AutoDiscover,
|
||||
],
|
||||
)
|
||||
.await
|
||||
.map(|records| BindSerializer::serialize(&records))
|
||||
let record_types = if domain.dns_management.allows_subdomain_signing() {
|
||||
BIND_RECORD_TYPES
|
||||
.split_last()
|
||||
.map_or(BIND_RECORD_TYPES, |(_, rest)| rest)
|
||||
} else {
|
||||
BIND_RECORD_TYPES
|
||||
};
|
||||
self.build_dns_records(domain_id, domain, record_types)
|
||||
.await
|
||||
.map(|records| BindSerializer::serialize(&records))
|
||||
}
|
||||
|
||||
pub async fn get_pacc_for_domain(&self, domain_name: &str) -> trc::Result<String> {
|
||||
|
|
@ -453,3 +456,19 @@ impl Pacc {
|
|||
fn provider_domain(url: &Url) -> Option<&str> {
|
||||
url.host_str().and_then(psl::domain_str)
|
||||
}
|
||||
|
||||
const BIND_RECORD_TYPES: &[DnsRecordType] = &[
|
||||
DnsRecordType::Dkim,
|
||||
DnsRecordType::Tlsa,
|
||||
DnsRecordType::Spf,
|
||||
DnsRecordType::Mx,
|
||||
DnsRecordType::Dmarc,
|
||||
DnsRecordType::Srv,
|
||||
DnsRecordType::MtaSts,
|
||||
DnsRecordType::TlsRpt,
|
||||
DnsRecordType::Caa,
|
||||
DnsRecordType::AutoConfig,
|
||||
DnsRecordType::AutoConfigLegacy,
|
||||
DnsRecordType::AutoDiscover,
|
||||
DnsRecordType::Dkim2Policy,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -7,13 +7,16 @@
|
|||
use self::limiter::{ConcurrencyLimiter, InFlight};
|
||||
use crate::{Server, config::server::ServerProtocol};
|
||||
use compact_str::{CompactString, ToCompactString};
|
||||
use futures::FutureExt;
|
||||
use registry::types::ipmask::IpAddrOrMask;
|
||||
use rustls::ServerConfig;
|
||||
use std::fmt::Debug;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
future::Future,
|
||||
io,
|
||||
net::IpAddr,
|
||||
net::{IpAddr, Ipv6Addr},
|
||||
pin::pin,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
|
@ -102,6 +105,14 @@ pub trait SessionStream: AsyncRead + AsyncWrite + Unpin + 'static + Sync + Send
|
|||
fn tls_version_and_cipher(&self) -> (Cow<'static, str>, Cow<'static, str>);
|
||||
}
|
||||
|
||||
pub async fn ready_or_timeout<F: Future>(duration: Duration, future: F) -> Option<F::Output> {
|
||||
let mut future = pin!(future);
|
||||
match future.as_mut().now_or_never() {
|
||||
Some(output) => Some(output),
|
||||
None => timeout(duration, future).await.ok(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SessionResult {
|
||||
Continue,
|
||||
|
|
@ -288,11 +299,17 @@ impl Debug for TcpAcceptor {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn ip_to_bytes(ip: &IpAddr) -> ArrayVec<[u8; 16]> {
|
||||
pub const IPV6_PREFIX_MASK: u128 = u128::MAX << 64;
|
||||
|
||||
pub fn ipv6_prefix(addr: Ipv6Addr) -> Ipv6Addr {
|
||||
Ipv6Addr::from_bits(addr.to_bits() & IPV6_PREFIX_MASK)
|
||||
}
|
||||
|
||||
pub fn ip_rate_key(ip: &IpAddr) -> ArrayVec<[u8; 16]> {
|
||||
let mut bytes = ArrayVec::new();
|
||||
match ip {
|
||||
match ip.to_canonical() {
|
||||
IpAddr::V4(ip) => bytes.extend_from_slice(&ip.octets()),
|
||||
IpAddr::V6(ip) => bytes.extend_from_slice(&ip.octets()),
|
||||
IpAddr::V6(ip) => bytes.extend_from_slice(&((ip.to_bits() >> 64) as u64).to_be_bytes()),
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
|
@ -313,3 +330,8 @@ pub fn ip_to_bytes_prefix(prefix: u8, ip: &IpAddr) -> Vec<u8> {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/common/src/network/tests.rs"]
|
||||
mod tests;
|
||||
|
|
|
|||
|
|
@ -173,10 +173,12 @@ impl Server {
|
|||
}
|
||||
EmailCache::MailingList(id) => {
|
||||
if let Some(list) = self.try_list(id).await? {
|
||||
return Ok(RcptResolution::Expand(
|
||||
self.expand_nested_lists(id, list.recipients.clone())
|
||||
.await?,
|
||||
));
|
||||
let members = self
|
||||
.expand_nested_lists(id, list.recipients.clone())
|
||||
.await?;
|
||||
if !members.is_empty() {
|
||||
return Ok(RcptResolution::Expand(members));
|
||||
}
|
||||
} else {
|
||||
self.inner
|
||||
.cache
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
use crate::{
|
||||
KV_RATE_LIMIT_AUTH, KV_RATE_LIMIT_LOITER, KV_RATE_LIMIT_RCPT, KV_RATE_LIMIT_SCAN, Server,
|
||||
ipc::{BroadcastEvent, RegistryChange},
|
||||
network::ip_to_bytes,
|
||||
network::{IPV6_PREFIX_MASK, ip_rate_key, ipv6_prefix},
|
||||
};
|
||||
use ahash::AHashSet;
|
||||
use registry::{
|
||||
|
|
@ -18,7 +18,11 @@ use registry::{
|
|||
},
|
||||
types::{datetime::UTCDateTime, ipmask::IpAddrOrMask},
|
||||
};
|
||||
use std::{fmt::Debug, hash::Hash, net::IpAddr};
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
hash::Hash,
|
||||
net::{IpAddr, Ipv6Addr},
|
||||
};
|
||||
use store::{
|
||||
blake3,
|
||||
registry::{
|
||||
|
|
@ -69,6 +73,7 @@ pub struct Security {
|
|||
#[derive(Default)]
|
||||
pub struct BlockedIps {
|
||||
pub blocked_ip_addresses: AHashSet<IpWithTtl<IpAddr>>,
|
||||
pub blocked_ipv6_prefixes: AHashSet<IpWithTtl<Ipv6Addr>>,
|
||||
pub blocked_ip_networks: Vec<IpWithTtl<IpAddrOrMask>>,
|
||||
pub has_blocked_networks: bool,
|
||||
}
|
||||
|
|
@ -246,7 +251,7 @@ impl Server {
|
|||
&& !self.is_ip_allowed(ip)
|
||||
{
|
||||
let store = self.in_memory_store();
|
||||
let ip_key = ip_to_bytes(&ip);
|
||||
let ip_key = ip_rate_key(&ip);
|
||||
let rcpt_key = blake3::hash(rcpt.as_bytes());
|
||||
let is_allowed = store
|
||||
.is_rate_allowed(KV_RATE_LIMIT_RCPT, &ip_key, rate)
|
||||
|
|
@ -314,7 +319,7 @@ impl Server {
|
|||
return Ok(false);
|
||||
}
|
||||
|
||||
let ip_key = ip_to_bytes(&ip);
|
||||
let ip_key = ip_rate_key(&ip);
|
||||
if self
|
||||
.in_memory_store()
|
||||
.is_rate_allowed(prefix, &ip_key, rate)
|
||||
|
|
@ -353,51 +358,85 @@ impl Server {
|
|||
&& !self.is_ip_allowed(ip)
|
||||
{
|
||||
let store = self.in_memory_store();
|
||||
let ip_key = ip_to_bytes(&ip);
|
||||
let login_key = login
|
||||
.filter(|login| !login.is_empty())
|
||||
.map(|login| blake3::hash(login.as_bytes()));
|
||||
let is_allowed = store
|
||||
let ip_key = ip_rate_key(&ip);
|
||||
if store
|
||||
.is_rate_allowed(KV_RATE_LIMIT_AUTH, &ip_key, rate)
|
||||
.await?
|
||||
.is_none()
|
||||
&& match &login_key {
|
||||
Some(login_key) => store
|
||||
.is_rate_allowed(KV_RATE_LIMIT_AUTH, login_key.as_bytes(), rate)
|
||||
.await?
|
||||
.is_none(),
|
||||
None => true,
|
||||
};
|
||||
|
||||
if !is_allowed {
|
||||
let keys: &[&[u8]] = match &login_key {
|
||||
Some(login_key) => &[ip_key.as_slice(), login_key.as_bytes()],
|
||||
None => &[ip_key.as_slice()],
|
||||
};
|
||||
.is_some()
|
||||
{
|
||||
return self
|
||||
.ban_and_reset(ip, BlockReason::AuthFailure, KV_RATE_LIMIT_AUTH, rate, keys)
|
||||
.ban_and_reset(
|
||||
ip,
|
||||
BlockReason::AuthFailure,
|
||||
KV_RATE_LIMIT_AUTH,
|
||||
rate,
|
||||
&[ip_key.as_slice()],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
if let Some(login) = login.filter(|login| !login.is_empty())
|
||||
&& let Some(expires_in) = store
|
||||
.is_rate_allowed(
|
||||
KV_RATE_LIMIT_AUTH,
|
||||
blake3::hash(login.as_bytes()).as_bytes(),
|
||||
rate,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
let period = self
|
||||
.core
|
||||
.network
|
||||
.security
|
||||
.auth_ban_period
|
||||
.map_or(expires_in, |period| period.min(expires_in));
|
||||
self.block_address(
|
||||
IpAddrOrMask::from_ip(ip.to_canonical()),
|
||||
BlockReason::AuthFailure,
|
||||
Some(period),
|
||||
)
|
||||
.await?;
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub async fn block_ip(&self, ip: IpAddr, reason: BlockReason) -> trc::Result<()> {
|
||||
// Add IP to blocked list
|
||||
let address = match ip.to_canonical() {
|
||||
IpAddr::V6(addr) => IpAddrOrMask::V6 {
|
||||
addr: ipv6_prefix(addr),
|
||||
mask: IPV6_PREFIX_MASK,
|
||||
},
|
||||
ip => IpAddrOrMask::from_ip(ip),
|
||||
};
|
||||
self.block_address(
|
||||
address,
|
||||
reason,
|
||||
self.core.network.security.ban_period(reason),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn block_address(
|
||||
&self,
|
||||
address: IpAddrOrMask,
|
||||
reason: BlockReason,
|
||||
ban_period: Option<u64>,
|
||||
) -> trc::Result<()> {
|
||||
let now = now();
|
||||
let expires_at = self
|
||||
.core
|
||||
.network
|
||||
.security
|
||||
.ban_period(reason)
|
||||
.map(|v| now + v);
|
||||
let expires_at = ban_period.map(|v| now + v);
|
||||
let expiry = expires_at.unwrap_or(u64::MAX);
|
||||
self.inner.data.blocked_ips.write().block(ip, expiry);
|
||||
self.inner
|
||||
.data
|
||||
.blocked_ips
|
||||
.write()
|
||||
.block(address.clone(), expiry);
|
||||
|
||||
// Write blocked IP to config
|
||||
let object = Object::from(BlockedIp {
|
||||
address: IpAddrOrMask::from_ip(ip),
|
||||
address,
|
||||
created_at: UTCDateTime::from_timestamp(now as i64),
|
||||
expires_at: expires_at.map(|ts| UTCDateTime::from_timestamp(ts as i64)),
|
||||
reason,
|
||||
|
|
@ -454,17 +493,7 @@ impl Server {
|
|||
}
|
||||
|
||||
pub fn is_ip_blocked(&self, ip: IpAddr) -> bool {
|
||||
let blocked_ips = self.inner.data.blocked_ips.read();
|
||||
(blocked_ips
|
||||
.blocked_ip_addresses
|
||||
.get(&IpWithTtl::new(ip, 0))
|
||||
.is_some_and(|v| !v.is_expired())
|
||||
|| (blocked_ips.has_blocked_networks
|
||||
&& blocked_ips
|
||||
.blocked_ip_networks
|
||||
.iter()
|
||||
.any(|network| network.ip.matches(&ip) && !network.is_expired())))
|
||||
&& !self.is_ip_allowed(ip)
|
||||
self.inner.data.blocked_ips.read().is_blocked(ip) && !self.is_ip_allowed(ip)
|
||||
}
|
||||
|
||||
pub fn is_ip_allowed(&self, ip: IpAddr) -> bool {
|
||||
|
|
@ -511,17 +540,45 @@ impl Server {
|
|||
}
|
||||
|
||||
impl BlockedIps {
|
||||
pub fn block(&mut self, ip: IpAddr, expires_at: u64) {
|
||||
let entry = IpWithTtl::new(ip, expires_at);
|
||||
if self
|
||||
.blocked_ip_addresses
|
||||
.get(&entry)
|
||||
.is_none_or(|current| current.expires_at < expires_at)
|
||||
{
|
||||
self.blocked_ip_addresses.replace(entry);
|
||||
pub fn block(&mut self, address: IpAddrOrMask, expires_at: u64) {
|
||||
match address {
|
||||
IpAddrOrMask::V6 {
|
||||
addr,
|
||||
mask: IPV6_PREFIX_MASK,
|
||||
} => insert_latest(
|
||||
&mut self.blocked_ipv6_prefixes,
|
||||
IpWithTtl::new(ipv6_prefix(addr), expires_at),
|
||||
),
|
||||
address => match address.try_to_ip() {
|
||||
Some(ip) => insert_latest(
|
||||
&mut self.blocked_ip_addresses,
|
||||
IpWithTtl::new(ip, expires_at),
|
||||
),
|
||||
None => {
|
||||
self.blocked_ip_networks
|
||||
.push(IpWithTtl::new(address, expires_at));
|
||||
self.has_blocked_networks = true;
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_blocked(&self, ip: IpAddr) -> bool {
|
||||
self.blocked_ip_addresses
|
||||
.get(&IpWithTtl::new(ip, 0))
|
||||
.is_some_and(|v| !v.is_expired())
|
||||
|| (!self.blocked_ipv6_prefixes.is_empty()
|
||||
&& matches!(ip.to_canonical(), IpAddr::V6(addr) if self
|
||||
.blocked_ipv6_prefixes
|
||||
.get(&IpWithTtl::new(ipv6_prefix(addr), 0))
|
||||
.is_some_and(|v| !v.is_expired())))
|
||||
|| (self.has_blocked_networks
|
||||
&& self
|
||||
.blocked_ip_networks
|
||||
.iter()
|
||||
.any(|network| network.ip.matches(&ip) && !network.is_expired()))
|
||||
}
|
||||
|
||||
pub async fn parse(bp: &mut Bootstrap) -> Self {
|
||||
let mut ips = Self::default();
|
||||
|
||||
|
|
@ -543,12 +600,7 @@ impl BlockedIps {
|
|||
.unwrap_or(u64::MAX);
|
||||
|
||||
if ip.expires_at.as_ref().is_none_or(|ip| ip.timestamp() > now) {
|
||||
if let Some(ip) = ip.address.try_to_ip() {
|
||||
ips.block(ip, expires_at);
|
||||
} else {
|
||||
ips.blocked_ip_networks
|
||||
.push(IpWithTtl::new(ip.address, expires_at));
|
||||
}
|
||||
ips.block(ip.address, expires_at);
|
||||
} else {
|
||||
expired_blocks.push((
|
||||
id,
|
||||
|
|
@ -583,11 +635,19 @@ impl BlockedIps {
|
|||
);
|
||||
}
|
||||
|
||||
ips.has_blocked_networks = !ips.blocked_ip_networks.is_empty();
|
||||
ips
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_latest<T: PartialEq + Eq + Hash>(set: &mut AHashSet<IpWithTtl<T>>, entry: IpWithTtl<T>) {
|
||||
if set
|
||||
.get(&entry)
|
||||
.is_none_or(|current| current.expires_at < entry.expires_at)
|
||||
{
|
||||
set.replace(entry);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq + Eq + Hash> Hash for IpWithTtl<T> {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.ip.hash(state);
|
||||
|
|
|
|||
|
|
@ -6,8 +6,10 @@
|
|||
|
||||
use ahash::{AHashMap, AHashSet};
|
||||
use sieve::{Context, runtime::Variable};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
const MAX_PRESIZE: usize = 2048;
|
||||
const LINEAR_DEDUP_MAX: usize = 16;
|
||||
|
||||
pub fn fn_count<'x>(_: &Context<'x>, v: &[Variable<'x>]) -> Variable<'x> {
|
||||
match &v[0] {
|
||||
|
|
@ -36,17 +38,49 @@ pub fn fn_sort<'x>(_: &Context<'x>, v: &[Variable<'x>]) -> Variable<'x> {
|
|||
|
||||
pub fn fn_dedup<'x>(_: &Context<'x>, v: &[Variable<'x>]) -> Variable<'x> {
|
||||
let arr = v[0].to_array();
|
||||
let mut result = Vec::with_capacity(arr.len());
|
||||
let capacity = arr.len().min(MAX_PRESIZE);
|
||||
let mut result = Vec::with_capacity(capacity);
|
||||
|
||||
for item in arr.iter() {
|
||||
if !result.contains(item) {
|
||||
result.push(item.clone());
|
||||
if arr.len() <= LINEAR_DEDUP_MAX {
|
||||
let mut seen: SmallVec<[DedupKey<'_>; LINEAR_DEDUP_MAX]> = SmallVec::new();
|
||||
for item in arr.iter() {
|
||||
let key = DedupKey::from(item);
|
||||
if !seen.contains(&key) {
|
||||
seen.push(key);
|
||||
result.push(item.clone());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut seen = AHashSet::with_capacity(capacity);
|
||||
for item in arr.iter() {
|
||||
if seen.insert(DedupKey::from(item)) {
|
||||
result.push(item.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.into()
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash)]
|
||||
enum DedupKey<'a> {
|
||||
Text(&'a str),
|
||||
Integer(i64),
|
||||
Float(u64),
|
||||
Array(&'a [Variable<'a>]),
|
||||
}
|
||||
|
||||
impl<'a> From<&'a Variable<'a>> for DedupKey<'a> {
|
||||
fn from(value: &'a Variable<'a>) -> Self {
|
||||
match value {
|
||||
Variable::String(text) => DedupKey::Text(text),
|
||||
Variable::Integer(number) => DedupKey::Integer(*number),
|
||||
Variable::Float(number) => DedupKey::Float(number.to_bits()),
|
||||
Variable::Array(items) => DedupKey::Array(items),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fn_cosine_similarity<'x>(_: &Context<'x>, v: &[Variable<'x>]) -> Variable<'x> {
|
||||
let mut word_freq: AHashMap<Variable, [u32; 2]> = AHashMap::with_capacity(
|
||||
v.iter()
|
||||
|
|
@ -168,3 +202,8 @@ pub fn fn_winnow<'x>(_: &Context<'x>, v: &[Variable<'x>]) -> Variable<'x> {
|
|||
v => v.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../../stalwart-tests/unit/common/src/scripts/functions/array/tests.rs"]
|
||||
mod tests;
|
||||
|
|
|
|||
66
crates/common/src/storage/create_lock.rs
Normal file
66
crates/common/src/storage/create_lock.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{KV_LOCK_CREATE, Server};
|
||||
use std::{ops::RangeInclusive, time::Duration};
|
||||
use store::{
|
||||
U32_LEN, U64_LEN,
|
||||
rand::{self, RngExt},
|
||||
xxhash_rust::xxh3::xxh3_64,
|
||||
};
|
||||
use trc::AddContext;
|
||||
|
||||
pub const CREATE_LOCK_ATTEMPTS: u32 = 3;
|
||||
const CREATE_LOCK_EXPIRY_SECS: u64 = 10;
|
||||
const CREATE_LOCK_RETRY_MS: RangeInclusive<u64> = 500..=1500;
|
||||
const CREATE_LOCK_KEY_LEN: usize = U32_LEN + 1 + U64_LEN;
|
||||
|
||||
pub struct CreateLock {
|
||||
key: [u8; CREATE_LOCK_KEY_LEN],
|
||||
}
|
||||
|
||||
impl CreateLock {
|
||||
pub fn new(account_id: u32, collection: u8, name: &[u8]) -> Self {
|
||||
let mut key = [0u8; CREATE_LOCK_KEY_LEN];
|
||||
for (dst, src) in key.iter_mut().zip(
|
||||
account_id
|
||||
.to_be_bytes()
|
||||
.into_iter()
|
||||
.chain([collection])
|
||||
.chain(xxh3_64(name).to_be_bytes()),
|
||||
) {
|
||||
*dst = src;
|
||||
}
|
||||
CreateLock { key }
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
pub async fn try_create_lock(&self, lock: &CreateLock) -> trc::Result<bool> {
|
||||
self.in_memory_store()
|
||||
.try_lock(KV_LOCK_CREATE, &lock.key, CREATE_LOCK_EXPIRY_SECS)
|
||||
.await
|
||||
.caused_by(trc::location!())
|
||||
}
|
||||
|
||||
pub async fn create_lock_backoff(&self) {
|
||||
let backoff = rand::rng().random_range(CREATE_LOCK_RETRY_MS);
|
||||
tokio::time::sleep(Duration::from_millis(backoff)).await;
|
||||
}
|
||||
|
||||
pub async fn release_create_lock(&self, lock: &CreateLock) {
|
||||
if let Err(err) = self
|
||||
.in_memory_store()
|
||||
.remove_lock(KV_LOCK_CREATE, &lock.key)
|
||||
.await
|
||||
{
|
||||
trc::error!(
|
||||
err.details("Failed to release resource creation lock")
|
||||
.caused_by(trc::location!())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -28,6 +28,7 @@ pub mod archive;
|
|||
pub mod batch;
|
||||
pub mod blob;
|
||||
pub mod chunk;
|
||||
pub mod create_lock;
|
||||
pub mod dav;
|
||||
pub mod document;
|
||||
pub mod encryption;
|
||||
|
|
|
|||
|
|
@ -5,14 +5,14 @@
|
|||
*/
|
||||
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::{ErrorKind, Write},
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{self, ErrorKind, Write},
|
||||
path::PathBuf,
|
||||
thread::Builder,
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use crate::config::telemetry::{LogTracer, RotationStrategy};
|
||||
use crate::config::telemetry::{LogFiles, LogTracer, RotationStrategy};
|
||||
|
||||
use compact_str::{CompactString, ToCompactString};
|
||||
use mail_parser::DateTime;
|
||||
|
|
@ -219,3 +219,21 @@ impl LogTracer {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LogFiles {
|
||||
pub fn newest_first(&self) -> io::Result<Vec<PathBuf>> {
|
||||
let mut files = Vec::new();
|
||||
for entry in fs::read_dir(&self.path)? {
|
||||
let entry = entry?;
|
||||
let is_log = entry.file_name().to_str().is_some_and(|name| {
|
||||
name.strip_prefix(self.prefix.as_str())
|
||||
.is_some_and(|suffix| suffix.is_empty() || suffix.starts_with('.'))
|
||||
});
|
||||
if is_log && entry.file_type()?.is_file() {
|
||||
files.push(entry.path());
|
||||
}
|
||||
}
|
||||
files.sort_unstable_by(|a, b| b.file_name().cmp(&a.file_name()));
|
||||
Ok(files)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "coordinator"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "crypto"
|
||||
description = "OpenPGP and S/MIME encryption, key validation and signature verification"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "dav-proto"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -8,8 +8,9 @@ use super::{RawElement, Token, XmlValueParser, tokenizer::Tokenizer, value::Inhe
|
|||
use crate::schema::{
|
||||
Attribute, AttributeValue, Element, NamedElement, Namespace,
|
||||
property::{
|
||||
CalDavProperty, CalDavPropertyName, CalendarData, CardDavProperty, CardDavPropertyName,
|
||||
Comp, DavProperty, DavValue, PrincipalProperty, ResourceType, WebDavProperty,
|
||||
AvailabilityNamespace, CalDavProperty, CalDavPropertyName, CalendarData, CardDavProperty,
|
||||
CardDavPropertyName, Comp, DavProperty, DavValue, PrincipalProperty, ResourceType,
|
||||
WebDavProperty,
|
||||
},
|
||||
request::{DavPropertyValue, VCardPropertyWithGroup},
|
||||
response::List,
|
||||
|
|
@ -312,7 +313,10 @@ impl<'x> Tokenizer<'x> {
|
|||
None => DavValue::Null,
|
||||
}
|
||||
}
|
||||
DavProperty::CalDav(CalDavProperty::CalendarTimezone) => {
|
||||
DavProperty::CalDav(
|
||||
CalDavProperty::CalendarTimezone
|
||||
| CalDavProperty::CalendarAvailability(_),
|
||||
) => {
|
||||
match self
|
||||
.collect_string_value()?
|
||||
.map(|v| ICalendar::parse(&v).map_err(|_| v))
|
||||
|
|
@ -599,6 +603,9 @@ impl DavProperty {
|
|||
(Namespace::CalDav, Element::ScheduleTag) => {
|
||||
Some(DavProperty::CalDav(CalDavProperty::ScheduleTag))
|
||||
}
|
||||
(Namespace::CalDav, Element::CalendarAvailability) => Some(DavProperty::CalDav(
|
||||
CalDavProperty::CalendarAvailability(AvailabilityNamespace::CalDav),
|
||||
)),
|
||||
(Namespace::CalDav, Element::ScheduleCalendarTransp) => {
|
||||
Some(DavProperty::CalDav(CalDavProperty::ScheduleCalendarTransp))
|
||||
}
|
||||
|
|
@ -629,6 +636,11 @@ impl DavProperty {
|
|||
(Namespace::CalendarServer, Element::Getctag) => {
|
||||
Some(DavProperty::WebDav(WebDavProperty::GetCTag))
|
||||
}
|
||||
(Namespace::CalendarServer, Element::CalendarAvailability) => {
|
||||
Some(DavProperty::CalDav(CalDavProperty::CalendarAvailability(
|
||||
AvailabilityNamespace::CalendarServer,
|
||||
)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@ use super::{XmlCdataEscape, XmlEscape};
|
|||
use crate::schema::{
|
||||
Namespace, Namespaces,
|
||||
property::{
|
||||
ActiveLock, CalDavProperty, CardDavProperty, Comp, DavProperty, DavValue, LockDiscovery,
|
||||
LockEntry, PrincipalProperty, Privilege, ReportSet, ResourceType, Rfc1123DateTime,
|
||||
SupportedCollation, SupportedLock, WebDavProperty,
|
||||
ActiveLock, AvailabilityNamespace, CalDavProperty, CardDavProperty, Comp, DavProperty,
|
||||
DavValue, LockDiscovery, LockEntry, PrincipalProperty, Privilege, ReportSet, ResourceType,
|
||||
Rfc1123DateTime, SupportedCollation, SupportedLock, WebDavProperty,
|
||||
},
|
||||
request::DavPropertyValue,
|
||||
response::{Ace, AclRestrictions, Href, List, PropResponse, SupportedPrivilege},
|
||||
|
|
@ -143,8 +143,6 @@ impl DavValue {
|
|||
Comp(ICalendarComponentType::VAlarm),
|
||||
Comp(ICalendarComponentType::Standard),
|
||||
Comp(ICalendarComponentType::Daylight),
|
||||
Comp(ICalendarComponentType::VAvailability),
|
||||
Comp(ICalendarComponentType::Available),
|
||||
Comp(ICalendarComponentType::Participant),
|
||||
Comp(ICalendarComponentType::VLocation),
|
||||
Comp(ICalendarComponentType::VResource),
|
||||
|
|
@ -207,6 +205,12 @@ impl DavProperty {
|
|||
CalDavProperty::ScheduleDefaultCalendarURL => "A:schedule-default-calendar-URL",
|
||||
CalDavProperty::ScheduleTag => "A:schedule-tag",
|
||||
CalDavProperty::ScheduleCalendarTransp => "A:schedule-calendar-transp",
|
||||
CalDavProperty::CalendarAvailability(AvailabilityNamespace::CalDav) => {
|
||||
"A:calendar-availability"
|
||||
}
|
||||
CalDavProperty::CalendarAvailability(AvailabilityNamespace::CalendarServer) => {
|
||||
"C:calendar-availability"
|
||||
}
|
||||
},
|
||||
DavProperty::Principal(prop) => match prop {
|
||||
PrincipalProperty::AlternateURISet => "D:alternate-URI-set",
|
||||
|
|
@ -227,7 +231,10 @@ impl DavProperty {
|
|||
|
||||
pub fn namespace(&self) -> Namespace {
|
||||
match self {
|
||||
DavProperty::WebDav(WebDavProperty::GetCTag) => Namespace::CalendarServer,
|
||||
DavProperty::WebDav(WebDavProperty::GetCTag)
|
||||
| DavProperty::CalDav(CalDavProperty::CalendarAvailability(
|
||||
AvailabilityNamespace::CalendarServer,
|
||||
)) => Namespace::CalendarServer,
|
||||
DavProperty::CardDav(_)
|
||||
| DavProperty::Principal(
|
||||
PrincipalProperty::AddressbookHomeSet | PrincipalProperty::PrincipalAddress,
|
||||
|
|
|
|||
|
|
@ -122,6 +122,17 @@ pub enum CalDavProperty {
|
|||
ScheduleDefaultCalendarURL,
|
||||
ScheduleTag,
|
||||
ScheduleCalendarTransp,
|
||||
CalendarAvailability(AvailabilityNamespace),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
all(test, stalwart_tests),
|
||||
derive(serde::Serialize, serde::Deserialize)
|
||||
)]
|
||||
pub enum AvailabilityNamespace {
|
||||
CalDav,
|
||||
CalendarServer,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "dav"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
185
crates/dav/src/calendar/availability.rs
Normal file
185
crates/dav/src/calendar/availability.rs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{DavError, PropStatBuilder, common::uri::DavUriResource};
|
||||
use calcard::icalendar::ICalendar;
|
||||
use common::{Server, auth::AccessToken};
|
||||
use dav_proto::{
|
||||
RequestHeaders, Return,
|
||||
schema::{
|
||||
Namespace,
|
||||
property::{CalDavProperty, DavProperty, DavValue},
|
||||
request::{DavPropertyValue, PropertyUpdate, PropertyUpdateOp},
|
||||
response::{CalCondition, MultiStatus, Response},
|
||||
},
|
||||
};
|
||||
use groupware::{
|
||||
cache::GroupwareCache,
|
||||
calendar::{
|
||||
SCHEDULE_INBOX_ID,
|
||||
working_hours::{
|
||||
WorkingHoursChange, WorkingHoursHandler, WorkingHoursUpdate, WorkingSchedule,
|
||||
ical::parse_vavailability,
|
||||
},
|
||||
},
|
||||
};
|
||||
use http_proto::HttpResponse;
|
||||
use hyper::StatusCode;
|
||||
use registry::schema::enums::Permission;
|
||||
use store::write::now;
|
||||
use trc::AddContext;
|
||||
use types::collection::SyncCollection;
|
||||
|
||||
pub(crate) trait CalendarAvailabilityRequestHandler: Sync + Send {
|
||||
fn handle_scheduling_proppatch_request(
|
||||
&self,
|
||||
access_token: &AccessToken,
|
||||
headers: &RequestHeaders<'_>,
|
||||
request: PropertyUpdate,
|
||||
) -> impl Future<Output = crate::Result<HttpResponse>> + Send;
|
||||
}
|
||||
|
||||
impl CalendarAvailabilityRequestHandler for Server {
|
||||
async fn handle_scheduling_proppatch_request(
|
||||
&self,
|
||||
access_token: &AccessToken,
|
||||
headers: &RequestHeaders<'_>,
|
||||
request: PropertyUpdate,
|
||||
) -> crate::Result<HttpResponse> {
|
||||
let resource_ = self
|
||||
.validate_uri(access_token, headers.uri)
|
||||
.await?
|
||||
.into_owned_uri()?;
|
||||
let account_id = resource_.account_id;
|
||||
let resources = self
|
||||
.fetch_groupware_resources(
|
||||
access_token.account_id(),
|
||||
account_id,
|
||||
SyncCollection::CalendarEventNotification,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let resource = resource_
|
||||
.resource
|
||||
.and_then(|path| resources.by_path(path))
|
||||
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
if !resource.is_container() || resource.document_id() != SCHEDULE_INBOX_ID {
|
||||
return Err(DavError::Code(StatusCode::METHOD_NOT_ALLOWED));
|
||||
}
|
||||
if !access_token.is_member(account_id)
|
||||
|| !access_token.has_permission(Permission::SysCalendarSettingsUpdate)
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
if request.ops.is_empty() {
|
||||
return Ok(HttpResponse::new(StatusCode::NO_CONTENT));
|
||||
}
|
||||
|
||||
let mut items = PropStatBuilder::default();
|
||||
let mut change = None;
|
||||
let mut multistatus =
|
||||
MultiStatus::new(Vec::with_capacity(1)).with_namespace(Namespace::CalDav);
|
||||
for op in request.ops {
|
||||
multistatus.set_namespace(match &op {
|
||||
PropertyUpdateOp::Set(DavPropertyValue { property, .. })
|
||||
| PropertyUpdateOp::Remove(property) => property.namespace(),
|
||||
});
|
||||
match op {
|
||||
PropertyUpdateOp::Set(DavPropertyValue {
|
||||
property:
|
||||
property @ DavProperty::CalDav(CalDavProperty::CalendarAvailability(_)),
|
||||
value,
|
||||
}) => match value {
|
||||
DavValue::ICalendar(ical)
|
||||
if ical.size() > self.core.groupware.max_ical_size =>
|
||||
{
|
||||
items.insert_error_with_description(
|
||||
property,
|
||||
StatusCode::INSUFFICIENT_STORAGE,
|
||||
"Property value is too long",
|
||||
);
|
||||
}
|
||||
DavValue::ICalendar(ical) => match working_hours_change(&ical) {
|
||||
Ok(new_change) => {
|
||||
change = Some(new_change);
|
||||
items.insert_ok(property);
|
||||
}
|
||||
Err(description) => {
|
||||
items.insert_precondition_failed_with_description(
|
||||
property,
|
||||
StatusCode::FORBIDDEN,
|
||||
CalCondition::ValidCalendarData,
|
||||
description,
|
||||
);
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
items.insert_precondition_failed_with_description(
|
||||
property,
|
||||
StatusCode::FORBIDDEN,
|
||||
CalCondition::ValidCalendarData,
|
||||
"Invalid calendar data",
|
||||
);
|
||||
}
|
||||
},
|
||||
PropertyUpdateOp::Remove(
|
||||
property @ DavProperty::CalDav(CalDavProperty::CalendarAvailability(_)),
|
||||
) => {
|
||||
change = Some(WorkingHoursChange::Disable);
|
||||
items.insert_ok(property);
|
||||
}
|
||||
PropertyUpdateOp::Set(DavPropertyValue { property, .. })
|
||||
| PropertyUpdateOp::Remove(property) => {
|
||||
items.insert_error_with_description(
|
||||
property,
|
||||
StatusCode::FORBIDDEN,
|
||||
"Property cannot be modified",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let is_success = !items.has_errors();
|
||||
if is_success {
|
||||
if let Some(change) = change {
|
||||
match self
|
||||
.update_working_hours(account_id, change)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
WorkingHoursUpdate::Updated => {}
|
||||
WorkingHoursUpdate::NotSupported => {
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
WorkingHoursUpdate::Rejected => {
|
||||
return Err(DavError::Code(StatusCode::CONFLICT));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
items.fail_dependencies();
|
||||
}
|
||||
|
||||
if headers.ret != Return::Minimal || !is_success {
|
||||
multistatus.add_response(Response::new_propstat(headers.uri, items.build()));
|
||||
Ok(HttpResponse::new(StatusCode::MULTI_STATUS).with_xml_body(multistatus.to_string()))
|
||||
} else {
|
||||
Ok(HttpResponse::new(StatusCode::NO_CONTENT))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn working_hours_change(ical: &ICalendar) -> Result<WorkingHoursChange, String> {
|
||||
let hours = parse_vavailability(ical, now() as i64).map_err(|err| err.to_string())?;
|
||||
if WorkingSchedule::parse(&hours, None)
|
||||
.map_err(|err| err.to_string())?
|
||||
.covers_whole_week()
|
||||
{
|
||||
Ok(WorkingHoursChange::Disable)
|
||||
} else {
|
||||
Ok(WorkingHoursChange::Replace(hours))
|
||||
}
|
||||
}
|
||||
|
|
@ -91,21 +91,6 @@ impl CalendarCopyMoveRequestHandler for Server {
|
|||
let from_resource = from_resources
|
||||
.by_path(from_resource_name)
|
||||
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
#[cfg(not(any(feature = "dev_mode", stalwart_tests)))]
|
||||
if is_move
|
||||
&& from_resource.is_container()
|
||||
&& self
|
||||
.core
|
||||
.groupware
|
||||
.default_calendar_name
|
||||
.as_ref()
|
||||
.is_some_and(|name| name == from_resource_name)
|
||||
{
|
||||
return Err(DavError::Condition(crate::DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
dav_proto::schema::response::CalCondition::DefaultCalendarNeeded,
|
||||
)));
|
||||
}
|
||||
|
||||
// Validate ACL
|
||||
let is_from_owner = access_token.is_member(from_account_id);
|
||||
|
|
@ -1261,6 +1246,15 @@ async fn copy_container(
|
|||
new_name: &str,
|
||||
remove_source: bool,
|
||||
) -> crate::Result<HttpResponse> {
|
||||
#[cfg(not(any(feature = "dev_mode", stalwart_tests)))]
|
||||
if remove_source && server.default_calendar_id(from_account_id).await? == Some(from_document_id)
|
||||
{
|
||||
return Err(DavError::Condition(crate::DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
dav_proto::schema::response::CalCondition::DefaultCalendarNeeded,
|
||||
)));
|
||||
}
|
||||
|
||||
// Fetch calendar
|
||||
let calendar_ = server
|
||||
.store()
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::assert_event_privacy_access;
|
||||
use crate::{
|
||||
DavError, DavMethod,
|
||||
common::{
|
||||
|
|
@ -19,17 +18,13 @@ use groupware::{
|
|||
DestroyArchive,
|
||||
cache::GroupwareCache,
|
||||
calendar::{
|
||||
Calendar, CalendarEvent, CalendarEventContent, EVENT_HAS_ALARMS,
|
||||
identity::ParticipantIdentityAddresses,
|
||||
notification::{NotificationAudience, may_have_viewers},
|
||||
Calendar, EVENT_HAS_ALARMS,
|
||||
privacy::EventViewer,
|
||||
rights::EventAcl,
|
||||
storage::{DirectChange, DirectChangeNotification, NotificationQuota},
|
||||
write::{EventWriter, ItipMode},
|
||||
},
|
||||
};
|
||||
use http_proto::HttpResponse;
|
||||
use hyper::StatusCode;
|
||||
use registry::schema::enums::Permission;
|
||||
use store::write::BatchBuilder;
|
||||
use store::{
|
||||
ValueKey,
|
||||
|
|
@ -37,9 +32,8 @@ use store::{
|
|||
};
|
||||
use trc::AddContext;
|
||||
use types::{
|
||||
acl::Acl,
|
||||
collection::{Collection, SyncCollection},
|
||||
field::{CalendarEventField, PrincipalField},
|
||||
field::PrincipalField,
|
||||
};
|
||||
|
||||
pub(crate) trait CalendarDeleteRequestHandler: Sync + Send {
|
||||
|
|
@ -81,23 +75,23 @@ impl CalendarDeleteRequestHandler for Server {
|
|||
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let document_id = delete_resource.document_id();
|
||||
let account_info = self.account_info(account_id).await?;
|
||||
let send_itip = self.core.groupware.itip_enabled
|
||||
&& !headers.no_schedule_reply
|
||||
&& !account_info.addresses().is_empty()
|
||||
&& access_token.has_permission(Permission::CalendarSchedulingSend);
|
||||
let writer = EventWriter {
|
||||
server: self,
|
||||
access_token,
|
||||
account_id,
|
||||
resources: &resources,
|
||||
account_info: &account_info,
|
||||
};
|
||||
let itip = if headers.no_schedule_reply {
|
||||
ItipMode::Suppress
|
||||
} else {
|
||||
ItipMode::Send
|
||||
};
|
||||
|
||||
// Fetch entry
|
||||
let mut batch = BatchBuilder::new();
|
||||
if delete_resource.is_container() {
|
||||
// Deleting the default calendar is not allowed
|
||||
#[cfg(not(any(feature = "dev_mode", stalwart_tests)))]
|
||||
if self
|
||||
.core
|
||||
.groupware
|
||||
.default_calendar_name
|
||||
.as_ref()
|
||||
.is_some_and(|name| name == delete_path)
|
||||
{
|
||||
if self.default_calendar_id(account_id).await? == Some(document_id) {
|
||||
return Err(DavError::Condition(crate::DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
dav_proto::schema::response::CalCondition::DefaultCalendarNeeded,
|
||||
|
|
@ -154,6 +148,7 @@ impl CalendarDeleteRequestHandler for Server {
|
|||
.await?;
|
||||
|
||||
// Delete calendar and events
|
||||
let mut batch = BatchBuilder::new();
|
||||
let cleanup = self
|
||||
.preload_container_cleanup(
|
||||
account_info.changed_by(),
|
||||
|
|
@ -182,7 +177,7 @@ impl CalendarDeleteRequestHandler for Server {
|
|||
&resources.event_ids_with_flags(EVENT_HAS_ALARMS),
|
||||
&cleanup,
|
||||
resources.format_resource(delete_resource).into(),
|
||||
send_itip,
|
||||
writer.sends_itip(itip),
|
||||
&mut batch,
|
||||
)
|
||||
.await
|
||||
|
|
@ -194,79 +189,13 @@ impl CalendarDeleteRequestHandler for Server {
|
|||
.with_collection(Collection::Principal)
|
||||
.with_document(0)
|
||||
.clear_if_equals(PrincipalField::DefaultCalendarId, document_id);
|
||||
self.commit_batch(batch).await.caused_by(trc::location!())?;
|
||||
} else {
|
||||
// Validate ACL
|
||||
let calendar_id = delete_resource
|
||||
.parent_id()
|
||||
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let is_owner = access_token.is_member(account_id);
|
||||
assert_event_privacy_access(
|
||||
delete_resource.resource.event_flags(),
|
||||
EventViewer::new(is_owner),
|
||||
)?;
|
||||
let may_remove_items = is_owner
|
||||
|| resources.has_access_to_container(access_token, calendar_id, Acl::RemoveItems);
|
||||
if !may_remove_items
|
||||
&& !EventAcl::for_calendar(&resources, access_token, calendar_id)
|
||||
.may_manage_own_items()
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
let deletion = writer.prepare_delete(calendar_id, document_id).await?;
|
||||
|
||||
let event_ = self
|
||||
.store()
|
||||
.get_value::<Archive<ArchiveBytes>>(ValueKey::archive(
|
||||
account_id,
|
||||
Collection::CalendarEvent,
|
||||
document_id,
|
||||
))
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let event = event_
|
||||
.to_unarchived::<CalendarEvent>()
|
||||
.caused_by(trc::location!())?;
|
||||
let event_flags = event.inner.flags.to_native();
|
||||
let may_notify = may_have_viewers(
|
||||
access_token,
|
||||
account_id,
|
||||
&resources,
|
||||
&[calendar_id],
|
||||
NotificationAudience::of_event(event_flags),
|
||||
);
|
||||
let content_ = if !may_remove_items || may_notify {
|
||||
self.store()
|
||||
.get_value::<Archive<ArchiveBytes>>(ValueKey::property(
|
||||
account_id,
|
||||
Collection::CalendarEvent,
|
||||
document_id,
|
||||
CalendarEventField::Content,
|
||||
))
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let previous_event = content_
|
||||
.as_ref()
|
||||
.map(|content| content.deserialize::<CalendarEventContent>())
|
||||
.transpose()
|
||||
.caused_by(trc::location!())?
|
||||
.map(|content| content.data.event);
|
||||
if !may_remove_items {
|
||||
let identities = self
|
||||
.account_identity_addresses(access_token.account_id())
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
if !previous_event
|
||||
.as_ref()
|
||||
.is_some_and(|ical| identities.event_ownership(ical).may_write_own())
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
}
|
||||
|
||||
// Validate headers
|
||||
self.validate_headers(
|
||||
access_token,
|
||||
headers,
|
||||
|
|
@ -274,7 +203,16 @@ impl CalendarDeleteRequestHandler for Server {
|
|||
account_id,
|
||||
collection: Collection::CalendarEvent,
|
||||
document_id: document_id.into(),
|
||||
etag: format!("\"{}\"", event.inner.etag.to_native()).into(),
|
||||
etag: format!(
|
||||
"\"{}\"",
|
||||
deletion
|
||||
.event()
|
||||
.caused_by(trc::location!())?
|
||||
.inner
|
||||
.etag
|
||||
.to_native()
|
||||
)
|
||||
.into(),
|
||||
path: delete_path,
|
||||
..Default::default()
|
||||
}],
|
||||
|
|
@ -283,50 +221,16 @@ impl CalendarDeleteRequestHandler for Server {
|
|||
)
|
||||
.await?;
|
||||
|
||||
// Validate schedule tag
|
||||
if headers.if_schedule_tag.is_some()
|
||||
&& event.inner.schedule_tag.as_ref().map(|t| t.to_native())
|
||||
!= headers.if_schedule_tag
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::PRECONDITION_FAILED));
|
||||
}
|
||||
|
||||
// Delete event
|
||||
if let Some(previous) = previous_event {
|
||||
self.notify_direct_change(
|
||||
access_token,
|
||||
account_id,
|
||||
DirectChange::Destroyed {
|
||||
event_id: document_id,
|
||||
previous,
|
||||
calendar_ids: vec![calendar_id],
|
||||
event_flags,
|
||||
},
|
||||
Some(&resources),
|
||||
&mut NotificationQuota::default(),
|
||||
&mut batch,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
}
|
||||
DestroyArchive(event)
|
||||
writer
|
||||
.delete(
|
||||
self,
|
||||
&account_info,
|
||||
account_id,
|
||||
document_id,
|
||||
calendar_id,
|
||||
content_,
|
||||
deletion,
|
||||
headers.if_schedule_tag,
|
||||
itip,
|
||||
resources.format_resource(delete_resource).into(),
|
||||
send_itip,
|
||||
&mut batch,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
.await?;
|
||||
}
|
||||
|
||||
self.commit_batch(batch).await.caused_by(trc::location!())?;
|
||||
|
||||
Ok(HttpResponse::new(StatusCode::NO_CONTENT))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ use groupware::{
|
|||
availability::{AvailabilityCalendars, ComponentBusy, Inclusion, PrincipalRole},
|
||||
identity::ParticipantIdentityAddresses,
|
||||
privacy::EventPrivacy,
|
||||
working_hours::WorkingHoursHandler,
|
||||
},
|
||||
};
|
||||
use http_proto::HttpResponse;
|
||||
|
|
@ -184,6 +185,7 @@ impl CalendarFreebusyRequestHandler for Server {
|
|||
let mut document_ids = RoaringBitmap::new();
|
||||
let mut selected = AHashMap::new();
|
||||
let mut role = PrincipalRole::Owner;
|
||||
let is_itip = matches!(scope, FreeBusyScope::Account(_));
|
||||
match scope {
|
||||
FreeBusyScope::Collection(collection) => {
|
||||
let shared_acls =
|
||||
|
|
@ -405,6 +407,32 @@ impl CalendarFreebusyRequestHandler for Server {
|
|||
.caused_by(trc::location!())?;
|
||||
}
|
||||
|
||||
if is_itip
|
||||
&& total_instances <= max_instances
|
||||
&& let Some(account) = self
|
||||
.try_account(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
&& let Some(schedule) = self
|
||||
.working_schedule(&account)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
let unavailable = fb_entries
|
||||
.entry(ICalendarFreeBusyType::BusyUnavailable)
|
||||
.or_default();
|
||||
for interval in schedule.unavailable(range.start, range.end) {
|
||||
total_instances = total_instances.saturating_add(1);
|
||||
if total_instances > max_instances {
|
||||
break;
|
||||
}
|
||||
unavailable.push(interval);
|
||||
}
|
||||
if unavailable.is_empty() {
|
||||
fb_entries.remove(&ICalendarFreeBusyType::BusyUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
if total_instances > max_instances {
|
||||
return Err(DavError::Code(StatusCode::PAYLOAD_TOO_LARGE));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod availability;
|
||||
pub mod copy_move;
|
||||
pub mod delete;
|
||||
pub mod filter;
|
||||
|
|
@ -29,17 +30,18 @@ use dav_proto::schema::{
|
|||
property::{CalDavProperty, CalendarData, DavProperty, WebDavProperty},
|
||||
response::CalCondition,
|
||||
};
|
||||
use groupware::{
|
||||
calendar::{
|
||||
Alarm, ArchivedCalendarEvent, ArchivedCalendarEventContent, Calendar, CalendarEventContent,
|
||||
EVENT_HAS_ALARMS, SupportedComponent,
|
||||
alarm::ExpandAlarm,
|
||||
alerts::{DefaultAlertsResolver, DefaultAlertsView, ICalendarDefaultAlerts},
|
||||
compare::{ComparisonScope, RecurrenceComponents},
|
||||
privacy::{EventPrivacy, EventViewer, ICalendarPrivacy, PrivacyDenied},
|
||||
user::{ICalendarUserData, UserDataError, UserDataView},
|
||||
use groupware::calendar::{
|
||||
Alarm, ArchivedCalendarEvent, ArchivedCalendarEventContent, CalendarEventContent,
|
||||
EVENT_HAS_ALARMS, SupportedComponent,
|
||||
alarm::ExpandAlarm,
|
||||
alerts::{DefaultAlertsResolver, DefaultAlertsView, ICalendarDefaultAlerts},
|
||||
compare::RecurrenceComponents,
|
||||
privacy::{EventPrivacy, EventViewer},
|
||||
user::{ICalendarUserData, UserDataError, UserDataView},
|
||||
write::{
|
||||
EventWriteError, SchedulingPrecondition, SupportedComponents, assert_privacy_access,
|
||||
assert_unique_uid,
|
||||
},
|
||||
scheduling::ItipError,
|
||||
};
|
||||
use hyper::StatusCode;
|
||||
use store::{
|
||||
|
|
@ -48,7 +50,6 @@ use store::{
|
|||
};
|
||||
use trc::AddContext;
|
||||
use types::{collection::Collection, field::CalendarEventField};
|
||||
use utils::map::bitmap::Bitmap;
|
||||
|
||||
pub(crate) static CALENDAR_CONTAINER_PROPS: [DavProperty; 31] = [
|
||||
DavProperty::WebDav(WebDavProperty::CreationDate),
|
||||
|
|
@ -119,30 +120,7 @@ pub(crate) fn assert_is_unique_uid(
|
|||
calendar_id: u32,
|
||||
uid: Option<&str>,
|
||||
) -> crate::Result<()> {
|
||||
let Some(uid) = uid else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let is_owner = access_token.is_member(account_id);
|
||||
let mut has_hidden_conflict = false;
|
||||
for path in resources.children_with_uid(calendar_id, uid) {
|
||||
if is_owner
|
||||
|| EventPrivacy::from_flags(path.resource.event_flags().unwrap_or_default())
|
||||
!= EventPrivacy::Secret
|
||||
{
|
||||
return Err(DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CalCondition::NoUidConflict(resources.format_resource(path).into()),
|
||||
)));
|
||||
}
|
||||
has_hidden_conflict = true;
|
||||
}
|
||||
|
||||
if has_hidden_conflict {
|
||||
Err(DavError::Code(StatusCode::FORBIDDEN))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
assert_unique_uid(resources, access_token, account_id, calendar_id, uid).map_err(Into::into)
|
||||
}
|
||||
|
||||
impl ContainerOperation {
|
||||
|
|
@ -167,25 +145,6 @@ impl ContainerOperation {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) struct SupportedComponents(Bitmap<SupportedComponent>);
|
||||
|
||||
impl SupportedComponents {
|
||||
fn is_restricted(&self) -> bool {
|
||||
!self.0.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn assert_supports(&self, component: SupportedComponent) -> crate::Result<()> {
|
||||
if !self.is_restricted() || self.0.contains(component) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CalCondition::SupportedCalendarComponent,
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait CalendarObjectComponent {
|
||||
fn object_component(&self) -> SupportedComponent;
|
||||
}
|
||||
|
|
@ -209,12 +168,6 @@ impl CalendarObjectComponent for ArchivedICalendar {
|
|||
}
|
||||
|
||||
pub(crate) trait CalendarComponentSupport: Sync + Send {
|
||||
fn supported_components(
|
||||
&self,
|
||||
account_id: u32,
|
||||
calendar_id: u32,
|
||||
) -> impl Future<Output = crate::Result<SupportedComponents>> + Send;
|
||||
|
||||
fn assert_stored_event_supported(
|
||||
&self,
|
||||
event_account_id: u32,
|
||||
|
|
@ -225,32 +178,6 @@ pub(crate) trait CalendarComponentSupport: Sync + Send {
|
|||
}
|
||||
|
||||
impl CalendarComponentSupport for Server {
|
||||
async fn supported_components(
|
||||
&self,
|
||||
account_id: u32,
|
||||
calendar_id: u32,
|
||||
) -> crate::Result<SupportedComponents> {
|
||||
self.store()
|
||||
.get_value::<Archive<ArchiveBytes>>(ValueKey::archive(
|
||||
account_id,
|
||||
Collection::Calendar,
|
||||
calendar_id,
|
||||
))
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.map(|archive| {
|
||||
archive
|
||||
.unarchive::<Calendar>()
|
||||
.map(|calendar| calendar.supported_components.to_native())
|
||||
})
|
||||
.transpose()
|
||||
.caused_by(trc::location!())
|
||||
.map(|supported_components| {
|
||||
SupportedComponents(Bitmap::from(supported_components.unwrap_or_default()))
|
||||
})
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
async fn assert_stored_event_supported(
|
||||
&self,
|
||||
event_account_id: u32,
|
||||
|
|
@ -258,7 +185,8 @@ impl CalendarComponentSupport for Server {
|
|||
account_id: u32,
|
||||
calendar_id: u32,
|
||||
) -> crate::Result<Option<Archive<ArchiveBytes>>> {
|
||||
let supported_components = self.supported_components(account_id, calendar_id).await?;
|
||||
let supported_components =
|
||||
SupportedComponents::fetch(self, account_id, calendar_id).await?;
|
||||
if !supported_components.is_restricted() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
|
@ -290,31 +218,7 @@ pub(crate) fn assert_event_privacy_access(
|
|||
flags: Option<u16>,
|
||||
viewer: EventViewer,
|
||||
) -> crate::Result<()> {
|
||||
flags
|
||||
.map(EventPrivacy::from_flags)
|
||||
.unwrap_or_default()
|
||||
.check_access(viewer)
|
||||
.map_err(|denied| {
|
||||
DavError::Code(match denied {
|
||||
PrivacyDenied::Forbidden => StatusCode::FORBIDDEN,
|
||||
PrivacyDenied::NotFound => StatusCode::NOT_FOUND,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn assert_event_privacy_allowed(
|
||||
ical: &ICalendar,
|
||||
viewer: EventViewer,
|
||||
) -> crate::Result<()> {
|
||||
if ical.privacy().may_be_set_by(viewer) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(DavError::Code(StatusCode::FORBIDDEN))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn serves_ical(view: &ICalendar, submitted: &ICalendar) -> bool {
|
||||
view == submitted || ComparisonScope::SharedData.component_eq(view, 0, submitted, 0)
|
||||
assert_privacy_access(flags, viewer).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub(crate) trait CalendarEventView: Sync + Send {
|
||||
|
|
@ -475,31 +379,61 @@ pub(crate) fn user_data_error(err: UserDataError) -> DavError {
|
|||
)
|
||||
}
|
||||
|
||||
pub(crate) trait ItipPrecondition {
|
||||
fn failed_precondition(&self) -> Option<CalCondition>;
|
||||
}
|
||||
|
||||
impl ItipPrecondition for ItipError {
|
||||
fn failed_precondition(&self) -> Option<CalCondition> {
|
||||
match self {
|
||||
ItipError::MultipleOrganizer => Some(CalCondition::SameOrganizerInAllComponents),
|
||||
ItipError::OrganizerIsLocalAddress
|
||||
| ItipError::SenderIsNotParticipant(_)
|
||||
| ItipError::OrganizerMismatch => Some(CalCondition::ValidOrganizer),
|
||||
ItipError::CannotModifyProperty(_)
|
||||
| ItipError::CannotModifyInstance
|
||||
| ItipError::CannotModifyAddress => Some(CalCondition::AllowedAttendeeObjectChange),
|
||||
ItipError::MissingUid
|
||||
| ItipError::MultipleUid
|
||||
| ItipError::MultipleObjectTypes
|
||||
| ItipError::MultipleObjectInstances
|
||||
| ItipError::MissingMethod
|
||||
| ItipError::InvalidComponentType
|
||||
| ItipError::OutOfSequence
|
||||
| ItipError::UnknownParticipant(_)
|
||||
| ItipError::UnsupportedMethod(_) => Some(CalCondition::ValidSchedulingMessage),
|
||||
ItipError::TooManyRecipients => Some(CalCondition::MaxAttendeesPerInstance),
|
||||
_ => None,
|
||||
impl From<EventWriteError> for DavError {
|
||||
fn from(err: EventWriteError) -> Self {
|
||||
match err {
|
||||
EventWriteError::NotFound => DavError::Code(StatusCode::NOT_FOUND),
|
||||
EventWriteError::Forbidden
|
||||
| EventWriteError::UidChanged(None)
|
||||
| EventWriteError::UidConflict { href: None, .. } => {
|
||||
DavError::Code(StatusCode::FORBIDDEN)
|
||||
}
|
||||
EventWriteError::InvalidObject => DavError::Condition(
|
||||
DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
CalCondition::ValidCalendarObjectResource,
|
||||
)
|
||||
.with_details("iCalendar must contain exactly one UID and same component types"),
|
||||
),
|
||||
EventWriteError::UidChanged(Some(path))
|
||||
| EventWriteError::UidConflict {
|
||||
href: Some(path), ..
|
||||
} => DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CalCondition::NoUidConflict(path.into()),
|
||||
)),
|
||||
EventWriteError::UnsupportedComponent => DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CalCondition::SupportedCalendarComponent,
|
||||
)),
|
||||
EventWriteError::ScheduleTagMismatch => DavError::Code(StatusCode::PRECONDITION_FAILED),
|
||||
EventWriteError::UserData(err) => user_data_error(err),
|
||||
EventWriteError::TooManyRecipients => DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
CalCondition::MaxAttendeesPerInstance,
|
||||
)),
|
||||
EventWriteError::Scheduling(precondition, err) => DavError::Condition(
|
||||
DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
match precondition {
|
||||
SchedulingPrecondition::SameOrganizerInAllComponents => {
|
||||
CalCondition::SameOrganizerInAllComponents
|
||||
}
|
||||
SchedulingPrecondition::ValidOrganizer => CalCondition::ValidOrganizer,
|
||||
SchedulingPrecondition::AllowedAttendeeObjectChange => {
|
||||
CalCondition::AllowedAttendeeObjectChange
|
||||
}
|
||||
SchedulingPrecondition::ValidSchedulingMessage => {
|
||||
CalCondition::ValidSchedulingMessage
|
||||
}
|
||||
SchedulingPrecondition::MaxAttendeesPerInstance => {
|
||||
CalCondition::MaxAttendeesPerInstance
|
||||
}
|
||||
},
|
||||
)
|
||||
.with_details(err.to_string()),
|
||||
),
|
||||
EventWriteError::Store(err) => DavError::Internal(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -494,7 +494,8 @@ impl CalendarPropPatchRequestHandler for Server {
|
|||
components
|
||||
.0
|
||||
.into_iter()
|
||||
.map(|v| SupportedComponent::from(v.0)),
|
||||
.map(|v| SupportedComponent::from(v.0))
|
||||
.filter(SupportedComponent::is_storable),
|
||||
)
|
||||
.into_inner();
|
||||
if calendar.supported_components != 0 {
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ use groupware::{
|
|||
cache::GroupwareCache,
|
||||
calendar::{
|
||||
CalendarEventNotification, CalendarEventNotificationContent,
|
||||
availability::AvailabilityCalendars,
|
||||
availability::{AvailabilityCalendars, DefaultFreeBusy},
|
||||
},
|
||||
strip_mailto_scheme,
|
||||
};
|
||||
|
|
@ -392,26 +392,34 @@ impl CalendarEventNotificationHandler for Server {
|
|||
let mut response = ScheduleResponse::default();
|
||||
|
||||
for (email, attendee) in attendees {
|
||||
let account_id = match self
|
||||
let target = match self
|
||||
.account_id_from_email(&email, true)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
Some(account_id)
|
||||
if access_token.is_member(account_id)
|
||||
|| access_token.has_permission(Permission::SysAccountQuery) =>
|
||||
{
|
||||
Some(account_id)
|
||||
}
|
||||
Some(account_id) => self
|
||||
.try_account(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.filter(|account| account.is_same_tenant(access_token))
|
||||
.map(|_| account_id),
|
||||
.and_then(|account| {
|
||||
if access_token.is_member(account_id) {
|
||||
return Some((account, DefaultFreeBusy::Granted));
|
||||
}
|
||||
let same_tenant = account.is_same_tenant(access_token);
|
||||
(same_tenant || access_token.has_permission(Permission::SysAccountQuery))
|
||||
.then(|| {
|
||||
(
|
||||
account,
|
||||
DefaultFreeBusy::of(
|
||||
same_tenant && self.core.groupware.share_free_busy,
|
||||
),
|
||||
)
|
||||
})
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
if let Some(account_id) = account_id {
|
||||
if let Some((account, default)) = target {
|
||||
let account_id = account.account_id();
|
||||
let resources = self
|
||||
.fetch_groupware_resources(
|
||||
access_token.account_id(),
|
||||
|
|
@ -420,9 +428,16 @@ impl CalendarEventNotificationHandler for Server {
|
|||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let Some(calendars) =
|
||||
AvailabilityCalendars::owner(&resources, account_id, access_token)
|
||||
else {
|
||||
let calendars = if account.resource_kind().is_some() {
|
||||
Some(AvailabilityCalendars::published(
|
||||
&resources,
|
||||
account_id,
|
||||
access_token,
|
||||
))
|
||||
} else {
|
||||
AvailabilityCalendars::owner(&resources, account_id, access_token, default)
|
||||
};
|
||||
let Some(calendars) = calendars else {
|
||||
response.items.0.push(ScheduleResponseItem {
|
||||
recipient: Href(format!("mailto:{email}")),
|
||||
request_status: "3.8;No authority".into(),
|
||||
|
|
|
|||
|
|
@ -4,13 +4,9 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{
|
||||
CalendarComponentSupport, CalendarEventView, assert_event_privacy_access,
|
||||
assert_event_privacy_allowed, assert_is_unique_uid, serves_ical, user_data_error,
|
||||
};
|
||||
use super::CalendarEventView;
|
||||
use crate::{
|
||||
DavError, DavErrorCondition, DavMethod,
|
||||
calendar::ItipPrecondition,
|
||||
common::{
|
||||
create::CreateLockHandler,
|
||||
lock::{LockRequestHandler, ResourceState},
|
||||
|
|
@ -18,56 +14,23 @@ use crate::{
|
|||
},
|
||||
file::DavFileResource,
|
||||
};
|
||||
use calcard::{
|
||||
Entry, Parser,
|
||||
common::timezone::Tz,
|
||||
icalendar::{ICalendar, ICalendarComponentType},
|
||||
};
|
||||
use common::{ArchivedDavName, DavName, Server, auth::AccessToken};
|
||||
use compact_str::ToCompactString;
|
||||
use calcard::{Entry, Parser};
|
||||
use common::{Server, auth::AccessToken};
|
||||
use dav_proto::{
|
||||
RequestHeaders, Return,
|
||||
schema::{property::Rfc1123DateTime, response::CalCondition},
|
||||
};
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
use groupware::SizeWriter;
|
||||
// SPDX-SnippetEnd
|
||||
use groupware::{
|
||||
cache::GroupwareCache,
|
||||
calendar::{
|
||||
CalendarEvent, CalendarEventContent, CalendarEventData, SupportedComponent,
|
||||
alerts::{DefaultAlertsResolver, DefaultAlertsView, ICalendarDefaultAlerts},
|
||||
identity::ParticipantIdentityAddresses,
|
||||
itip::ItipSendStatus,
|
||||
notification::{NotificationAudience, may_have_viewers},
|
||||
privacy::EventViewer,
|
||||
rights::{EventAcl, EventChanges},
|
||||
schedule::{AlarmTasks, EventAlarmScheduler, EventAlarmUsers},
|
||||
storage::{DirectChange, DirectChangeNotification, NotificationQuota},
|
||||
user::{ICalendarUserData, UpdatedPolicy, UserDataSplit, UserDataUpdate, UserDataView},
|
||||
},
|
||||
scheduling::{
|
||||
ItipMessages,
|
||||
event_create::{itip_create, itip_unscheduled_update},
|
||||
event_update::itip_update,
|
||||
itip::itip_set_unreachable_status,
|
||||
recipient::RecipientPolicy,
|
||||
alerts::DefaultAlertsResolver,
|
||||
write::{EventCreate, EventWrite, EventWriter, ItipMode},
|
||||
},
|
||||
};
|
||||
use http_proto::HttpResponse;
|
||||
use hyper::StatusCode;
|
||||
use registry::schema::enums::StorageQuota;
|
||||
use store::write::{BatchBuilder, now};
|
||||
use trc::AddContext;
|
||||
use types::{
|
||||
acl::Acl,
|
||||
collection::{Collection, SyncCollection},
|
||||
field::CalendarEventField,
|
||||
};
|
||||
use utils::map::bitmap::Bitmap;
|
||||
use types::collection::{Collection, SyncCollection};
|
||||
|
||||
pub(crate) trait CalendarUpdateRequestHandler: Sync + Send {
|
||||
fn handle_calendar_update_request(
|
||||
|
|
@ -121,7 +84,7 @@ impl CalendarUpdateRequestHandler for Server {
|
|||
)
|
||||
})?;
|
||||
|
||||
let mut ical = match Parser::new(ical_raw).entry() {
|
||||
let ical = match Parser::new(ical_raw).entry() {
|
||||
Entry::ICalendar(ical) => ical,
|
||||
_ => {
|
||||
return Err(DavError::Condition(
|
||||
|
|
@ -148,60 +111,28 @@ impl CalendarUpdateRequestHandler for Server {
|
|||
)),
|
||||
));
|
||||
}
|
||||
let personal_id = access_token.personal_id(account_id, Collection::Calendar);
|
||||
|
||||
let account_info = self
|
||||
.account_info(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let writer = EventWriter {
|
||||
server: self,
|
||||
access_token,
|
||||
account_id,
|
||||
resources: &resources,
|
||||
account_info: &account_info,
|
||||
};
|
||||
|
||||
if let Some(resource) = resources.by_path(resource_name) {
|
||||
if resource.is_container() {
|
||||
return Err(DavError::Code(StatusCode::METHOD_NOT_ALLOWED));
|
||||
}
|
||||
|
||||
// Validate ACL
|
||||
let parent_id = resource.parent_id().unwrap();
|
||||
let document_id = resource.document_id();
|
||||
let is_owner = access_token.is_member(account_id);
|
||||
if !is_owner
|
||||
&& !resources.has_access_to_container(
|
||||
access_token,
|
||||
parent_id,
|
||||
Bitmap::from_iter([
|
||||
Acl::ModifyItems,
|
||||
Acl::ModifyItemsOwn,
|
||||
Acl::ModifyPrivateProperties,
|
||||
Acl::ModifyRSVP,
|
||||
]),
|
||||
)
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
let viewer = EventViewer::new(is_owner);
|
||||
assert_event_privacy_access(resource.resource.event_flags(), viewer)?;
|
||||
assert_event_privacy_allowed(&ical, viewer)?;
|
||||
let stored = writer
|
||||
.prepare_update(resource.parent_id().unwrap(), resource.document_id(), &ical)
|
||||
.await?;
|
||||
let event = stored.event().caused_by(trc::location!())?;
|
||||
|
||||
// Update
|
||||
let (event_, content_) = self
|
||||
.archive_and_field(
|
||||
account_id,
|
||||
Collection::CalendarEvent,
|
||||
document_id,
|
||||
CalendarEventField::Content.field(),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let event_ = event_.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let event = event_
|
||||
.to_unarchived::<CalendarEvent>()
|
||||
.caused_by(trc::location!())?;
|
||||
let content_ = content_.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let content = content_
|
||||
.to_unarchived::<CalendarEventContent>()
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Validate headers
|
||||
match self
|
||||
.validate_headers(
|
||||
access_token,
|
||||
|
|
@ -209,7 +140,7 @@ impl CalendarUpdateRequestHandler for Server {
|
|||
vec![ResourceState {
|
||||
account_id,
|
||||
collection: Collection::CalendarEvent,
|
||||
document_id: Some(document_id),
|
||||
document_id: Some(stored.document_id()),
|
||||
etag: format!("\"{}\"", event.inner.etag.to_native()).into(),
|
||||
path: resource_name,
|
||||
..Default::default()
|
||||
|
|
@ -223,6 +154,7 @@ impl CalendarUpdateRequestHandler for Server {
|
|||
Err(DavError::Code(StatusCode::PRECONDITION_FAILED))
|
||||
if headers.ret == Return::Representation =>
|
||||
{
|
||||
let content = stored.content().caused_by(trc::location!())?;
|
||||
let body = match self
|
||||
.calendar_event_view(
|
||||
access_token,
|
||||
|
|
@ -248,413 +180,22 @@ impl CalendarUpdateRequestHandler for Server {
|
|||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
if ical == content.inner.data.event {
|
||||
// No changes, return existing event
|
||||
return Ok(HttpResponse::new(StatusCode::NO_CONTENT));
|
||||
}
|
||||
|
||||
// Validate iCal
|
||||
let (uid, component) = validate_ical(&ical)?;
|
||||
if event.inner.uid.as_str() != uid {
|
||||
return Err(DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CalCondition::NoUidConflict(resources.format_resource(resource).into()),
|
||||
)));
|
||||
}
|
||||
self.supported_components(account_id, parent_id)
|
||||
match writer
|
||||
.update(stored, ical, headers.if_schedule_tag, ItipMode::Send)
|
||||
.await?
|
||||
.assert_supports(component)?;
|
||||
|
||||
// Validate schedule tag
|
||||
if headers.if_schedule_tag.is_some()
|
||||
&& event.inner.schedule_tag.as_ref().map(|t| t.to_native())
|
||||
!= headers.if_schedule_tag
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::PRECONDITION_FAILED));
|
||||
EventWrite::Unchanged => Ok(HttpResponse::new(StatusCode::NO_CONTENT)),
|
||||
EventWrite::Written(written) => Ok(HttpResponse::new(StatusCode::NO_CONTENT)
|
||||
.with_etag_opt(written.serves_submitted.then_some(written.etag))
|
||||
.with_schedule_tag_opt(written.schedule_tag)),
|
||||
}
|
||||
|
||||
// Obtain previous alarm
|
||||
let now = now() as i64;
|
||||
let calendar_ids = event
|
||||
.inner
|
||||
.names
|
||||
.iter()
|
||||
.map(ArchivedDavName::parent_id)
|
||||
.collect::<Vec<_>>();
|
||||
let mut default_alerts_resolver =
|
||||
DefaultAlertsResolver::with_resources(account_id, resources.clone());
|
||||
let prev_email_alarms = self
|
||||
.next_event_alarms(
|
||||
account_id,
|
||||
&EventAlarmUsers::new(account_id, content.inner)?
|
||||
.with_event_flags(event.inner.flags.to_native()),
|
||||
&content.inner.data,
|
||||
&calendar_ids,
|
||||
now,
|
||||
&mut default_alerts_resolver,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Build event
|
||||
let mut new_event = event
|
||||
.deserialize::<CalendarEvent>()
|
||||
.caused_by(trc::location!())?;
|
||||
let mut new_content = content
|
||||
.deserialize::<CalendarEventContent>()
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
let writer_default_alerts = default_alerts_resolver
|
||||
.resolve_for_content(
|
||||
self,
|
||||
account_id,
|
||||
personal_id,
|
||||
&new_content,
|
||||
event.inner.names.iter().map(ArchivedDavName::parent_id),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let has_default_alerts = writer_default_alerts.is_enabled();
|
||||
let submitted_ical = ical.clone();
|
||||
ical.strip_default_alerts(&writer_default_alerts);
|
||||
let sharee_alerts_view = |content: &CalendarEventContent| {
|
||||
let mut view = content.data.event.clone();
|
||||
view.apply_user_data(content.preferences(personal_id), UserDataView::AlertsOnly);
|
||||
view
|
||||
};
|
||||
let mut sharee_view = None;
|
||||
if has_default_alerts {
|
||||
if is_owner {
|
||||
ical.restore_hidden_alerts(&new_content.data.event, &writer_default_alerts);
|
||||
} else {
|
||||
ical.restore_hidden_alerts(
|
||||
sharee_view.insert(sharee_alerts_view(&new_content)),
|
||||
&writer_default_alerts,
|
||||
);
|
||||
}
|
||||
}
|
||||
let changes_shared_user_data =
|
||||
!is_owner && !ical.has_same_user_data(&new_content.data.event);
|
||||
if is_owner || changes_shared_user_data {
|
||||
ical.validate_user_data_changes(&new_content.data.event)
|
||||
.map_err(user_data_error)?;
|
||||
}
|
||||
|
||||
if !is_owner {
|
||||
let identities = self
|
||||
.account_identity_addresses(access_token.account_id())
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let ownership = identities.event_ownership(&new_content.data.event);
|
||||
let acl = EventAcl::for_calendars(
|
||||
&resources,
|
||||
access_token,
|
||||
event.inner.names.iter().map(ArchivedDavName::parent_id),
|
||||
);
|
||||
if !acl.may_write(ownership) {
|
||||
if changes_shared_user_data {
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
let event_flags = event.inner.flags.to_native();
|
||||
let sharee_view =
|
||||
sharee_view.unwrap_or_else(|| sharee_alerts_view(&new_content));
|
||||
let mut changes = EventChanges::between(
|
||||
&sharee_view.into_jscalendar(),
|
||||
&ical.clone().into_jscalendar(),
|
||||
event_flags,
|
||||
event_flags,
|
||||
&identities,
|
||||
);
|
||||
changes.classify_recurrence_sets(&new_content.data.event, &ical);
|
||||
changes
|
||||
.assert_allowed(&acl, ownership, event_flags)
|
||||
.map_err(|_| DavError::Code(StatusCode::FORBIDDEN))?;
|
||||
}
|
||||
}
|
||||
|
||||
let is_user_data_only = if is_owner {
|
||||
false
|
||||
} else {
|
||||
let stored_preferences = new_content
|
||||
.preferences
|
||||
.iter()
|
||||
.find(|p| p.account_id == personal_id);
|
||||
let (preferences, split) = ical
|
||||
.split_user_data(
|
||||
&new_content.data.event,
|
||||
UserDataUpdate {
|
||||
account_id: personal_id,
|
||||
view: UserDataView::AlertsOnly,
|
||||
previous: stored_preferences,
|
||||
current: stored_preferences,
|
||||
updated: UpdatedPolicy::Server(now),
|
||||
},
|
||||
)
|
||||
.map_err(user_data_error)?;
|
||||
new_content.set_preferences(preferences);
|
||||
split == UserDataSplit::UserDataOnly
|
||||
};
|
||||
let old_ical = if is_user_data_only {
|
||||
None
|
||||
} else {
|
||||
let old_ical = std::mem::take(&mut new_content.data.event);
|
||||
let owner_default_alerts = default_alerts_resolver
|
||||
.resolve_for_content(
|
||||
self,
|
||||
account_id,
|
||||
account_id,
|
||||
&new_content,
|
||||
event.inner.names.iter().map(ArchivedDavName::parent_id),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
new_content.data = CalendarEventData::new_with_default_alerts(
|
||||
ical,
|
||||
Tz::Floating,
|
||||
self.core.groupware.max_ical_instances,
|
||||
&owner_default_alerts,
|
||||
);
|
||||
Some(old_ical)
|
||||
};
|
||||
let next_email_alarms = self
|
||||
.next_event_alarms(
|
||||
account_id,
|
||||
&EventAlarmUsers::new(account_id, &new_content)?
|
||||
.with_event_flags(new_event.flags),
|
||||
&new_content.data,
|
||||
&calendar_ids,
|
||||
now,
|
||||
&mut default_alerts_resolver,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Scheduling
|
||||
let mut itip_messages = None;
|
||||
let itip_status = if is_user_data_only {
|
||||
ItipSendStatus::NotRequested
|
||||
} else {
|
||||
ItipSendStatus::resolve(
|
||||
self,
|
||||
access_token,
|
||||
&account_info,
|
||||
new_content.data.event_range_end(),
|
||||
)
|
||||
};
|
||||
if itip_status.is_send() {
|
||||
let policy = RecipientPolicy::new(&self.core.groupware, new_event.flags);
|
||||
let result = match (&old_ical, new_event.schedule_tag) {
|
||||
(Some(old_ical), Some(_)) => itip_update(
|
||||
&mut new_content.data.event,
|
||||
old_ical,
|
||||
account_info.addresses(),
|
||||
policy,
|
||||
),
|
||||
(Some(old_ical), None) => itip_unscheduled_update(
|
||||
&mut new_content.data.event,
|
||||
old_ical,
|
||||
account_info.addresses(),
|
||||
policy,
|
||||
),
|
||||
(None, _) => itip_create(
|
||||
&mut new_content.data.event,
|
||||
account_info.addresses(),
|
||||
policy,
|
||||
),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(messages) => {
|
||||
let mut is_organizer = false;
|
||||
if messages
|
||||
.iter()
|
||||
.map(|r| {
|
||||
is_organizer = r.from_organizer;
|
||||
r.to.len()
|
||||
})
|
||||
.sum::<usize>()
|
||||
< self.core.groupware.itip_outbound_max_recipients
|
||||
{
|
||||
match &mut new_event.schedule_tag {
|
||||
Some(schedule_tag) if is_organizer => *schedule_tag += 1,
|
||||
Some(_) => {}
|
||||
None => new_event.schedule_tag = Some(1),
|
||||
}
|
||||
|
||||
itip_messages = Some(ItipMessages::new(messages));
|
||||
} else {
|
||||
return Err(DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
CalCondition::MaxAttendeesPerInstance,
|
||||
)));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
if let Some(failed_precondition) = err.failed_precondition() {
|
||||
return Err(DavError::Condition(
|
||||
DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
failed_precondition,
|
||||
)
|
||||
.with_details(err.to_string()),
|
||||
));
|
||||
}
|
||||
|
||||
trc::event!(
|
||||
Calendar(trc::CalendarEvent::ItipMessageError),
|
||||
AccountId = account_id,
|
||||
DocumentId = document_id,
|
||||
Reason = err.to_compact_string(),
|
||||
);
|
||||
|
||||
// Event changed, but there are no iTIP messages to send
|
||||
if let Some(schedule_tag) = &mut new_event.schedule_tag {
|
||||
*schedule_tag += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
itip_set_unreachable_status(&mut new_content.data.event, account_info.addresses());
|
||||
} else if let Some(reason) = itip_status.reason() {
|
||||
trc::event!(
|
||||
Calendar(trc::CalendarEvent::ItipMessageError),
|
||||
AccountId = account_id,
|
||||
DocumentId = document_id,
|
||||
Reason = reason,
|
||||
);
|
||||
}
|
||||
|
||||
let account = self.account(account_id).await?;
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
// Validate quota
|
||||
#[cfg(feature = "enterprise")]
|
||||
let extra_bytes = (SizeWriter::ical(&new_content.data.event) as u64)
|
||||
.saturating_sub(u32::from(event.inner.size) as u64);
|
||||
#[cfg(feature = "enterprise")]
|
||||
if extra_bytes > 0 {
|
||||
self.has_available_tenant_quota(&account, extra_bytes)
|
||||
.await?;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
// Prepare write batch
|
||||
let mut batch = BatchBuilder::new();
|
||||
batch.with_account_id(account_id);
|
||||
self.limit_disk_quota(&mut batch, &account);
|
||||
let notify_event_flags = new_event.flags | event.inner.flags.to_native();
|
||||
if let Some(old_ical) = old_ical.filter(|_| {
|
||||
may_have_viewers(
|
||||
access_token,
|
||||
account_id,
|
||||
&resources,
|
||||
&calendar_ids,
|
||||
NotificationAudience::of_event(notify_event_flags),
|
||||
)
|
||||
}) {
|
||||
self.notify_direct_change(
|
||||
access_token,
|
||||
account_id,
|
||||
DirectChange::Updated {
|
||||
event_id: document_id,
|
||||
previous: old_ical,
|
||||
current: new_content.data.event.clone(),
|
||||
calendar_ids: calendar_ids.clone(),
|
||||
event_flags: notify_event_flags,
|
||||
},
|
||||
Some(&resources),
|
||||
&mut NotificationQuota::default(),
|
||||
&mut batch,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
}
|
||||
let serves_submitted_ical = if is_owner && !has_default_alerts {
|
||||
serves_ical(&new_content.data.event, &submitted_ical)
|
||||
} else {
|
||||
let view_default_alerts = default_alerts_resolver
|
||||
.resolve_for_ical_view(
|
||||
self,
|
||||
account_id,
|
||||
personal_id,
|
||||
&new_content,
|
||||
calendar_ids.iter().copied(),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let mut view = new_content.data.event.clone();
|
||||
if !is_owner {
|
||||
view.apply_user_data(
|
||||
new_content.preferences(personal_id),
|
||||
UserDataView::AlertsOnly,
|
||||
);
|
||||
}
|
||||
view.apply_default_alerts(&view_default_alerts, DefaultAlertsView::ICalendar);
|
||||
serves_ical(&view, &submitted_ical)
|
||||
};
|
||||
|
||||
let schedule_tag = new_event.schedule_tag;
|
||||
let etag = new_event
|
||||
.update_full(
|
||||
new_content,
|
||||
access_token.changed_by(),
|
||||
event,
|
||||
content.inner,
|
||||
account_id,
|
||||
document_id,
|
||||
None,
|
||||
&mut batch,
|
||||
)
|
||||
.caused_by(trc::location!())?;
|
||||
self.replace_event_alarms(
|
||||
account_id,
|
||||
document_id,
|
||||
prev_email_alarms,
|
||||
next_email_alarms,
|
||||
&mut AlarmTasks::None,
|
||||
&mut batch,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
if let Some(itip_messages) = itip_messages {
|
||||
itip_messages
|
||||
.queue(&mut batch)
|
||||
.caused_by(trc::location!())?;
|
||||
}
|
||||
self.commit_batch(batch).await.caused_by(trc::location!())?;
|
||||
|
||||
Ok(HttpResponse::new(StatusCode::NO_CONTENT)
|
||||
.with_etag_opt(serves_submitted_ical.then_some(etag))
|
||||
.with_schedule_tag_opt(schedule_tag))
|
||||
} else if let Some((Some(parent), name)) = resources.map_parent(resource_name) {
|
||||
if !parent.is_container() {
|
||||
return Err(DavError::Code(StatusCode::METHOD_NOT_ALLOWED));
|
||||
}
|
||||
|
||||
// Validate ACL
|
||||
let is_owner = access_token.is_member(account_id);
|
||||
if !is_owner
|
||||
&& !resources.has_access_to_container(
|
||||
access_token,
|
||||
parent.document_id(),
|
||||
Acl::AddItems,
|
||||
)
|
||||
&& !(EventAcl::for_calendar(&resources, access_token, parent.document_id())
|
||||
.may_manage_own_items()
|
||||
&& self
|
||||
.account_identity_addresses(access_token.account_id())
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.event_ownership(&ical)
|
||||
.may_write_own())
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
assert_event_privacy_allowed(&ical, EventViewer::new(is_owner))?;
|
||||
ical.validate_user_data().map_err(user_data_error)?;
|
||||
let new = writer.prepare_create(parent.document_id(), &ical).await?;
|
||||
|
||||
// Validate headers
|
||||
self.validate_headers(
|
||||
access_token,
|
||||
headers,
|
||||
|
|
@ -670,185 +211,6 @@ impl CalendarUpdateRequestHandler for Server {
|
|||
)
|
||||
.await?;
|
||||
|
||||
// Validate ical object
|
||||
let (uid, component) = validate_ical(&ical)?;
|
||||
assert_is_unique_uid(
|
||||
&resources,
|
||||
access_token,
|
||||
account_id,
|
||||
parent.document_id(),
|
||||
Some(uid),
|
||||
)?;
|
||||
self.supported_components(account_id, parent.document_id())
|
||||
.await?
|
||||
.assert_supports(component)?;
|
||||
|
||||
// Validate object quota
|
||||
let account = self.account(account_id).await?;
|
||||
self.assert_object_quota(&account, StorageQuota::MaxCalendarEvents, 1, || {
|
||||
resources.resources.count(false)
|
||||
})?;
|
||||
|
||||
let submitted_ical = ical.clone();
|
||||
let mut preferences = Vec::new();
|
||||
if !is_owner {
|
||||
let extracted = ical
|
||||
.extract_user_data(personal_id)
|
||||
.map_err(user_data_error)?;
|
||||
ical.apply_user_data(None, UserDataView::Full);
|
||||
if !extracted.is_empty() {
|
||||
preferences.push(extracted);
|
||||
}
|
||||
}
|
||||
|
||||
// Build event
|
||||
let mut event = CalendarEvent {
|
||||
names: vec![DavName {
|
||||
name: name.to_string(),
|
||||
parent_id: parent.document_id(),
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut content = CalendarEventContent {
|
||||
data: CalendarEventData::new(
|
||||
ical,
|
||||
Tz::Floating,
|
||||
self.core.groupware.max_ical_instances,
|
||||
),
|
||||
preferences,
|
||||
};
|
||||
let next_email_alarms = self
|
||||
.next_event_alarms(
|
||||
account_id,
|
||||
&EventAlarmUsers::new(account_id, &content)?,
|
||||
&content.data,
|
||||
&[parent.document_id()],
|
||||
now() as i64,
|
||||
&mut DefaultAlertsResolver::with_resources(account_id, resources.clone()),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Scheduling
|
||||
let mut itip_messages = None;
|
||||
let itip_status = ItipSendStatus::resolve(
|
||||
self,
|
||||
access_token,
|
||||
&account_info,
|
||||
content.data.event_range_end(),
|
||||
);
|
||||
if itip_status.is_send() {
|
||||
match itip_create(
|
||||
&mut content.data.event,
|
||||
account_info.addresses(),
|
||||
RecipientPolicy::new(&self.core.groupware, event.flags),
|
||||
) {
|
||||
Ok(messages) => {
|
||||
if messages.iter().map(|r| r.to.len()).sum::<usize>()
|
||||
< self.core.groupware.itip_outbound_max_recipients
|
||||
{
|
||||
event.schedule_tag = Some(1);
|
||||
itip_messages = Some(ItipMessages::new(messages));
|
||||
} else {
|
||||
return Err(DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
CalCondition::MaxAttendeesPerInstance,
|
||||
)));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
if let Some(failed_precondition) = err.failed_precondition() {
|
||||
return Err(DavError::Condition(
|
||||
DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
failed_precondition,
|
||||
)
|
||||
.with_details(err.to_string()),
|
||||
));
|
||||
}
|
||||
|
||||
trc::event!(
|
||||
Calendar(trc::CalendarEvent::ItipMessageError),
|
||||
AccountId = account_id,
|
||||
Reason = err.to_compact_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
itip_set_unreachable_status(&mut content.data.event, account_info.addresses());
|
||||
} else if let Some(reason) = itip_status.reason() {
|
||||
trc::event!(
|
||||
Calendar(trc::CalendarEvent::ItipMessageError),
|
||||
AccountId = account_id,
|
||||
Reason = reason,
|
||||
);
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
// Validate quota
|
||||
#[cfg(feature = "enterprise")]
|
||||
if !bytes.is_empty() {
|
||||
self.has_available_tenant_quota(&account, bytes.len() as u64)
|
||||
.await?;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
// Prepare write batch
|
||||
let mut batch = BatchBuilder::new();
|
||||
batch.with_account_id(account_id);
|
||||
self.limit_disk_quota(&mut batch, &account);
|
||||
let document_id = batch.reserve_document_id(account_id, Collection::CalendarEvent);
|
||||
let notify_calendar_ids = event.calendar_ids().collect::<Vec<_>>();
|
||||
if may_have_viewers(
|
||||
access_token,
|
||||
account_id,
|
||||
&resources,
|
||||
¬ify_calendar_ids,
|
||||
NotificationAudience::of_event(event.flags),
|
||||
) {
|
||||
self.notify_direct_change(
|
||||
access_token,
|
||||
account_id,
|
||||
DirectChange::Created {
|
||||
event_id: document_id.into(),
|
||||
current: content.data.event.clone(),
|
||||
calendar_ids: notify_calendar_ids,
|
||||
event_flags: event.flags,
|
||||
},
|
||||
Some(&resources),
|
||||
&mut NotificationQuota::default(),
|
||||
&mut batch,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
}
|
||||
let serves_submitted_ical = if is_owner {
|
||||
serves_ical(&content.data.event, &submitted_ical)
|
||||
} else {
|
||||
let mut view = content.data.event.clone();
|
||||
view.apply_user_data(content.preferences(personal_id), UserDataView::AlertsOnly);
|
||||
serves_ical(&view, &submitted_ical)
|
||||
};
|
||||
|
||||
let schedule_tag = event.schedule_tag;
|
||||
let etag = event
|
||||
.insert(
|
||||
content,
|
||||
access_token.changed_by(),
|
||||
account_id,
|
||||
document_id,
|
||||
None,
|
||||
next_email_alarms,
|
||||
&mut batch,
|
||||
)
|
||||
.caused_by(trc::location!())?;
|
||||
if let Some(itip_messages) = itip_messages {
|
||||
itip_messages
|
||||
.queue(&mut batch)
|
||||
.caused_by(trc::location!())?;
|
||||
}
|
||||
let lock = self
|
||||
.lock_create(
|
||||
access_token,
|
||||
|
|
@ -858,54 +220,25 @@ impl CalendarUpdateRequestHandler for Server {
|
|||
headers,
|
||||
)
|
||||
.await?;
|
||||
self.commit_create(lock, batch)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let written = writer
|
||||
.create(
|
||||
new,
|
||||
EventCreate {
|
||||
name: name.to_string(),
|
||||
ical,
|
||||
size: Some(bytes.len()),
|
||||
itip: ItipMode::Send,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
self.release_create_lock(&lock).await;
|
||||
let written = written?;
|
||||
|
||||
Ok(HttpResponse::new(StatusCode::CREATED)
|
||||
.with_etag_opt(serves_submitted_ical.then_some(etag))
|
||||
.with_schedule_tag_opt(schedule_tag))
|
||||
.with_etag_opt(written.serves_submitted.then_some(written.etag))
|
||||
.with_schedule_tag_opt(written.schedule_tag))
|
||||
} else {
|
||||
Err(DavError::Code(StatusCode::CONFLICT))?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_ical(ical: &ICalendar) -> crate::Result<(&str, SupportedComponent)> {
|
||||
let mut uid = None;
|
||||
let mut has_mixed_uids = false;
|
||||
let mut object_type = None;
|
||||
let mut has_mixed_types = false;
|
||||
for comp in &ical.components {
|
||||
let component = match comp.component_type {
|
||||
ICalendarComponentType::VEvent => SupportedComponent::VEvent,
|
||||
ICalendarComponentType::VTodo => SupportedComponent::VTodo,
|
||||
ICalendarComponentType::VJournal => SupportedComponent::VJournal,
|
||||
ICalendarComponentType::VFreebusy => SupportedComponent::VFreebusy,
|
||||
ICalendarComponentType::VAvailability => SupportedComponent::VAvailability,
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
has_mixed_types |= object_type
|
||||
.replace(component)
|
||||
.is_some_and(|previous| previous != component);
|
||||
|
||||
if let Some(comp_uid) = comp.uid() {
|
||||
has_mixed_uids |= uid
|
||||
.replace(comp_uid)
|
||||
.is_some_and(|previous| previous != comp_uid);
|
||||
}
|
||||
}
|
||||
|
||||
match (uid.filter(|_| !has_mixed_uids), object_type) {
|
||||
(Some(uid), Some(object_type)) if !has_mixed_types => Ok((uid, object_type)),
|
||||
_ => Err(DavError::Condition(
|
||||
DavErrorCondition::new(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
CalCondition::ValidCalendarObjectResource,
|
||||
)
|
||||
.with_details("iCalendar must contain exactly one UID and same component types"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ use dav_proto::RequestHeaders;
|
|||
use groupware::{
|
||||
DestroyArchive,
|
||||
cache::GroupwareCache,
|
||||
contact::{AddressBook, ContactCard},
|
||||
contact::{AddressBook, write::CardWriter},
|
||||
};
|
||||
use http_proto::HttpResponse;
|
||||
use hyper::StatusCode;
|
||||
|
|
@ -28,7 +28,6 @@ use store::{
|
|||
};
|
||||
use trc::AddContext;
|
||||
use types::{
|
||||
acl::Acl,
|
||||
collection::{Collection, SyncCollection},
|
||||
field::PrincipalField,
|
||||
};
|
||||
|
|
@ -72,8 +71,6 @@ impl CardDeleteRequestHandler for Server {
|
|||
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let document_id = delete_resource.document_id();
|
||||
|
||||
// Fetch entry
|
||||
let mut batch = BatchBuilder::new();
|
||||
if delete_resource.is_container() {
|
||||
let book_ = self
|
||||
.store()
|
||||
|
|
@ -119,6 +116,7 @@ impl CardDeleteRequestHandler for Server {
|
|||
.await?;
|
||||
|
||||
// Delete addressbook and cards
|
||||
let mut batch = BatchBuilder::new();
|
||||
let children = resources
|
||||
.subtree(delete_path)
|
||||
.filter(|r| !r.is_container())
|
||||
|
|
@ -160,34 +158,18 @@ impl CardDeleteRequestHandler for Server {
|
|||
.with_collection(Collection::Principal)
|
||||
.with_document(0)
|
||||
.clear_if_equals(PrincipalField::DefaultAddressBookId, document_id);
|
||||
self.commit_batch(batch).await.caused_by(trc::location!())?;
|
||||
} else {
|
||||
// Validate ACL
|
||||
let addressbook_id = delete_resource.parent_id().unwrap();
|
||||
if !access_token.is_member(account_id)
|
||||
&& !resources.has_access_to_container(
|
||||
access_token,
|
||||
addressbook_id,
|
||||
Acl::RemoveItems,
|
||||
)
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
let writer = CardWriter {
|
||||
server: self,
|
||||
access_token,
|
||||
account_id,
|
||||
resources: &resources,
|
||||
};
|
||||
let deletion = writer
|
||||
.prepare_delete(delete_resource.parent_id().unwrap(), document_id)
|
||||
.await?;
|
||||
|
||||
let card_ = self
|
||||
.store()
|
||||
.get_value::<Archive<ArchiveBytes>>(ValueKey::archive(
|
||||
account_id,
|
||||
Collection::ContactCard,
|
||||
document_id,
|
||||
))
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let card = card_
|
||||
.to_unarchived::<ContactCard>()
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Validate headers
|
||||
self.validate_headers(
|
||||
access_token,
|
||||
headers,
|
||||
|
|
@ -195,7 +177,16 @@ impl CardDeleteRequestHandler for Server {
|
|||
account_id,
|
||||
collection: Collection::ContactCard,
|
||||
document_id: document_id.into(),
|
||||
etag: format!("\"{}\"", card.inner.etag.to_native()).into(),
|
||||
etag: format!(
|
||||
"\"{}\"",
|
||||
deletion
|
||||
.card()
|
||||
.caused_by(trc::location!())?
|
||||
.inner
|
||||
.etag
|
||||
.to_native()
|
||||
)
|
||||
.into(),
|
||||
path: delete_path,
|
||||
..Default::default()
|
||||
}],
|
||||
|
|
@ -204,23 +195,11 @@ impl CardDeleteRequestHandler for Server {
|
|||
)
|
||||
.await?;
|
||||
|
||||
// Delete card
|
||||
DestroyArchive(card)
|
||||
.delete(
|
||||
self,
|
||||
access_token.changed_by(),
|
||||
account_id,
|
||||
document_id,
|
||||
addressbook_id,
|
||||
resources.format_resource(delete_resource).into(),
|
||||
&mut batch,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
writer
|
||||
.delete(deletion, resources.format_resource(delete_resource).into())
|
||||
.await?;
|
||||
}
|
||||
|
||||
self.commit_batch(batch).await.caused_by(trc::location!())?;
|
||||
|
||||
Ok(HttpResponse::new(StatusCode::NO_CONTENT))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ use dav_proto::schema::{
|
|||
property::{CardDavProperty, DavProperty, WebDavProperty},
|
||||
response::CardCondition,
|
||||
};
|
||||
use groupware::contact::write::{CardWriteError, assert_unique_uid};
|
||||
use hyper::StatusCode;
|
||||
|
||||
pub mod copy_move;
|
||||
|
|
@ -78,44 +79,26 @@ pub(crate) fn assert_is_unique_uid(
|
|||
addressbook_id: u32,
|
||||
uid: Option<&str>,
|
||||
) -> crate::Result<()> {
|
||||
let Some(uid) = uid else {
|
||||
return Ok(());
|
||||
};
|
||||
assert_unique_uid(resources, addressbook_id, uid).map_err(Into::into)
|
||||
}
|
||||
|
||||
if let Some(path) = resources.children_with_uid(addressbook_id, uid).next() {
|
||||
return Err(DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CardCondition::NoUidConflict(resources.format_resource(path).into()),
|
||||
)));
|
||||
impl From<CardWriteError> for DavError {
|
||||
fn from(err: CardWriteError) -> Self {
|
||||
match err {
|
||||
CardWriteError::NotFound => DavError::Code(StatusCode::NOT_FOUND),
|
||||
CardWriteError::Forbidden | CardWriteError::UidChanged(None) => {
|
||||
DavError::Code(StatusCode::FORBIDDEN)
|
||||
}
|
||||
CardWriteError::UidChanged(Some(path))
|
||||
| CardWriteError::UidConflict { href: path, .. } => {
|
||||
DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CardCondition::NoUidConflict(path.into()),
|
||||
))
|
||||
}
|
||||
CardWriteError::Store(err) => DavError::Internal(err),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const URN_UUID_PREFIX: &str = "urn:uuid:";
|
||||
const UUID_GROUP_LENGTHS: [usize; 5] = [8, 4, 4, 4, 12];
|
||||
|
||||
pub(crate) fn is_same_uid(uid: &str, other: &str) -> bool {
|
||||
uid == other
|
||||
|| matches!(
|
||||
(uuid_of(uid), uuid_of(other)),
|
||||
(Some(uuid), Some(other_uuid)) if uuid.eq_ignore_ascii_case(other_uuid)
|
||||
)
|
||||
}
|
||||
|
||||
fn uuid_of(uid: &str) -> Option<&str> {
|
||||
let uuid = uid
|
||||
.split_at_checked(URN_UUID_PREFIX.len())
|
||||
.filter(|(prefix, _)| prefix.eq_ignore_ascii_case(URN_UUID_PREFIX))
|
||||
.map_or(uid, |(_, uuid)| uuid);
|
||||
let mut groups = uuid.split('-');
|
||||
|
||||
(UUID_GROUP_LENGTHS.iter().all(|&len| {
|
||||
groups
|
||||
.next()
|
||||
.is_some_and(|group| group.len() == len && group.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
}) && groups.next().is_none())
|
||||
.then_some(uuid)
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{assert_is_unique_uid, is_same_uid};
|
||||
use crate::{
|
||||
DavError, DavErrorCondition, DavMethod,
|
||||
common::{
|
||||
|
|
@ -14,35 +13,20 @@ use crate::{
|
|||
},
|
||||
file::DavFileResource,
|
||||
};
|
||||
use calcard::{
|
||||
Entry, Parser,
|
||||
vcard::{VCardProperty, VCardValue},
|
||||
};
|
||||
use common::{DavName, Server, auth::AccessToken};
|
||||
use calcard::{Entry, Parser};
|
||||
use common::{Server, auth::AccessToken};
|
||||
use dav_proto::{
|
||||
RequestHeaders, Return,
|
||||
schema::{property::Rfc1123DateTime, response::CardCondition},
|
||||
};
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
use groupware::SizeWriter;
|
||||
// SPDX-SnippetEnd
|
||||
use groupware::{
|
||||
cache::GroupwareCache,
|
||||
contact::{ContactCard, ContactCardContent},
|
||||
contact::write::{CardCreate, CardWriter},
|
||||
};
|
||||
use http_proto::HttpResponse;
|
||||
use hyper::StatusCode;
|
||||
use registry::schema::enums::StorageQuota;
|
||||
use store::write::BatchBuilder;
|
||||
use trc::AddContext;
|
||||
use types::{
|
||||
acl::Acl,
|
||||
collection::{Collection, SyncCollection},
|
||||
field::ContactField,
|
||||
};
|
||||
use types::collection::{Collection, SyncCollection};
|
||||
|
||||
pub(crate) trait CardUpdateRequestHandler: Sync + Send {
|
||||
fn handle_card_update_request(
|
||||
|
|
@ -96,7 +80,7 @@ impl CardUpdateRequestHandler for Server {
|
|||
)
|
||||
})?;
|
||||
|
||||
let mut vcard = match Parser::new(vcard_raw).strict().entry() {
|
||||
let vcard = match Parser::new(vcard_raw).strict().entry() {
|
||||
Entry::VCard(vcard) => vcard,
|
||||
_ => {
|
||||
return Err(DavError::Condition(
|
||||
|
|
@ -124,40 +108,23 @@ impl CardUpdateRequestHandler for Server {
|
|||
));
|
||||
}
|
||||
|
||||
let writer = CardWriter {
|
||||
server: self,
|
||||
access_token,
|
||||
account_id,
|
||||
resources: &resources,
|
||||
};
|
||||
|
||||
if let Some(resource) = resources.by_path(resource_name) {
|
||||
if resource.is_container() {
|
||||
return Err(DavError::Code(StatusCode::METHOD_NOT_ALLOWED));
|
||||
}
|
||||
|
||||
// Validate ACL
|
||||
let parent_id = resource.parent_id().unwrap();
|
||||
let document_id = resource.document_id();
|
||||
if !access_token.is_member(account_id)
|
||||
&& !resources.has_access_to_container(access_token, parent_id, Acl::ModifyItems)
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
let stored = writer
|
||||
.prepare_update(resource.parent_id().unwrap(), resource.document_id())
|
||||
.await?;
|
||||
let card = stored.card().caused_by(trc::location!())?;
|
||||
|
||||
// Update
|
||||
let (card_, content_) = self
|
||||
.archive_and_field(
|
||||
account_id,
|
||||
Collection::ContactCard,
|
||||
document_id,
|
||||
ContactField::Content.field(),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let card_ = card_.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let card = card_
|
||||
.to_unarchived::<ContactCard>()
|
||||
.caused_by(trc::location!())?;
|
||||
let content_ = content_.ok_or(DavError::Code(StatusCode::NOT_FOUND))?;
|
||||
let content = content_
|
||||
.to_unarchived::<ContactCardContent>()
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Validate headers
|
||||
match self
|
||||
.validate_headers(
|
||||
access_token,
|
||||
|
|
@ -165,7 +132,7 @@ impl CardUpdateRequestHandler for Server {
|
|||
vec![ResourceState {
|
||||
account_id,
|
||||
collection: Collection::ContactCard,
|
||||
document_id: Some(document_id),
|
||||
document_id: Some(stored.document_id()),
|
||||
etag: format!("\"{}\"", card.inner.etag.to_native()).into(),
|
||||
path: resource_name,
|
||||
..Default::default()
|
||||
|
|
@ -179,6 +146,7 @@ impl CardUpdateRequestHandler for Server {
|
|||
Err(DavError::Code(StatusCode::PRECONDITION_FAILED))
|
||||
if headers.ret == Return::Representation =>
|
||||
{
|
||||
let content = stored.content().caused_by(trc::location!())?;
|
||||
let mut vcard = String::with_capacity(u32::from(card.inner.size) as usize);
|
||||
let _ = content.inner.card.write_to(
|
||||
&mut vcard,
|
||||
|
|
@ -199,95 +167,17 @@ impl CardUpdateRequestHandler for Server {
|
|||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
// Validate UID
|
||||
let restored_uid = match (
|
||||
content.inner.card.uid().filter(|uid| !uid.is_empty()),
|
||||
vcard.uid().filter(|uid| !uid.is_empty()),
|
||||
) {
|
||||
(Some(stored_uid), Some(uid)) if is_same_uid(stored_uid, uid) => {
|
||||
(stored_uid != uid).then_some(stored_uid)
|
||||
}
|
||||
(None, uid) => {
|
||||
assert_is_unique_uid(&resources, parent_id, uid)?;
|
||||
None
|
||||
}
|
||||
_ => {
|
||||
return Err(DavError::Condition(DavErrorCondition::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
CardCondition::NoUidConflict(resources.format_resource(resource).into()),
|
||||
)));
|
||||
}
|
||||
};
|
||||
if let Some(stored_uid) = restored_uid
|
||||
&& let Some(value) = vcard
|
||||
.entries
|
||||
.iter_mut()
|
||||
.find(|entry| entry.name == VCardProperty::Uid)
|
||||
.and_then(|entry| entry.values.first_mut())
|
||||
{
|
||||
*value = VCardValue::Text(stored_uid.to_string());
|
||||
}
|
||||
|
||||
// Build node
|
||||
let new_card = card
|
||||
.deserialize::<ContactCard>()
|
||||
.caused_by(trc::location!())?;
|
||||
let new_content = ContactCardContent { card: vcard };
|
||||
|
||||
let account = self.account(account_id).await?;
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
// Validate quota
|
||||
#[cfg(feature = "enterprise")]
|
||||
let extra_bytes =
|
||||
(SizeWriter::vcard(&new_content.card, self.core.groupware.vcard_version) as u64)
|
||||
.saturating_sub(u32::from(card.inner.size) as u64);
|
||||
#[cfg(feature = "enterprise")]
|
||||
if extra_bytes > 0 {
|
||||
self.has_available_tenant_quota(&account, extra_bytes)
|
||||
.await?;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
// Prepare write batch
|
||||
let mut batch = BatchBuilder::new();
|
||||
batch.with_account_id(account_id);
|
||||
self.limit_disk_quota(&mut batch, &account);
|
||||
let etag = new_card
|
||||
.update_full(
|
||||
new_content,
|
||||
self.core.groupware.vcard_version,
|
||||
access_token.changed_by(),
|
||||
card,
|
||||
content.inner,
|
||||
account_id,
|
||||
document_id,
|
||||
None,
|
||||
&mut batch,
|
||||
)
|
||||
.caused_by(trc::location!())?;
|
||||
self.commit_batch(batch).await.caused_by(trc::location!())?;
|
||||
let written = writer.update(stored, vcard).await?;
|
||||
|
||||
Ok(HttpResponse::new(StatusCode::NO_CONTENT)
|
||||
.with_etag_opt(restored_uid.is_none().then_some(etag)))
|
||||
.with_etag_opt(written.serves_submitted.then_some(written.etag)))
|
||||
} else if let Some((Some(parent), name)) = resources.map_parent(resource_name) {
|
||||
if !parent.is_container() {
|
||||
return Err(DavError::Code(StatusCode::METHOD_NOT_ALLOWED));
|
||||
}
|
||||
|
||||
// Validate ACL
|
||||
if !access_token.is_member(account_id)
|
||||
&& !resources.has_access_to_container(
|
||||
access_token,
|
||||
parent.document_id(),
|
||||
Acl::AddItems,
|
||||
)
|
||||
{
|
||||
return Err(DavError::Code(StatusCode::FORBIDDEN));
|
||||
}
|
||||
let new = writer.prepare_create(parent.document_id())?;
|
||||
|
||||
// Validate headers
|
||||
self.validate_headers(
|
||||
access_token,
|
||||
headers,
|
||||
|
|
@ -303,52 +193,6 @@ impl CardUpdateRequestHandler for Server {
|
|||
)
|
||||
.await?;
|
||||
|
||||
// Validate UID
|
||||
assert_is_unique_uid(&resources, parent.document_id(), vcard.uid())?;
|
||||
|
||||
// Validate object quota
|
||||
let account = self.account(account_id).await?;
|
||||
self.assert_object_quota(&account, StorageQuota::MaxContactCards, 1, || {
|
||||
resources.resources.count(false)
|
||||
})?;
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
// Validate quota
|
||||
#[cfg(feature = "enterprise")]
|
||||
if !bytes.is_empty() {
|
||||
self.has_available_tenant_quota(&account, bytes.len() as u64)
|
||||
.await?;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
// Build node
|
||||
let card = ContactCard {
|
||||
names: vec![DavName {
|
||||
name: name.to_string(),
|
||||
parent_id: parent.document_id(),
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let content = ContactCardContent { card: vcard };
|
||||
|
||||
// Prepare write batch
|
||||
let mut batch = BatchBuilder::new();
|
||||
batch.with_account_id(account_id);
|
||||
self.limit_disk_quota(&mut batch, &account);
|
||||
let document_id = batch.reserve_document_id(account_id, Collection::ContactCard);
|
||||
let etag = card
|
||||
.insert(
|
||||
content,
|
||||
self.core.groupware.vcard_version,
|
||||
access_token.changed_by(),
|
||||
account_id,
|
||||
document_id,
|
||||
None,
|
||||
&mut batch,
|
||||
)
|
||||
.caused_by(trc::location!())?;
|
||||
let lock = self
|
||||
.lock_create(
|
||||
access_token,
|
||||
|
|
@ -358,11 +202,20 @@ impl CardUpdateRequestHandler for Server {
|
|||
headers,
|
||||
)
|
||||
.await?;
|
||||
self.commit_create(lock, batch)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let written = writer
|
||||
.create(
|
||||
new,
|
||||
CardCreate {
|
||||
name: name.to_string(),
|
||||
vcard,
|
||||
size: Some(bytes.len()),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
self.release_create_lock(&lock).await;
|
||||
let written = written?;
|
||||
|
||||
Ok(HttpResponse::new(StatusCode::CREATED).with_etag(etag))
|
||||
Ok(HttpResponse::new(StatusCode::CREATED).with_etag(written.etag))
|
||||
} else {
|
||||
Err(DavError::Code(StatusCode::CONFLICT))?
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,29 +5,21 @@
|
|||
*/
|
||||
|
||||
use crate::DavError;
|
||||
use common::{KV_LOCK_DAV, Server, auth::AccessToken};
|
||||
use common::{
|
||||
Server,
|
||||
auth::AccessToken,
|
||||
storage::create_lock::{CREATE_LOCK_ATTEMPTS, CreateLock},
|
||||
};
|
||||
use dav_proto::{Condition, RequestHeaders};
|
||||
use groupware::cache::GroupwareCache;
|
||||
use hyper::StatusCode;
|
||||
use std::{ops::RangeInclusive, time::Duration};
|
||||
use store::{
|
||||
InMemoryStore, U32_LEN, U64_LEN,
|
||||
rand::{self, RngExt},
|
||||
InMemoryStore,
|
||||
write::{AssignedIds, BatchBuilder},
|
||||
xxhash_rust::xxh3::xxh3_64,
|
||||
};
|
||||
use trc::AddContext;
|
||||
use types::collection::SyncCollection;
|
||||
|
||||
const CREATE_LOCK_EXPIRY_SECS: u64 = 10;
|
||||
const CREATE_LOCK_ATTEMPTS: u32 = 3;
|
||||
const CREATE_LOCK_RETRY_MS: RangeInclusive<u64> = 500..=1500;
|
||||
const CREATE_LOCK_KEY_LEN: usize = U32_LEN + 1 + U64_LEN;
|
||||
|
||||
pub(crate) struct CreateLock {
|
||||
key: [u8; CREATE_LOCK_KEY_LEN],
|
||||
}
|
||||
|
||||
pub(crate) trait CreateLockHandler: Sync + Send {
|
||||
fn lock_create(
|
||||
&self,
|
||||
|
|
@ -43,8 +35,6 @@ pub(crate) trait CreateLockHandler: Sync + Send {
|
|||
lock: CreateLock,
|
||||
batch: BatchBuilder,
|
||||
) -> impl Future<Output = trc::Result<AssignedIds>> + Send;
|
||||
|
||||
fn release_create_lock(&self, lock: &CreateLock) -> impl Future<Output = ()> + Send;
|
||||
}
|
||||
|
||||
impl CreateLockHandler for Server {
|
||||
|
|
@ -56,25 +46,19 @@ impl CreateLockHandler for Server {
|
|||
path: &str,
|
||||
headers: &RequestHeaders<'_>,
|
||||
) -> crate::Result<CreateLock> {
|
||||
let lock = CreateLock::new(account_id, collection, path);
|
||||
let store = self.in_memory_store();
|
||||
let min_change_id = if matches!(store, InMemoryStore::Local(_)) {
|
||||
let lock = CreateLock::new(account_id, collection.into(), path.as_bytes());
|
||||
let min_change_id = if matches!(self.in_memory_store(), InMemoryStore::Local(_)) {
|
||||
0
|
||||
} else {
|
||||
u64::MAX
|
||||
};
|
||||
let mut attempts = 1;
|
||||
while !store
|
||||
.try_lock(KV_LOCK_DAV, &lock.key, CREATE_LOCK_EXPIRY_SECS)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
while !self.try_create_lock(&lock).await? {
|
||||
if attempts == CREATE_LOCK_ATTEMPTS {
|
||||
return Err(DavError::Code(StatusCode::SERVICE_UNAVAILABLE));
|
||||
}
|
||||
attempts += 1;
|
||||
let backoff = rand::rng().random_range(CREATE_LOCK_RETRY_MS);
|
||||
tokio::time::sleep(Duration::from_millis(backoff)).await;
|
||||
self.create_lock_backoff().await;
|
||||
if resource_exists(
|
||||
self,
|
||||
access_token,
|
||||
|
|
@ -120,35 +104,6 @@ impl CreateLockHandler for Server {
|
|||
self.release_create_lock(&lock).await;
|
||||
result
|
||||
}
|
||||
|
||||
async fn release_create_lock(&self, lock: &CreateLock) {
|
||||
if let Err(err) = self
|
||||
.in_memory_store()
|
||||
.remove_lock(KV_LOCK_DAV, &lock.key)
|
||||
.await
|
||||
{
|
||||
trc::error!(
|
||||
err.details("Failed to release resource creation lock")
|
||||
.caused_by(trc::location!())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CreateLock {
|
||||
fn new(account_id: u32, collection: SyncCollection, path: &str) -> Self {
|
||||
let mut key = [0u8; CREATE_LOCK_KEY_LEN];
|
||||
for (dst, src) in key.iter_mut().zip(
|
||||
account_id
|
||||
.to_be_bytes()
|
||||
.into_iter()
|
||||
.chain([u8::from(collection)])
|
||||
.chain(xxh3_64(path.as_bytes()).to_be_bytes()),
|
||||
) {
|
||||
*dst = src;
|
||||
}
|
||||
CreateLock { key }
|
||||
}
|
||||
}
|
||||
|
||||
async fn resource_exists(
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ use common::{Server, storage::dav::DISPLAY_NAME_PROPERTY};
|
|||
use dav_proto::schema::{
|
||||
Collation, Namespace,
|
||||
property::{
|
||||
CalDavProperty, CardDavProperty, Comp, DavProperty, DavValue, Privilege, Rfc1123DateTime,
|
||||
SupportedCollation, SupportedLock, WebDavProperty,
|
||||
AvailabilityNamespace, CalDavProperty, CardDavProperty, Comp, DavProperty, DavValue,
|
||||
Privilege, Rfc1123DateTime, SupportedCollation, SupportedLock, WebDavProperty,
|
||||
},
|
||||
request::DavPropertyValue,
|
||||
response::{
|
||||
|
|
@ -35,17 +35,23 @@ use dav_proto::schema::{
|
|||
};
|
||||
use groupware::{
|
||||
DavCalendarResource, DavResourceName,
|
||||
cache::GroupwareCache,
|
||||
calendar::{
|
||||
ArchivedTimezone, SupportedComponent,
|
||||
availability::{Inclusion, PrincipalRole},
|
||||
privacy::EventPrivacy,
|
||||
working_hours::{WorkingHoursHandler, ical::always_available_vavailability},
|
||||
},
|
||||
};
|
||||
use hyper::StatusCode;
|
||||
use registry::schema::enums::Permission;
|
||||
use std::borrow::Cow;
|
||||
use store::write::metadata::MetadataBuf;
|
||||
use trc::AddContext;
|
||||
use types::{acl::Acl, collection::Collection};
|
||||
use types::{
|
||||
acl::Acl,
|
||||
collection::{Collection, SyncCollection},
|
||||
};
|
||||
use utils::map::bitmap::Bitmap;
|
||||
|
||||
pub(super) trait PropFindItemBuilder: Sync + Send {
|
||||
|
|
@ -582,6 +588,7 @@ impl PropFindItemBuilder for Server {
|
|||
DavValue::Components(List(
|
||||
Bitmap::<SupportedComponent>::from(supported_components)
|
||||
.into_iter()
|
||||
.filter(|component| component.is_storable())
|
||||
.map(ICalendarComponentType::from)
|
||||
.map(Comp)
|
||||
.collect(),
|
||||
|
|
@ -742,14 +749,61 @@ impl PropFindItemBuilder for Server {
|
|||
CalDavProperty::ScheduleDefaultCalendarURL,
|
||||
ArchivedResource::CalendarEventNotificationCollection(true),
|
||||
) => {
|
||||
if let Some(default_cal) = &self.core.groupware.default_calendar_name {
|
||||
let resources = self
|
||||
.fetch_groupware_resources(
|
||||
access_token.account_id(),
|
||||
account_id,
|
||||
SyncCollection::Calendar,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let default_href = self
|
||||
.default_calendar_id(account_id)
|
||||
.await?
|
||||
.and_then(|calendar_id| {
|
||||
resources.container_resource_path_by_id(calendar_id)
|
||||
})
|
||||
.map(|path| resources.format_resource(path));
|
||||
if let Some(default_href) = default_href {
|
||||
fields.push(DavPropertyValue::new(
|
||||
property.clone(),
|
||||
vec![Href(format!(
|
||||
"{}/{}/{default_cal}/",
|
||||
DavResourceName::Cal.base_path(),
|
||||
item.name.split('/').nth(3).unwrap_or_default()
|
||||
))],
|
||||
vec![Href(default_href)],
|
||||
));
|
||||
} else {
|
||||
fields_not_found.push(DavPropertyValue::empty(property.clone()));
|
||||
}
|
||||
}
|
||||
(
|
||||
CalDavProperty::CalendarAvailability(namespace),
|
||||
ArchivedResource::CalendarEventNotificationCollection(true),
|
||||
) => {
|
||||
let vavailability = if access_token
|
||||
.has_permission(Permission::SysCalendarSettingsGet)
|
||||
&& let Some(account) = self
|
||||
.try_account(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
match self
|
||||
.working_hours_vavailability(&account)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
Some(vavailability) => Some(vavailability),
|
||||
None if *namespace == AvailabilityNamespace::CalendarServer
|
||||
&& !account.is_group_account() =>
|
||||
{
|
||||
Some(always_available_vavailability(account.id))
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(vavailability) = vavailability {
|
||||
fields.push(DavPropertyValue::new(
|
||||
property.clone(),
|
||||
DavValue::CData(vavailability),
|
||||
));
|
||||
} else {
|
||||
fields_not_found.push(DavPropertyValue::empty(property.clone()));
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ use dav_proto::schema::{
|
|||
use groupware::RFC_3986;
|
||||
use groupware::cache::GroupwareCache;
|
||||
use hyper::StatusCode;
|
||||
use registry::schema::enums::Permission;
|
||||
use registry::schema::enums::{Permission, ResourceKind};
|
||||
use std::borrow::Cow;
|
||||
use trc::AddContext;
|
||||
use types::collection::Collection;
|
||||
|
|
@ -315,11 +315,15 @@ impl PrincipalPropFind for Server {
|
|||
PrincipalProperty::CalendarUserType => {
|
||||
fields.push(DavPropertyValue::new(
|
||||
property.clone(),
|
||||
if account.is_user_account() {
|
||||
DavValue::String("INDIVIDUAL".to_string())
|
||||
} else {
|
||||
DavValue::String("GROUP".to_string())
|
||||
},
|
||||
DavValue::String(
|
||||
match account.resource_kind() {
|
||||
Some(ResourceKind::Room) => "ROOM",
|
||||
Some(ResourceKind::Equipment) => "RESOURCE",
|
||||
None if account.is_user_account() => "INDIVIDUAL",
|
||||
None => "GROUP",
|
||||
}
|
||||
.to_string(),
|
||||
),
|
||||
));
|
||||
}
|
||||
PrincipalProperty::ScheduleInboxURL => {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ use dav_proto::schema::{
|
|||
use groupware::strip_mailto_scheme;
|
||||
use http_proto::HttpResponse;
|
||||
use hyper::StatusCode;
|
||||
use registry::schema::prelude::{ObjectType, Permission, Property};
|
||||
use registry::schema::prelude::{AccountType, ObjectType, Permission, Property, ResourceKind};
|
||||
use store::{registry::RegistryQuery, roaring::RoaringBitmap};
|
||||
use trc::AddContext;
|
||||
use types::collection::Collection;
|
||||
|
|
@ -128,6 +128,31 @@ impl PrincipalPropSearch for Server {
|
|||
}
|
||||
address
|
||||
}
|
||||
DavProperty::Principal(PrincipalProperty::CalendarUserType) => {
|
||||
let Some((property, value)) = hashify::map_ignore_case!(
|
||||
text.trim().as_bytes(),
|
||||
(Property, u16),
|
||||
b"INDIVIDUAL" => (Property::Type, AccountType::User as u16),
|
||||
b"GROUP" => (Property::Type, AccountType::Group as u16),
|
||||
b"ROOM" => (Property::Kind, ResourceKind::Room as u16),
|
||||
b"RESOURCE" => (Property::Kind, ResourceKind::Equipment as u16),
|
||||
) else {
|
||||
return Ok(RoaringBitmap::new());
|
||||
};
|
||||
let query = RegistryQuery::new(ObjectType::Account);
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
let query = query.with_tenant(access_token.tenant_id());
|
||||
// SPDX-SnippetEnd
|
||||
return self
|
||||
.registry()
|
||||
.query::<RoaringBitmap>(query.equal(*property, *value))
|
||||
.await
|
||||
.caused_by(trc::location!())
|
||||
.map_err(Into::into);
|
||||
}
|
||||
_ => return Ok(RoaringBitmap::new()),
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
use crate::{
|
||||
DavError, DavErrorCondition, DavMethod, DavResourceName,
|
||||
calendar::{
|
||||
availability::CalendarAvailabilityRequestHandler,
|
||||
copy_move::CalendarCopyMoveRequestHandler, delete::CalendarDeleteRequestHandler,
|
||||
freebusy::CalendarFreebusyRequestHandler, get::CalendarGetRequestHandler,
|
||||
mkcol::CalendarMkColRequestHandler, proppatch::CalendarPropPatchRequestHandler,
|
||||
|
|
@ -234,6 +235,10 @@ impl DavRequestDispatcher for Server {
|
|||
),
|
||||
"Calendar user address",
|
||||
),
|
||||
PrincipalSearchProperty::new(
|
||||
DavProperty::Principal(PrincipalProperty::CalendarUserType),
|
||||
"Calendar user type",
|
||||
),
|
||||
])
|
||||
.with_namespace(Namespace::CalDav)
|
||||
.to_string(),
|
||||
|
|
@ -347,7 +352,14 @@ impl DavRequestDispatcher for Server {
|
|||
self.handle_file_proppatch_request(&access_token, headers, request)
|
||||
.await
|
||||
}
|
||||
DavResourceName::Principal | DavResourceName::Scheduling => {
|
||||
DavResourceName::Scheduling => {
|
||||
let access_token =
|
||||
access_token.assert_has_permission(Permission::DavCalPropPatch)?;
|
||||
|
||||
self.handle_scheduling_proppatch_request(&access_token, headers, request)
|
||||
.await
|
||||
}
|
||||
DavResourceName::Principal => {
|
||||
Err(DavError::Code(StatusCode::METHOD_NOT_ALLOWED))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "directory"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ impl Directories {
|
|||
let directory = match result {
|
||||
Ok(directory) => directory,
|
||||
Err(err) => {
|
||||
bp.build_error(id, err.clone());
|
||||
bp.build_warning(id, err.clone());
|
||||
Directory::Unavailable(UnavailableDirectory::new(directory_type, err))
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -177,12 +177,16 @@ fn digest_matches(digest: &[u8], encoded: &str) -> bool {
|
|||
|
||||
const MAX_ENCODED_DIGEST_LEN: usize = STANDARD.encoded_len(64);
|
||||
|
||||
const MAX_SECRET_LEN: usize = 1024;
|
||||
|
||||
pub async fn verify_secret_hash(
|
||||
verifier: &PasswordVerifier,
|
||||
hashed_secret: &str,
|
||||
secret: &[u8],
|
||||
) -> trc::Result<bool> {
|
||||
if hashed_secret.starts_with('$') {
|
||||
if secret.len() > MAX_SECRET_LEN {
|
||||
Ok(false)
|
||||
} else if hashed_secret.starts_with('$') {
|
||||
verify_hash_prefix(verifier, hashed_secret, secret).await
|
||||
} else if hashed_secret.starts_with('_') {
|
||||
CryptScheme::BsdiCrypt
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "email"
|
||||
version = "1.1.1"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
@ -26,12 +26,14 @@ rkyv.workspace = true
|
|||
compact_str = "0.10.0"
|
||||
tinyvec = { version = "1.13.3", features = ["alloc"] }
|
||||
bytecount = "0.6"
|
||||
encodify = "1.0"
|
||||
percent-encoding = "2.3.2"
|
||||
blake3 = "1.8"
|
||||
|
||||
[features]
|
||||
enterprise = ["utils/enterprise", "store/enterprise", "trc/enterprise", "jmap_proto/enterprise", "common/enterprise", "groupware/enterprise", "registry/enterprise"]
|
||||
|
||||
[dev-dependencies]
|
||||
encodify = "1.0"
|
||||
tokio = { version = "1.54", features = ["full"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
|
|
|
|||
325
crates/email/src/cache/mod.rs
vendored
325
crates/email/src/cache/mod.rs
vendored
|
|
@ -39,6 +39,19 @@ pub trait MessageCacheFetch: Sync + Send {
|
|||
|
||||
fn fresh_messages(&self, account_id: u32) -> Option<Arc<MessageStoreCache>>;
|
||||
|
||||
fn get_current_messages(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<Arc<MessageStoreCache>>> + Send;
|
||||
|
||||
fn refresh_messages(
|
||||
&self,
|
||||
account_id: u32,
|
||||
cache: Arc<MessageStoreCache>,
|
||||
start_time: Instant,
|
||||
verified_after: Option<u64>,
|
||||
) -> impl Future<Output = trc::Result<Arc<MessageStoreCache>>> + Send;
|
||||
|
||||
fn apply_keyword_writes(
|
||||
&self,
|
||||
account_id: u32,
|
||||
|
|
@ -67,6 +80,173 @@ impl MessageCacheFetch for Server {
|
|||
revalidate_messages(self, account_id, cache).await
|
||||
}
|
||||
|
||||
async fn get_current_messages(&self, account_id: u32) -> trc::Result<Arc<MessageStoreCache>> {
|
||||
let cache = match self.inner.cache.resident_messages(account_id) {
|
||||
Some(cache) => cache,
|
||||
None => match load_cache(self, account_id).await? {
|
||||
LoadedCache::Resident(cache) => cache,
|
||||
LoadedCache::Built(cache) => return Ok(cache),
|
||||
},
|
||||
};
|
||||
let verified_after = self.inner.cache.revalidate.now();
|
||||
self.refresh_messages(account_id, cache, Instant::now(), Some(verified_after))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn refresh_messages(
|
||||
&self,
|
||||
account_id: u32,
|
||||
cache: Arc<MessageStoreCache>,
|
||||
start_time: Instant,
|
||||
verified_after: Option<u64>,
|
||||
) -> trc::Result<Arc<MessageStoreCache>> {
|
||||
let caches = &self.inner.cache;
|
||||
let revalidate = &caches.revalidate;
|
||||
let lock = cache.update_lock.clone();
|
||||
let entry_epoch = lock.epoch();
|
||||
let (_permit, cache) = match lock.try_update() {
|
||||
Some(permit) => (permit, cache),
|
||||
None => loop {
|
||||
let released = lock.released();
|
||||
let permit = lock.try_update();
|
||||
if permit.is_none() {
|
||||
released.await;
|
||||
}
|
||||
match (caches.peek_messages(account_id), permit) {
|
||||
(Some(current), _)
|
||||
if (current.is_fresh(revalidate)
|
||||
|| (Arc::ptr_eq(¤t.update_lock, &lock)
|
||||
&& current
|
||||
.verification
|
||||
.is_verified_since(entry_epoch, revalidate)))
|
||||
&& verified_after.is_none_or(|after| {
|
||||
current.verification.is_verified_after(after)
|
||||
}) =>
|
||||
{
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Hit),
|
||||
AccountId = account_id,
|
||||
Collection = SyncCollection::Email.as_str(),
|
||||
ChangeId = current.last_change_id,
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
return Ok(current);
|
||||
}
|
||||
(current, Some(permit)) => break (permit, current.unwrap_or(cache)),
|
||||
_ => {}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Obtain current state
|
||||
let verification = Verification::capture(revalidate, &cache.update_lock);
|
||||
let changes = self
|
||||
.core
|
||||
.storage
|
||||
.data
|
||||
.changes(
|
||||
account_id,
|
||||
SyncCollection::Email.into(),
|
||||
Query::Since(cache.last_change_id),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Regenerate cache if the change log has been truncated
|
||||
if changes.needs_full_rebuild(cache.last_change_id) {
|
||||
let mut cache =
|
||||
full_cache_build(self, account_id, cache.update_lock.clone(), verification).await?;
|
||||
if !is_resident_lock(self, account_id, &cache.update_lock)
|
||||
&& let Some(cache) = Arc::get_mut(&mut cache)
|
||||
{
|
||||
cache.verification = Verification::default();
|
||||
}
|
||||
caches.publish_messages(
|
||||
account_id,
|
||||
&cache,
|
||||
Some(SwapChanges::rebuilt(
|
||||
cache.last_change_id,
|
||||
cache.emails.len(),
|
||||
)),
|
||||
);
|
||||
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Stale),
|
||||
AccountId = account_id,
|
||||
Collection = SyncCollection::Email.as_str(),
|
||||
ChangeId = cache.last_change_id,
|
||||
Total = vec![cache.emails.len(), cache.mailboxes.items.len()],
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
|
||||
return Ok(cache);
|
||||
}
|
||||
|
||||
// Verify changes
|
||||
if changes.changes.is_empty() {
|
||||
let is_current = verification.is_current(&cache.update_lock);
|
||||
let is_advanced = changes.to_change_id > cache.last_change_id;
|
||||
let cache = if is_current || is_advanced {
|
||||
let mut verified = cache.as_ref().clone();
|
||||
if is_current && is_resident_lock(self, account_id, &verified.update_lock) {
|
||||
verified.verification = verification;
|
||||
}
|
||||
if is_advanced {
|
||||
verified.last_change_id = changes.to_change_id;
|
||||
if changes.item_change_id.is_some() {
|
||||
verified.refresh = Arc::new(verified.refresh.with_new_uid_next());
|
||||
}
|
||||
}
|
||||
let verified = Arc::new(verified);
|
||||
caches.publish_messages(account_id, &verified, None);
|
||||
verified
|
||||
} else {
|
||||
cache
|
||||
};
|
||||
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Hit),
|
||||
AccountId = account_id,
|
||||
Collection = SyncCollection::Email.as_str(),
|
||||
ChangeId = cache.last_change_id,
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
|
||||
return Ok(cache);
|
||||
}
|
||||
|
||||
let change_set = ChangeSet::classify(changes);
|
||||
let base_change_id = cache.last_change_id;
|
||||
let mut cache = change_set.apply(self, account_id, cache.as_ref()).await?;
|
||||
if is_resident_lock(self, account_id, &cache.update_lock) {
|
||||
cache.verification = verification;
|
||||
}
|
||||
|
||||
let cache = Arc::new(cache);
|
||||
caches.publish_messages(
|
||||
account_id,
|
||||
&cache,
|
||||
Some(SwapChanges::applied(
|
||||
change_set.items.len(),
|
||||
base_change_id,
|
||||
cache.last_change_id,
|
||||
cache.emails.len(),
|
||||
)),
|
||||
);
|
||||
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Update),
|
||||
AccountId = account_id,
|
||||
Collection = SyncCollection::Email.as_str(),
|
||||
ChangeId = cache.last_change_id,
|
||||
Details = vec![change_set.items.len(), change_set.containers.len()],
|
||||
Total = vec![cache.emails.len(), cache.mailboxes.items.len()],
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
async fn get_resident_messages(
|
||||
&self,
|
||||
account_id: u32,
|
||||
|
|
@ -205,12 +385,9 @@ async fn revalidate_messages(
|
|||
account_id: u32,
|
||||
cache: Arc<MessageStoreCache>,
|
||||
) -> trc::Result<Arc<MessageStoreCache>> {
|
||||
let caches = &server.inner.cache;
|
||||
|
||||
// Serve the snapshot without revalidating while it is within the freshness window
|
||||
let start_time = Instant::now();
|
||||
let revalidate = &caches.revalidate;
|
||||
let served = |cache: Arc<MessageStoreCache>| {
|
||||
if cache.is_fresh(&server.inner.cache.revalidate) {
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Hit),
|
||||
AccountId = account_id,
|
||||
|
|
@ -218,145 +395,11 @@ async fn revalidate_messages(
|
|||
ChangeId = cache.last_change_id,
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
Ok(cache)
|
||||
};
|
||||
if cache.is_fresh(revalidate) {
|
||||
return served(cache);
|
||||
return Ok(cache);
|
||||
}
|
||||
|
||||
let lock = cache.update_lock.clone();
|
||||
let entry_epoch = lock.epoch();
|
||||
let (_permit, cache) = match lock.try_update() {
|
||||
Some(permit) => (permit, cache),
|
||||
None => loop {
|
||||
let released = lock.released();
|
||||
let permit = lock.try_update();
|
||||
if permit.is_none() {
|
||||
released.await;
|
||||
}
|
||||
match (caches.peek_messages(account_id), permit) {
|
||||
(Some(current), _)
|
||||
if current.is_fresh(revalidate)
|
||||
|| (Arc::ptr_eq(¤t.update_lock, &lock)
|
||||
&& current
|
||||
.verification
|
||||
.is_verified_since(entry_epoch, revalidate)) =>
|
||||
{
|
||||
return served(current);
|
||||
}
|
||||
(current, Some(permit)) => break (permit, current.unwrap_or(cache)),
|
||||
_ => {}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Obtain current state
|
||||
let verification = Verification::capture(revalidate, &cache.update_lock);
|
||||
let changes = server
|
||||
.core
|
||||
.storage
|
||||
.data
|
||||
.changes(
|
||||
account_id,
|
||||
SyncCollection::Email.into(),
|
||||
Query::Since(cache.last_change_id),
|
||||
)
|
||||
server
|
||||
.refresh_messages(account_id, cache, start_time, None)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
// Regenerate cache if the change log has been truncated
|
||||
if changes.needs_full_rebuild(cache.last_change_id) {
|
||||
let mut cache =
|
||||
full_cache_build(server, account_id, cache.update_lock.clone(), verification).await?;
|
||||
if !is_resident_lock(server, account_id, &cache.update_lock)
|
||||
&& let Some(cache) = Arc::get_mut(&mut cache)
|
||||
{
|
||||
cache.verification = Verification::default();
|
||||
}
|
||||
caches.publish_messages(
|
||||
account_id,
|
||||
&cache,
|
||||
Some(SwapChanges::rebuilt(
|
||||
cache.last_change_id,
|
||||
cache.emails.len(),
|
||||
)),
|
||||
);
|
||||
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Stale),
|
||||
AccountId = account_id,
|
||||
Collection = SyncCollection::Email.as_str(),
|
||||
ChangeId = cache.last_change_id,
|
||||
Total = vec![cache.emails.len(), cache.mailboxes.items.len()],
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
|
||||
return Ok(cache);
|
||||
}
|
||||
|
||||
// Verify changes
|
||||
if changes.changes.is_empty() {
|
||||
let is_current = verification.is_current(&cache.update_lock);
|
||||
let is_advanced = changes.to_change_id > cache.last_change_id;
|
||||
let cache = if is_current || is_advanced {
|
||||
let mut verified = cache.as_ref().clone();
|
||||
if is_current && is_resident_lock(server, account_id, &verified.update_lock) {
|
||||
verified.verification = verification;
|
||||
}
|
||||
if is_advanced {
|
||||
verified.last_change_id = changes.to_change_id;
|
||||
if changes.item_change_id.is_some() {
|
||||
verified.refresh = Arc::new(verified.refresh.with_new_uid_next());
|
||||
}
|
||||
}
|
||||
let verified = Arc::new(verified);
|
||||
caches.publish_messages(account_id, &verified, None);
|
||||
verified
|
||||
} else {
|
||||
cache
|
||||
};
|
||||
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Hit),
|
||||
AccountId = account_id,
|
||||
Collection = SyncCollection::Email.as_str(),
|
||||
ChangeId = cache.last_change_id,
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
|
||||
return Ok(cache);
|
||||
}
|
||||
|
||||
let change_set = ChangeSet::classify(changes);
|
||||
let base_change_id = cache.last_change_id;
|
||||
let mut cache = change_set.apply(server, account_id, cache.as_ref()).await?;
|
||||
if is_resident_lock(server, account_id, &cache.update_lock) {
|
||||
cache.verification = verification;
|
||||
}
|
||||
|
||||
let cache = Arc::new(cache);
|
||||
caches.publish_messages(
|
||||
account_id,
|
||||
&cache,
|
||||
Some(SwapChanges::applied(
|
||||
change_set.items.len(),
|
||||
base_change_id,
|
||||
cache.last_change_id,
|
||||
cache.emails.len(),
|
||||
)),
|
||||
);
|
||||
|
||||
trc::event!(
|
||||
Cache(CacheEvent::Update),
|
||||
AccountId = account_id,
|
||||
Collection = SyncCollection::Email.as_str(),
|
||||
ChangeId = cache.last_change_id,
|
||||
Details = vec![change_set.items.len(), change_set.containers.len()],
|
||||
Total = vec![cache.emails.len(), cache.mailboxes.items.len()],
|
||||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
struct ChangeSet {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,13 @@
|
|||
|
||||
use super::*;
|
||||
use crate::cache::{MessageCacheFetch, mailbox::MailboxCacheAccess};
|
||||
use common::{Server, storage::index::ObjectIndexBuilder};
|
||||
use common::{
|
||||
Server,
|
||||
storage::{
|
||||
create_lock::{CREATE_LOCK_ATTEMPTS, CreateLock},
|
||||
index::ObjectIndexBuilder,
|
||||
},
|
||||
};
|
||||
use registry::schema::enums::StorageQuota;
|
||||
use std::future::Future;
|
||||
use store::write::BatchBuilder;
|
||||
|
|
@ -24,9 +30,43 @@ pub trait MailboxFnc: Sync + Send {
|
|||
account_id: u32,
|
||||
path: &str,
|
||||
) -> impl Future<Output = trc::Result<Option<u32>>> + Send;
|
||||
|
||||
fn lock_mailbox_names(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<CreateLock>> + Send;
|
||||
|
||||
fn unlock_mailbox_names(&self, lock: CreateLock) -> impl Future<Output = ()> + Send;
|
||||
|
||||
fn create_mailbox_path(
|
||||
&self,
|
||||
account_id: u32,
|
||||
path: &str,
|
||||
) -> impl Future<Output = trc::Result<Option<u32>>> + Send;
|
||||
}
|
||||
|
||||
impl MailboxFnc for Server {
|
||||
async fn lock_mailbox_names(&self, account_id: u32) -> trc::Result<CreateLock> {
|
||||
let lock = CreateLock::new(account_id, Collection::Mailbox.into(), &[]);
|
||||
for _ in 1..CREATE_LOCK_ATTEMPTS {
|
||||
if self.try_create_lock(&lock).await? {
|
||||
return Ok(lock);
|
||||
}
|
||||
self.create_lock_backoff().await;
|
||||
}
|
||||
if self.try_create_lock(&lock).await? {
|
||||
Ok(lock)
|
||||
} else {
|
||||
Err(trc::LimitEvent::ConcurrentRequest
|
||||
.into_err()
|
||||
.details("Mailboxes are being changed by another session"))
|
||||
}
|
||||
}
|
||||
|
||||
async fn unlock_mailbox_names(&self, lock: CreateLock) {
|
||||
self.release_create_lock(&lock).await;
|
||||
}
|
||||
|
||||
async fn create_system_folders(&self, account_id: u32) -> trc::Result<()> {
|
||||
#[cfg(stalwart_tests)]
|
||||
if account_id == 0 {
|
||||
|
|
@ -80,8 +120,15 @@ impl MailboxFnc for Server {
|
|||
}
|
||||
|
||||
async fn mailbox_create_path(&self, account_id: u32, path: &str) -> trc::Result<Option<u32>> {
|
||||
let lock = self.lock_mailbox_names(account_id).await?;
|
||||
let result = self.create_mailbox_path(account_id, path).await;
|
||||
self.unlock_mailbox_names(lock).await;
|
||||
result
|
||||
}
|
||||
|
||||
async fn create_mailbox_path(&self, account_id: u32, path: &str) -> trc::Result<Option<u32>> {
|
||||
let cache = self
|
||||
.get_cached_messages(account_id)
|
||||
.get_current_messages(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ pub const ORCPT_ADDR_TYPE: &str = "rfc822;";
|
|||
pub struct IngestMessage {
|
||||
pub sender_address: String,
|
||||
pub sender_authentication: SenderAuthentication,
|
||||
pub return_path_status: ReturnPathStatus,
|
||||
pub recipients: Vec<IngestRecipient>,
|
||||
pub message_blob: BlobHash,
|
||||
pub message_size: u64,
|
||||
|
|
@ -38,6 +39,12 @@ pub enum SenderAuthentication {
|
|||
Submission,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ReturnPathStatus {
|
||||
Verified,
|
||||
Unverified,
|
||||
}
|
||||
|
||||
impl SenderAuthentication {
|
||||
pub fn is_authenticated(&self) -> bool {
|
||||
!matches!(self, SenderAuthentication::Unauthenticated)
|
||||
|
|
@ -99,6 +106,7 @@ pub struct AutogeneratedMessage {
|
|||
pub message: Vec<u8>,
|
||||
pub notify: Notify,
|
||||
pub source: MessageSource,
|
||||
pub spam_percentage: Option<u8>,
|
||||
pub exploded: bool,
|
||||
}
|
||||
|
||||
|
|
@ -242,6 +250,7 @@ impl MailDelivery for Server {
|
|||
&raw_message,
|
||||
&message.sender_address,
|
||||
message.sender_authentication,
|
||||
message.return_path_status,
|
||||
&rcpt,
|
||||
message.session_id,
|
||||
active_script,
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ use groupware::{
|
|||
calendar::itip::{ItipIngest, ItipIngestError, ItipOrigin},
|
||||
scheduling::{ItipError, ItipMessages},
|
||||
};
|
||||
use mail_parser::{Message, MessageParser, thread_name};
|
||||
use mail_parser::{HeaderName, Message, MessageParser, thread_name};
|
||||
use recheck::PendingThread;
|
||||
use registry::{
|
||||
schema::{
|
||||
|
|
@ -94,6 +94,12 @@ pub struct PendingEmail {
|
|||
start_time: Instant,
|
||||
}
|
||||
|
||||
impl PendingEmail {
|
||||
pub fn document_id(&self) -> PendingId {
|
||||
PendingId::Slot(self.document_slot)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct IngestEmail<'x> {
|
||||
pub raw_message: &'x [u8],
|
||||
pub blob_hash: Option<&'x BlobHash>,
|
||||
|
|
@ -356,7 +362,11 @@ impl EmailIngest for Server {
|
|||
|
||||
// Skip duplicate messages for SMTP ingestion
|
||||
if !thread_result.duplicate_ids.is_empty()
|
||||
&& params.source.is_smtp()
|
||||
&& let IngestSource::Smtp {
|
||||
envelope_from,
|
||||
sender_authentication,
|
||||
..
|
||||
} = params.source
|
||||
&& Box::pin(checks::has_duplicate_in(
|
||||
self,
|
||||
account_id,
|
||||
|
|
@ -365,6 +375,11 @@ impl EmailIngest for Server {
|
|||
))
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
&& !(sender_authentication == SenderAuthentication::Submission
|
||||
&& matches!(
|
||||
self.account_id_from_email(envelope_from, false).await,
|
||||
Ok(Some(id)) if id == account_id
|
||||
))
|
||||
{
|
||||
trc::event!(
|
||||
MessageIngest(MessageIngestEvent::Duplicate),
|
||||
|
|
@ -395,6 +410,10 @@ impl EmailIngest for Server {
|
|||
sender_authentication,
|
||||
mut is_spam,
|
||||
} => {
|
||||
if !message.headers().contains(HeaderName::ReturnPath) {
|
||||
extra_headers.push(HeaderId::RETURN_PATH, &format!("<{envelope_from}>"));
|
||||
}
|
||||
|
||||
// Add delivered to header
|
||||
if self.core.smtp.session.data.add_delivered_to {
|
||||
extra_headers.push(HeaderId::DELIVERED_TO, deliver_to);
|
||||
|
|
@ -403,6 +422,11 @@ impl EmailIngest for Server {
|
|||
// Spam training on confirmed false positives
|
||||
if self.core.spam.enabled {
|
||||
let mut overridden = None;
|
||||
if is_spam && params.keywords.contains(&Keyword::NotJunk) {
|
||||
is_spam = false;
|
||||
overridden = Some("trusted-sender");
|
||||
}
|
||||
|
||||
// If the message is classified as spam, check whether the
|
||||
// sender address is present in the user's address book.
|
||||
if is_spam
|
||||
|
|
@ -495,15 +519,21 @@ impl EmailIngest for Server {
|
|||
} else {
|
||||
ItipOrigin::Delivery
|
||||
};
|
||||
for part in message.root().parts() {
|
||||
if part.content_type().is_some_and(|ct| {
|
||||
ct.ctype().eq_ignore_ascii_case("text")
|
||||
&& ct
|
||||
.subtype()
|
||||
.is_some_and(|st| st.eq_ignore_ascii_case("calendar"))
|
||||
&& ct.has_attribute("method")
|
||||
}) && let Some(itip_message) = part.text()
|
||||
{
|
||||
for part in message
|
||||
.root()
|
||||
.parts()
|
||||
.filter(|part| {
|
||||
part.content_type().is_some_and(|ct| {
|
||||
ct.ctype().eq_ignore_ascii_case("text")
|
||||
&& ct
|
||||
.subtype()
|
||||
.is_some_and(|st| st.eq_ignore_ascii_case("calendar"))
|
||||
&& ct.has_attribute("method")
|
||||
})
|
||||
})
|
||||
.take(MAX_ITIP_PARTS)
|
||||
{
|
||||
if let Some(itip_message) = part.text() {
|
||||
if itip_message.len() < self.core.groupware.itip_inbound_max_ical_size {
|
||||
if let Some(sender) = sender.get_or_insert_with(|| {
|
||||
if sender_authentication == SenderAuthentication::Submission {
|
||||
|
|
@ -1287,6 +1317,7 @@ impl From<ThreadInfo<'_>> for SizedSetValue {
|
|||
}
|
||||
|
||||
const THREAD_SCAN_WINDOW: usize = 256;
|
||||
const MAX_ITIP_PARTS: usize = 4;
|
||||
|
||||
pub struct ThreadMerge {
|
||||
entries: AHashMap<u32, Vec<u32>>,
|
||||
|
|
|
|||
573
crates/email/src/message/mdn.rs
Normal file
573
crates/email/src/message/mdn.rs
Normal file
|
|
@ -0,0 +1,573 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::message::metadata::{ArchivedMessageMetadata, HeaderId, view::HeaderList};
|
||||
use jmap_proto::object::mdn::{
|
||||
ActionMode, Disposition, DispositionType, Mdn, MdnProperty, SendingMode,
|
||||
};
|
||||
use mail_builder::{
|
||||
MessageBuilder,
|
||||
headers::{HeaderType, address::Address, content_type::ContentType},
|
||||
mime::{BodyPart, MimePart, make_boundary},
|
||||
};
|
||||
use mail_parser::{HeaderForm, MessageParser, MessagePart};
|
||||
use std::{borrow::Cow, fmt::Write};
|
||||
use utils::{DomainPart, map::vec_map::VecMap, sanitize_email};
|
||||
|
||||
pub const MAX_NOTIFY_ADDRESSES: usize = 5;
|
||||
pub const MAX_FIELD_LEN: usize = 900;
|
||||
pub const MAX_SUBJECT_LEN: usize = 998;
|
||||
pub const MAX_TEXT_BODY_LEN: usize = 8192;
|
||||
pub const MAX_EXTENSION_FIELDS: usize = 32;
|
||||
pub const MAX_REPORT_FIELDS: usize = 64;
|
||||
pub const MAX_ERRORS: usize = 16;
|
||||
const MAX_FIELD_NAME_LEN: usize = 76;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MdnStatus {
|
||||
NotRequested,
|
||||
Report,
|
||||
Requested(MdnRequest),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MdnRequest {
|
||||
pub notify: Vec<String>,
|
||||
pub message_id: Option<String>,
|
||||
pub subject: Option<String>,
|
||||
pub original_recipient: Option<String>,
|
||||
pub return_path: Option<String>,
|
||||
pub utf8_headers: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MdnInvalid {
|
||||
pub property: MdnProperty,
|
||||
pub reason: &'static str,
|
||||
}
|
||||
|
||||
pub struct MdnMessage<'x> {
|
||||
pub mdn: &'x Mdn,
|
||||
pub disposition: Disposition,
|
||||
pub from_name: Option<&'x str>,
|
||||
pub from_address: &'x str,
|
||||
pub to: &'x [String],
|
||||
pub original_message: Option<OriginalMessage<'x>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct OriginalMessage<'x> {
|
||||
pub raw: &'x [u8],
|
||||
pub utf8_headers: bool,
|
||||
}
|
||||
|
||||
impl MdnStatus {
|
||||
pub fn new(metadata: &ArchivedMessageMetadata, raw_headers: &[u8]) -> Self {
|
||||
let root = metadata.root();
|
||||
let part = root.root_part();
|
||||
if part.content_type().is_some_and(|ct| {
|
||||
ct.ctype().eq_ignore_ascii_case("multipart")
|
||||
&& ct
|
||||
.subtype()
|
||||
.is_some_and(|subtype| subtype.eq_ignore_ascii_case("report"))
|
||||
}) {
|
||||
return MdnStatus::Report;
|
||||
}
|
||||
|
||||
let headers = part.headers();
|
||||
let Some(parsed) = headers.last_parsed(
|
||||
HeaderId::DISPOSITION_NOTIFICATION_TO,
|
||||
raw_headers,
|
||||
HeaderForm::Addresses,
|
||||
) else {
|
||||
return MdnStatus::NotRequested;
|
||||
};
|
||||
let Some(list) = parsed.value().as_address() else {
|
||||
return MdnStatus::NotRequested;
|
||||
};
|
||||
let mut notify = Vec::new();
|
||||
for address in list
|
||||
.mailboxes()
|
||||
.filter_map(|mailbox| mailbox.address().and_then(sanitize_email))
|
||||
{
|
||||
if !notify.contains(&address) {
|
||||
notify.push(address);
|
||||
if notify.len() == MAX_NOTIFY_ADDRESSES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if notify.is_empty() {
|
||||
return MdnStatus::NotRequested;
|
||||
}
|
||||
|
||||
let envelope = root.envelope();
|
||||
MdnStatus::Requested(MdnRequest {
|
||||
notify,
|
||||
message_id: envelope
|
||||
.message_id()
|
||||
.last()
|
||||
.filter(|id| is_valid_field_value(id))
|
||||
.map(|id| format!("<{id}>")),
|
||||
subject: envelope.subject().map(str::to_string),
|
||||
original_recipient: headers
|
||||
.last_parsed(HeaderId::ORIGINAL_RECIPIENT, raw_headers, HeaderForm::Text)
|
||||
.and_then(|value| {
|
||||
value
|
||||
.value()
|
||||
.as_text()
|
||||
.map(str::trim)
|
||||
.filter(|text| is_valid_field_value(text))
|
||||
.map(str::to_string)
|
||||
}),
|
||||
return_path: single_return_path(&headers, raw_headers),
|
||||
utf8_headers: !headers.iter().all(|header| {
|
||||
raw_headers
|
||||
.get(header.field_range())
|
||||
.is_none_or(<[u8]>::is_ascii)
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl MdnRequest {
|
||||
pub fn allows_automatic(&self) -> bool {
|
||||
matches!(
|
||||
(self.notify.as_slice(), &self.return_path),
|
||||
([notify], Some(return_path)) if notify == return_path
|
||||
)
|
||||
}
|
||||
|
||||
pub fn apply_defaults(
|
||||
&mut self,
|
||||
mdn: &mut Mdn,
|
||||
disposition: Disposition,
|
||||
final_recipient: &str,
|
||||
) {
|
||||
if mdn.final_recipient.is_none() {
|
||||
mdn.final_recipient = Some(format!("rfc822; {final_recipient}"));
|
||||
}
|
||||
if mdn.subject.is_none() {
|
||||
mdn.subject = Some(default_subject(
|
||||
disposition.disposition_type,
|
||||
self.subject.as_deref(),
|
||||
));
|
||||
}
|
||||
if mdn.text_body.is_none() {
|
||||
mdn.text_body = Some(default_text(
|
||||
disposition.disposition_type,
|
||||
self.subject.as_deref(),
|
||||
));
|
||||
}
|
||||
mdn.original_message_id = self.message_id.take();
|
||||
mdn.original_recipient = self.original_recipient.take();
|
||||
}
|
||||
}
|
||||
|
||||
impl MdnInvalid {
|
||||
fn new(property: MdnProperty, reason: &'static str) -> Self {
|
||||
MdnInvalid { property, reason }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_mdn(mdn: &Mdn) -> Result<Disposition, MdnInvalid> {
|
||||
let Some(disposition) = mdn.disposition else {
|
||||
return Err(MdnInvalid::new(
|
||||
MdnProperty::Disposition,
|
||||
"A valid disposition is required.",
|
||||
));
|
||||
};
|
||||
for (property, is_set) in [
|
||||
(MdnProperty::MdnGateway, mdn.mdn_gateway.is_some()),
|
||||
(
|
||||
MdnProperty::OriginalRecipient,
|
||||
mdn.original_recipient.is_some(),
|
||||
),
|
||||
(
|
||||
MdnProperty::OriginalMessageId,
|
||||
mdn.original_message_id.is_some(),
|
||||
),
|
||||
(MdnProperty::Error, mdn.error.is_some()),
|
||||
] {
|
||||
if is_set {
|
||||
return Err(MdnInvalid::new(property, "Property is server-set."));
|
||||
}
|
||||
}
|
||||
if let Some(subject) = &mdn.subject
|
||||
&& (subject.len() > MAX_SUBJECT_LEN || subject.contains(['\r', '\n']))
|
||||
{
|
||||
return Err(MdnInvalid::new(
|
||||
MdnProperty::Subject,
|
||||
"Subject is too long or contains line breaks.",
|
||||
));
|
||||
}
|
||||
if mdn
|
||||
.text_body
|
||||
.as_ref()
|
||||
.is_some_and(|text_body| text_body.len() > MAX_TEXT_BODY_LEN)
|
||||
{
|
||||
return Err(MdnInvalid::new(
|
||||
MdnProperty::TextBody,
|
||||
"Text body is too long.",
|
||||
));
|
||||
}
|
||||
for (property, value) in [
|
||||
(MdnProperty::ReportingUa, &mdn.reporting_ua),
|
||||
(MdnProperty::FinalRecipient, &mdn.final_recipient),
|
||||
] {
|
||||
if value
|
||||
.as_deref()
|
||||
.is_some_and(|value| !is_valid_field_value(value))
|
||||
{
|
||||
return Err(MdnInvalid::new(property, "Invalid field value."));
|
||||
}
|
||||
}
|
||||
if let Some(fields) = &mdn.extension_fields {
|
||||
if fields.len() > MAX_EXTENSION_FIELDS {
|
||||
return Err(MdnInvalid::new(
|
||||
MdnProperty::ExtensionFields,
|
||||
"Too many extension fields.",
|
||||
));
|
||||
}
|
||||
for (name, value) in fields.iter() {
|
||||
if !is_valid_extension_name(name) || !is_valid_field_value(value) {
|
||||
return Err(MdnInvalid::new(
|
||||
MdnProperty::ExtensionFields,
|
||||
"Invalid extension field.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(disposition)
|
||||
}
|
||||
|
||||
pub fn final_recipient_address(value: &str) -> Option<String> {
|
||||
let (addr_type, address) = value.split_once(';')?;
|
||||
if addr_type.trim().eq_ignore_ascii_case("rfc822") {
|
||||
sanitize_email(address.trim())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl MdnMessage<'_> {
|
||||
pub fn build(&self) -> Option<Vec<u8>> {
|
||||
let mut report = String::with_capacity(256);
|
||||
self.write_report(&mut report);
|
||||
let (report_type, report_encoding) = if report.is_ascii() {
|
||||
("message/disposition-notification", "7bit")
|
||||
} else {
|
||||
("message/global-disposition-notification", "8bit")
|
||||
};
|
||||
|
||||
let mut parts = Vec::with_capacity(3);
|
||||
parts.push(MimePart::new(
|
||||
ContentType::new("text/plain"),
|
||||
BodyPart::Text(Cow::Borrowed(
|
||||
self.mdn.text_body.as_deref().unwrap_or_default(),
|
||||
)),
|
||||
));
|
||||
parts.push(
|
||||
MimePart::new(
|
||||
ContentType::new(report_type),
|
||||
BodyPart::Binary(Cow::Owned(report.into_bytes())),
|
||||
)
|
||||
.transfer_encoding(report_encoding),
|
||||
);
|
||||
if let Some(original) = self.original_message {
|
||||
let original_type = if original.utf8_headers {
|
||||
"message/global"
|
||||
} else {
|
||||
"message/rfc822"
|
||||
};
|
||||
let original_encoding = if original.raw.is_ascii() {
|
||||
"7bit"
|
||||
} else {
|
||||
"8bit"
|
||||
};
|
||||
parts.push(
|
||||
MimePart::new(
|
||||
ContentType::new(original_type),
|
||||
BodyPart::Binary(Cow::Borrowed(original.raw)),
|
||||
)
|
||||
.transfer_encoding(original_encoding),
|
||||
);
|
||||
}
|
||||
|
||||
let mut builder = MessageBuilder::new()
|
||||
.from(match self.from_name {
|
||||
Some(name) => Address::from((name, self.from_address)),
|
||||
None => Address::from(self.from_address),
|
||||
})
|
||||
.to(self.to.iter().map(String::as_str).collect::<Vec<_>>())
|
||||
.message_id(format!(
|
||||
"{}@{}",
|
||||
make_boundary("."),
|
||||
self.from_address.domain_part()
|
||||
))
|
||||
.subject(self.mdn.subject.as_deref().unwrap_or_default());
|
||||
if self.disposition.is_automatic() {
|
||||
builder = builder.header("Auto-Submitted", HeaderType::Text("auto-replied".into()));
|
||||
}
|
||||
builder
|
||||
.body(MimePart::new(
|
||||
ContentType::new("multipart/report")
|
||||
.attribute("report-type", "disposition-notification"),
|
||||
BodyPart::Multipart(parts),
|
||||
))
|
||||
.write_to_vec()
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn write_report(&self, out: &mut String) {
|
||||
let mdn = self.mdn;
|
||||
if let Some(value) = &mdn.reporting_ua {
|
||||
let _ = write!(out, "Reporting-UA: {value}\r\n");
|
||||
}
|
||||
if let Some(value) = &mdn.original_recipient {
|
||||
let _ = write!(out, "Original-Recipient: {value}\r\n");
|
||||
}
|
||||
if let Some(value) = &mdn.final_recipient {
|
||||
let _ = write!(out, "Final-Recipient: {value}\r\n");
|
||||
}
|
||||
if let Some(value) = &mdn.original_message_id {
|
||||
let _ = write!(out, "Original-Message-ID: {value}\r\n");
|
||||
}
|
||||
let _ = write!(
|
||||
out,
|
||||
"Disposition: {}/{}; {}\r\n",
|
||||
self.disposition.action_mode.as_str(),
|
||||
self.disposition.sending_mode.as_field(),
|
||||
self.disposition.disposition_type.as_str()
|
||||
);
|
||||
if let Some(fields) = &mdn.extension_fields {
|
||||
for (name, value) in fields.iter() {
|
||||
let _ = write!(out, "{name}: {value}\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_mdn(raw: &[u8]) -> Option<Mdn> {
|
||||
let message = MessageParser::new().parse(raw)?;
|
||||
let root = message.root_part();
|
||||
if !root.is_content_type("multipart", "report") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut mdn = Mdn {
|
||||
subject: message.subject().map(str::to_string),
|
||||
..Default::default()
|
||||
};
|
||||
let mut has_report = false;
|
||||
for part in root.children() {
|
||||
if has_report {
|
||||
mdn.include_original_message = true;
|
||||
break;
|
||||
} else if is_report_part(&part) {
|
||||
let fields = part.decoded();
|
||||
parse_report_fields(&String::from_utf8_lossy(&fields), &mut mdn);
|
||||
has_report = true;
|
||||
} else if mdn.text_body.is_none() && part.is_content_type("text", "plain") {
|
||||
mdn.text_body = part.text().map(Cow::into_owned);
|
||||
}
|
||||
}
|
||||
|
||||
(has_report && mdn.disposition.is_some()).then_some(mdn)
|
||||
}
|
||||
|
||||
fn is_report_part(part: &MessagePart<'_>) -> bool {
|
||||
part.is_content_type("message", "disposition-notification")
|
||||
|| part.is_content_type("message", "global-disposition-notification")
|
||||
}
|
||||
|
||||
fn parse_report_fields(data: &str, mdn: &mut Mdn) {
|
||||
let mut current: Option<(&str, String)> = None;
|
||||
let mut count = 0;
|
||||
for line in data.split('\n') {
|
||||
let line = line.strip_suffix('\r').unwrap_or(line);
|
||||
if line.starts_with([' ', '\t']) {
|
||||
if let Some((_, value)) = &mut current
|
||||
&& value.len() < MAX_FIELD_LEN
|
||||
{
|
||||
value.push(' ');
|
||||
value.push_str(line.trim());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((name, value)) = current.take() {
|
||||
apply_report_field(mdn, name, value);
|
||||
}
|
||||
if let Some((name, value)) = line.split_once(':') {
|
||||
count += 1;
|
||||
if count > MAX_REPORT_FIELDS {
|
||||
return;
|
||||
}
|
||||
current = Some((name.trim(), value.trim().to_string()));
|
||||
}
|
||||
}
|
||||
if let Some((name, value)) = current {
|
||||
apply_report_field(mdn, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ReportField {
|
||||
ReportingUa,
|
||||
MdnGateway,
|
||||
OriginalRecipient,
|
||||
FinalRecipient,
|
||||
OriginalMessageId,
|
||||
Disposition,
|
||||
Error,
|
||||
Ignore,
|
||||
}
|
||||
|
||||
fn report_field(name: &str) -> Option<ReportField> {
|
||||
hashify::map_ignore_case!(name.as_bytes(), ReportField,
|
||||
"Reporting-UA" => ReportField::ReportingUa,
|
||||
"MDN-Gateway" => ReportField::MdnGateway,
|
||||
"Original-Recipient" => ReportField::OriginalRecipient,
|
||||
"Final-Recipient" => ReportField::FinalRecipient,
|
||||
"Original-Message-ID" => ReportField::OriginalMessageId,
|
||||
"Disposition" => ReportField::Disposition,
|
||||
"Error" => ReportField::Error,
|
||||
"Failure" => ReportField::Ignore,
|
||||
"Warning" => ReportField::Ignore,
|
||||
)
|
||||
.copied()
|
||||
}
|
||||
|
||||
fn apply_report_field(mdn: &mut Mdn, name: &str, value: String) {
|
||||
match report_field(name) {
|
||||
Some(ReportField::ReportingUa) => mdn.reporting_ua = Some(value),
|
||||
Some(ReportField::MdnGateway) => mdn.mdn_gateway = Some(value),
|
||||
Some(ReportField::OriginalRecipient) => mdn.original_recipient = Some(value),
|
||||
Some(ReportField::FinalRecipient) => mdn.final_recipient = Some(value),
|
||||
Some(ReportField::OriginalMessageId) => mdn.original_message_id = Some(value),
|
||||
Some(ReportField::Disposition) => mdn.disposition = parse_disposition(&value),
|
||||
Some(ReportField::Error) => {
|
||||
let errors = mdn.error.get_or_insert_with(Vec::new);
|
||||
if errors.len() < MAX_ERRORS {
|
||||
errors.push(value);
|
||||
}
|
||||
}
|
||||
Some(ReportField::Ignore) => {}
|
||||
None => {
|
||||
if is_valid_extension_name(name) {
|
||||
let fields = mdn.extension_fields.get_or_insert_with(VecMap::new);
|
||||
if fields.len() < MAX_EXTENSION_FIELDS {
|
||||
fields.append(name.to_string(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_disposition(value: &str) -> Option<Disposition> {
|
||||
let value = strip_comments(value);
|
||||
let (modes, disposition_type) = value.split_once(';')?;
|
||||
let (action_mode, sending_mode) = modes.split_once('/')?;
|
||||
let disposition_type = disposition_type
|
||||
.split_once('/')
|
||||
.map_or(disposition_type, |(disposition_type, _)| disposition_type);
|
||||
Some(Disposition {
|
||||
action_mode: ActionMode::parse(action_mode.trim())?,
|
||||
sending_mode: SendingMode::parse(sending_mode.trim())?,
|
||||
disposition_type: DispositionType::parse(disposition_type.trim())?,
|
||||
})
|
||||
}
|
||||
|
||||
fn single_return_path(headers: &HeaderList<'_>, raw_headers: &[u8]) -> Option<String> {
|
||||
let mut return_paths = headers.all(HeaderId::RETURN_PATH);
|
||||
let (Some(header), None) = (return_paths.next(), return_paths.next()) else {
|
||||
return None;
|
||||
};
|
||||
let parsed = HeaderForm::Addresses.parse(header.raw_value(raw_headers)?);
|
||||
parsed
|
||||
.value()
|
||||
.as_address()
|
||||
.and_then(|list| list.mailboxes().next())
|
||||
.and_then(|mailbox| mailbox.address())
|
||||
.and_then(sanitize_email)
|
||||
}
|
||||
|
||||
fn strip_comments(value: &str) -> Cow<'_, str> {
|
||||
if !value.contains('(') {
|
||||
return Cow::Borrowed(value);
|
||||
}
|
||||
let mut result = String::with_capacity(value.len());
|
||||
let mut depth = 0usize;
|
||||
let mut escaped = false;
|
||||
for ch in value.chars() {
|
||||
if depth > 0 {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if ch == '\\' {
|
||||
escaped = true;
|
||||
} else if ch == '(' {
|
||||
depth += 1;
|
||||
} else if ch == ')' {
|
||||
depth -= 1;
|
||||
}
|
||||
} else if ch == '(' {
|
||||
depth = 1;
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
}
|
||||
Cow::Owned(result)
|
||||
}
|
||||
|
||||
fn default_subject(disposition_type: DispositionType, subject: Option<&str>) -> String {
|
||||
let prefix = match disposition_type {
|
||||
DispositionType::Displayed => "Read",
|
||||
DispositionType::Deleted => "Not read",
|
||||
DispositionType::Dispatched => "Dispatched",
|
||||
DispositionType::Processed => "Processed",
|
||||
};
|
||||
match subject {
|
||||
Some(subject) => format!("{prefix}: {subject}"),
|
||||
None => prefix.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn default_text(disposition_type: DispositionType, subject: Option<&str>) -> String {
|
||||
let outcome = match disposition_type {
|
||||
DispositionType::Displayed => {
|
||||
"was displayed to the recipient. This is no guarantee that the message has been read or understood."
|
||||
}
|
||||
DispositionType::Deleted => "was deleted. The recipient may or may not have seen it.",
|
||||
DispositionType::Dispatched => {
|
||||
"was dispatched by the recipient without necessarily being displayed."
|
||||
}
|
||||
DispositionType::Processed => "was processed without being displayed to the recipient.",
|
||||
};
|
||||
match subject {
|
||||
Some(subject) => format!("Your message \"{subject}\" {outcome}\r\n"),
|
||||
None => format!("Your message {outcome}\r\n"),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_valid_field_value(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value.len() <= MAX_FIELD_LEN
|
||||
&& !value.chars().any(|ch| ch.is_control() && ch != '\t')
|
||||
}
|
||||
|
||||
fn is_valid_extension_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& name.len() <= MAX_FIELD_NAME_LEN
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|ch| (33..=126).contains(&ch) && ch != b':')
|
||||
&& report_field(name).is_none()
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/email/src/message/mdn/tests.rs"]
|
||||
mod tests;
|
||||
|
|
@ -13,7 +13,9 @@ pub mod index;
|
|||
pub mod ingest;
|
||||
pub mod ingest_metadata;
|
||||
pub mod jmap;
|
||||
pub mod mdn;
|
||||
pub mod messagedata;
|
||||
pub mod metadata;
|
||||
pub mod query;
|
||||
pub mod sortkeys;
|
||||
pub mod thread;
|
||||
|
|
|
|||
649
crates/email/src/message/query/filter.rs
Normal file
649
crates/email/src/message/query/filter.rs
Normal file
|
|
@ -0,0 +1,649 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{
|
||||
MailCondition, MailFilter, MailTextField, ThreadKeywordMatch,
|
||||
text::{push_text, strip_subject_prefix},
|
||||
};
|
||||
use crate::cache::email::{MessageAccess, MessageCacheAccess, SearchOperator, thread_keywords};
|
||||
use common::{MessageStoreCache, cache::email::MessageRef};
|
||||
use mail_parser::HeaderName;
|
||||
use nlp::language::Language;
|
||||
use std::ops::RangeInclusive;
|
||||
use store::{
|
||||
roaring::RoaringBitmap,
|
||||
search::{EmailSearchField, KeyValueMatch, SearchFilter},
|
||||
};
|
||||
use types::keyword::{HASATTACHMENT, HASNOATTACHMENT, Keyword};
|
||||
|
||||
pub struct RowFilter {
|
||||
pub access: MessageAccess,
|
||||
mailboxes: Mailboxes,
|
||||
not_in_mailboxes: Option<Box<[u32]>>,
|
||||
thread_id: Option<u32>,
|
||||
all_keywords: u32,
|
||||
no_keywords: u32,
|
||||
received: Option<RangeInclusive<i64>>,
|
||||
sent: Option<RangeInclusive<i64>>,
|
||||
size: Option<RangeInclusive<i64>>,
|
||||
pub residual: Option<RoaringBitmap>,
|
||||
}
|
||||
|
||||
enum Mailboxes {
|
||||
Any,
|
||||
One(u32),
|
||||
All(Vec<u32>),
|
||||
}
|
||||
|
||||
pub struct QueryFilter {
|
||||
pub row: RowFilter,
|
||||
pub residual: Vec<SearchFilter>,
|
||||
pub text: Vec<SearchFilter>,
|
||||
visible: Option<RoaringBitmap>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Absorbed {
|
||||
Yes,
|
||||
Contradiction,
|
||||
}
|
||||
|
||||
impl RowFilter {
|
||||
pub fn new(access: MessageAccess) -> Self {
|
||||
RowFilter {
|
||||
access,
|
||||
mailboxes: Mailboxes::Any,
|
||||
not_in_mailboxes: None,
|
||||
thread_id: None,
|
||||
all_keywords: 0,
|
||||
no_keywords: 0,
|
||||
received: None,
|
||||
sent: None,
|
||||
size: None,
|
||||
residual: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn matches(&self, message: MessageRef<'_>) -> bool {
|
||||
(match &self.mailboxes {
|
||||
Mailboxes::Any => true,
|
||||
Mailboxes::One(mailbox_id) => message.has_mailbox_id(*mailbox_id),
|
||||
Mailboxes::All(mailbox_ids) => mailbox_ids
|
||||
.iter()
|
||||
.all(|mailbox_id| message.has_mailbox_id(*mailbox_id)),
|
||||
}) && (self.all_keywords | self.no_keywords == 0 || {
|
||||
let keywords = message.keywords();
|
||||
keywords & self.all_keywords == self.all_keywords && keywords & self.no_keywords == 0
|
||||
}) && self
|
||||
.thread_id
|
||||
.is_none_or(|thread_id| message.thread_id() == thread_id)
|
||||
&& self
|
||||
.received
|
||||
.as_ref()
|
||||
.is_none_or(|range| range.contains(&(message.received_at() as i64)))
|
||||
&& self
|
||||
.sent
|
||||
.as_ref()
|
||||
.is_none_or(|range| range.contains(&message.sent_at_absolute()))
|
||||
&& self
|
||||
.size
|
||||
.as_ref()
|
||||
.is_none_or(|range| range.contains(&i64::from(message.size())))
|
||||
&& self.not_in_mailboxes.as_deref().is_none_or(|mailboxes| {
|
||||
message
|
||||
.mailboxes()
|
||||
.iter()
|
||||
.any(|uid| mailboxes.binary_search(&uid.mailbox_id).is_err())
|
||||
})
|
||||
&& self
|
||||
.residual
|
||||
.as_ref()
|
||||
.is_none_or(|documents| documents.contains(message.document_id()))
|
||||
&& self.access.allows(message)
|
||||
}
|
||||
|
||||
fn absorb(&mut self, condition: MailCondition) -> Result<Absorbed, MailCondition> {
|
||||
match condition {
|
||||
MailCondition::InMailbox(mailbox_id) => {
|
||||
match &mut self.mailboxes {
|
||||
Mailboxes::Any => self.mailboxes = Mailboxes::One(mailbox_id),
|
||||
Mailboxes::One(current) if *current == mailbox_id => (),
|
||||
Mailboxes::One(current) => {
|
||||
self.mailboxes = Mailboxes::All(vec![*current, mailbox_id]);
|
||||
}
|
||||
Mailboxes::All(current) => current.push(mailbox_id),
|
||||
}
|
||||
Ok(Absorbed::Yes)
|
||||
}
|
||||
MailCondition::InThread(thread_id) => Ok(narrow_id(&mut self.thread_id, thread_id)),
|
||||
MailCondition::InMailboxOtherThan(mut mailboxes) if self.not_in_mailboxes.is_none() => {
|
||||
mailboxes.sort_unstable();
|
||||
self.not_in_mailboxes = Some(mailboxes);
|
||||
Ok(Absorbed::Yes)
|
||||
}
|
||||
MailCondition::HasKeyword(keyword) => match keyword.id() {
|
||||
Ok(id) => {
|
||||
self.all_keywords |= 1 << id;
|
||||
Ok(Absorbed::Yes)
|
||||
}
|
||||
Err(_) => Err(MailCondition::HasKeyword(keyword)),
|
||||
},
|
||||
MailCondition::NotKeyword(keyword) => match keyword.id() {
|
||||
Ok(id) => {
|
||||
self.no_keywords |= 1 << id;
|
||||
Ok(Absorbed::Yes)
|
||||
}
|
||||
Err(_) => Err(MailCondition::NotKeyword(keyword)),
|
||||
},
|
||||
MailCondition::HasAttachment(has_attachment) => {
|
||||
self.all_keywords |= if has_attachment {
|
||||
1 << HASATTACHMENT
|
||||
} else {
|
||||
1 << HASNOATTACHMENT
|
||||
};
|
||||
Ok(Absorbed::Yes)
|
||||
}
|
||||
MailCondition::ReceivedBefore(timestamp) => {
|
||||
narrow_range(&mut self.received, i64::MIN, timestamp.saturating_sub(1))
|
||||
}
|
||||
MailCondition::ReceivedAfter(timestamp) => {
|
||||
narrow_range(&mut self.received, timestamp, i64::MAX)
|
||||
}
|
||||
MailCondition::SentBefore(timestamp) => {
|
||||
narrow_range(&mut self.sent, i64::MIN, timestamp.saturating_sub(1))
|
||||
}
|
||||
MailCondition::SentAfter(timestamp) => {
|
||||
narrow_range(&mut self.sent, timestamp.saturating_add(1), i64::MAX)
|
||||
}
|
||||
MailCondition::MinSize(size) => narrow_range(&mut self.size, i64::from(size), i64::MAX),
|
||||
MailCondition::MaxSize(size) => {
|
||||
narrow_range(&mut self.size, i64::MIN, i64::from(size) - 1)
|
||||
}
|
||||
condition => Err(condition),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn narrow_id(current: &mut Option<u32>, id: u32) -> Absorbed {
|
||||
match current {
|
||||
Some(current) if *current != id => Absorbed::Contradiction,
|
||||
_ => {
|
||||
*current = Some(id);
|
||||
Absorbed::Yes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn narrow_range(
|
||||
current: &mut Option<RangeInclusive<i64>>,
|
||||
from: i64,
|
||||
to: i64,
|
||||
) -> Result<Absorbed, MailCondition> {
|
||||
let range = match current.take() {
|
||||
Some(range) => (*range.start()).max(from)..=(*range.end()).min(to),
|
||||
None => from..=to,
|
||||
};
|
||||
let absorbed = if range.is_empty() {
|
||||
Absorbed::Contradiction
|
||||
} else {
|
||||
Absorbed::Yes
|
||||
};
|
||||
*current = Some(range);
|
||||
Ok(absorbed)
|
||||
}
|
||||
|
||||
impl QueryFilter {
|
||||
pub fn parse(
|
||||
filters: Vec<MailFilter>,
|
||||
cache: &MessageStoreCache,
|
||||
access: MessageAccess,
|
||||
default_language: Language,
|
||||
) -> Option<Self> {
|
||||
let mut row = RowFilter::new(access);
|
||||
let mut residual = Vec::new();
|
||||
let mut text = Vec::new();
|
||||
let mut subtrees = 0usize;
|
||||
let mut is_empty = false;
|
||||
let mut visible = None;
|
||||
let verbatim = has_empty_group(&filters);
|
||||
|
||||
for filter in filters {
|
||||
let top_level = !verbatim && subtrees == 0;
|
||||
match filter {
|
||||
MailFilter::Condition(condition) if top_level => match row.absorb(condition) {
|
||||
Ok(Absorbed::Yes) => (),
|
||||
Ok(Absorbed::Contradiction) => is_empty = true,
|
||||
Err(condition) if is_text(&condition) => push_condition(
|
||||
&mut text,
|
||||
condition,
|
||||
cache,
|
||||
&row.access,
|
||||
&mut visible,
|
||||
default_language,
|
||||
),
|
||||
Err(condition) => push_condition(
|
||||
&mut residual,
|
||||
condition,
|
||||
cache,
|
||||
&row.access,
|
||||
&mut visible,
|
||||
default_language,
|
||||
),
|
||||
},
|
||||
MailFilter::Condition(condition) => push_condition(
|
||||
&mut residual,
|
||||
condition,
|
||||
cache,
|
||||
&row.access,
|
||||
&mut visible,
|
||||
default_language,
|
||||
),
|
||||
MailFilter::And if top_level => (),
|
||||
MailFilter::And => {
|
||||
subtrees += 1;
|
||||
residual.push(SearchFilter::And);
|
||||
}
|
||||
MailFilter::Or => {
|
||||
subtrees += 1;
|
||||
residual.push(SearchFilter::Or);
|
||||
}
|
||||
MailFilter::Not => {
|
||||
subtrees += 1;
|
||||
residual.push(SearchFilter::Not);
|
||||
}
|
||||
MailFilter::Close if subtrees > 0 || verbatim => {
|
||||
subtrees = subtrees.saturating_sub(1);
|
||||
residual.push(SearchFilter::End);
|
||||
}
|
||||
MailFilter::Close => (),
|
||||
}
|
||||
}
|
||||
|
||||
if let Mailboxes::All(mailbox_ids) = &mut row.mailboxes {
|
||||
mailbox_ids.sort_unstable();
|
||||
mailbox_ids.dedup();
|
||||
}
|
||||
|
||||
(!is_empty).then_some(QueryFilter {
|
||||
row,
|
||||
residual,
|
||||
text,
|
||||
visible,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn visible(&mut self, cache: &MessageStoreCache) -> Option<&RoaringBitmap> {
|
||||
visible_ids(cache, &self.row.access, &mut self.visible)
|
||||
}
|
||||
|
||||
pub fn readable(&mut self, cache: &MessageStoreCache) -> RoaringBitmap {
|
||||
match &self.row.access {
|
||||
MessageAccess::All => cache.email_document_ids(),
|
||||
access => self
|
||||
.visible
|
||||
.take()
|
||||
.unwrap_or_else(|| readable_ids(cache, access)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_row(self) -> RowFilter {
|
||||
let QueryFilter {
|
||||
mut row, visible, ..
|
||||
} = self;
|
||||
if matches!(row.access, MessageAccess::Mailboxes(_)) {
|
||||
row.residual = row.residual.or(visible);
|
||||
if row.residual.is_some() {
|
||||
row.access = MessageAccess::All;
|
||||
}
|
||||
}
|
||||
row
|
||||
}
|
||||
|
||||
pub fn residual_filters(&mut self) -> Vec<SearchFilter> {
|
||||
let mut filters = std::mem::take(&mut self.residual);
|
||||
filters.append(&mut self.text);
|
||||
filters
|
||||
}
|
||||
|
||||
pub fn take_text(&mut self) -> Option<Vec<SearchFilter>> {
|
||||
if self.text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut external = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
let mut start = 0;
|
||||
let mut locality = Locality::None;
|
||||
for (end, filter) in self.residual.iter().enumerate() {
|
||||
locality = locality.with(filter);
|
||||
match filter {
|
||||
SearchFilter::And | SearchFilter::Or | SearchFilter::Not => depth += 1,
|
||||
SearchFilter::End => depth = depth.saturating_sub(1),
|
||||
_ => (),
|
||||
}
|
||||
if depth == 0 {
|
||||
match locality {
|
||||
Locality::Mixed => return None,
|
||||
Locality::External => external.push(start..end + 1),
|
||||
Locality::None | Locality::Local => (),
|
||||
}
|
||||
start = end + 1;
|
||||
locality = Locality::None;
|
||||
}
|
||||
}
|
||||
|
||||
let mut text = std::mem::take(&mut self.text);
|
||||
if !external.is_empty() {
|
||||
let mut external = external.into_iter().peekable();
|
||||
let mut local = Vec::with_capacity(self.residual.len());
|
||||
for (pos, filter) in std::mem::take(&mut self.residual).into_iter().enumerate() {
|
||||
while external.next_if(|range| range.end <= pos).is_some() {}
|
||||
if external.peek().is_some_and(|range| range.contains(&pos)) {
|
||||
text.push(filter);
|
||||
} else {
|
||||
local.push(filter);
|
||||
}
|
||||
}
|
||||
self.residual = local;
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Locality {
|
||||
None,
|
||||
Local,
|
||||
External,
|
||||
Mixed,
|
||||
}
|
||||
|
||||
impl Locality {
|
||||
fn with(self, filter: &SearchFilter) -> Self {
|
||||
let other = match filter {
|
||||
SearchFilter::DocumentSet(_) => Locality::Local,
|
||||
SearchFilter::Text { .. }
|
||||
| SearchFilter::KeyValue { .. }
|
||||
| SearchFilter::Integer { .. } => Locality::External,
|
||||
SearchFilter::And | SearchFilter::Or | SearchFilter::Not | SearchFilter::End => {
|
||||
return self;
|
||||
}
|
||||
};
|
||||
match self {
|
||||
Locality::None => other,
|
||||
current if current == other => current,
|
||||
_ => Locality::Mixed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn readable_ids(cache: &MessageStoreCache, access: &MessageAccess) -> RoaringBitmap {
|
||||
cache
|
||||
.emails
|
||||
.iter()
|
||||
.filter(|message| access.allows(*message))
|
||||
.map(|message| message.document_id())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn visible_ids<'x>(
|
||||
cache: &MessageStoreCache,
|
||||
access: &MessageAccess,
|
||||
visible: &'x mut Option<RoaringBitmap>,
|
||||
) -> Option<&'x RoaringBitmap> {
|
||||
match access {
|
||||
MessageAccess::All => None,
|
||||
access => Some(visible.get_or_insert_with(|| readable_ids(cache, access))),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_empty_group(filters: &[MailFilter]) -> bool {
|
||||
let mut leaves: Vec<usize> = Vec::new();
|
||||
for filter in filters {
|
||||
match filter {
|
||||
MailFilter::And | MailFilter::Or | MailFilter::Not => leaves.push(0),
|
||||
MailFilter::Close => match leaves.pop() {
|
||||
Some(0) => return true,
|
||||
Some(count) => {
|
||||
if let Some(parent) = leaves.last_mut() {
|
||||
*parent += count;
|
||||
}
|
||||
}
|
||||
None => (),
|
||||
},
|
||||
MailFilter::Condition(MailCondition::Header(name, _))
|
||||
if HeaderName::parse(name.as_str()).is_none() => {}
|
||||
MailFilter::Condition(_) => {
|
||||
if let Some(count) = leaves.last_mut() {
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
leaves.contains(&0)
|
||||
}
|
||||
|
||||
fn is_text(condition: &MailCondition) -> bool {
|
||||
matches!(
|
||||
condition,
|
||||
MailCondition::Text(..) | MailCondition::Header(..)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn push_condition(
|
||||
filters: &mut Vec<SearchFilter>,
|
||||
condition: MailCondition,
|
||||
cache: &MessageStoreCache,
|
||||
access: &MessageAccess,
|
||||
visible: &mut Option<RoaringBitmap>,
|
||||
default_language: Language,
|
||||
) {
|
||||
match condition {
|
||||
MailCondition::Text(MailTextField::Any, text) => {
|
||||
let (text, language) = Language::detect(text, default_language);
|
||||
push_text(filters, &strip_subject_prefix(&text), language);
|
||||
}
|
||||
MailCondition::Text(MailTextField::From, text) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::From,
|
||||
text,
|
||||
Language::None,
|
||||
)),
|
||||
MailCondition::Text(MailTextField::To, text) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::To,
|
||||
text,
|
||||
Language::None,
|
||||
)),
|
||||
MailCondition::Text(MailTextField::Cc, text) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::Cc,
|
||||
text,
|
||||
Language::None,
|
||||
)),
|
||||
MailCondition::Text(MailTextField::Bcc, text) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::Bcc,
|
||||
text,
|
||||
Language::None,
|
||||
)),
|
||||
MailCondition::Text(MailTextField::Subject, text) => {
|
||||
filters.push(SearchFilter::has_text_detect(
|
||||
EmailSearchField::Subject,
|
||||
strip_subject_prefix(&text),
|
||||
default_language,
|
||||
))
|
||||
}
|
||||
MailCondition::Text(MailTextField::Body, text) => filters.push(
|
||||
SearchFilter::has_text_detect(EmailSearchField::Body, text, default_language),
|
||||
),
|
||||
MailCondition::Header(header_name, value) => {
|
||||
match (HeaderName::parse(header_name), value) {
|
||||
(Some(HeaderName::Subject), Some(value)) => {
|
||||
filters.push(SearchFilter::has_text_detect(
|
||||
EmailSearchField::Subject,
|
||||
strip_subject_prefix(&value),
|
||||
default_language,
|
||||
))
|
||||
}
|
||||
(Some(HeaderName::From), Some(value)) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::From,
|
||||
value,
|
||||
Language::None,
|
||||
)),
|
||||
(Some(HeaderName::To), Some(value)) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::To,
|
||||
value,
|
||||
Language::None,
|
||||
)),
|
||||
(Some(HeaderName::Cc), Some(value)) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::Cc,
|
||||
value,
|
||||
Language::None,
|
||||
)),
|
||||
(Some(HeaderName::Bcc), Some(value)) => filters.push(SearchFilter::has_text(
|
||||
EmailSearchField::Bcc,
|
||||
value,
|
||||
Language::None,
|
||||
)),
|
||||
(Some(header_name), value) => {
|
||||
let op = match value {
|
||||
Some(value)
|
||||
if matches!(
|
||||
header_name,
|
||||
HeaderName::MessageId
|
||||
| HeaderName::InReplyTo
|
||||
| HeaderName::References
|
||||
| HeaderName::ResentMessageId
|
||||
) =>
|
||||
{
|
||||
KeyValueMatch::Equals(value)
|
||||
}
|
||||
Some(value) => KeyValueMatch::Contains(value),
|
||||
None => KeyValueMatch::Exists,
|
||||
};
|
||||
filters.push(SearchFilter::KeyValue {
|
||||
field: EmailSearchField::Headers.into(),
|
||||
key: header_name.as_str().to_lowercase(),
|
||||
op,
|
||||
});
|
||||
}
|
||||
(None, _) => {}
|
||||
}
|
||||
}
|
||||
MailCondition::InMailbox(mailbox_id) => filters.push(SearchFilter::is_in_set(
|
||||
RoaringBitmap::from_iter(cache.in_mailbox(mailbox_id).map(|item| item.document_id())),
|
||||
)),
|
||||
MailCondition::InMailboxOtherThan(mut mailboxes) => {
|
||||
mailboxes.sort_unstable();
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache.emails.iter().filter_map(|item| {
|
||||
if item
|
||||
.mailboxes()
|
||||
.iter()
|
||||
.any(|mb| mailboxes.binary_search(&mb.mailbox_id).is_err())
|
||||
{
|
||||
Some(item.document_id())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}),
|
||||
)));
|
||||
}
|
||||
MailCondition::ReceivedBefore(timestamp) => {
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache
|
||||
.received(timestamp, SearchOperator::LowerThan)
|
||||
.map(|m| m.document_id()),
|
||||
)))
|
||||
}
|
||||
MailCondition::ReceivedAfter(timestamp) => {
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache
|
||||
.received(timestamp, SearchOperator::GreaterEqualThan)
|
||||
.map(|m| m.document_id()),
|
||||
)))
|
||||
}
|
||||
MailCondition::MinSize(size) => {
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache
|
||||
.size(size, SearchOperator::GreaterEqualThan)
|
||||
.map(|m| m.document_id()),
|
||||
)))
|
||||
}
|
||||
MailCondition::MaxSize(size) => {
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache
|
||||
.size(size, SearchOperator::LowerThan)
|
||||
.map(|m| m.document_id()),
|
||||
)))
|
||||
}
|
||||
MailCondition::ThreadKeyword(keyword, ThreadKeywordMatch::All) => {
|
||||
filters.push(SearchFilter::is_in_set(thread_keywords(
|
||||
cache,
|
||||
&keyword,
|
||||
true,
|
||||
None,
|
||||
visible_ids(cache, access, visible),
|
||||
)))
|
||||
}
|
||||
MailCondition::ThreadKeyword(keyword, ThreadKeywordMatch::Some) => {
|
||||
filters.push(SearchFilter::is_in_set(thread_keywords(
|
||||
cache,
|
||||
&keyword,
|
||||
false,
|
||||
None,
|
||||
visible_ids(cache, access, visible),
|
||||
)))
|
||||
}
|
||||
MailCondition::ThreadKeyword(keyword, ThreadKeywordMatch::None) => {
|
||||
filters.push(SearchFilter::Not);
|
||||
filters.push(SearchFilter::is_in_set(thread_keywords(
|
||||
cache,
|
||||
&keyword,
|
||||
false,
|
||||
None,
|
||||
visible_ids(cache, access, visible),
|
||||
)));
|
||||
filters.push(SearchFilter::End);
|
||||
}
|
||||
MailCondition::HasKeyword(keyword) => filters.push(SearchFilter::is_in_set(
|
||||
RoaringBitmap::from_iter(cache.with_keyword(&keyword).map(|item| item.document_id())),
|
||||
)),
|
||||
MailCondition::NotKeyword(keyword) => {
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache
|
||||
.without_keyword(&keyword)
|
||||
.map(|item| item.document_id()),
|
||||
)))
|
||||
}
|
||||
MailCondition::HasAttachment(has_attach) => {
|
||||
let keyword = if has_attach {
|
||||
Keyword::HasAttachment
|
||||
} else {
|
||||
Keyword::HasNoAttachment
|
||||
};
|
||||
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache.with_keyword(&keyword).map(|item| item.document_id()),
|
||||
)));
|
||||
}
|
||||
MailCondition::DocumentSet(set) => filters.push(SearchFilter::is_in_set(set)),
|
||||
MailCondition::SentBefore(timestamp) => {
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache
|
||||
.sent(timestamp, SearchOperator::LowerThan)
|
||||
.map(|m| m.document_id()),
|
||||
)))
|
||||
}
|
||||
MailCondition::SentAfter(timestamp) => {
|
||||
filters.push(SearchFilter::is_in_set(RoaringBitmap::from_iter(
|
||||
cache
|
||||
.sent(timestamp, SearchOperator::GreaterThan)
|
||||
.map(|m| m.document_id()),
|
||||
)))
|
||||
}
|
||||
MailCondition::InThread(thread_id) => filters.push(SearchFilter::is_in_set(
|
||||
RoaringBitmap::from_iter(cache.in_thread(thread_id).map(|item| item.document_id())),
|
||||
)),
|
||||
}
|
||||
}
|
||||
59
crates/email/src/message/query/mod.rs
Normal file
59
crates/email/src/message/query/mod.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
mod filter;
|
||||
mod text;
|
||||
|
||||
pub use filter::{QueryFilter, RowFilter, push_condition};
|
||||
use store::roaring::RoaringBitmap;
|
||||
use types::keyword::Keyword;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum MailFilter {
|
||||
Condition(MailCondition),
|
||||
And,
|
||||
Or,
|
||||
Not,
|
||||
Close,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum MailCondition {
|
||||
InMailbox(u32),
|
||||
InMailboxOtherThan(Box<[u32]>),
|
||||
InThread(u32),
|
||||
HasKeyword(Keyword),
|
||||
NotKeyword(Keyword),
|
||||
HasAttachment(bool),
|
||||
ReceivedBefore(i64),
|
||||
ReceivedAfter(i64),
|
||||
SentBefore(i64),
|
||||
SentAfter(i64),
|
||||
MinSize(u32),
|
||||
MaxSize(u32),
|
||||
Text(MailTextField, String),
|
||||
Header(String, Option<String>),
|
||||
ThreadKeyword(Keyword, ThreadKeywordMatch),
|
||||
DocumentSet(RoaringBitmap),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MailTextField {
|
||||
Any,
|
||||
From,
|
||||
To,
|
||||
Cc,
|
||||
Bcc,
|
||||
Subject,
|
||||
Body,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ThreadKeywordMatch {
|
||||
All,
|
||||
Some,
|
||||
None,
|
||||
}
|
||||
|
|
@ -4,8 +4,8 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use email::message::index::subject::{search_subject, search_subject_query};
|
||||
use nlp::language::Language;
|
||||
use crate::message::index::subject::{search_subject, search_subject_query};
|
||||
use nlp::{language::Language, tokenizers::word::has_alnum_run};
|
||||
use std::borrow::Cow;
|
||||
use store::search::{EmailSearchField, SearchFilter};
|
||||
|
||||
|
|
@ -35,19 +35,20 @@ pub(super) fn strip_subject_prefix(text: &str) -> Cow<'_, str> {
|
|||
}
|
||||
|
||||
pub(super) fn push_text(filters: &mut Vec<SearchFilter>, text: &str, language: Language) {
|
||||
let mut tokens = TextTokens { rest: text };
|
||||
let mut tokens = TextTokens { rest: text }.filter(|token| has_alnum_run(token));
|
||||
let Some(first) = tokens.next() else {
|
||||
push_text_fields(filters, text, language);
|
||||
return;
|
||||
};
|
||||
if tokens.remainder().is_empty() {
|
||||
let Some(second) = tokens.next() else {
|
||||
push_text_fields(filters, first, language);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
filters.push(SearchFilter::And);
|
||||
push_text_fields(filters, first, language);
|
||||
for token in tokens.take(MAX_TEXT_TOKENS - 1) {
|
||||
push_text_fields(filters, second, language);
|
||||
for token in tokens.take(MAX_TEXT_TOKENS - 2) {
|
||||
push_text_fields(filters, token, language);
|
||||
}
|
||||
filters.push(SearchFilter::End);
|
||||
|
|
@ -71,12 +72,6 @@ struct TextTokens<'x> {
|
|||
rest: &'x str,
|
||||
}
|
||||
|
||||
impl<'x> TextTokens<'x> {
|
||||
fn remainder(&self) -> &'x str {
|
||||
self.rest.trim()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'x> Iterator for TextTokens<'x> {
|
||||
type Item = &'x str;
|
||||
|
||||
|
|
@ -105,5 +100,5 @@ fn split_phrase(text: &str, quote: char) -> Option<(&str, &str)> {
|
|||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../../stalwart-tests/unit/jmap/src/email/query/text/tests.rs"]
|
||||
#[path = "../../../../../../stalwart-tests/unit/email/src/message/query/text/tests.rs"]
|
||||
mod tests;
|
||||
|
|
@ -223,7 +223,7 @@ impl EmailSortKeys for Server {
|
|||
|
||||
impl MessageSortField {
|
||||
#[inline(always)]
|
||||
fn index(&self) -> usize {
|
||||
pub fn index(&self) -> usize {
|
||||
match self {
|
||||
MessageSortField::From => 0,
|
||||
MessageSortField::To => 1,
|
||||
|
|
|
|||
189
crates/email/src/sieve/addrbook.rs
Normal file
189
crates/email/src/sieve/addrbook.rs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use common::{GroupwareResources, Server};
|
||||
use groupware::cache::GroupwareCache;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use std::sync::Arc;
|
||||
use store::{ahash::AHashMap, roaring::RoaringBitmap};
|
||||
use trc::AddContext;
|
||||
use types::{collection::Collection, collection::SyncCollection, field::ContactField};
|
||||
|
||||
const ADDRBOOK_PREFIXES: [&str; 2] = [":addrbook:", "urn:ietf:params:sieve:addrbook:"];
|
||||
const DEFAULT_ADDRBOOK: &str = "default";
|
||||
pub(super) const MAX_LIST_LOOKUPS: usize = 64;
|
||||
const MAX_DELIVERY_LOOKUPS: usize = 256;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) enum AddressBookList {
|
||||
Default,
|
||||
Named(Box<str>),
|
||||
}
|
||||
|
||||
impl AddressBookList {
|
||||
pub(super) fn parse(list: &str) -> Option<Self> {
|
||||
let name = ADDRBOOK_PREFIXES.iter().find_map(|prefix| {
|
||||
let (head, name) = list.split_at_checked(prefix.len())?;
|
||||
head.eq_ignore_ascii_case(prefix).then_some(name)
|
||||
})?;
|
||||
let name = percent_decode_str(name).decode_utf8().ok()?;
|
||||
match name.as_ref() {
|
||||
"" => None,
|
||||
name if name.eq_ignore_ascii_case(DEFAULT_ADDRBOOK) => Some(AddressBookList::Default),
|
||||
name => Some(AddressBookList::Named(name.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn name_slug(name: &str) -> String {
|
||||
let mut slug = String::with_capacity(name.len());
|
||||
let mut separator = false;
|
||||
for ch in name.chars() {
|
||||
if ch.is_alphanumeric() {
|
||||
if separator && !slug.is_empty() {
|
||||
slug.push('-');
|
||||
}
|
||||
separator = false;
|
||||
slug.extend(ch.to_lowercase());
|
||||
} else if !matches!(ch, '\'' | '\u{2019}' | '`') {
|
||||
separator = true;
|
||||
}
|
||||
}
|
||||
slug
|
||||
}
|
||||
|
||||
pub(super) struct AddressBooks {
|
||||
account_id: u32,
|
||||
resources: Option<Arc<GroupwareResources>>,
|
||||
card_ids: AHashMap<String, RoaringBitmap>,
|
||||
lookups_left: usize,
|
||||
}
|
||||
|
||||
impl AddressBooks {
|
||||
pub(super) fn new(account_id: u32) -> Self {
|
||||
AddressBooks {
|
||||
account_id,
|
||||
resources: None,
|
||||
card_ids: AHashMap::new(),
|
||||
lookups_left: MAX_DELIVERY_LOOKUPS,
|
||||
}
|
||||
}
|
||||
|
||||
async fn resources(&mut self, server: &Server) -> trc::Result<Arc<GroupwareResources>> {
|
||||
if let Some(resources) = &self.resources {
|
||||
return Ok(resources.clone());
|
||||
}
|
||||
let resources = server
|
||||
.fetch_groupware_resources(
|
||||
self.account_id,
|
||||
self.account_id,
|
||||
SyncCollection::AddressBook,
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
Ok(self.resources.insert(resources).clone())
|
||||
}
|
||||
|
||||
async fn any_card(
|
||||
&mut self,
|
||||
server: &Server,
|
||||
email: &str,
|
||||
matches: impl Fn(&RoaringBitmap) -> bool,
|
||||
) -> trc::Result<bool> {
|
||||
if let Some(card_ids) = self.card_ids.get(email) {
|
||||
return Ok(matches(card_ids));
|
||||
}
|
||||
let Some(lookups_left) = self.lookups_left.checked_sub(1) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.lookups_left = lookups_left;
|
||||
let card_ids = server
|
||||
.document_ids_matching(
|
||||
self.account_id,
|
||||
Collection::ContactCard,
|
||||
ContactField::Email,
|
||||
email.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let result = matches(&card_ids);
|
||||
self.card_ids.insert(email.into(), card_ids);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn book_id(&mut self, server: &Server, name: &str) -> trc::Result<Option<u32>> {
|
||||
let slug = name_slug(name);
|
||||
let resources = self.resources(server).await?;
|
||||
Ok(resources
|
||||
.containers()
|
||||
.find(|book| {
|
||||
book.container_name().is_some_and(|href| {
|
||||
href.eq_ignore_ascii_case(name)
|
||||
|| (!slug.is_empty() && href.eq_ignore_ascii_case(&slug))
|
||||
})
|
||||
})
|
||||
.map(|book| book.document_id()))
|
||||
}
|
||||
|
||||
pub(super) async fn exist(&mut self, server: &Server, names: &[Box<str>]) -> trc::Result<bool> {
|
||||
for name in names {
|
||||
if self.book_id(server, name).await?.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(super) async fn contains(
|
||||
&mut self,
|
||||
server: &Server,
|
||||
lists: &[AddressBookList],
|
||||
emails: &[String],
|
||||
) -> trc::Result<bool> {
|
||||
for list in lists {
|
||||
match list {
|
||||
AddressBookList::Default => {
|
||||
for email in emails {
|
||||
if self
|
||||
.any_card(server, email, |card_ids| !card_ids.is_empty())
|
||||
.await?
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
AddressBookList::Named(name) => {
|
||||
let Some(book_id) = self.book_id(server, name).await? else {
|
||||
continue;
|
||||
};
|
||||
let resources = self.resources(server).await?;
|
||||
for email in emails {
|
||||
if self
|
||||
.any_card(server, email, |card_ids| {
|
||||
card_ids.iter().any(|card_id| {
|
||||
resources.item_by_id(card_id).is_some_and(|card| {
|
||||
card.child_names()
|
||||
.iter()
|
||||
.any(|name| name.parent_id == book_id)
|
||||
})
|
||||
})
|
||||
})
|
||||
.await?
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/email/src/sieve/addrbook/tests.rs"]
|
||||
mod tests;
|
||||
|
|
@ -4,17 +4,21 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{ActiveScript, ArchivedSieveScript, Bytecode, SeenId, SeenIdHash, SieveScript};
|
||||
use super::{
|
||||
ActiveScript, ArchivedSieveScript, Bytecode, SeenId, SeenIdHash, SieveScript,
|
||||
addrbook::{AddressBookList, AddressBooks, MAX_LIST_LOOKUPS},
|
||||
rules::{MANAGED_SCRIPT_ID, SENDER_AUTHENTICATED_ENV, is_managed_script},
|
||||
};
|
||||
use crate::{
|
||||
cache::{MessageCacheFetch, mailbox::MailboxCacheAccess},
|
||||
mailbox::{INBOX_ID, TRASH_ID, lookup::MailboxLookup, manage::MailboxFnc},
|
||||
message::{
|
||||
delivery::{
|
||||
AutogeneratedMessage, AutogeneratedReturnPath, IngestRecipient, SenderAuthentication,
|
||||
AutogeneratedMessage, AutogeneratedReturnPath, IngestRecipient, ReturnPathStatus,
|
||||
SenderAuthentication,
|
||||
},
|
||||
ingest::{EmailIngest, IngestEmail, IngestSource, IngestedEmail},
|
||||
},
|
||||
sieve::VacationResponse,
|
||||
};
|
||||
use common::{
|
||||
MessageStoreCache, Server,
|
||||
|
|
@ -26,7 +30,7 @@ use compact_str::{CompactString, ToCompactString};
|
|||
use mail_builder::headers::date::Date;
|
||||
use mail_parser::{HeaderName, MessageParser};
|
||||
use sieve::{
|
||||
Arena, Context, Envelope, Handler, Input, Mailbox, MessageSource, Recipient, Reply,
|
||||
Arena, Context, Envelope, Handler, Input, Mailbox, MatchAs, MessageSource, Recipient, Reply,
|
||||
ScriptArena, Sieve, SieveAction, Status,
|
||||
compiler::grammar::actions::action_redirect::Notify,
|
||||
runtime::{Script, Variable},
|
||||
|
|
@ -47,6 +51,7 @@ use types::{
|
|||
keyword::Keyword,
|
||||
special_use::SpecialUse,
|
||||
};
|
||||
use utils::sanitize_email;
|
||||
|
||||
struct SieveMessage<'x> {
|
||||
pub raw_message: Cow<'x, [u8]>,
|
||||
|
|
@ -63,6 +68,8 @@ struct SieveHandler<'x, 'r> {
|
|||
resolved: Vec<(MailboxQuery, Option<u32>)>,
|
||||
has_mailboxes: bool,
|
||||
mail_from: &'x str,
|
||||
return_path_status: ReturnPathStatus,
|
||||
spam_percentage: Option<u8>,
|
||||
server_name: &'x str,
|
||||
mail_max_size: usize,
|
||||
max_received_headers: usize,
|
||||
|
|
@ -71,7 +78,11 @@ struct SieveHandler<'x, 'r> {
|
|||
autogenerated: Vec<AutogeneratedMessage>,
|
||||
checked_ids: AHashMap<SeenIdHash, bool>,
|
||||
seen_ids: Vec<SeenId>,
|
||||
vacation_id: Option<SeenIdHash>,
|
||||
last_duplicate_id: Option<SeenIdHash>,
|
||||
reject_reason: Option<String>,
|
||||
reply_message_id: Option<usize>,
|
||||
did_reject: bool,
|
||||
do_discard: bool,
|
||||
do_deliver: bool,
|
||||
do_redirect: bool,
|
||||
|
|
@ -94,6 +105,13 @@ enum PendingWork<'x> {
|
|||
},
|
||||
MailboxExists(MailboxExistsRequest),
|
||||
FileInto(FileIntoRequest),
|
||||
ListContains {
|
||||
lists: Vec<AddressBookList>,
|
||||
emails: Vec<String>,
|
||||
},
|
||||
ValidExtLists {
|
||||
names: Vec<Box<str>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
@ -266,6 +284,8 @@ impl SieveHandler<'_, '_> {
|
|||
message_id: usize,
|
||||
) {
|
||||
let (sender_address, return_path) = if source == MessageSource::Vacation {
|
||||
self.reply_message_id = Some(message_id);
|
||||
self.vacation_id = self.last_duplicate_id;
|
||||
("", AutogeneratedReturnPath::Null)
|
||||
} else {
|
||||
(self.mail_from, AutogeneratedReturnPath::Account)
|
||||
|
|
@ -327,9 +347,12 @@ impl SieveHandler<'_, '_> {
|
|||
write_received_header(&mut raw_message, self.server_name, self.session_id);
|
||||
raw_message.extend_from_slice(message.raw_message.as_ref());
|
||||
|
||||
if source == MessageSource::Redirect {
|
||||
let spam_percentage = if source == MessageSource::Redirect {
|
||||
self.redirect_copies += recipients.len();
|
||||
}
|
||||
self.spam_percentage
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.autogenerated.push(AutogeneratedMessage {
|
||||
account_address: self.mail_from.to_string(),
|
||||
return_path,
|
||||
|
|
@ -337,6 +360,7 @@ impl SieveHandler<'_, '_> {
|
|||
message: raw_message,
|
||||
notify,
|
||||
source,
|
||||
spam_percentage,
|
||||
exploded: false,
|
||||
});
|
||||
self.do_redirect = true;
|
||||
|
|
@ -405,12 +429,59 @@ impl<'x> Handler<'x> for SieveHandler<'x, '_> {
|
|||
}
|
||||
}
|
||||
|
||||
fn list_contains(
|
||||
&mut self,
|
||||
_: &Context<'x>,
|
||||
lists: &[&str],
|
||||
values: &[&str],
|
||||
_: MatchAs,
|
||||
) -> Reply<bool> {
|
||||
let lists: Vec<AddressBookList> = lists
|
||||
.iter()
|
||||
.filter_map(|list| AddressBookList::parse(list))
|
||||
.collect();
|
||||
if lists.is_empty() {
|
||||
return Reply::Ready(false);
|
||||
}
|
||||
let mut emails: Vec<String> = values
|
||||
.iter()
|
||||
.filter_map(|value| sanitize_email(value))
|
||||
.take(MAX_LIST_LOOKUPS)
|
||||
.collect();
|
||||
emails.sort_unstable();
|
||||
emails.dedup();
|
||||
if emails.is_empty() {
|
||||
return Reply::Ready(false);
|
||||
}
|
||||
self.pending = Some(PendingWork::ListContains { lists, emails });
|
||||
Reply::Pending
|
||||
}
|
||||
|
||||
fn valid_ext_lists(&mut self, _: &Context<'x>, lists: &[&str]) -> Reply<bool> {
|
||||
let mut names = Vec::new();
|
||||
for list in lists {
|
||||
match AddressBookList::parse(list) {
|
||||
Some(AddressBookList::Default) => (),
|
||||
Some(AddressBookList::Named(name)) => names.push(name),
|
||||
None => return Reply::Ready(false),
|
||||
}
|
||||
}
|
||||
if names.is_empty() {
|
||||
Reply::Ready(true)
|
||||
} else {
|
||||
self.pending = Some(PendingWork::ValidExtLists { names });
|
||||
Reply::Pending
|
||||
}
|
||||
}
|
||||
|
||||
fn duplicate_id(&mut self, _: &Context<'x>, id: &str, expiry: u64, last: bool) -> Reply<bool> {
|
||||
if expiry == 0 {
|
||||
self.last_duplicate_id = None;
|
||||
return Reply::Ready(false);
|
||||
}
|
||||
|
||||
let hash = SeenIdHash::new(self.script_hash, id);
|
||||
self.last_duplicate_id = Some(hash);
|
||||
match self.checked_ids.get(&hash) {
|
||||
Some(result) => Reply::Ready(*result),
|
||||
None => {
|
||||
|
|
@ -443,7 +514,10 @@ impl<'x> Handler<'x> for SieveHandler<'x, '_> {
|
|||
self.do_discard = true;
|
||||
}
|
||||
SieveAction::Reject { reason, .. } => {
|
||||
self.reject_reason = reason.to_string().into();
|
||||
if self.return_path_status == ReturnPathStatus::Verified {
|
||||
self.reject_reason = reason.to_string().into();
|
||||
}
|
||||
self.did_reject = true;
|
||||
self.do_discard = true;
|
||||
}
|
||||
SieveAction::FileInto {
|
||||
|
|
@ -505,6 +579,7 @@ pub trait SieveScriptIngest: Sync + Send {
|
|||
raw_message: &[u8],
|
||||
envelope_from: &str,
|
||||
sender_authentication: SenderAuthentication,
|
||||
return_path_status: ReturnPathStatus,
|
||||
envelope_to: &IngestRecipient,
|
||||
session_id: u64,
|
||||
active_script: ActiveScript,
|
||||
|
|
@ -516,6 +591,11 @@ pub trait SieveScriptIngest: Sync + Send {
|
|||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<Option<u32>>> + Send;
|
||||
|
||||
fn sieve_script_get_active_id_cached(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<Option<u32>>> + Send;
|
||||
|
||||
fn sieve_script_get_active(
|
||||
&self,
|
||||
account_id: u32,
|
||||
|
|
@ -552,6 +632,7 @@ impl SieveScriptIngest for Server {
|
|||
raw_message: &[u8],
|
||||
envelope_from: &str,
|
||||
sender_authentication: SenderAuthentication,
|
||||
return_path_status: ReturnPathStatus,
|
||||
envelope_to: &IngestRecipient,
|
||||
session_id: u64,
|
||||
active_script: ActiveScript,
|
||||
|
|
@ -573,10 +654,12 @@ impl SieveScriptIngest for Server {
|
|||
// Set account name and email
|
||||
let account_info = self.account(account_id).await.caused_by(trc::location!())?;
|
||||
let mail_from = account_info.name();
|
||||
let max_received_headers = self.core.sieve.max_received_headers;
|
||||
|
||||
// Load the compiled script
|
||||
let included = ScriptArena::new();
|
||||
let mut resolved_includes: Vec<(String, &Sieve<'static>)> = Vec::new();
|
||||
let mut address_books = AddressBooks::new(account_id);
|
||||
let mut recompiled = None;
|
||||
let script = verified_script(self, account_id, &active_script, &mut recompiled).await?;
|
||||
|
||||
|
|
@ -599,6 +682,14 @@ impl SieveScriptIngest for Server {
|
|||
ctx.set_envelope(Envelope::Orcpt, orcpt);
|
||||
}
|
||||
ctx.set_spam_status(spam_status(envelope_to.spam_percentage));
|
||||
ctx.set_env_variable(
|
||||
SENDER_AUTHENTICATED_ENV,
|
||||
if sender_authentication.is_authenticated() {
|
||||
"yes"
|
||||
} else {
|
||||
"no"
|
||||
},
|
||||
);
|
||||
|
||||
let mut handler = SieveHandler {
|
||||
server: self,
|
||||
|
|
@ -608,9 +699,11 @@ impl SieveScriptIngest for Server {
|
|||
resolved: Vec::new(),
|
||||
has_mailboxes: false,
|
||||
mail_from,
|
||||
return_path_status,
|
||||
spam_percentage: envelope_to.spam_percentage,
|
||||
server_name: self.core.network.server_name.as_str(),
|
||||
mail_max_size: self.core.email.mail_max_size,
|
||||
max_received_headers: self.core.sieve.max_received_headers,
|
||||
max_received_headers,
|
||||
received_headers,
|
||||
messages: vec![SieveMessage {
|
||||
raw_message: raw_message.into(),
|
||||
|
|
@ -621,7 +714,11 @@ impl SieveScriptIngest for Server {
|
|||
autogenerated: Vec::new(),
|
||||
checked_ids: AHashMap::new(),
|
||||
seen_ids: Vec::new(),
|
||||
vacation_id: None,
|
||||
last_duplicate_id: None,
|
||||
reject_reason: None,
|
||||
reply_message_id: None,
|
||||
did_reject: false,
|
||||
do_discard: false,
|
||||
do_deliver: false,
|
||||
do_redirect: false,
|
||||
|
|
@ -749,6 +846,12 @@ impl SieveScriptIngest for Server {
|
|||
|
||||
Input::Continue
|
||||
}
|
||||
Some(PendingWork::ListContains { lists, emails }) => {
|
||||
Input::Bool(address_books.contains(self, &lists, &emails).await?)
|
||||
}
|
||||
Some(PendingWork::ValidExtLists { names }) => {
|
||||
Input::Bool(address_books.exist(self, &names).await?)
|
||||
}
|
||||
None => Input::Continue,
|
||||
};
|
||||
|
||||
|
|
@ -773,8 +876,11 @@ impl SieveScriptIngest for Server {
|
|||
let SieveHandler {
|
||||
mut messages,
|
||||
autogenerated: mut generated,
|
||||
seen_ids,
|
||||
mut seen_ids,
|
||||
vacation_id,
|
||||
reject_reason,
|
||||
reply_message_id,
|
||||
did_reject,
|
||||
do_discard,
|
||||
do_deliver,
|
||||
do_redirect,
|
||||
|
|
@ -782,9 +888,28 @@ impl SieveScriptIngest for Server {
|
|||
..
|
||||
} = handler;
|
||||
let message_changed = ctx.has_message_changed();
|
||||
if ctx.is_hop_limited() {
|
||||
trc::event!(
|
||||
Smtp(SmtpEvent::LoopDetected),
|
||||
From = CompactString::from(mail_from),
|
||||
Total = received_headers,
|
||||
Limit = max_received_headers,
|
||||
SpanId = session_id,
|
||||
);
|
||||
}
|
||||
drop(ctx);
|
||||
let mut message = Some(message);
|
||||
|
||||
if did_reject && let Some(reply_id) = reply_message_id {
|
||||
generated.retain(|message| message.source != MessageSource::Vacation);
|
||||
if let Some(vacation_id) = vacation_id {
|
||||
seen_ids.retain(|seen| seen.hash != vacation_id);
|
||||
}
|
||||
if let Some(reply) = messages.get_mut(reply_id) {
|
||||
reply.file_into.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Fail-safe, no discard and no keep seen, assume that something went wrong and file anyway.
|
||||
if !do_deliver
|
||||
&& !do_discard
|
||||
|
|
@ -902,21 +1027,23 @@ impl SieveScriptIngest for Server {
|
|||
.caused_by(trc::location!())
|
||||
}
|
||||
|
||||
async fn sieve_script_get_active(&self, account_id: u32) -> trc::Result<Option<ActiveScript>> {
|
||||
async fn sieve_script_get_active_id_cached(&self, account_id: u32) -> trc::Result<Option<u32>> {
|
||||
let account = self.account(account_id).await.caused_by(trc::location!())?;
|
||||
let document_id = match account.active_script.get() {
|
||||
CachedActiveScript::Known(document_id) => document_id,
|
||||
match account.active_script.get() {
|
||||
CachedActiveScript::Known(document_id) => Ok(document_id),
|
||||
CachedActiveScript::Unknown(ticket) => {
|
||||
let document_id = self
|
||||
.sieve_script_get_active_id(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
account.active_script.fill(ticket, document_id);
|
||||
document_id
|
||||
Ok(document_id)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
match document_id {
|
||||
async fn sieve_script_get_active(&self, account_id: u32) -> trc::Result<Option<ActiveScript>> {
|
||||
match self.sieve_script_get_active_id_cached(account_id).await? {
|
||||
Some(document_id) => self.sieve_script_load(account_id, document_id).await,
|
||||
None => Ok(None),
|
||||
}
|
||||
|
|
@ -927,8 +1054,9 @@ impl SieveScriptIngest for Server {
|
|||
account_id: u32,
|
||||
name: &str,
|
||||
) -> trc::Result<Option<Sieve<'static>>> {
|
||||
// Find the script by name
|
||||
let Some(document_id) = self
|
||||
let document_id = if is_managed_script(name) {
|
||||
MANAGED_SCRIPT_ID
|
||||
} else if let Some(document_id) = self
|
||||
.document_ids_matching(
|
||||
account_id,
|
||||
Collection::SieveScript,
|
||||
|
|
@ -938,7 +1066,9 @@ impl SieveScriptIngest for Server {
|
|||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.min()
|
||||
else {
|
||||
{
|
||||
document_id
|
||||
} else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
|
|
@ -1007,15 +1137,7 @@ impl SieveScriptIngest for Server {
|
|||
name: script_object.name.to_string(),
|
||||
blob_hash: BlobHash::from(&script_object.blob_hash),
|
||||
size: script_object.size.to_native(),
|
||||
vacation_response: script_object.vacation_response.as_ref().map(|vr| {
|
||||
VacationResponse {
|
||||
from_date: vr.from_date.as_ref().map(|v| v.to_native()),
|
||||
to_date: vr.to_date.as_ref().map(|v| v.to_native()),
|
||||
subject: vr.subject.as_ref().map(|v| v.to_string()),
|
||||
text_body: vr.text_body.as_ref().map(|v| v.to_string()),
|
||||
html_body: vr.html_body.as_ref().map(|v| v.to_string()),
|
||||
}
|
||||
}),
|
||||
_vacation: None,
|
||||
script: script.to_bytes(),
|
||||
metadata_flags: script_object.metadata_flags,
|
||||
};
|
||||
|
|
@ -1072,7 +1194,7 @@ async fn resolve_mailbox(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
async fn verified_script<'x>(
|
||||
pub(crate) async fn verified_script<'x>(
|
||||
server: &Server,
|
||||
account_id: u32,
|
||||
script: &'x ActiveScript,
|
||||
|
|
|
|||
|
|
@ -13,9 +13,11 @@ use trc::AddContext;
|
|||
use types::{blob_hash::BlobHash, collection::Collection, field::SieveField};
|
||||
use utils::hash128::Hash128;
|
||||
|
||||
mod addrbook;
|
||||
pub mod delete;
|
||||
pub mod index;
|
||||
pub mod ingest;
|
||||
pub mod rules;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ActiveScript {
|
||||
|
|
@ -50,7 +52,7 @@ pub struct SieveScript {
|
|||
pub name: String,
|
||||
pub blob_hash: BlobHash,
|
||||
pub size: u32,
|
||||
pub vacation_response: Option<VacationResponse>,
|
||||
pub _vacation: Option<VacationResponse>,
|
||||
pub script: Vec<u8>,
|
||||
pub metadata_flags: u8,
|
||||
}
|
||||
|
|
@ -72,7 +74,7 @@ impl SieveScript {
|
|||
SieveScript {
|
||||
name: name.into(),
|
||||
blob_hash,
|
||||
vacation_response: None,
|
||||
_vacation: None,
|
||||
size: 0,
|
||||
script: Vec::new(),
|
||||
metadata_flags: 0,
|
||||
|
|
@ -94,11 +96,6 @@ impl SieveScript {
|
|||
self
|
||||
}
|
||||
|
||||
pub fn with_vacation_response(mut self, vacation_response: VacationResponse) -> Self {
|
||||
self.vacation_response = Some(vacation_response);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_script(mut self, script: &Sieve<'_>) -> Self {
|
||||
self.set_script(script);
|
||||
self
|
||||
|
|
|
|||
1909
crates/email/src/sieve/rules/decode.rs
Normal file
1909
crates/email/src/sieve/rules/decode.rs
Normal file
File diff suppressed because it is too large
Load diff
1025
crates/email/src/sieve/rules/emit.rs
Normal file
1025
crates/email/src/sieve/rules/emit.rs
Normal file
File diff suppressed because it is too large
Load diff
554
crates/email/src/sieve/rules/managed.rs
Normal file
554
crates/email/src/sieve/rules/managed.rs
Normal file
|
|
@ -0,0 +1,554 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{
|
||||
FORWARDED_BY_HEADER, ForwarderId, MANAGED_SCRIPT_ID, MANAGED_SCRIPT_NAME, ManagedScript,
|
||||
RuleError, VacationResponse, is_managed_script,
|
||||
};
|
||||
use crate::sieve::{
|
||||
ArchivedSieveScript, SieveScript,
|
||||
ingest::{SieveScriptIngest, verified_script},
|
||||
};
|
||||
use common::{
|
||||
Server,
|
||||
auth::{AccessToken, AccountInfo},
|
||||
ipc::CacheInvalidation,
|
||||
storage::index::ObjectIndexBuilder,
|
||||
};
|
||||
use groupware::calendar::working_hours::WorkingHoursHandler;
|
||||
use registry::schema::enums::StorageQuota;
|
||||
use sieve::{
|
||||
Sieve,
|
||||
bytecode::view::{Op, Value},
|
||||
};
|
||||
use std::{fmt::Display, future::Future};
|
||||
use store::{
|
||||
SerializeInfallible, ValueKey,
|
||||
write::{Archive, ArchiveBytes, BatchBuilder, ValueClass, assert::AssertValue, now},
|
||||
};
|
||||
use trc::{AddContext, StoreEvent};
|
||||
use types::{
|
||||
blob_hash::BlobHash,
|
||||
collection::{Collection, SyncCollection},
|
||||
field::{Field, PrincipalField, SieveField},
|
||||
};
|
||||
|
||||
pub struct ManagedScriptState {
|
||||
pub script: ManagedScript,
|
||||
stored: Stored,
|
||||
activity: ManagedActivity,
|
||||
}
|
||||
|
||||
enum Stored {
|
||||
Absent,
|
||||
Decoded {
|
||||
archive: Archive<ArchiveBytes>,
|
||||
bytecode: Bytecode,
|
||||
},
|
||||
Undecodable {
|
||||
archive: Archive<ArchiveBytes>,
|
||||
reason: trc::Error,
|
||||
keep_copy: bool,
|
||||
},
|
||||
}
|
||||
|
||||
enum Bytecode {
|
||||
Current { source: BlobHash },
|
||||
Recompiled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ManagedActivity {
|
||||
Inactive { active: Option<u32> },
|
||||
Active,
|
||||
IncludedBy(u32),
|
||||
Unknown,
|
||||
}
|
||||
|
||||
enum Activation {
|
||||
Unchanged,
|
||||
Activate { observed: Option<u32> },
|
||||
Deactivate,
|
||||
Included(u32),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SaveError {
|
||||
Conflict,
|
||||
Invalid(RuleError),
|
||||
}
|
||||
|
||||
pub trait ManagedSieveScript: Sync + Send {
|
||||
fn managed_script_read(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<ManagedScript>> + Send;
|
||||
|
||||
fn managed_script_load(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<ManagedScriptState>> + Send;
|
||||
|
||||
fn managed_vacation_read(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<Option<VacationResponse>>> + Send;
|
||||
|
||||
fn managed_script_activity(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> impl Future<Output = trc::Result<ManagedActivity>> + Send;
|
||||
|
||||
fn managed_script_included_by(
|
||||
&self,
|
||||
account_id: u32,
|
||||
document_id: u32,
|
||||
) -> impl Future<Output = trc::Result<bool>> + Send;
|
||||
|
||||
fn managed_script_save(
|
||||
&self,
|
||||
access_token: &AccessToken,
|
||||
account_id: u32,
|
||||
state: ManagedScriptState,
|
||||
) -> impl Future<Output = trc::Result<Result<Option<u64>, SaveError>>> + Send;
|
||||
}
|
||||
|
||||
impl ManagedSieveScript for Server {
|
||||
async fn managed_script_read(&self, account_id: u32) -> trc::Result<ManagedScript> {
|
||||
read_stored(self, account_id)
|
||||
.await
|
||||
.map(|(script, _)| script)
|
||||
}
|
||||
|
||||
async fn managed_script_load(&self, account_id: u32) -> trc::Result<ManagedScriptState> {
|
||||
let (mut script, stored) = read_stored(self, account_id).await?;
|
||||
let activity = match self.managed_script_activity(account_id).await? {
|
||||
ManagedActivity::Active if matches!(stored, Stored::Absent) => {
|
||||
ManagedActivity::Inactive {
|
||||
active: Some(MANAGED_SCRIPT_ID),
|
||||
}
|
||||
}
|
||||
activity => activity,
|
||||
};
|
||||
if activity.is_inactive()
|
||||
&& let Some(vacation) = &mut script.vacation
|
||||
{
|
||||
vacation.is_enabled = false;
|
||||
}
|
||||
Ok(ManagedScriptState {
|
||||
script,
|
||||
stored,
|
||||
activity,
|
||||
})
|
||||
}
|
||||
|
||||
async fn managed_vacation_read(
|
||||
&self,
|
||||
account_id: u32,
|
||||
) -> trc::Result<Option<VacationResponse>> {
|
||||
let Some(mut vacation) = read_stored(self, account_id).await?.0.vacation else {
|
||||
return Ok(None);
|
||||
};
|
||||
if vacation.is_enabled
|
||||
&& self
|
||||
.managed_script_activity(account_id)
|
||||
.await?
|
||||
.is_inactive()
|
||||
{
|
||||
vacation.is_enabled = false;
|
||||
}
|
||||
Ok(Some(vacation))
|
||||
}
|
||||
|
||||
async fn managed_script_activity(&self, account_id: u32) -> trc::Result<ManagedActivity> {
|
||||
let active = self.sieve_script_get_active_id_cached(account_id).await?;
|
||||
Ok(match active {
|
||||
Some(MANAGED_SCRIPT_ID) => ManagedActivity::Active,
|
||||
Some(document_id) => match self
|
||||
.managed_script_included_by(account_id, document_id)
|
||||
.await
|
||||
{
|
||||
Ok(true) => ManagedActivity::IncludedBy(document_id),
|
||||
Ok(false) => ManagedActivity::Inactive { active },
|
||||
Err(err) => {
|
||||
trc::error!(
|
||||
err.account_id(account_id)
|
||||
.document_id(document_id)
|
||||
.details("Failed to check whether the active Sieve script includes the managed script")
|
||||
.caused_by(trc::location!())
|
||||
);
|
||||
ManagedActivity::Unknown
|
||||
}
|
||||
},
|
||||
None => ManagedActivity::Inactive { active },
|
||||
})
|
||||
}
|
||||
|
||||
async fn managed_script_included_by(
|
||||
&self,
|
||||
account_id: u32,
|
||||
document_id: u32,
|
||||
) -> trc::Result<bool> {
|
||||
let Some(active) = self
|
||||
.sieve_script_load(account_id, document_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut recompiled = None;
|
||||
let sieve = verified_script(self, account_id, &active, &mut recompiled).await?;
|
||||
Ok(sieve.ops().any(|op| {
|
||||
matches!(
|
||||
op,
|
||||
Ok((_, Op::Include { global: false, name: Value::Text(name), .. }))
|
||||
if is_managed_script(name)
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
async fn managed_script_save(
|
||||
&self,
|
||||
access_token: &AccessToken,
|
||||
account_id: u32,
|
||||
state: ManagedScriptState,
|
||||
) -> trc::Result<Result<Option<u64>, SaveError>> {
|
||||
let ManagedScriptState {
|
||||
script,
|
||||
stored,
|
||||
activity,
|
||||
} = state;
|
||||
let account = self
|
||||
.account_info(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let account_zone = if script.uses_account_zone() {
|
||||
self.account_time_zone(account_id)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let forwarder = self
|
||||
.core
|
||||
.sieve
|
||||
.untrusted_runtime
|
||||
.can_edit_header(FORWARDED_BY_HEADER)
|
||||
.then(|| ForwarderId::new(self.core.oauth.oauth_key.as_bytes(), account_id));
|
||||
let text = script.emit(forwarder, account.addresses(), account_zone);
|
||||
let text_hash = BlobHash::generate(text.as_bytes());
|
||||
let activation = match (script.runs_anything(), activity) {
|
||||
(_, ManagedActivity::IncludedBy(document_id)) => Activation::Included(document_id),
|
||||
(true, ManagedActivity::Inactive { active }) => {
|
||||
Activation::Activate { observed: active }
|
||||
}
|
||||
(false, ManagedActivity::Active) => Activation::Deactivate,
|
||||
_ => Activation::Unchanged,
|
||||
};
|
||||
if let Stored::Decoded {
|
||||
bytecode: Bytecode::Current { source },
|
||||
..
|
||||
} = &stored
|
||||
&& *source == text_hash
|
||||
&& matches!(activation, Activation::Unchanged | Activation::Included(_))
|
||||
{
|
||||
return Ok(Ok(None));
|
||||
}
|
||||
let compiled = match self.core.sieve.untrusted_compiler.compile(text.as_bytes()) {
|
||||
Ok(compiled) => compiled,
|
||||
Err(err) => return Ok(Err(SaveError::Invalid(RuleError::Compile(err.to_string())))),
|
||||
};
|
||||
let instructions = match script.verify(&compiled) {
|
||||
Ok(instructions) => instructions,
|
||||
Err(err) => return Ok(Err(SaveError::Invalid(err))),
|
||||
};
|
||||
let cpu_limit = self.core.sieve.untrusted_runtime.cpu_limit();
|
||||
if instructions > cpu_limit {
|
||||
return Ok(Err(SaveError::Invalid(RuleError::TooManyInstructions {
|
||||
instructions,
|
||||
limit: cpu_limit,
|
||||
})));
|
||||
}
|
||||
|
||||
let (current, decode_failure) = match stored {
|
||||
Stored::Absent => (None, None),
|
||||
Stored::Decoded { archive, .. } => (Some(archive), None),
|
||||
Stored::Undecodable {
|
||||
archive,
|
||||
reason,
|
||||
keep_copy,
|
||||
} => (Some(archive), Some((reason, keep_copy))),
|
||||
};
|
||||
let current = current
|
||||
.as_ref()
|
||||
.map(|archive| archive.to_unarchived::<SieveScript>())
|
||||
.transpose()
|
||||
.caused_by(trc::location!())?;
|
||||
let (blob_hash, blob_hold) = self
|
||||
.hold_blob(
|
||||
account_id,
|
||||
text_hash,
|
||||
text.as_bytes(),
|
||||
60,
|
||||
&self.core.blob.email,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut batch = BatchBuilder::new();
|
||||
batch
|
||||
.with_account_id(account_id)
|
||||
.with_collection(Collection::SieveScript);
|
||||
let recovered = match (&decode_failure, ¤t) {
|
||||
(Some((_, true)), Some(current)) => {
|
||||
keep_recovered_copy(self, &mut batch, access_token, &account, current.inner).await?
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
|
||||
let changes = SieveScript {
|
||||
name: MANAGED_SCRIPT_NAME.to_string(),
|
||||
blob_hash,
|
||||
size: u32::try_from(text.len()).unwrap_or(u32::MAX),
|
||||
_vacation: None,
|
||||
script: compiled.to_bytes(),
|
||||
metadata_flags: current
|
||||
.as_ref()
|
||||
.map_or(0, |current| current.inner.metadata_flags),
|
||||
};
|
||||
batch.with_document(MANAGED_SCRIPT_ID);
|
||||
if current.is_none() {
|
||||
batch.assert_value(
|
||||
ValueClass::Property(Field::ARCHIVE.into()),
|
||||
AssertValue::None,
|
||||
);
|
||||
}
|
||||
batch
|
||||
.custom(
|
||||
ObjectIndexBuilder::new()
|
||||
.with_current_opt(current)
|
||||
.with_changes(changes)
|
||||
.with_changed_by(access_token.changed_by()),
|
||||
)
|
||||
.caused_by(trc::location!())?;
|
||||
blob_hold.release(&mut batch);
|
||||
|
||||
let active_changed = match activation {
|
||||
Activation::Activate { observed } => {
|
||||
batch
|
||||
.with_collection(Collection::Principal)
|
||||
.with_document(0)
|
||||
.assert_value(
|
||||
PrincipalField::ActiveScriptId,
|
||||
observed.map_or(AssertValue::None, AssertValue::U32),
|
||||
)
|
||||
.set(
|
||||
PrincipalField::ActiveScriptId,
|
||||
MANAGED_SCRIPT_ID.serialize(),
|
||||
);
|
||||
true
|
||||
}
|
||||
Activation::Deactivate => {
|
||||
batch
|
||||
.with_collection(Collection::Principal)
|
||||
.with_document(0)
|
||||
.clear_if_equals(PrincipalField::ActiveScriptId, MANAGED_SCRIPT_ID);
|
||||
true
|
||||
}
|
||||
Activation::Included(document_id) => {
|
||||
batch
|
||||
.with_collection(Collection::Principal)
|
||||
.with_document(0)
|
||||
.assert_value(PrincipalField::ActiveScriptId, document_id);
|
||||
false
|
||||
}
|
||||
Activation::Unchanged => false,
|
||||
};
|
||||
|
||||
match self.commit_batch(batch).await {
|
||||
Ok(ids) => {
|
||||
if let Some((reason, keep_copy)) = decode_failure {
|
||||
trc::error!(
|
||||
StoreEvent::UnexpectedError
|
||||
.into_err()
|
||||
.account_id(account_id)
|
||||
.reason(reason)
|
||||
.details(match (keep_copy, recovered) {
|
||||
(true, true) => {
|
||||
"Replaced the undecodable managed Sieve script and kept an inactive copy"
|
||||
}
|
||||
(true, false) => {
|
||||
"Replaced the undecodable managed Sieve script, no room for a recovered copy"
|
||||
}
|
||||
(false, _) => {
|
||||
"Replaced the managed Sieve script whose source is missing"
|
||||
}
|
||||
})
|
||||
.caused_by(trc::location!())
|
||||
);
|
||||
}
|
||||
if active_changed {
|
||||
self.invalidate_caches(CacheInvalidation::ActiveSieveScript(account_id).into())
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
}
|
||||
Ok(Ok(Some(
|
||||
ids.last_change_id(account_id, SyncCollection::SieveScript),
|
||||
)))
|
||||
}
|
||||
Err(err) if err.is_assertion_failure() => Ok(Err(SaveError::Conflict)),
|
||||
Err(err) => Err(err.caused_by(trc::location!())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ManagedActivity {
|
||||
pub fn is_active(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
ManagedActivity::Active | ManagedActivity::IncludedBy(_)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_inactive(self) -> bool {
|
||||
matches!(self, ManagedActivity::Inactive { .. })
|
||||
}
|
||||
}
|
||||
|
||||
impl ManagedScriptState {
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.activity.is_active()
|
||||
}
|
||||
|
||||
pub fn keep_activation(&mut self) {
|
||||
if let ManagedActivity::Inactive { .. } = self.activity {
|
||||
self.activity = ManagedActivity::Unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn keep_recovered_copy(
|
||||
server: &Server,
|
||||
batch: &mut BatchBuilder,
|
||||
access_token: &AccessToken,
|
||||
account: &AccountInfo,
|
||||
current: &ArchivedSieveScript,
|
||||
) -> trc::Result<bool> {
|
||||
let account_id = account.account_id;
|
||||
let script_count = server
|
||||
.document_ids(account_id, Collection::SieveScript, SieveField::Name)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.len();
|
||||
let max_scripts =
|
||||
u64::from(server.object_quota(account.object_quotas(), StorageQuota::MaxSieveScripts));
|
||||
let name = format!("{MANAGED_SCRIPT_NAME}-recovered-{}", now());
|
||||
let is_taken = !server
|
||||
.document_ids_matching(
|
||||
account_id,
|
||||
Collection::SieveScript,
|
||||
SieveField::Name,
|
||||
name.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
.is_empty();
|
||||
if script_count >= max_scripts || is_taken {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let slot = batch.reserve_document_id(account_id, Collection::SieveScript);
|
||||
batch
|
||||
.create_document(slot)
|
||||
.custom(
|
||||
ObjectIndexBuilder::<(), _>::new()
|
||||
.with_changes(SieveScript {
|
||||
name,
|
||||
blob_hash: BlobHash::from(¤t.blob_hash),
|
||||
size: current.size.to_native(),
|
||||
_vacation: None,
|
||||
script: current.script.to_vec(),
|
||||
metadata_flags: 0,
|
||||
})
|
||||
.with_changed_by(access_token.changed_by()),
|
||||
)
|
||||
.caused_by(trc::location!())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn read_stored(server: &Server, account_id: u32) -> trc::Result<(ManagedScript, Stored)> {
|
||||
let Some(archive) = server
|
||||
.store()
|
||||
.get_value::<Archive<ArchiveBytes>>(ValueKey::archive(
|
||||
account_id,
|
||||
Collection::SieveScript,
|
||||
MANAGED_SCRIPT_ID,
|
||||
))
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
else {
|
||||
return Ok((ManagedScript::default(), Stored::Absent));
|
||||
};
|
||||
let stored = archive
|
||||
.unarchive::<SieveScript>()
|
||||
.caused_by(trc::location!())?;
|
||||
let decoded = Sieve::from_bytes(stored.script.as_ref())
|
||||
.ok()
|
||||
.map(|sieve| ManagedScript::decode(&sieve).map_err(undecodable));
|
||||
if let Some(decoded) = decoded {
|
||||
let bytecode = Bytecode::Current {
|
||||
source: BlobHash::from(&stored.blob_hash),
|
||||
};
|
||||
return Ok(classify(archive, decoded, bytecode));
|
||||
}
|
||||
|
||||
let Some(source) = server
|
||||
.get_blob(stored.blob_hash.0.as_ref(), 0..usize::MAX)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
else {
|
||||
return Ok((
|
||||
ManagedScript::default(),
|
||||
Stored::Undecodable {
|
||||
archive,
|
||||
reason: undecodable("The source of the managed Sieve script is missing"),
|
||||
keep_copy: false,
|
||||
},
|
||||
));
|
||||
};
|
||||
let decoded = server
|
||||
.core
|
||||
.sieve
|
||||
.untrusted_compiler
|
||||
.compile(&source)
|
||||
.map_err(undecodable)
|
||||
.and_then(|sieve| ManagedScript::decode(&sieve).map_err(undecodable));
|
||||
Ok(classify(archive, decoded, Bytecode::Recompiled))
|
||||
}
|
||||
|
||||
fn classify(
|
||||
archive: Archive<ArchiveBytes>,
|
||||
decoded: trc::Result<ManagedScript>,
|
||||
bytecode: Bytecode,
|
||||
) -> (ManagedScript, Stored) {
|
||||
match decoded {
|
||||
Ok(script) => (script, Stored::Decoded { archive, bytecode }),
|
||||
Err(reason) => (
|
||||
ManagedScript::default(),
|
||||
Stored::Undecodable {
|
||||
archive,
|
||||
reason,
|
||||
keep_copy: true,
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn undecodable(err: impl Display) -> trc::Error {
|
||||
StoreEvent::UnexpectedError
|
||||
.into_err()
|
||||
.reason(err)
|
||||
.caused_by(trc::location!())
|
||||
}
|
||||
883
crates/email/src/sieve/rules/mod.rs
Normal file
883
crates/email/src/sieve/rules/mod.rs
Normal file
|
|
@ -0,0 +1,883 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::mailbox::JUNK_ID;
|
||||
use decode::DecodeError;
|
||||
use registry::{
|
||||
schema::{
|
||||
enums::{
|
||||
MailRuleAddressOperator, MailRuleMessageKind, MailRuleSensitivityLevel,
|
||||
MailRuleTextOperator, Weekday,
|
||||
},
|
||||
structs::{
|
||||
MailRule, MailRuleActions, MailRuleCondition, MailRuleConditions, MailRuleMessageType,
|
||||
MailRuleRedirect, MailRuleSchedule, MailRuleSensitivity, MailRuleTextTest,
|
||||
},
|
||||
},
|
||||
types::{
|
||||
EnumImpl,
|
||||
list::List,
|
||||
localtime::LocalTime,
|
||||
map::{Map, MapItem},
|
||||
},
|
||||
};
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use types::{id::Id, keyword::Keyword};
|
||||
|
||||
pub mod decode;
|
||||
pub mod emit;
|
||||
pub mod managed;
|
||||
|
||||
pub const MANAGED_SCRIPT_NAME: &str = "managed";
|
||||
pub const MANAGED_SCRIPT_ID: u32 = 0;
|
||||
pub const SENDER_AUTHENTICATED_ENV: &str = "vnd.stalwart.sender-authenticated";
|
||||
pub const NOT_JUNK_FLAG: &str = "$notjunk";
|
||||
pub const FLAGGED_FLAG: &str = "\\Flagged";
|
||||
pub const MAX_SIZE_KB: u64 = 1 << 32;
|
||||
pub const MAX_TIMESTAMP: i64 = 32_535_215_999;
|
||||
pub const MAX_SCHEDULE_SLOTS: usize = 14;
|
||||
pub const MINUTES_PER_DAY: u16 = 24 * 60;
|
||||
|
||||
pub const MAX_SENDER_ENTRIES: usize = 1024;
|
||||
|
||||
pub(crate) const JUNK_FLAG: &str = "$junk";
|
||||
const MAX_ADDRESS_VALUE_LEN: usize = 320;
|
||||
pub(crate) const FORMAT_VERSION: &str = "1";
|
||||
pub(crate) const HEADER_VAR: &str = "rule";
|
||||
pub(crate) const DOLLAR_VAR: &str = "d";
|
||||
pub(crate) const SENDERS_HEADER: &str = "senders";
|
||||
pub(crate) const FORWARDED_BY_HEADER: &str = "X-Forwarded-By";
|
||||
const FORWARDER_ID_CONTEXT: &str = "Stalwart mail rules X-Forwarded-By";
|
||||
pub(crate) const DEFAULT_VACATION_TEXT: &str = "I am away.";
|
||||
pub(crate) const AUTO_SUBMITTED_HEADER: &str = "auto-submitted";
|
||||
pub(crate) const AUTO_SUBMITTED_PATTERN: &str = "auto-*";
|
||||
pub(crate) const IS_SPAM_PERCENT: u64 = 50;
|
||||
pub(crate) const RULE_ENABLED: u8 = 1;
|
||||
pub(crate) const RULE_MATCH_ANY: u8 = 1 << 1;
|
||||
pub(crate) const VOICEMAIL_HEADER: &str = "content-class";
|
||||
pub(crate) const VOICEMAIL_CLASSES: &[&str] = &["voice", "voice-ca"];
|
||||
pub(crate) const UTC_ZONE: &str = "UTC";
|
||||
const DAYS_PER_WEEK: u16 = 7;
|
||||
|
||||
macro_rules! system_flags {
|
||||
($($keyword:tt => $flag:tt),+ $(,)?) => {
|
||||
pub(crate) fn script_keyword(keyword: &str) -> &str {
|
||||
hashify::map!(keyword.as_bytes(), &str, $($keyword => $flag),+)
|
||||
.copied()
|
||||
.unwrap_or(keyword)
|
||||
}
|
||||
|
||||
pub(crate) fn api_keyword(flag: String) -> String {
|
||||
match hashify::map!(flag.as_bytes(), &str, $($flag => $keyword),+) {
|
||||
Some(keyword) => keyword.to_string(),
|
||||
None => flag,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
system_flags! {
|
||||
"$seen" => "\\Seen",
|
||||
"$flagged" => "\\Flagged",
|
||||
"$answered" => "\\Answered",
|
||||
"$draft" => "\\Draft",
|
||||
"$deleted" => "\\Deleted",
|
||||
"$recent" => "\\Recent",
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct DayMask(u8);
|
||||
|
||||
impl DayMask {
|
||||
const ALL: u8 = (1 << DAYS_PER_WEEK) - 1;
|
||||
|
||||
fn of(days: &Map<Weekday>) -> Self {
|
||||
DayMask(days.iter().fold(0, |mask, day| mask | (1 << day.to_id())))
|
||||
}
|
||||
|
||||
fn from_sieve_keys(keys: impl Iterator<Item = Option<u16>>) -> Option<Self> {
|
||||
let mut mask = 0u8;
|
||||
let mut last = None;
|
||||
for key in keys {
|
||||
let id = key.filter(|key| *key < DAYS_PER_WEEK)? + DAYS_PER_WEEK - 1;
|
||||
let id = id % DAYS_PER_WEEK;
|
||||
if last.is_some_and(|last| id <= last) {
|
||||
return None;
|
||||
}
|
||||
last = Some(id);
|
||||
mask |= 1 << id;
|
||||
}
|
||||
(mask != 0).then_some(DayMask(mask))
|
||||
}
|
||||
|
||||
fn next_day(self) -> Self {
|
||||
DayMask(((self.0 << 1) | (self.0 >> (DAYS_PER_WEEK - 1))) & Self::ALL)
|
||||
}
|
||||
|
||||
fn ids(self) -> impl Iterator<Item = u16> {
|
||||
(0..DAYS_PER_WEEK).filter(move |id| self.0 & (1 << id) != 0)
|
||||
}
|
||||
|
||||
fn sieve_keys(self) -> impl Iterator<Item = u16> {
|
||||
self.ids().map(|id| (id + 1) % DAYS_PER_WEEK)
|
||||
}
|
||||
|
||||
fn days(self) -> Map<Weekday> {
|
||||
Map::new(self.ids().filter_map(Weekday::from_id).collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ManagedScript {
|
||||
pub rules: Vec<ManagedRule>,
|
||||
pub blocked_senders: SenderList,
|
||||
pub safe_senders: SenderList,
|
||||
pub vacation: Option<VacationResponse>,
|
||||
pub last_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SenderListKind {
|
||||
Blocked,
|
||||
Safe,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct SenderList(Vec<SenderEntry>);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SenderEntry {
|
||||
pub id: u64,
|
||||
pub entry: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ForwarderId(u64);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ManagedRule {
|
||||
pub id: u64,
|
||||
pub rule: MailRule,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct VacationResponse {
|
||||
pub is_enabled: bool,
|
||||
pub from_date: Option<u64>,
|
||||
pub to_date: Option<u64>,
|
||||
pub subject: Option<String>,
|
||||
pub text_body: Option<String>,
|
||||
pub html_body: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) struct ScriptVars {
|
||||
pub(crate) away: bool,
|
||||
pub(crate) keywords: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RuleError {
|
||||
InvalidEntry(String),
|
||||
InvalidHeaderName(String),
|
||||
InvalidKeyword(String),
|
||||
ConflictingKeyword(String),
|
||||
InvalidDomain(String),
|
||||
AddressTooLong,
|
||||
InvalidSize(u64),
|
||||
InvalidDate(i64),
|
||||
InvalidSchedule,
|
||||
RejectNotAlone,
|
||||
EntryExists(u64),
|
||||
EntryIdTaken,
|
||||
TooManyEntries,
|
||||
NotFound(u64),
|
||||
Empty(&'static str),
|
||||
Compile(String),
|
||||
Decode(DecodeError),
|
||||
TooManyInstructions { instructions: usize, limit: usize },
|
||||
}
|
||||
|
||||
pub fn is_managed_script(name: &str) -> bool {
|
||||
name.eq_ignore_ascii_case(MANAGED_SCRIPT_NAME)
|
||||
}
|
||||
|
||||
impl ManagedScript {
|
||||
pub fn runs_anything(&self) -> bool {
|
||||
self.rules.iter().any(|rule| rule.rule.is_enabled)
|
||||
|| !self.blocked_senders.is_empty()
|
||||
|| !self.safe_senders.is_empty()
|
||||
|| self.vacation.as_ref().is_some_and(|v| v.is_enabled)
|
||||
}
|
||||
|
||||
pub fn uses_account_zone(&self) -> bool {
|
||||
self.rules
|
||||
.iter()
|
||||
.flat_map(ManagedRule::conditions)
|
||||
.any(|condition| {
|
||||
matches!(
|
||||
condition,
|
||||
MailRuleCondition::Schedule(schedule) if schedule.time_zone.is_none()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn senders(&self, kind: SenderListKind) -> &SenderList {
|
||||
match kind {
|
||||
SenderListKind::Blocked => &self.blocked_senders,
|
||||
SenderListKind::Safe => &self.safe_senders,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_senders(self, kind: SenderListKind) -> SenderList {
|
||||
match kind {
|
||||
SenderListKind::Blocked => self.blocked_senders,
|
||||
SenderListKind::Safe => self.safe_senders,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn senders_mut(&mut self, kind: SenderListKind) -> &mut SenderList {
|
||||
match kind {
|
||||
SenderListKind::Blocked => &mut self.blocked_senders,
|
||||
SenderListKind::Safe => &mut self.safe_senders,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_id(&self) -> u64 {
|
||||
self.max_rule_id().max(self.last_id) + 1
|
||||
}
|
||||
|
||||
pub(crate) fn vars(&self) -> ScriptVars {
|
||||
let mut vars = ScriptVars::default();
|
||||
for rule in &self.rules {
|
||||
vars.keywords |= rule.rule.actions.clear_keywords;
|
||||
for condition in rule.conditions() {
|
||||
vars.away |= matches!(condition, MailRuleCondition::IsAway);
|
||||
vars.keywords |= matches!(condition, MailRuleCondition::AnyKeyword);
|
||||
}
|
||||
}
|
||||
vars
|
||||
}
|
||||
|
||||
pub(crate) fn max_rule_id(&self) -> u64 {
|
||||
self.rules.iter().map(|rule| rule.id).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn rule(&self, id: u64) -> Option<&ManagedRule> {
|
||||
self.rules.iter().find(|rule| rule.id == id)
|
||||
}
|
||||
|
||||
pub fn upsert(&mut self, mut rule: ManagedRule) -> Result<(), RuleError> {
|
||||
rule.canonicalize()?;
|
||||
self.last_id = self.last_id.max(rule.id);
|
||||
if let Some(existing) = self.rules.iter_mut().find(|other| other.id == rule.id) {
|
||||
*existing = rule;
|
||||
} else {
|
||||
self.rules.push(rule);
|
||||
}
|
||||
self.sort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, id: u64) -> Result<ManagedRule, RuleError> {
|
||||
self.rules
|
||||
.iter()
|
||||
.position(|rule| rule.id == id)
|
||||
.map(|idx| self.rules.remove(idx))
|
||||
.ok_or(RuleError::NotFound(id))
|
||||
}
|
||||
|
||||
pub fn set_vacation(&mut self, mut vacation: VacationResponse) {
|
||||
vacation.canonicalize();
|
||||
self.vacation = Some(vacation);
|
||||
}
|
||||
|
||||
pub(crate) fn sort(&mut self) {
|
||||
self.rules
|
||||
.sort_unstable_by_key(|rule| (rule.rule.position, rule.id));
|
||||
}
|
||||
}
|
||||
|
||||
impl ManagedRule {
|
||||
pub fn canonicalize(&mut self) -> Result<(), RuleError> {
|
||||
canonicalize_rule(&mut self.rule)
|
||||
}
|
||||
|
||||
pub(crate) fn conditions(&self) -> impl Iterator<Item = &MailRuleCondition> {
|
||||
let conditions = &self.rule.conditions;
|
||||
conditions
|
||||
.match_all
|
||||
.iter()
|
||||
.chain(conditions.match_any.iter())
|
||||
.chain(conditions.match_none.iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl SenderList {
|
||||
pub fn entry_id(entry: &str) -> u64 {
|
||||
blake3::hash(entry.as_bytes())
|
||||
.as_bytes()
|
||||
.first_chunk()
|
||||
.map_or(0, |bytes| u64::from_be_bytes(*bytes) >> 1)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> impl Iterator<Item = &SenderEntry> {
|
||||
self.0.iter()
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, entry: &str) -> Result<u64, RuleError> {
|
||||
let mut entry = entry.trim().to_lowercase();
|
||||
strip_line_breaks(&mut entry);
|
||||
validate_list_entry(&entry)?;
|
||||
let id = Self::entry_id(&entry);
|
||||
let idx = match self
|
||||
.0
|
||||
.binary_search_by(|other| other.entry.as_str().cmp(&entry))
|
||||
{
|
||||
Ok(_) => return Err(RuleError::EntryExists(id)),
|
||||
Err(idx) => idx,
|
||||
};
|
||||
if self.0.len() >= MAX_SENDER_ENTRIES {
|
||||
return Err(RuleError::TooManyEntries);
|
||||
}
|
||||
if self.0.iter().any(|other| other.id == id) {
|
||||
return Err(RuleError::EntryIdTaken);
|
||||
}
|
||||
self.0.insert(idx, SenderEntry { id, entry });
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, id: u64) -> Option<SenderEntry> {
|
||||
self.0
|
||||
.iter()
|
||||
.position(|entry| entry.id == id)
|
||||
.map(|idx| self.0.remove(idx))
|
||||
}
|
||||
|
||||
pub(crate) fn addresses(&self) -> impl Iterator<Item = &str> {
|
||||
self.0
|
||||
.iter()
|
||||
.map(|entry| entry.entry.as_str())
|
||||
.filter(|entry| !entry.starts_with('@'))
|
||||
}
|
||||
|
||||
pub(crate) fn domains(&self) -> impl Iterator<Item = &str> {
|
||||
self.0
|
||||
.iter()
|
||||
.filter_map(|entry| entry.entry.strip_prefix('@'))
|
||||
}
|
||||
|
||||
pub(crate) fn push_decoded(&mut self, entry: String) {
|
||||
self.0.push(SenderEntry {
|
||||
id: Self::entry_id(&entry),
|
||||
entry,
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn finish_decoded(&mut self) -> bool {
|
||||
self.0.sort_unstable_by(|a, b| a.entry.cmp(&b.entry));
|
||||
self.0.len() <= MAX_SENDER_ENTRIES
|
||||
&& self
|
||||
.0
|
||||
.windows(2)
|
||||
.all(|pair| matches!(pair, [a, b] if a.entry != b.entry))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoIterator for SenderList {
|
||||
type Item = SenderEntry;
|
||||
type IntoIter = std::vec::IntoIter<SenderEntry>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.0.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl ForwarderId {
|
||||
pub fn new(secret: &[u8], account_id: u32) -> Self {
|
||||
let mut hasher = blake3::Hasher::new_derive_key(FORWARDER_ID_CONTEXT);
|
||||
hasher.update(secret);
|
||||
hasher.update(&account_id.to_be_bytes());
|
||||
ForwarderId(
|
||||
hasher
|
||||
.finalize()
|
||||
.as_bytes()
|
||||
.first_chunk()
|
||||
.map_or(0, |bytes| u64::from_be_bytes(*bytes)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ForwarderId {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{:016x}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl VacationResponse {
|
||||
pub fn canonicalize(&mut self) {
|
||||
if let Some(subject) = &mut self.subject {
|
||||
strip_line_breaks(subject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn canonicalize_rule(rule: &mut MailRule) -> Result<(), RuleError> {
|
||||
canonicalize_line(&mut rule.name, "name")?;
|
||||
let MailRuleConditions {
|
||||
match_all,
|
||||
match_any,
|
||||
match_none,
|
||||
} = &mut rule.conditions;
|
||||
for list in [match_all, match_any, match_none] {
|
||||
*list = std::mem::take(list)
|
||||
.into_iter()
|
||||
.map(canonicalize_condition)
|
||||
.collect::<Result<List<_>, _>>()?;
|
||||
}
|
||||
canonicalize_actions(&mut rule.actions)
|
||||
}
|
||||
|
||||
fn canonicalize_condition(condition: MailRuleCondition) -> Result<MailRuleCondition, RuleError> {
|
||||
Ok(match condition {
|
||||
MailRuleCondition::From(mut test) => {
|
||||
canonicalize_address_test(&mut test.operator, &mut test.values)?;
|
||||
MailRuleCondition::From(test)
|
||||
}
|
||||
MailRuleCondition::To(mut test) => {
|
||||
canonicalize_address_test(&mut test.operator, &mut test.values)?;
|
||||
MailRuleCondition::To(test)
|
||||
}
|
||||
MailRuleCondition::Cc(mut test) => {
|
||||
canonicalize_address_test(&mut test.operator, &mut test.values)?;
|
||||
MailRuleCondition::Cc(test)
|
||||
}
|
||||
MailRuleCondition::ToOrCc(mut test) => {
|
||||
canonicalize_address_test(&mut test.operator, &mut test.values)?;
|
||||
MailRuleCondition::ToOrCc(test)
|
||||
}
|
||||
MailRuleCondition::Subject(mut test) => {
|
||||
canonicalize_values(&mut test.values)?;
|
||||
MailRuleCondition::Subject(test)
|
||||
}
|
||||
MailRuleCondition::Body(mut test) => {
|
||||
canonicalize_values(&mut test.values)?;
|
||||
MailRuleCondition::Body(test)
|
||||
}
|
||||
MailRuleCondition::Header(mut test) => {
|
||||
canonicalize_header_name(&mut test.header)?;
|
||||
canonicalize_values(&mut test.values)?;
|
||||
if test.header == "subject" {
|
||||
MailRuleCondition::Subject(MailRuleTextTest {
|
||||
operator: test.operator,
|
||||
values: test.values,
|
||||
})
|
||||
} else if let (true, MailRuleTextOperator::Is, [value]) = (
|
||||
test.header == "sensitivity",
|
||||
test.operator,
|
||||
test.values.as_slice(),
|
||||
) && let Some(level) = sensitivity_level(value)
|
||||
{
|
||||
MailRuleCondition::Sensitivity(MailRuleSensitivity { level })
|
||||
} else if test.header == VOICEMAIL_HEADER
|
||||
&& test.operator == MailRuleTextOperator::Is
|
||||
&& test.values.len() == VOICEMAIL_CLASSES.len()
|
||||
&& VOICEMAIL_CLASSES.iter().all(|class| {
|
||||
test.values
|
||||
.iter()
|
||||
.any(|value| value.eq_ignore_ascii_case(class))
|
||||
})
|
||||
{
|
||||
MailRuleCondition::MessageType(MailRuleMessageType {
|
||||
kind: MailRuleMessageKind::Voicemail,
|
||||
})
|
||||
} else if test.header == AUTO_SUBMITTED_HEADER
|
||||
&& test.operator == MailRuleTextOperator::Matches
|
||||
&& matches!(test.values.as_slice(), [value] if value == AUTO_SUBMITTED_PATTERN)
|
||||
{
|
||||
MailRuleCondition::MessageType(MailRuleMessageType {
|
||||
kind: MailRuleMessageKind::AutomaticReply,
|
||||
})
|
||||
} else {
|
||||
MailRuleCondition::Header(test)
|
||||
}
|
||||
}
|
||||
MailRuleCondition::HeaderExists(mut header) => {
|
||||
canonicalize_header_name(&mut header.header)?;
|
||||
MailRuleCondition::HeaderExists(header)
|
||||
}
|
||||
MailRuleCondition::AttachmentName(mut test) => {
|
||||
canonicalize_values(&mut test.values)?;
|
||||
MailRuleCondition::AttachmentName(test)
|
||||
}
|
||||
MailRuleCondition::AttachmentType(mut test) => {
|
||||
canonicalize_values(&mut test.values)?;
|
||||
MailRuleCondition::AttachmentType(test)
|
||||
}
|
||||
MailRuleCondition::RecipientAddress(mut test) => {
|
||||
canonicalize_address_test(&mut test.operator, &mut test.values)?;
|
||||
MailRuleCondition::RecipientAddress(test)
|
||||
}
|
||||
MailRuleCondition::RecipientDetail(mut test) => {
|
||||
canonicalize_values(&mut test.values)?;
|
||||
MailRuleCondition::RecipientDetail(test)
|
||||
}
|
||||
MailRuleCondition::SubjectOrBody(mut test) => {
|
||||
canonicalize_values(&mut test.values)?;
|
||||
MailRuleCondition::SubjectOrBody(test)
|
||||
}
|
||||
MailRuleCondition::ReceivedAfter(date) | MailRuleCondition::ReceivedBefore(date)
|
||||
if !(0..=MAX_TIMESTAMP).contains(&date.date.timestamp()) =>
|
||||
{
|
||||
return Err(RuleError::InvalidDate(date.date.timestamp()));
|
||||
}
|
||||
MailRuleCondition::Schedule(mut schedule) => {
|
||||
canonicalize_schedule(&mut schedule)?;
|
||||
MailRuleCondition::Schedule(schedule)
|
||||
}
|
||||
MailRuleCondition::SizeOver(size) | MailRuleCondition::SizeUnder(size)
|
||||
if size.kilobytes == 0 || size.kilobytes > MAX_SIZE_KB =>
|
||||
{
|
||||
return Err(RuleError::InvalidSize(size.kilobytes));
|
||||
}
|
||||
MailRuleCondition::Keyword(mut test) => {
|
||||
canonicalize_keywords(&mut test.keywords)?;
|
||||
if test.keywords.is_empty() {
|
||||
return Err(RuleError::Empty("keywords"));
|
||||
}
|
||||
MailRuleCondition::Keyword(test)
|
||||
}
|
||||
condition => condition,
|
||||
})
|
||||
}
|
||||
|
||||
fn canonicalize_actions(actions: &mut MailRuleActions) -> Result<(), RuleError> {
|
||||
let MailRuleActions {
|
||||
add_keywords,
|
||||
remove_keywords,
|
||||
clear_keywords,
|
||||
set_importance,
|
||||
redirect,
|
||||
reply,
|
||||
copy_to,
|
||||
move_to,
|
||||
discard,
|
||||
reject,
|
||||
stop_processing,
|
||||
} = actions;
|
||||
canonicalize_keywords(add_keywords)?;
|
||||
canonicalize_keywords(remove_keywords)?;
|
||||
if let Some(keyword) = remove_keywords
|
||||
.iter()
|
||||
.find(|keyword| add_keywords.contains(keyword))
|
||||
{
|
||||
return Err(RuleError::ConflictingKeyword(keyword.clone()));
|
||||
}
|
||||
if let Some(redirect) = redirect {
|
||||
canonicalize_values(&mut redirect.addresses)?;
|
||||
check_address_lengths(&redirect.addresses)?;
|
||||
if redirect.addresses.is_empty() {
|
||||
return Err(RuleError::Empty("redirect addresses"));
|
||||
}
|
||||
}
|
||||
if let Some(subject) = reply.as_mut().and_then(|reply| reply.subject.as_mut()) {
|
||||
canonicalize_line(subject, "reply subject")?;
|
||||
}
|
||||
canonicalize_mailboxes(copy_to)?;
|
||||
canonicalize_mailboxes(move_to)?;
|
||||
move_to
|
||||
.inner_mut()
|
||||
.sort_by_key(|id| id.document_id() == JUNK_ID);
|
||||
|
||||
let has_other_action = *clear_keywords
|
||||
|| !add_keywords.is_empty()
|
||||
|| !remove_keywords.is_empty()
|
||||
|| set_importance.is_some()
|
||||
|| redirect.is_some()
|
||||
|| reply.is_some()
|
||||
|| !copy_to.is_empty()
|
||||
|| !move_to.is_empty()
|
||||
|| *discard;
|
||||
if let Some(reject) = reject {
|
||||
if has_other_action {
|
||||
return Err(RuleError::RejectNotAlone);
|
||||
}
|
||||
canonicalize_line(&mut reject.reason, "reject reason")?;
|
||||
*stop_processing = true;
|
||||
} else if !has_other_action && !*stop_processing {
|
||||
return Err(RuleError::Empty("actions"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn canonicalize_set<T: MapItem>(
|
||||
set: &mut Map<T>,
|
||||
mut canonicalize: impl FnMut(T) -> Result<T, RuleError>,
|
||||
) -> Result<(), RuleError> {
|
||||
let items = std::mem::take(set.inner_mut());
|
||||
set.inner_mut().reserve_exact(items.len());
|
||||
for item in items {
|
||||
set.push(canonicalize(item)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn canonicalize_mailboxes(mailboxes: &mut Map<Id>) -> Result<(), RuleError> {
|
||||
canonicalize_set(mailboxes, |id| Ok(Id::from(id.document_id())))
|
||||
}
|
||||
|
||||
fn canonicalize_keywords(keywords: &mut Map<String>) -> Result<(), RuleError> {
|
||||
canonicalize_set(keywords, canonical_keyword)
|
||||
}
|
||||
|
||||
pub fn canonical_keyword(mut keyword: String) -> Result<String, RuleError> {
|
||||
strip_line_breaks(&mut keyword);
|
||||
match Keyword::try_parse(&keyword) {
|
||||
Some(system) if keyword != system.as_str() => Ok(system.as_str().to_string()),
|
||||
Some(_) => Ok(keyword),
|
||||
None if Keyword::is_valid_jmap_name(&keyword) => {
|
||||
keyword.make_ascii_lowercase();
|
||||
Ok(keyword)
|
||||
}
|
||||
None => Err(RuleError::InvalidKeyword(keyword)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_custom_keyword(keyword: &str) -> bool {
|
||||
Keyword::try_parse(keyword).is_none()
|
||||
}
|
||||
|
||||
fn canonicalize_schedule(schedule: &mut MailRuleSchedule) -> Result<(), RuleError> {
|
||||
if schedule.slots.is_empty() {
|
||||
return Err(RuleError::Empty("schedule slots"));
|
||||
}
|
||||
if schedule.slots.len() > MAX_SCHEDULE_SLOTS {
|
||||
return Err(RuleError::InvalidSchedule);
|
||||
}
|
||||
schedule.slots = std::mem::take(&mut schedule.slots).into_iter().collect();
|
||||
for slot in schedule.slots.values_mut() {
|
||||
let days = slot.days.inner_mut();
|
||||
days.sort_unstable_by_key(EnumImpl::to_id);
|
||||
days.dedup();
|
||||
if days.is_empty() {
|
||||
return Err(RuleError::Empty("schedule days"));
|
||||
}
|
||||
if slot.end.minutes() == 0 {
|
||||
slot.end = LocalTime::from_minutes(MINUTES_PER_DAY);
|
||||
}
|
||||
let (start, end) = (slot.start.minutes(), slot.end.minutes());
|
||||
if start >= MINUTES_PER_DAY || end > MINUTES_PER_DAY || start == end {
|
||||
return Err(RuleError::InvalidSchedule);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn canonicalize_header_name(header: &mut String) -> Result<(), RuleError> {
|
||||
header.make_ascii_lowercase();
|
||||
if !header.is_empty()
|
||||
&& header
|
||||
.bytes()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, b'-' | b'_' | b'.'))
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RuleError::InvalidHeaderName(std::mem::take(header)))
|
||||
}
|
||||
}
|
||||
|
||||
fn canonicalize_address_test(
|
||||
operator: &mut MailRuleAddressOperator,
|
||||
values: &mut Map<String>,
|
||||
) -> Result<(), RuleError> {
|
||||
canonicalize_values(values)?;
|
||||
check_address_lengths(values)?;
|
||||
if *operator == MailRuleAddressOperator::Domain {
|
||||
canonicalize_set(values, |domain| {
|
||||
let domain = domain.trim().trim_start_matches('@').to_ascii_lowercase();
|
||||
validate_domain(&domain)?;
|
||||
Ok(domain)
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_address_lengths(values: &Map<String>) -> Result<(), RuleError> {
|
||||
if values
|
||||
.iter()
|
||||
.all(|value| value.len() <= MAX_ADDRESS_VALUE_LEN)
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RuleError::AddressTooLong)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn active_redirects(rule: &MailRule) -> Option<&MailRuleRedirect> {
|
||||
rule.actions.redirect.as_ref().filter(|_| rule.is_enabled)
|
||||
}
|
||||
|
||||
pub fn is_same_redirects(
|
||||
left: Option<&MailRuleRedirect>,
|
||||
right: Option<&MailRuleRedirect>,
|
||||
) -> bool {
|
||||
match (left, right) {
|
||||
(Some(left), Some(right)) => {
|
||||
left.keep_copy == right.keep_copy
|
||||
&& is_same_addresses(left.addresses.as_slice(), right.addresses.as_slice())
|
||||
}
|
||||
(left, right) => left.is_none() && right.is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_same_addresses(left: &[String], right: &[String]) -> bool {
|
||||
let covers = |outer: &[String], inner: &[String]| {
|
||||
inner.iter().all(|address| {
|
||||
outer
|
||||
.iter()
|
||||
.any(|other| other.eq_ignore_ascii_case(address))
|
||||
})
|
||||
};
|
||||
left.len() == right.len() && covers(left, right) && covers(right, left)
|
||||
}
|
||||
|
||||
pub(crate) fn sensitivity_level(value: &str) -> Option<MailRuleSensitivityLevel> {
|
||||
hashify::map!(
|
||||
value.as_bytes(),
|
||||
MailRuleSensitivityLevel,
|
||||
"personal" => MailRuleSensitivityLevel::Personal,
|
||||
"private" => MailRuleSensitivityLevel::Private,
|
||||
"company-confidential" => MailRuleSensitivityLevel::Confidential,
|
||||
)
|
||||
.copied()
|
||||
}
|
||||
|
||||
fn canonicalize_values(values: &mut Map<String>) -> Result<(), RuleError> {
|
||||
canonicalize_set(values, |mut value| {
|
||||
strip_line_breaks(&mut value);
|
||||
if value.is_empty() {
|
||||
Err(RuleError::Empty("values"))
|
||||
} else {
|
||||
Ok(value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn canonicalize_line(value: &mut String, what: &'static str) -> Result<(), RuleError> {
|
||||
if value.contains(['\r', '\n']) {
|
||||
strip_line_breaks(value);
|
||||
if value.is_empty() {
|
||||
return Err(RuleError::Empty(what));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn strip_line_breaks(value: &mut String) {
|
||||
if value.contains(['\r', '\n']) {
|
||||
value.retain(|ch| !matches!(ch, '\r' | '\n'));
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_list_entry(entry: &str) -> Result<(), RuleError> {
|
||||
let is_valid = !entry.contains(|ch: char| ch.is_whitespace() || ch.is_control())
|
||||
&& match entry.strip_prefix('@') {
|
||||
Some(domain) => validate_domain(domain).is_ok(),
|
||||
None => entry
|
||||
.rsplit_once('@')
|
||||
.is_some_and(|(local, domain)| !local.is_empty() && !domain.is_empty()),
|
||||
};
|
||||
if is_valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RuleError::InvalidEntry(entry.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_domain(domain: &str) -> Result<(), RuleError> {
|
||||
if !domain.is_empty()
|
||||
&& !domain
|
||||
.bytes()
|
||||
.any(|ch| matches!(ch, b'*' | b'?' | b'\\' | b'@') || ch.is_ascii_whitespace())
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RuleError::InvalidDomain(domain.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for RuleError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
RuleError::InvalidEntry(entry) => write!(
|
||||
f,
|
||||
"Invalid entry {entry:?}: use an email address or a domain written as @example.org."
|
||||
),
|
||||
RuleError::InvalidHeaderName(name) => write!(f, "Invalid header name {name:?}."),
|
||||
RuleError::InvalidKeyword(keyword) => write!(f, "Invalid keyword {keyword:?}."),
|
||||
RuleError::ConflictingKeyword(keyword) => write!(
|
||||
f,
|
||||
"The keyword {keyword:?} cannot be both added and removed."
|
||||
),
|
||||
RuleError::InvalidDomain(domain) => write!(f, "Invalid domain {domain:?}."),
|
||||
RuleError::AddressTooLong => write!(
|
||||
f,
|
||||
"An address value is too long: use at most {MAX_ADDRESS_VALUE_LEN} bytes."
|
||||
),
|
||||
RuleError::InvalidSize(size) => {
|
||||
write!(f, "Invalid size {size}: use 1 to {MAX_SIZE_KB} kilobytes.")
|
||||
}
|
||||
RuleError::InvalidDate(timestamp) => {
|
||||
write!(
|
||||
f,
|
||||
"Invalid date {timestamp}: use a date between 1970 and 3000."
|
||||
)
|
||||
}
|
||||
RuleError::InvalidSchedule => write!(
|
||||
f,
|
||||
"Invalid schedule: use at most {MAX_SCHEDULE_SLOTS} slots per condition, each starting before 24:00 and ending at a different time."
|
||||
),
|
||||
RuleError::RejectNotAlone => {
|
||||
write!(f, "A rule that rejects mail cannot have other actions.")
|
||||
}
|
||||
RuleError::EntryExists(_) => write!(f, "The entry is already in the list."),
|
||||
RuleError::EntryIdTaken => write!(
|
||||
f,
|
||||
"The entry cannot be added because its identifier is taken, remove a similar entry first."
|
||||
),
|
||||
RuleError::TooManyEntries => {
|
||||
write!(
|
||||
f,
|
||||
"The list cannot have more than {MAX_SENDER_ENTRIES} entries."
|
||||
)
|
||||
}
|
||||
RuleError::NotFound(id) => write!(f, "Rule {id} not found."),
|
||||
RuleError::Empty(what) => write!(f, "The rule {what} must not be empty."),
|
||||
RuleError::Compile(err) => write!(f, "The rules script failed to compile: {err}."),
|
||||
RuleError::Decode(err) => write!(f, "The rules cannot be stored: {err}."),
|
||||
RuleError::TooManyInstructions {
|
||||
instructions,
|
||||
limit,
|
||||
} => write!(
|
||||
f,
|
||||
"The rules script has {instructions} instructions, above the limit of {limit} (maxCpuCycles)."
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../../stalwart-tests/unit/email/src/sieve/rules/tests/mod.rs"]
|
||||
mod tests;
|
||||
41
crates/exchange-proto/Cargo.toml
Normal file
41
crates/exchange-proto/Cargo.toml
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
[package]
|
||||
name = "exchange-proto"
|
||||
description = "EWS, Autodiscover, Exchange ActiveSync and MAPI over HTTP protocol codecs"
|
||||
version = "1.2.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
ahash = "0.8.12"
|
||||
ammonia = "4.2.4"
|
||||
arrayvec = "0.7"
|
||||
bytes = "1"
|
||||
calcard = { path = "../calcard", optional = true }
|
||||
compact_str = "0.10.0"
|
||||
crc32fast = "1.5"
|
||||
encodify = "1.0"
|
||||
hashbrown = "0.17.1"
|
||||
hashify = "0.3"
|
||||
html5ever = "0.40"
|
||||
jiff = { version = "0.2.38", optional = true }
|
||||
mail-builder = { version = "2.0", optional = true }
|
||||
mail-parser = { version = "1.0", features = ["full_encoding"], optional = true }
|
||||
memchr = "2.8.3"
|
||||
quick-xml = "0.42"
|
||||
roaring = "0.11"
|
||||
simdutf8 = "0.1.5"
|
||||
smallvec = { version = "1.16", features = ["union"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
sieve-rs = { path = "../sieve" }
|
||||
zstd = { version = "0.14", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["convert"]
|
||||
convert = ["dep:mail-parser", "dep:mail-builder", "dep:calcard", "dep:jiff"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
66
crates/exchange-proto/src/autodiscover/headers.rs
Normal file
66
crates/exchange-proto/src/autodiscover/headers.rs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
const OFFICE_PRODUCT: &[u8] = b"Microsoft Office/";
|
||||
const MAPI_HTTP_MIN_OFFICE_MAJOR: u32 = 16;
|
||||
const MAX_DECIMAL_DIGITS: usize = 10;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct MapiHttpCapability(pub NonZeroU32);
|
||||
|
||||
impl MapiHttpCapability {
|
||||
pub fn parse(value: Option<&[u8]>) -> Option<Self> {
|
||||
parse_decimal(value?.trim_ascii())
|
||||
.and_then(NonZeroU32::new)
|
||||
.map(MapiHttpCapability)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct ClientCanHandle {
|
||||
pub negotiate: bool,
|
||||
pub ex_http_info: bool,
|
||||
}
|
||||
|
||||
impl ClientCanHandle {
|
||||
pub fn parse(value: Option<&[u8]>) -> Self {
|
||||
let mut result = ClientCanHandle::default();
|
||||
for item in value.unwrap_or_default().split(|&ch| ch == b',') {
|
||||
hashify::fnc_map_ignore_case!(item.trim_ascii(),
|
||||
"Negotiate" => { result.negotiate = true; },
|
||||
"ExHttpInfo" => { result.ex_http_info = true; },
|
||||
_ => {}
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn user_agent_is_mapi_http_outlook(ua: &[u8]) -> bool {
|
||||
memchr::memmem::find(ua, OFFICE_PRODUCT)
|
||||
.and_then(|pos| ua.get(pos + OFFICE_PRODUCT.len()..))
|
||||
.and_then(|version| {
|
||||
let digits = version.iter().take_while(|ch| ch.is_ascii_digit()).count();
|
||||
version.get(..digits)
|
||||
})
|
||||
.and_then(parse_decimal)
|
||||
.is_some_and(|major| major >= MAPI_HTTP_MIN_OFFICE_MAJOR)
|
||||
}
|
||||
|
||||
fn parse_decimal(digits: &[u8]) -> Option<u32> {
|
||||
if digits.is_empty() || digits.len() > MAX_DECIMAL_DIGITS {
|
||||
return None;
|
||||
}
|
||||
digits.iter().try_fold(0u32, |acc, &ch| {
|
||||
if ch.is_ascii_digit() {
|
||||
acc.checked_mul(10)?.checked_add(u32::from(ch - b'0'))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
107
crates/exchange-proto/src/autodiscover/mobilesync.rs
Normal file
107
crates/exchange-proto/src/autodiscover/mobilesync.rs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::pox::write::{begin_document, close, line, newline, open, open_ns};
|
||||
use crate::xml::{Ns, XmlWriter};
|
||||
use smallvec::SmallVec;
|
||||
use std::{borrow::Cow, iter};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MobileSyncResponse<'x> {
|
||||
pub culture: &'static str,
|
||||
pub display_name: Option<Cow<'x, str>>,
|
||||
pub email: Cow<'x, str>,
|
||||
pub action: MobileSyncAction<'x>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MobileSyncAction<'x> {
|
||||
Redirect(Cow<'x, str>),
|
||||
Settings {
|
||||
server: MobileServer<'x>,
|
||||
more_servers: SmallVec<[MobileServer<'x>; 1]>,
|
||||
},
|
||||
Error {
|
||||
status: u8,
|
||||
message: Cow<'x, str>,
|
||||
debug_data: Cow<'x, str>,
|
||||
error_code: u32,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MobileServer<'x> {
|
||||
MobileSync {
|
||||
url: Cow<'x, str>,
|
||||
},
|
||||
CertEnroll {
|
||||
url: Cow<'x, str>,
|
||||
server_data: Option<Cow<'x, str>>,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn write_mobilesync_response(out: &mut Vec<u8>, resp: &MobileSyncResponse<'_>) {
|
||||
let mut w = XmlWriter::new(out);
|
||||
begin_document(&mut w);
|
||||
open_ns(&mut w, "Response", Ns::AdResponseMobile);
|
||||
line(&mut w, "Culture", resp.culture);
|
||||
open(&mut w, "User");
|
||||
if let Some(display_name) = &resp.display_name {
|
||||
line(&mut w, "DisplayName", display_name);
|
||||
}
|
||||
line(&mut w, "EMailAddress", &resp.email);
|
||||
close(&mut w, "User");
|
||||
|
||||
open(&mut w, "Action");
|
||||
match &resp.action {
|
||||
MobileSyncAction::Redirect(address) => line(&mut w, "Redirect", address),
|
||||
MobileSyncAction::Settings {
|
||||
server,
|
||||
more_servers,
|
||||
} => {
|
||||
open(&mut w, "Settings");
|
||||
for server in iter::once(server).chain(more_servers) {
|
||||
open(&mut w, "Server");
|
||||
match server {
|
||||
MobileServer::MobileSync { url } => {
|
||||
line(&mut w, "Type", "MobileSync");
|
||||
line(&mut w, "Url", url);
|
||||
line(&mut w, "Name", url);
|
||||
}
|
||||
MobileServer::CertEnroll { url, server_data } => {
|
||||
line(&mut w, "Type", "CertEnroll");
|
||||
line(&mut w, "Url", url);
|
||||
w.empty_leaf("", "Name");
|
||||
newline(&mut w);
|
||||
if let Some(server_data) = server_data {
|
||||
line(&mut w, "ServerData", server_data);
|
||||
}
|
||||
}
|
||||
}
|
||||
close(&mut w, "Server");
|
||||
}
|
||||
close(&mut w, "Settings");
|
||||
}
|
||||
MobileSyncAction::Error {
|
||||
status,
|
||||
message,
|
||||
debug_data,
|
||||
error_code,
|
||||
} => {
|
||||
open(&mut w, "Error");
|
||||
w.leaf_u64("", "Status", u64::from(*status));
|
||||
newline(&mut w);
|
||||
line(&mut w, "Message", message);
|
||||
line(&mut w, "DebugData", debug_data);
|
||||
w.leaf_u64("", "ErrorCode", u64::from(*error_code));
|
||||
newline(&mut w);
|
||||
close(&mut w, "Error");
|
||||
}
|
||||
}
|
||||
close(&mut w, "Action");
|
||||
close(&mut w, "Response");
|
||||
close(&mut w, "Autodiscover");
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue