- Rust 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
Drop the "moved" banner. Add a recorded memstore session, a quick start that actually compiles against the current API (Server::new/with_defaults, listen_tls), and honest support/limits tables: STARTTLS stub, ENVELOPE/BODYSTRUCTURE not returned, MIME part paths, literal cap behaviour. |
||
| imap-core | ||
| imap-server | ||
| .gitignore | ||
| Cargo.lock | ||
| Cargo.toml | ||
| LICENSE | ||
| README.md | ||
imap-rs
An IMAP4rev1 server library for Tokio. You supply the mail storage, and imap-rs handles the protocol.
Quick start · Writing a backend · Protocol support · Limits · Building
imap-rs is a port of the server half of go-imap v2. It has two crates:
| Crate | What it does | Depends on |
|---|---|---|
imap-core |
Protocol types and a hand-written wire codec | tokio only |
imap-server |
Connection state machine and the Backend / UserSession traits |
imap-core, tokio-rustls, async-trait, tracing |
It was written for yggmail-ng, and its regression tests replay the request patterns of real clients (DeltaChat, Tyr).
A real session
The repository includes an in-memory server with five messages in INBOX:
$ cargo run --example memstore
Starting in-memory IMAP server on 127.0.0.1:11443
Here is what a client sees. C: lines are sent by the client and S: lines come
from the server (recorded from the example above, unedited):
S: * OK [CAPABILITY CHILDREN ENABLE ID IDLE IMAP4rev1 LITERAL+ MOVE NAMESPACE SASL-IR UIDPLUS UNSELECT] IMAP server ready
C: a1 LOGIN alice secret
S: a1 OK [CAPABILITY CHILDREN ENABLE ID IDLE IMAP4rev1 LITERAL+ MOVE NAMESPACE SASL-IR UIDPLUS UNSELECT] Logged in
C: a2 SELECT INBOX
S: * 5 EXISTS
S: * 0 RECENT
S: * OK [UNSEEN 1] Message(s) unseen
S: * OK [UIDVALIDITY 1] UIDs valid
S: * OK [UIDNEXT 6] Predicted next UID
S: * FLAGS (\Seen \Answered \Flagged \Deleted \Draft \Recent)
S: * OK [PERMANENTFLAGS (\Seen \Answered \Flagged \Deleted \Draft)] Permanent flags
S: a2 OK [READ-WRITE] SELECT completed
C: a3 UID FETCH 1:2 (FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT)])
S: * 1 FETCH (FLAGS () UID 1 BODY[HEADER.FIELDS (SUBJECT)] {27}
S: Subject: Test Message 1
S:
S: )
S: * 2 FETCH (FLAGS (\Seen) UID 2 BODY[HEADER.FIELDS (SUBJECT)] {27}
S: Subject: Test Message 2
S:
S: )
S: a3 OK FETCH completed
C: a4 LOGOUT
S: * BYE Logging out
S: a4 OK LOGOUT completed
The server answers a BODY.PEEK[...] request with BODY[...], as RFC 3501
§7.4.2 requires. Some clients silently drop messages when this is wrong.
Quick start
imap-rs is not on crates.io. Depend on it from git:
[dependencies]
imap-server = { git = "https://git.shd.company/bubblegum/imap-rs" }
imap-core = { git = "https://git.shd.company/bubblegum/imap-rs" }
tokio = { version = "1", features = ["full"] }
rustls = "0.23"
Serve implicit TLS on port 993:
use std::sync::Arc;
use imap_server::Server;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tls: Arc<rustls::ServerConfig> = load_certs()?; // your rustls config
Server::with_defaults(MyBackend::new())
.listen_tls("0.0.0.0:993", tls)
.await
}
Plaintext LOGIN is refused by default: the server advertises LOGINDISABLED
and answers NO [PRIVACYREQUIRED]. To allow it on a trusted link such as
localhost or an encrypted overlay network, set Options { insecure_auth: true, .. }
and use Server::new(backend, options) with listen. To run over any other
transport, pass the read and write halves to Server::serve_conn.
Writing a backend
Two traits sit between the protocol and your storage:
#[async_trait]
pub trait Backend: Send + Sync + 'static {
async fn login(&self, conn: &ConnInfo, username: &str, password: &str)
-> Result<Box<dyn UserSession>, ImapError>;
}
#[async_trait]
pub trait UserSession: Send + 'static {
// list, create, delete, rename, status, select, close,
// fetch, store, search, copy, expunge, append, ...
}
Backendis shared by every connection.loginchecks credentials and returns a session. Reject a login withImapError::No.UserSessionhandles one authenticated connection.move_messages(COPY then EXPUNGE),idle,namespaceandpollhave default implementations.- IDLE push: return
Some(n)fromcurrent_message_countand the server sends* n EXISTSwhile a client idles. If you returnNone, IDLE still works but pushes nothing. - FETCH bodies: put the whole RFC 5322 message in
FetchedMessage.body. The server cutsHEADER,HEADER.FIELDS,TEXTand<offset.size>itself, so do not pre-filter. - Errors:
ImapError::NoandImapError::Badbecome taggedNOandBADresponses.InternalbecomesNO [SERVERBUG].Closedends the connection.
examples/memstore.rs is a complete backend in about 650 lines.
Protocol support
| Status | |
|---|---|
| IMAP4rev1 core: LOGIN, SELECT/EXAMINE, LIST, STATUS, FETCH, STORE, SEARCH, COPY, EXPUNGE, APPEND | Supported |
AUTHENTICATE PLAIN, with or without an initial response (SASL-IR) |
Supported |
IDLE, MOVE, UIDPLUS, LITERAL+, NAMESPACE, UNSELECT, ENABLE, ID, CHILDREN |
Supported |
Implicit TLS (Server::listen_tls) |
Supported |
STARTTLS |
Advertised when the backend returns a TLS config, but answers BAD. Not implemented yet |
FETCH ENVELOPE, BODYSTRUCTURE |
Parsed but not returned |
FETCH MIME part paths such as BODY[1.2] |
Return the whole message |
| IMAP4rev2 | No |
Limits
| Command line | 50 KiB |
| Literal | 35 MiB. A larger or negative size closes the connection instead of returning BAD: with LITERAL+ the payload is already on the wire, so the stream cannot be resynced |
| Read / write timeout | 30 s |
| IDLE timeout | 35 min |
| Any command not allowed before login | BYE and disconnect, against cross-protocol attacks |
Design notes
- Hand-written codec. The encoder and decoder in
imap-core/src/codec.rsfollow go-imap v2. There is nonomand no parser generator. - Plain error types.
ImapErroris an ordinary enum with manualDisplay,ErrorandFromimpls. The crates use neitherthiserrornoranyhow. imap-corestays small. Its only dependency istokiowithio-utilandsync. Test-only runtime features live in dev-dependencies.
Building
You need stable Rust. imap-server uses rustls, whose default aws-lc-rs
backend compiles C code, so you also need a C compiler and CMake (and NASM on
Windows). imap-core alone needs none of these.
$ cargo build
$ cargo test
$ cargo clippy --all-targets -- -D warnings
The tests run a real server on a random localhost port. They need no network or external services.
License
MIT