rusmes-imap 0.1.2

Async IMAP4rev2 server for RusMES — RFC 9051 compliant with CONDSTORE, QRESYNC, UIDPLUS, MOVE, IDLE, NAMESPACE, and SPECIAL-USE extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! IMAP mailbox command handlers
//!
//! Covers: SELECT, EXAMINE, LIST, LSUB, SUBSCRIBE, UNSUBSCRIBE,
//!         CREATE, CREATE_SPECIAL_USE, DELETE, RENAME, NAMESPACE, IDLE

use crate::handler::HandlerContext;
use crate::response::ImapResponse;
use crate::session::{ImapSession, ImapState};
use rusmes_storage::MailboxPath;

/// Handle SELECT/EXAMINE command
pub(crate) async fn handle_select(
    ctx: &HandlerContext,
    session: &mut ImapSession,
    tag: &str,
    mailbox: &str,
    read_only: bool,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Optimize for INBOX - use direct lookup
    let mailbox_obj = if mailbox.eq_ignore_ascii_case("INBOX") {
        // Use optimized INBOX lookup
        if let Some(inbox_id) = ctx.mailbox_store.get_user_inbox(&username).await? {
            ctx.mailbox_store.get_mailbox(&inbox_id).await?
        } else {
            None
        }
    } else {
        // List mailboxes to find the requested one
        let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
        mailboxes
            .iter()
            .find(|m| m.path().name() == Some(mailbox))
            .cloned()
    };

    match mailbox_obj {
        Some(mb) => {
            let mailbox_id = *mb.id();

            // Get mailbox counters
            let counters = ctx.metadata_store.get_mailbox_counters(&mailbox_id).await?;

            // Update session state
            session.state = ImapState::Selected { mailbox_id };

            // Subscribe to cross-session broadcast for this mailbox (RFC 3501 §5.2).
            // Any previous subscription is replaced when switching mailboxes.
            session.mailbox_event_rx = Some(ctx.mailbox_registry.subscribe(mailbox_id));

            // Build response with untagged responses
            let mode = if read_only { "READ-ONLY" } else { "READ-WRITE" };
            let response_text = format!(
                "* {} EXISTS\r\n* {} RECENT\r\n* OK [UIDVALIDITY {}]\r\n* OK [UIDNEXT {}]\r\n* FLAGS (\\Seen \\Answered \\Flagged \\Deleted \\Draft)\r\n{} OK [{}] {} completed",
                counters.exists,
                counters.recent,
                mb.uid_validity(),
                mb.uid_next(),
                tag,
                mode,
                if read_only { "EXAMINE" } else { "SELECT" }
            );

            Ok(ImapResponse::new(None, "", response_text))
        }
        None => Ok(ImapResponse::no(tag, "Mailbox does not exist")),
    }
}

