1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Each instance of this represents an IMAP client connected to
5 # public-inbox-imapd. Much of this was taken from NNTP, but
6 # further refined while experimenting on future ideas to handle
11 # * NNTP article numbers are UIDs, mm->created_at is UIDVALIDITY
13 # * public-inboxes are sliced into mailboxes of 50K messages
14 # to not overload MUAs: $NEWSGROUP_NAME.$SLICE_INDEX
15 # Slices are similar in concept to v2 "epochs". Epochs
16 # are for the limitations of git clients, while slices are
17 # for the limitations of IMAP clients.
19 # * We also take advantage of slices being only 50K to store
20 # "UID offset" to message sequence number (MSN) mapping
21 # as a 50K uint16_t array (via pack("S*", ...)). "UID offset"
22 # is the offset from {uid_base} which determines the start of
26 # imapd: PublicInbox::IMAPD ref
27 # ibx: PublicInbox::Inbox ref
28 # long_cb: long_response private data
29 # uid_base: base UID for mailbox slice (0-based)
30 # -login_tag: IMAP TAG for LOGIN
31 # -idle_tag: IMAP response tag for IDLE
32 # uo2m: UID-to-MSN mapping
33 package PublicInbox::IMAP;
35 use parent qw(PublicInbox::DS);
37 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
38 use PublicInbox::DS qw(now);
39 use PublicInbox::GitAsyncCat;
40 use Text::ParseWords qw(parse_line);
42 use PublicInbox::IMAPsearchqp;
45 for my $mod (qw(Email::Address::XS Mail::Address)) {
46 eval "require $mod" or next;
47 $Address = $mod and last;
49 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
51 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
53 # Changing UID_SLICE will cause grief for clients which cache.
54 # This also needs to be <64K: we pack it into a uint16_t
55 # for long_response UID (offset) => MSN mappings
56 sub UID_SLICE () { 50_000 }
58 # these values area also used for sorting
59 sub NEED_SMSG () { 1 }
60 sub NEED_BLOB () { NEED_SMSG|2 }
61 sub CRLF_BREF () { 4 }
63 sub CRLF_HDR () { 16 }
65 sub CRLF_BDY () { 64 }
66 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
67 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
68 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
69 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
72 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
73 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
74 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
75 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
76 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
77 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
78 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
79 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
80 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
81 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
82 FLAGS => [ 0, \&emit_flags ],
83 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
85 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
87 # aliases (RFC 3501 section 6.4.5)
88 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
89 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
90 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
92 for my $att (keys %FETCH_ATT) {
93 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
94 $FETCH_ATT{$att} = \%h;
98 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
99 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
103 my $capa = capa($self);
104 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
108 my (undef, $sock, $imapd) = @_;
109 (bless { imapd => $imapd }, 'PublicInbox::IMAP_preauth')->greet($sock)
117 # dovecot advertises IDLE pre-login; perhaps because some clients
118 # depend on it, so we'll do the same
119 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
120 if ($self->logged_in) {
121 $capa .= ' COMPRESS=DEFLATE';
123 if (!($self->{sock} // $self)->can('accept_SSL') &&
124 $self->{imapd}->{ssl_ctx_opt}) {
125 $capa .= ' STARTTLS';
127 $capa .= ' AUTH=ANONYMOUS';
131 sub login_success ($$) {
132 my ($self, $tag) = @_;
133 bless $self, 'PublicInbox::IMAP';
134 my $capa = capa($self);
135 "$tag OK [$capa] Logged in\r\n";
138 sub auth_challenge_ok ($) {
140 my $tag = delete($self->{-login_tag}) or return;
142 login_success($self, $tag);
145 sub cmd_login ($$$$) {
146 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
147 login_success($self, $tag);
151 my ($self, $tag) = @_;
152 delete @$self{qw(uid_base uo2m)};
153 delete $self->{ibx} ? "$tag OK Close done\r\n"
154 : "$tag BAD No mailbox\r\n";
157 sub cmd_logout ($$) {
158 my ($self, $tag) = @_;
159 delete $self->{-idle_tag};
160 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
161 $self->shutdn; # PublicInbox::DS::shutdn
165 sub cmd_authenticate ($$$) {
166 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
167 $self->{-login_tag} = $tag;
171 sub cmd_capability ($$) {
172 my ($self, $tag) = @_;
173 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
176 # uo2m: UID Offset to MSN, this is an arrayref by default,
177 # but uo2m_hibernate can compact and deduplicate it
178 sub uo2m_ary_new ($;$) {
179 my ($self, $exists) = @_;
180 my $ub = $self->{uid_base};
181 my $uids = $self->{ibx}->over(1)->uid_range($ub + 1, $ub + UID_SLICE);
183 # convert UIDs to offsets from {base}
184 my @tmp; # [$UID_OFFSET] => $MSN
187 $tmp[$_ - $ub] = ++$msn for @$uids;
188 $$exists = $msn if $exists;
192 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
193 # uint16_t uo2m[UID_SLICE].
194 # May be swapped out for idle clients if THP is disabled.
195 sub uo2m_hibernate ($) {
197 ref(my $uo2m = $self->{uo2m}) or return;
198 my %dedupe = ( uo2m_pack($uo2m) => undef );
199 $self->{uo2m} = (keys(%dedupe))[0];
203 sub uo2m_last_uid ($) {
205 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
206 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
210 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
211 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
212 no warnings 'uninitialized';
213 pack('S*', @{$_[0]});
216 # extend {uo2m} to account for new messages which arrived since
217 # {uo2m} was created.
218 sub uo2m_extend ($$;$) {
219 my ($self, $new_uid_max) = @_;
220 defined(my $uo2m = $self->{uo2m}) or
221 return($self->{uo2m} = uo2m_ary_new($self));
222 my $beg = uo2m_last_uid($self); # last UID we've learned
223 return $uo2m if $beg >= $new_uid_max; # fast path
225 # need to extend the current range:
226 my $base = $self->{uid_base};
228 my $uids = $self->{ibx}->over(1)->uid_range($beg, $base + UID_SLICE);
229 return $uo2m if !scalar(@$uids);
230 my @tmp; # [$UID_OFFSET] => $MSN
231 my $write_method = $_[2] // 'msg_more';
233 my $msn = $uo2m->[-1];
234 $tmp[$_ - $beg] = ++$msn for @$uids;
235 $self->$write_method("* $msn EXISTS\r\n");
239 my $msn = unpack('S', substr($uo2m, -2, 2));
240 $tmp[$_ - $beg] = ++$msn for @$uids;
241 $self->$write_method("* $msn EXISTS\r\n");
242 $uo2m .= uo2m_pack(\@tmp);
243 my %dedupe = ($uo2m => undef);
244 $self->{uo2m} = (keys %dedupe)[0];
249 my ($self, $tag) = @_;
250 defined($self->{uid_base}) and
251 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
252 \"$tag OK Noop done\r\n";
255 # the flexible version which works on scalars and array refs.
256 # Must call uo2m_extend before this
258 my ($self, $uid) = @_;
259 my $uo2m = $self->{uo2m};
260 my $off = $uid - $self->{uid_base} - 1;
261 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
264 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
265 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
266 # and does not live beyond the event loop.
269 my $base = $self->{uid_base};
270 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
271 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
275 for my $msn (@$uo2m) {
277 $msn2uid[$msn - 1] = $uo + $base if $msn;
282 # converts a set of message sequence numbers in requests to UIDs:
283 sub msn_to_uid_range ($$) {
285 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] // 0 + 1)!sge;
288 # called by PublicInbox::InboxIdle
289 sub on_inbox_unlock {
290 my ($self, $ibx) = @_;
291 my $uid_end = $self->{uid_base} + UID_SLICE;
292 uo2m_extend($self, $uid_end, 'write');
293 my $new = uo2m_last_uid($self);
294 if ($new == $uid_end) { # max exceeded $uid_end
295 # continue idling w/o inotify
296 my $sock = $self->{sock} or return;
297 $ibx->unsubscribe_unlock(fileno($sock));
301 # called every minute or so by PublicInbox::DS::later
302 my $IDLERS; # fileno($obj->{sock}) => PublicInbox::IMAP
306 for my $i (values %$old) {
307 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
308 $IDLERS->{fileno($i->{sock})} = $i;
309 $i->write(\"* OK Still here\r\n");
312 PublicInbox::DS::add_uniq_timer('idle', 60, \&idle_tick_all);
316 my ($self, $tag) = @_;
317 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
318 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
319 my $uid_end = $self->{uid_base} + UID_SLICE;
320 uo2m_extend($self, $uid_end);
321 my $sock = $self->{sock} or return;
322 my $fd = fileno($sock);
323 $self->{-idle_tag} = $tag;
324 # only do inotify on most recent slice
325 if ($ibx->over(1)->max < $uid_end) {
326 $ibx->subscribe_unlock($fd, $self);
327 $self->{imapd}->idler_start;
329 PublicInbox::DS::add_uniq_timer('idle', 60, \&idle_tick_all);
330 $IDLERS->{$fd} = $self;
335 my ($self, $ibx) = @_;
336 my $sock = $self->{sock} or return;
337 my $fd = fileno($sock);
338 delete $IDLERS->{$fd};
339 $ibx->unsubscribe_unlock($fd);
343 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
344 defined(my $idle_tag = delete $self->{-idle_tag}) or
345 return "$tag BAD not idle\r\n";
346 my $ibx = $self->{ibx} or do {
347 warn "BUG: idle_tag set w/o inbox";
348 return "$tag BAD internal bug\r\n";
350 stop_idle($self, $ibx);
351 "$idle_tag OK Idle done\r\n";
354 sub ensure_slices_exist ($$) {
355 my ($imapd, $ibx) = @_;
356 my $mb_top = $ibx->{newsgroup} // return;
357 my $mailboxes = $imapd->{mailboxes};
358 my $list = $imapd->{mailboxlist}; # may be undef, just autoviv + noop
359 for (my $i = int($ibx->art_max/UID_SLICE); $i >= 0; --$i) {
360 my $sub_mailbox = "$mb_top.$i";
361 last if exists $mailboxes->{$sub_mailbox};
362 $mailboxes->{$sub_mailbox} = $ibx;
363 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
364 push @$list, qq[* LIST (\\HasNoChildren) "." $sub_mailbox\r\n]
368 sub inbox_lookup ($$;$) {
369 my ($self, $mailbox, $examine) = @_;
370 my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
371 $mailbox = lc $mailbox;
372 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
373 my $over = $ibx->over(1);
374 if ($over != $ibx) { # not a dummy
375 $mailbox =~ /\.([0-9]+)\z/ or
376 die "BUG: unexpected dummy mailbox: $mailbox\n";
377 $uid_base = $1 * UID_SLICE;
379 $uidmax = $ibx->mm->num_highwater // 0;
381 $self->{uid_base} = $uid_base;
383 $self->{uo2m} = uo2m_ary_new($self, \$exists);
385 my $uid_end = $uid_base + UID_SLICE;
386 $exists = $over->imap_exists($uid_base, $uid_end);
388 delete $ibx->{-art_max};
389 ensure_slices_exist($self->{imapd}, $ibx);
392 $self->{uid_base} = $uid_base;
394 delete $self->{uo2m};
396 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
397 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
398 if (my $ibx = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
399 delete $ibx->{-art_max};
400 ensure_slices_exist($self->{imapd}, $ibx);
403 ($ibx, $exists, $uidmax + 1, $uid_base);
406 sub cmd_examine ($$$) {
407 my ($self, $tag, $mailbox) = @_;
408 # XXX: do we need this? RFC 5162/7162
409 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
410 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox, 1);
411 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
416 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
417 * OK [UNSEEN $exists]\r
418 * OK [UIDNEXT $uidnext]\r
419 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
420 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
428 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
429 '{' . length($v) . "}\r\n" . $v;
430 } else { # quoted string
435 sub addr_envelope ($$;$) {
436 my ($eml, $x, $y) = @_;
437 my $v = $eml->header_raw($x) //
438 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
440 my @x = $Address->parse($v) or return 'NIL';
442 map { '(' . join(' ',
443 _esc($_->name), 'NIL',
444 _esc($_->user), _esc($_->host)
450 sub eml_envelope ($) {
453 _esc($eml->header_raw('Date')),
454 _esc($eml->header_raw('Subject')),
455 addr_envelope($eml, 'From'),
456 addr_envelope($eml, 'Sender', 'From'),
457 addr_envelope($eml, 'Reply-To', 'From'),
458 addr_envelope($eml, 'To'),
459 addr_envelope($eml, 'Cc'),
460 addr_envelope($eml, 'Bcc'),
461 _esc($eml->header_raw('In-Reply-To')),
462 _esc($eml->header_raw('Message-ID')),
468 if ($hash && scalar keys %$hash) {
469 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
470 '(' . join(' ', map { _esc($_) } @$hash) . ')';
476 sub body_disposition ($) {
478 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
479 $cd = parse_content_disposition($cd);
480 my $buf = '('._esc($cd->{type});
481 $buf .= ' ' . _esc_hash($cd->{attributes});
485 sub body_leaf ($$;$) {
486 my ($eml, $structure, $hold) = @_;
488 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
489 $buf .= eml_envelope($eml). ' ';
491 $buf .= '('._esc($ct->{type}).' ';
492 $buf .= _esc($ct->{subtype});
493 $buf .= ' ' . _esc_hash($ct->{attributes});
494 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
495 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
496 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
497 $buf .= ' ' . _esc($cte);
498 $buf .= ' ' . $eml->{imap_body_len};
499 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
501 # for message/(rfc822|global|news), $hold[0] should have envelope
502 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
505 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
506 $buf .= ' '. body_disposition($eml);
507 $buf .= ' '._esc($eml->header_raw('Content-Language'));
508 $buf .= ' '._esc($eml->header_raw('Content-Location'));
513 sub body_parent ($$$) {
514 my ($eml, $structure, $hold) = @_;
516 my $type = lc($ct->{type});
517 if ($type eq 'multipart') {
519 $buf .= @$hold ? join('', @$hold) : 'NIL';
520 $buf .= ' '._esc($ct->{subtype});
522 $buf .= ' '._esc_hash($ct->{attributes});
523 $buf .= ' '.body_disposition($eml);
524 $buf .= ' '._esc($eml->header_raw('Content-Language'));
525 $buf .= ' '._esc($eml->header_raw('Content-Location'));
529 } else { # message/(rfc822|global|news)
530 @$hold = (body_leaf($eml, $structure, $hold));
534 # this is gross, but we need to process the parent part AFTER
535 # the child parts are done
536 sub bodystructure_prep {
538 my ($eml, $depth) = @$p; # ignore idx
539 # set length here, as $eml->{bdy} gets deleted for message/rfc822
540 $eml->{imap_body_len} = length($eml->body_raw);
541 push @$q, $eml, $depth;
544 # for FETCH BODY and FETCH BODYSTRUCTURE
545 sub fetch_body ($;$) {
546 my ($eml, $structure) = @_;
548 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
552 my ($part, $depth) = splice(@q, -2);
553 my $is_mp_parent = $depth == ($cur_depth - 1);
557 body_parent($part, $structure, \@hold);
559 unshift @hold, body_leaf($part, $structure);
566 my ($self, $smsg, $bref, $ops, $partial) = @_;
567 my $uid = $smsg->{num};
568 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
570 for (my $i = 0; $i < @$ops;) {
572 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
574 partial_emit($self, $partial, $eml) if $partial;
575 $self->msg_more(")\r\n");
578 sub requeue { # overrides PublicInbox::DS::requeue
580 if ($self->{anon}) { # AUTH=ANONYMOUS gets high priority
581 $self->SUPER::requeue;
582 } else { # low priority
583 push(@{$self->{imapd}->{-authed_q}}, $self) == 1 and
584 PublicInbox::DS::requeue($self->{imapd});
588 sub fetch_blob_cb { # called by git->cat_async via ibx_async_cat
589 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
590 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
591 my $ibx = $self->{ibx} or return $self->close; # client disconnected
592 my $smsg = shift @$msgs or die 'BUG: no smsg';
593 if (!defined($oid)) {
594 # it's possible to have TOCTOU if an admin runs
595 # public-inbox-(edit|purge), just move onto the next message
596 warn "E: $smsg->{blob} missing in $ibx->{inboxdir}\n";
597 return $self->requeue_once;
599 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
602 ($self->{anon} && !$self->{wbuf} && $msgs->[0]) and
603 $pre = ibx_async_prefetch($ibx, $msgs->[0]->{blob},
604 \&fetch_blob_cb, $fetch_arg);
605 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
606 $pre ? $self->dflush : $self->requeue_once;
610 my ($self, $k, undef, $bref) = @_;
611 $self->msg_more(" $k {" . length($$bref)."}\r\n");
612 $self->msg_more($$bref);
615 # Mail::IMAPClient::message_string cares about this by default,
616 # (->Ignoresizeerrors attribute). Admins are encouraged to
617 # --reindex for IMAP support, anyways.
618 sub emit_rfc822_size {
619 my ($self, $k, $smsg) = @_;
620 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
623 sub emit_internaldate {
624 my ($self, undef, $smsg) = @_;
625 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
628 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
631 my ($self, undef, undef, undef, $eml) = @_;
632 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
635 sub emit_rfc822_header {
636 my ($self, $k, undef, undef, $eml) = @_;
637 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
638 $self->msg_more(${$eml->{hdr}});
641 # n.b. this is sorted to be after any emit_eml_new ops
642 sub emit_rfc822_text {
643 my ($self, $k, undef, $bref) = @_;
644 $self->msg_more(" $k {".length($$bref)."}\r\n");
645 $self->msg_more($$bref);
648 sub emit_bodystructure {
649 my ($self, undef, undef, undef, $eml) = @_;
650 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
654 my ($self, undef, undef, undef, $eml) = @_;
655 $self->msg_more(' BODY '.fetch_body($eml));
658 # set $eml once ($_[4] == $eml, $_[3] == $bref)
659 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
661 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
663 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
664 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
667 sub op_crlf_bref { to_crlf_full($_[3]) }
669 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
671 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
673 sub uid_clamp ($$$) {
674 my ($self, $beg, $end) = @_;
675 my $uid_min = $self->{uid_base} + 1;
676 my $uid_end = $uid_min + UID_SLICE - 1;
677 $$beg = $uid_min if $$beg < $uid_min;
678 $$end = $uid_end if $$end > $uid_end;
681 sub range_step ($$) {
682 my ($self, $range_csv) = @_;
683 my ($beg, $end, $range);
684 if ($$range_csv =~ s/\A([^,]+),//) {
687 $range = $$range_csv;
690 my $uid_base = $self->{uid_base};
691 my $uid_end = $uid_base + UID_SLICE;
692 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
693 ($beg, $end) = ($1 + 0, $2 + 0);
694 uid_clamp($self, \$beg, \$end);
695 } elsif ($range =~ /\A([0-9]+):\*\z/) {
697 $end = $self->{ibx}->over(1)->max;
698 $end = $uid_end if $end > $uid_end;
699 $beg = $end if $beg > $end;
700 uid_clamp($self, \$beg, \$end);
701 } elsif ($range =~ /\A[0-9]+\z/) {
702 $beg = $end = $range + 0;
703 # just let the caller do an out-of-range query if a single
704 # UID is out-of-range
705 ++$beg if ($beg <= $uid_base || $end > $uid_end);
707 return 'BAD fetch range';
709 [ $beg, $end, $$range_csv ];
712 sub refill_range ($$$) {
713 my ($self, $msgs, $range_info) = @_;
714 my ($beg, $end, $range_csv) = @$range_info;
715 if (scalar(@$msgs = @{$self->{ibx}->over(1)->query_xover($beg, $end)})){
716 $range_info->[0] = $msgs->[-1]->{num} + 1;
719 return 'OK Fetch done' if !$range_csv;
720 my $next_range = range_step($self, \$range_csv);
721 return $next_range if !ref($next_range); # error
722 @$range_info = @$next_range;
723 undef; # keep looping
726 sub fetch_blob { # long_response
727 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
728 while (!@$msgs) { # rare
729 if (my $end = refill_range($self, $msgs, $range_info)) {
730 $self->write(\"$tag $end\r\n");
734 uo2m_extend($self, $msgs->[-1]->{num});
735 ibx_async_cat($self->{ibx}, $msgs->[0]->{blob},
736 \&fetch_blob_cb, \@_);
739 sub fetch_smsg { # long_response
740 my ($self, $tag, $msgs, $range_info, $ops) = @_;
741 while (!@$msgs) { # rare
742 if (my $end = refill_range($self, $msgs, $range_info)) {
743 $self->write(\"$tag $end\r\n");
747 uo2m_extend($self, $msgs->[-1]->{num});
748 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
753 sub refill_uids ($$$;$) {
754 my ($self, $uids, $range_info, $sql) = @_;
755 my ($beg, $end, $range_csv) = @$range_info;
756 my $over = $self->{ibx}->over(1);
758 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
759 $range_info->[0] = $uids->[-1] + 1; # update $beg
761 } elsif (!$range_csv) {
764 my $next_range = range_step($self, \$range_csv);
765 return $next_range if !ref($next_range); # error
766 ($beg, $end, $range_csv) = @$range_info = @$next_range;
772 sub fetch_uid { # long_response
773 my ($self, $tag, $uids, $range_info, $ops) = @_;
774 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
775 $err ||= 'OK Fetch done';
776 $self->write("$tag $err\r\n");
779 my $adj = $self->{uid_base} + 1;
780 my $uo2m = uo2m_extend($self, $uids->[-1]);
781 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
784 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
785 for ($i = 0; $i < @$ops;) {
787 $ops->[$i++]->($self, $k);
789 $self->msg_more(")\r\n");
795 sub cmd_status ($$$;@) {
796 my ($self, $tag, $mailbox, @items) = @_;
797 return "$tag BAD no items\r\n" if !scalar(@items);
798 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
799 return "$tag BAD invalid args\r\n";
800 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
801 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
803 for my $it (@items) {
806 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
808 } elsif ($it eq 'UIDNEXT') {
810 } elsif ($it eq 'UIDVALIDITY') {
811 push @it, $ibx->{uidvalidity};
813 return "$tag BAD invalid item\r\n";
816 return "$tag BAD no items\r\n" if !@it;
817 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
818 "$tag OK Status done\r\n";
821 my %patmap = ('*' => '.*', '%' => '[^\.]*');
822 sub cmd_list ($$$$) {
823 my ($self, $tag, $refname, $wildcard) = @_;
824 my $l = $self->{imapd}->{mailboxlist};
825 if ($refname eq '' && $wildcard eq '') {
826 # request for hierarchy delimiter
827 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
828 } elsif ($refname ne '' || $wildcard ne '*') {
829 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
830 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
832 \(join('', @$l, "$tag OK List done\r\n"));
835 sub cmd_lsub ($$$$) {
836 my (undef, $tag) = @_; # same args as cmd_list
837 "$tag OK Lsub done\r\n";
840 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
842 my ($eml, undef, $idx) = @$p;
843 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
844 $eml->{imap_bdy} = $eml->{bdy} // \'';
846 $all->{$idx} = $eml; # $idx => Eml
849 # prepares an index for BODY[$SECTION_IDX] fetches
850 sub eml_body_idx ($$) {
851 my ($eml, $section_idx) = @_;
852 my $idx = $eml->{imap_all_parts} // do {
854 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
855 # top-level of multipart, BODY[0] not allowed (nz-number)
857 $eml->{imap_all_parts} = $all;
859 $idx->{$section_idx};
862 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
864 my ($eml, $section_idx, $section_name) = @_;
865 if (defined $section_idx) {
866 $eml = eml_body_idx($eml, $section_idx) or return;
868 if (defined $section_name) {
869 if ($section_name eq 'MIME') {
870 # RFC 3501 6.4.5 states:
871 # The MIME part specifier MUST be prefixed
872 # by one or more numeric part specifiers
873 return unless defined $section_idx;
874 return $eml->header_obj->as_string . "\r\n";
876 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
877 $eml = PublicInbox::Eml->new($$bdy);
878 if ($section_name eq 'TEXT') {
879 return $eml->body_raw;
880 } elsif ($section_name eq 'HEADER') {
881 return $eml->header_obj->as_string . "\r\n";
883 die "BUG: bad section_name=$section_name";
886 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
889 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
890 # to avoid OOM with malicious users
891 sub hdrs_regexp ($) {
893 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
894 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
895 # continuation lines:
896 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
900 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
901 sub partial_hdr_not {
902 my ($eml, $section_idx, $hdrs_re) = @_;
903 if (defined $section_idx) {
904 $eml = eml_body_idx($eml, $section_idx) or return;
906 my $str = $eml->header_obj->as_string;
907 $str =~ s/$hdrs_re//g;
908 $str =~ s/(?<!\r)\n/\r\n/sg;
912 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
913 sub partial_hdr_get {
914 my ($eml, $section_idx, $hdrs_re) = @_;
915 if (defined $section_idx) {
916 $eml = eml_body_idx($eml, $section_idx) or return;
918 my $str = $eml->header_obj->as_string;
919 $str = join('', ($str =~ m/($hdrs_re)/g));
920 $str =~ s/(?<!\r)\n/\r\n/sg;
924 sub partial_prepare ($$$$) {
925 my ($need, $partial, $want, $att) = @_;
927 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
928 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
929 return unless $att =~ /\ABODY\[/s;
930 until (rindex($att, ']') >= 0) {
931 my $next = shift @$want or return;
932 $att .= ' ' . uc($next);
934 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
935 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
936 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
937 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
938 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
939 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
940 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
941 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
942 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
943 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
946 $tmp->[2] = hdrs_regexp($3);
948 # don't emit CRLF_HDR instruction, here, partial_hdr_*
949 # will do CRLF conversion with only the extracted result
950 # and not waste time converting lines we don't care about.
957 sub partial_emit ($$$) {
958 my ($self, $partial, $eml) = @_;
960 my ($k, $cb, @args) = @$_;
961 my ($offset, $len) = splice(@args, -2);
962 # $cb is partial_body|partial_hdr_get|partial_hdr_not
963 my $str = $cb->($eml, @args) // '';
964 if (defined $offset) {
966 $str = substr($str, $offset, $len);
967 $k =~ s/\.$len>\z/>/ or warn
968 "BUG: unable to remove `.$len>' from `$k'";
970 $str = substr($str, $offset);
976 $self->msg_more(" $k {$len}\r\n");
977 $self->msg_more($str);
981 sub fetch_compile ($) {
983 if ($want->[0] =~ s/\A\(//s) {
984 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
986 my (%partial, %seen, @op);
988 while (defined(my $att = shift @$want)) {
990 next if $att eq 'UID'; # always returned
991 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
992 my $x = $FETCH_ATT{$att};
994 while (my ($k, $fl_cb) = each %$x) {
996 $need |= $fl_cb->[0];
997 push @op, [ @$fl_cb, $k ];
999 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1000 return "BAD param: $att";
1005 # stabilize partial order for consistency and ease-of-debugging:
1006 if (scalar keys %partial) {
1008 @{$r[2]} = map { [ $_, @{$partial{$_}} ] } sort keys %partial;
1011 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1013 # do we need CRLF conversion?
1014 if ($need & CRLF_BREF) {
1015 push @op, $OP_CRLF_BREF;
1016 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1017 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1018 push @op, $OP_CRLF_BREF;
1019 } elsif ($need & CRLF_HDR) {
1020 push @op, $OP_CRLF_HDR;
1022 push @op, $OP_CRLF_BDY;
1026 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1027 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1029 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1030 use sort 'stable'; # makes output more consistent
1031 @{$r[1]} = map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op;
1035 sub cmd_uid_fetch ($$$$;@) {
1036 my ($self, $tag, $range_csv, @want) = @_;
1037 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1038 my ($cb, $ops, $partial) = fetch_compile(\@want);
1039 return "$tag $cb\r\n" unless $ops;
1041 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1042 $range_csv = 'bad' if $range_csv !~ $valid_range;
1043 my $range_info = range_step($self, \$range_csv);
1044 return "$tag $range_info\r\n" if !ref($range_info);
1045 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1046 $self->long_response($cb, $tag, [], $range_info, $ops, $partial);
1049 sub cmd_fetch ($$$$;@) {
1050 my ($self, $tag, $range_csv, @want) = @_;
1051 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1052 my ($cb, $ops, $partial) = fetch_compile(\@want);
1053 return "$tag $cb\r\n" unless $ops;
1055 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1056 $range_csv = 'bad' if $range_csv !~ $valid_range;
1057 msn_to_uid_range(msn2uid($self), $range_csv);
1058 my $range_info = range_step($self, \$range_csv);
1059 return "$tag $range_info\r\n" if !ref($range_info);
1060 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1061 $self->long_response($cb, $tag, [], $range_info, $ops, $partial);
1064 sub msn_convert ($$) {
1065 my ($self, $uids) = @_;
1066 my $adj = $self->{uid_base} + 1;
1067 my $uo2m = uo2m_extend($self, $uids->[-1]);
1068 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1069 $_ = $uo2m->[$_ - $adj] for @$uids;
1072 sub search_uid_range { # long_response
1073 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1075 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1076 $err ||= 'OK Search done';
1077 $self->write("\r\n$tag $err\r\n");
1080 msn_convert($self, $uids) if $want_msn;
1081 $self->msg_more(join(' ', '', @$uids));
1085 sub parse_imap_query ($$) {
1086 my ($self, $query) = @_;
1087 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1089 my $max = $self->{ibx}->over(1)->max;
1091 uid_clamp($self, \$beg, \$max);
1092 $q->{range_info} = [ $beg, $max ];
1098 my ($self, $tag, $query, $want_msn) = @_;
1099 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1100 my $q = parse_imap_query($self, $query);
1101 return "$tag $q\r\n" if !ref($q);
1102 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1103 if (!scalar(keys %$q)) { # overview.sqlite3
1104 $self->msg_more('* SEARCH');
1105 $self->long_response(\&search_uid_range,
1106 $tag, $sql, $range_info, $want_msn);
1107 } elsif ($q = $q->{xap}) {
1108 my $srch = $self->{ibx}->isrch or
1109 return "$tag BAD search not available for mailbox\r\n";
1113 uid_range => $range_info
1115 my $mset = $srch->mset($q, $opt);
1116 my $uids = $srch->mset_to_artnums($mset, $opt);
1117 msn_convert($self, $uids) if scalar(@$uids) && $want_msn;
1118 "* SEARCH @$uids\r\n$tag OK Search done\r\n";
1120 "$tag BAD Error\r\n";
1124 sub cmd_uid_search ($$$) {
1125 my ($self, $tag, $query) = @_;
1126 search_common($self, $tag, $query);
1129 sub cmd_search ($$$;) {
1130 my ($self, $tag, $query) = @_;
1131 search_common($self, $tag, $query, 1);
1134 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1135 sub process_line ($$) {
1136 my ($self, $l) = @_;
1138 # TODO: IMAP allows literals for big requests to upload messages
1139 # (which we don't support) but maybe some big search queries use it.
1140 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1141 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1142 pop(@args) if (@args && !defined($args[-1]));
1143 if (@args && uc($req) eq 'UID') {
1144 $req .= "_".(shift @args);
1147 if (defined(my $idle_tag = $self->{-idle_tag})) {
1148 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1149 idle_done($self, $tag) :
1150 "$idle_tag BAD expected DONE\r\n";
1151 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1152 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1153 # preserve user-supplied quotes for search
1154 (undef, @args) = split(/ search /i, $l, 2);
1156 $cmd->($self, $tag, @args);
1157 } else { # this is weird
1158 auth_challenge_ok($self) //
1160 ' BAD Error in IMAP command '.
1162 ": Unknown command\r\n";
1166 if ($err && $self->{sock}) {
1168 warn("error from: $l ($err)\n");
1170 $res = \"$tag BAD program fault - command not performed\r\n";
1172 defined($res) ? $self->write($res) : 0;
1176 my ($self, $fmt, @args) = @_;
1177 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1180 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1183 local $SIG{__WARN__} = $self->{imapd}->{warn_cb};
1184 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1186 # only read more requests if we've drained the write buffer,
1187 # otherwise we can be buffering infinitely w/o backpressure
1189 my $rbuf = $self->{rbuf} // \(my $x = '');
1190 my $line = index($$rbuf, "\n");
1192 if (length($$rbuf) >= LINE_MAX) {
1193 $self->write(\"\* BAD request too long\r\n");
1194 return $self->close;
1196 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1197 return uo2m_hibernate($self);
1198 $line = index($$rbuf, "\n");
1200 $line = substr($$rbuf, 0, $line + 1, '');
1201 $line =~ s/\r?\n\z//s;
1202 return $self->close if $line =~ /[[:cntrl:]]/s;
1204 my $fd = fileno($self->{sock});
1205 my $r = eval { process_line($self, $line) };
1206 my $pending = $self->{wbuf} ? ' pending' : '';
1207 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1209 return $self->close if $r < 0;
1210 $self->rbuf_idle($rbuf);
1212 # maybe there's more pipelined data, or we'll have
1213 # to register it for socket-readiness notifications
1214 $self->requeue unless $pending;
1218 sub cmd_compress ($$$) {
1219 my ($self, $tag, $alg) = @_;
1220 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1221 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1223 # CRIME made TLS compression obsolete
1224 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1226 PublicInbox::IMAPdeflate->enable($self) or return
1227 \"$tag BAD failed to activate compression\r\n";
1228 PublicInbox::DS::write($self, \"$tag OK DEFLATE active\r\n");
1233 sub cmd_starttls ($$) {
1234 my ($self, $tag) = @_;
1235 (($self->{sock} // return)->can('stop_SSL') || $self->compressed) and
1236 return "$tag BAD TLS or compression already enabled\r\n";
1237 $self->{imapd}->{ssl_ctx_opt} or
1238 return "$tag BAD can not initiate TLS negotiation\r\n";
1239 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1240 PublicInbox::TLS::start($self->{sock}, $self->{imapd});
1241 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1245 sub busy { # for graceful shutdown in PublicInbox::Daemon:
1247 if (defined($self->{-idle_tag})) {
1248 $self->write(\"* BYE server shutting down\r\n");
1249 return; # not busy anymore
1251 defined($self->{rbuf}) || defined($self->{wbuf}) ||
1252 !$self->write(\"* BYE server shutting down\r\n");
1257 if (my $ibx = delete $self->{ibx}) {
1258 stop_idle($self, $ibx);
1260 $self->SUPER::close; # PublicInbox::DS::close
1263 # we're read-only, so SELECT and EXAMINE do the same thing
1265 *cmd_select = \&cmd_examine;
1267 package PublicInbox::IMAP_preauth;
1268 our @ISA = qw(PublicInbox::IMAP);
1272 package PublicInbox::IMAPdeflate;
1273 use PublicInbox::DSdeflate;
1274 our @ISA = qw(PublicInbox::DSdeflate PublicInbox::IMAP);