/// Handle LIST command
pub(crate) async fn handle_list(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    _reference: &str,
    pattern: &str,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // List mailboxes
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;

    // Filter by pattern (simplified - just check if pattern is * or mailbox name)
    let mut responses = Vec::new();
    for mailbox in mailboxes {
        if pattern == "*" || mailbox.path().name() == Some(pattern) {
            let name = mailbox.path().name().unwrap_or("INBOX");
            responses.push(format!(r#"* LIST () "/" "{}""#, name));
        }
    }

    // Build response
    let mut full_response = responses.join("\r\n");
    if !full_response.is_empty() {
        full_response.push_str("\r\n");
    }
    full_response.push_str(&format!("{} OK LIST completed", tag));

    Ok(ImapResponse::new(None, "", full_response))
}

/// Handle LSUB command
pub(crate) async fn handle_lsub(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    _reference: &str,
    pattern: &str,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Get subscribed mailboxes
    let subscriptions = ctx.mailbox_store.list_subscriptions(&username).await?;

    // Filter by pattern and build responses
    let mut responses = Vec::new();
    for mailbox_name in subscriptions {
        // Pattern matching: "*" matches all, otherwise exact match or wildcard matching
        let matches = if pattern == "*" {
            true
        } else if pattern.contains('*') || pattern.contains('%') {
            // Simplified wildcard matching
            match_mailbox_pattern(&mailbox_name, pattern)
        } else {
            mailbox_name == pattern
        };

        if matches {
            responses.push(format!(r#"* LSUB () "/" "{}""#, mailbox_name));
        }
    }

    // Build response
    let mut full_response = responses.join("\r\n");
    if !full_response.is_empty() {
        full_response.push_str("\r\n");
    }
    full_response.push_str(&format!("{} OK LSUB completed", tag));

    Ok(ImapResponse::new(None, "", full_response))
}

/// Handle SUBSCRIBE command
pub(crate) async fn handle_subscribe(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Strip quotes from mailbox name if present
    let mailbox_name = mailbox.trim_matches('"');

    // Subscribe to the mailbox
    ctx.mailbox_store
        .subscribe_mailbox(&username, mailbox_name.to_string())
        .await?;

    Ok(ImapResponse::ok(tag, "SUBSCRIBE completed"))
}

/// Handle UNSUBSCRIBE command
pub(crate) async fn handle_unsubscribe(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Strip quotes from mailbox name if present
    let mailbox_name = mailbox.trim_matches('"');

    // Unsubscribe from the mailbox
    ctx.mailbox_store
        .unsubscribe_mailbox(&username, mailbox_name)
        .await?;

    Ok(ImapResponse::ok(tag, "UNSUBSCRIBE completed"))
}

/// Handle CREATE command
pub(crate) async fn handle_create(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Create mailbox path
    let path = MailboxPath::new(username, vec![mailbox.to_string()]);

    // Create mailbox
    ctx.mailbox_store.create_mailbox(&path).await?;

    Ok(ImapResponse::ok(tag, "CREATE completed"))
}

/// Handle CREATE-SPECIAL-USE command (RFC 6154)
pub(crate) async fn handle_create_special_use(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    mailbox: &str,
    special_use: &str,
) -> anyhow::Result<ImapResponse> {
    use rusmes_storage::SpecialUseAttributes;

    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Create mailbox path
    let path = MailboxPath::new(username, vec![mailbox.to_string()]);

    // Create special-use attributes
    let attrs = SpecialUseAttributes::single(special_use.to_string());

    // Create mailbox with special-use attribute
    ctx.mailbox_store
        .create_mailbox_with_special_use(&path, attrs)
        .await?;

    Ok(ImapResponse::ok(tag, "CREATE completed"))
}

/// Handle DELETE command
pub(crate) async fn handle_delete(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Find the mailbox
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
    let mailbox_obj = mailboxes.iter().find(|m| m.path().name() == Some(mailbox));

    match mailbox_obj {
        Some(mb) => {
            ctx.mailbox_store.delete_mailbox(mb.id()).await?;
            Ok(ImapResponse::ok(tag, "DELETE completed"))
        }
        None => Ok(ImapResponse::no(tag, "Mailbox does not exist")),
    }
}

/// Handle RENAME command
pub(crate) async fn handle_rename(
    ctx: &HandlerContext,
    session: &ImapSession,
    tag: &str,
    old_mailbox: &str,
    new_mailbox: &str,
) -> anyhow::Result<ImapResponse> {
    // Must be authenticated
    if !matches!(
        session.state(),
        ImapState::Authenticated | ImapState::Selected { .. }
    ) {
        return Ok(ImapResponse::no(tag, "Not authenticated"));
    }

    // Get username from session
    let username = match &session.username {
        Some(u) => u.clone(),
        None => return Ok(ImapResponse::no(tag, "No username in session")),
    };

    // Find the old mailbox
    let mailboxes = ctx.mailbox_store.list_mailboxes(&username).await?;
    let mailbox_obj = mailboxes
        .iter()
        .find(|m| m.path().name() == Some(old_mailbox));

    match mailbox_obj {
        Some(mb) => {
            // Create new mailbox path
            let new_path = MailboxPath::new(username, vec![new_mailbox.to_string()]);
            ctx.mailbox_store.rename_mailbox(mb.id(), &new_path).await?;
            Ok(ImapResponse::ok(tag, "RENAME completed"))
        }
        None => Ok(ImapResponse::no(tag, "Mailbox does not exist")),
    }
}

/// Handle IDLE command (RFC 2177)
/// Prepares for IDLE mode - actual IDLE loop must be handled by server
pub(crate) async fn handle_idle(
    ctx: &HandlerContext,
    session: &mut ImapSession,
    tag: &str,
) -> anyhow::Result<ImapResponse> {
    // Must have a mailbox selected
    let mailbox_id = match session.state() {
        ImapState::Selected { mailbox_id } => *mailbox_id,
        _ => return Ok(ImapResponse::no(tag, "No mailbox selected")),
    };

    // Get current mailbox state for snapshot
    let counters = ctx.metadata_store.get_mailbox_counters(&mailbox_id).await?;
    session.update_snapshot(counters.exists, counters.recent);

    // Transition to IDLE state
    session.state = ImapState::Idle { mailbox_id };
    session.tag = Some(tag.to_string());

    // Return continuation response
    // The server will handle the IDLE loop and send the OK response later
    Ok(ImapResponse::new(None, "+", "idling"))
}

/// Handle NAMESPACE command (RFC 2342)
/// Returns namespace information for personal, other users, and shared mailboxes
pub(crate) async fn handle_namespace(
    tag: &str,
    session: &ImapSession,
) -> anyhow::Result<ImapResponse> {
    // Only works in Authenticated or Selected state
    match session.state() {
        ImapState::NotAuthenticated => {
            return Ok(ImapResponse::no(tag, "NAMESPACE requires authentication"));
        }
        ImapState::Logout => {
            return Ok(ImapResponse::no(tag, "Already logged out"));
        }
        _ => {}
    }

    // Personal namespace: empty prefix with "." delimiter
    // This means mailboxes like "INBOX", "Sent", "Drafts" etc. are at the root
    let personal = vec![("".to_string(), ".".to_string())];

    // Other users namespace: not supported (NIL)
    let other_users: Vec<(String, String)> = Vec::new();

    // Shared namespace: not supported (NIL)
    let shared: Vec<(String, String)> = Vec::new();

    // Format the namespace response
    let personal_str = format_namespace_list(&personal);
    let other_users_str = format_namespace_list(&other_users);
    let shared_str = format_namespace_list(&shared);

    // Build untagged NAMESPACE response
    let untagged_response = format!(
        "* NAMESPACE {} {} {}",
        personal_str, other_users_str, shared_str
    );

    // Build full response with untagged response followed by tagged OK
    let full_response = format!("{}\r\n{} OK NAMESPACE completed", untagged_response, tag);

    Ok(ImapResponse::new(None, "", full_response))
}

/// Format a list of namespaces according to RFC 2342
/// Each namespace is a tuple of (prefix, delimiter)
/// Returns "NIL" if the list is empty, otherwise returns a parenthesized list
fn format_namespace_list(namespaces: &[(String, String)]) -> String {
    if namespaces.is_empty() {
        "NIL".to_string()
    } else {
        let items: Vec<String> = namespaces
            .iter()
            .map(|(prefix, delim)| format!("(\"{}\" \"{}\")", prefix, delim))
            .collect();
        format!("({})", items.join(" "))
    }
}

/// Match mailbox name against pattern
/// Supports IMAP wildcards: * (matches any sequence) and % (matches any sequence except hierarchy delimiter)
pub(crate) fn match_mailbox_pattern(name: &str, pattern: &str) -> bool {
    // Simplified pattern matching for IMAP LIST/LSUB
    // * matches zero or more characters including hierarchy delimiter
    // % matches zero or more characters excluding hierarchy delimiter (/)

    if pattern == "*" {
        return true;
    }

    // Convert IMAP pattern to regex-like matching
    let mut pattern_chars = pattern.chars().peekable();
    let mut name_chars = name.chars().peekable();

    loop {
        match (pattern_chars.peek(), name_chars.peek()) {
            (None, None) => return true,
            (None, Some(_)) => return false,
            (Some(&'*'), _) => {
                pattern_chars.next();
                // * matches everything, so just continue with rest of pattern
                if pattern_chars.peek().is_none() {
                    return true;
                }
                // Try to match rest of pattern at each position
                let rest_pattern: String = pattern_chars.collect();
                for i in 0..=name_chars.clone().count() {
                    let rest_name: String = name_chars.clone().skip(i).collect();
                    if match_mailbox_pattern(&rest_name, &rest_pattern) {
                        return true;
                    }
                }
                return false;
            }
            (Some(&'%'), _) => {
                pattern_chars.next();
                // % matches everything except hierarchy delimiter
                if pattern_chars.peek().is_none() {
                    // % at end matches if no more hierarchy delimiters
                    return !name_chars.clone().any(|c| c == '/');
                }
                let rest_pattern: String = pattern_chars.collect();
                for i in 0..=name_chars.clone().count() {
                    let rest_name: String = name_chars.clone().skip(i).collect();
                    // Check if we crossed a hierarchy delimiter
                    let skipped: String = name_chars.clone().take(i).collect();
                    if !skipped.contains('/') && match_mailbox_pattern(&rest_name, &rest_pattern) {
                        return true;
                    }
                }
                return false;
            }
            (Some(&p), Some(&n)) => {
                if p == n {
                    pattern_chars.next();
                    name_chars.next();
                } else {
                    return false;
                }
            }
            (Some(_), None) => return false,
        }
    }
}