1 # Copyright (C) 2020 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
25 package PublicInbox::IMAP;
27 use base qw(PublicInbox::DS);
28 use fields qw(imapd ibx long_cb -login_tag
29 uid_base -idle_tag uo2m);
31 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
32 use PublicInbox::DS qw(now);
33 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
34 use PublicInbox::GitAsyncCat;
35 use Text::ParseWords qw(parse_line);
37 use Time::Local qw(timegm);
38 use POSIX qw(strftime);
39 use Hash::Util qw(unlock_hash); # dependency of fields for perl 5.10+, anyways
40 use PublicInbox::Search;
41 *mdocid = \&PublicInbox::Search::mdocid;
44 for my $mod (qw(Email::Address::XS Mail::Address)) {
45 eval "require $mod" or next;
46 $Address = $mod and last;
48 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
50 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
52 # Changing UID_SLICE will cause grief for clients which cache.
53 # This also needs to be <64K: we pack it into a uint16_t
54 # for long_response UID (offset) => MSN mappings
55 sub UID_SLICE () { 50_000 }
57 # these values area also used for sorting
58 sub NEED_SMSG () { 1 }
59 sub NEED_BLOB () { NEED_SMSG|2 }
60 sub CRLF_BREF () { 4 }
62 sub CRLF_HDR () { 16 }
64 sub CRLF_BDY () { 64 }
65 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
66 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
67 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
68 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
71 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
72 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
73 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
74 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
75 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
76 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
77 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
78 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
79 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
80 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
81 FLAGS => [ 0, \&emit_flags ],
82 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
84 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
86 # aliases (RFC 3501 section 6.4.5)
87 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
88 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
89 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
91 for my $att (keys %FETCH_ATT) {
92 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
93 $FETCH_ATT{$att} = \%h;
97 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
98 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
100 my @MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
102 @MoY{@MoY} = (0..11);
104 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
105 $PublicInbox::DS::EXPTIME = 60 * 30;
109 my $capa = capa($self);
110 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
114 my ($class, $sock, $imapd) = @_;
115 my $self = fields::new('PublicInbox::IMAP_preauth');
119 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
120 return CORE::close($sock) if $! != EAGAIN;
121 $ev = PublicInbox::TLS::epollbit();
122 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
124 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
125 $self->{imapd} = $imapd;
127 $self->{wbuf} = $wbuf;
131 $self->update_idle_time;
140 # dovecot advertises IDLE pre-login; perhaps because some clients
141 # depend on it, so we'll do the same
142 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
143 if ($self->logged_in) {
144 $capa .= ' COMPRESS=DEFLATE';
146 if (!($self->{sock} // $self)->can('accept_SSL') &&
147 $self->{imapd}->{accept_tls}) {
148 $capa .= ' STARTTLS';
150 $capa .= ' AUTH=ANONYMOUS';
154 sub login_success ($$) {
155 my ($self, $tag) = @_;
156 bless $self, 'PublicInbox::IMAP';
157 my $capa = capa($self);
158 "$tag OK [$capa] Logged in\r\n";
161 sub auth_challenge_ok ($) {
163 my $tag = delete($self->{-login_tag}) or return;
164 login_success($self, $tag);
167 sub cmd_login ($$$$) {
168 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
169 login_success($self, $tag);
173 my ($self, $tag) = @_;
174 delete $self->{uid_base};
175 delete $self->{ibx} ? "$tag OK Close done\r\n"
176 : "$tag BAD No mailbox\r\n";
179 sub cmd_logout ($$) {
180 my ($self, $tag) = @_;
181 delete $self->{-idle_tag};
182 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
183 $self->shutdn; # PublicInbox::DS::shutdn
187 sub cmd_authenticate ($$$) {
188 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
189 $self->{-login_tag} = $tag;
193 sub cmd_capability ($$) {
194 my ($self, $tag) = @_;
195 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
198 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
200 # uo2m: UID Offset to MSN, this is an arrayref by default,
201 # but uo2m_hibernate can compact and deduplicate it
202 sub uo2m_ary_new ($) {
204 my $base = $self->{uid_base};
205 my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
207 # convert UIDs to offsets from {base}
208 my @tmp; # [$UID_OFFSET] => $MSN
211 $tmp[$_ - $base] = ++$msn for @$uids;
215 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
216 # uint16_t uo2m[UID_SLICE].
217 # May be swapped out for idle clients if THP is disabled.
218 sub uo2m_hibernate ($) {
220 ref(my $uo2m = $self->{uo2m}) or return;
221 my %dedupe = ( uo2m_pack($uo2m) => undef );
222 $self->{uo2m} = (keys(%dedupe))[0];
226 sub uo2m_last_uid ($) {
228 my $uo2m = $self->{uo2m} or die 'BUG: uo2m_last_uid w/o {uo2m}';
229 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
233 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
234 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
235 no warnings 'uninitialized';
236 pack('S*', @{$_[0]});
239 # extend {uo2m} to account for new messages which arrived since
240 # {uo2m} was created.
241 sub uo2m_extend ($$) {
242 my ($self, $new_uid_max) = @_;
243 defined(my $uo2m = $self->{uo2m}) or
244 return($self->{uo2m} = uo2m_ary_new($self));
245 my $beg = uo2m_last_uid($self); # last UID we've learned
246 return $uo2m if $beg >= $new_uid_max; # fast path
248 # need to extend the current range:
249 my $base = $self->{uid_base};
251 my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
252 my @tmp; # [$UID_OFFSET] => $MSN
254 my $msn = $uo2m->[-1];
255 $tmp[$_ - $beg] = ++$msn for @$uids;
259 my $msn = unpack('S', substr($uo2m, -2, 2));
260 $tmp[$_ - $beg] = ++$msn for @$uids;
261 $uo2m .= uo2m_pack(\@tmp);
262 my %dedupe = ($uo2m => undef);
263 $self->{uo2m} = (keys %dedupe)[0];
267 # the flexible version which works on scalars and array refs.
268 # Must call uo2m_extend before this
270 my ($self, $uid) = @_;
271 my $uo2m = $self->{uo2m};
272 my $off = $uid - $self->{uid_base} - 1;
273 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
276 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
277 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
278 # and does not live beyond the event loop.
281 my $base = $self->{uid_base};
282 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
283 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
287 for my $msn (@$uo2m) {
289 $msn2uid[$msn - 1] = $uo + $base if $msn;
294 # converts a set of message sequence numbers in requests to UIDs:
295 sub msn_to_uid_range ($$) {
297 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
300 # called by PublicInbox::InboxIdle
301 sub on_inbox_unlock {
302 my ($self, $ibx) = @_;
303 my $old = uo2m_last_uid($self);
304 my $uid_end = $self->{uid_base} + UID_SLICE;
305 uo2m_extend($self, $uid_end);
306 my $new = uo2m_last_uid($self);
308 my $msn = uid2msn($self, $new);
309 $self->write(\"* $msn EXISTS\r\n");
310 } elsif ($new == $uid_end) { # max exceeded $uid_end
311 # continue idling w/o inotify
312 my $sock = $self->{sock} or return;
313 $ibx->unsubscribe_unlock(fileno($sock));
317 # called every X minute(s) or so by PublicInbox::DS::later
323 for my $i (values %$old) {
324 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
325 $i->update_idle_time or next;
326 $IDLERS->{fileno($i->{sock})} = $i;
327 $i->write(\"* OK Still here\r\n");
329 $idle_timer = scalar keys %$IDLERS ?
330 PublicInbox::DS::later(\&idle_tick_all) : undef;
334 my ($self, $tag) = @_;
335 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
336 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
337 $self->{-idle_tag} = $tag;
338 my $max = $ibx->over->max;
339 my $uid_end = $self->{uid_base} + UID_SLICE;
340 my $sock = $self->{sock} or return;
341 my $fd = fileno($sock);
342 # only do inotify on most recent slice
343 if ($max < $uid_end) {
344 uo2m_extend($self, $uid_end);
345 $ibx->subscribe_unlock($fd, $self);
346 $self->{imapd}->idler_start;
348 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
349 $IDLERS->{$fd} = $self;
354 my ($self, $ibx) = @_;
355 my $sock = $self->{sock} or return;
356 my $fd = fileno($sock);
357 delete $IDLERS->{$fd};
358 $ibx->unsubscribe_unlock($fd);
362 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
363 defined(my $idle_tag = delete $self->{-idle_tag}) or
364 return "$tag BAD not idle\r\n";
365 my $ibx = $self->{ibx} or do {
366 warn "BUG: idle_tag set w/o inbox";
367 return "$tag BAD internal bug\r\n";
369 stop_idle($self, $ibx);
370 "$idle_tag OK Idle done\r\n";
373 sub ensure_slices_exist ($$$) {
374 my ($imapd, $ibx, $max) = @_;
375 defined(my $mb_top = $ibx->{newsgroup}) or return;
376 my $mailboxes = $imapd->{mailboxes};
378 for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
379 my $sub_mailbox = "$mb_top.$i";
380 last if exists $mailboxes->{$sub_mailbox};
381 $mailboxes->{$sub_mailbox} = $ibx;
382 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
383 push @created, $sub_mailbox;
385 return unless @created;
386 my $l = $imapd->{inboxlist} or return;
387 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
390 sub inbox_lookup ($$) {
391 my ($self, $mailbox) = @_;
392 my ($ibx, $exists, $uidnext, $uid_base);
393 if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
394 # old mail: inbox.comp.foo.$SLICE_IDX
396 $uid_base = $2 * UID_SLICE;
397 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
399 ($exists, $uidnext, $max) = $ibx->over->imap_status($uid_base,
400 $uid_base + UID_SLICE);
401 ensure_slices_exist($self->{imapd}, $ibx, $max);
402 } else { # check for dummy inboxes
403 $mailbox = lc $mailbox;
404 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
406 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
407 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
408 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
409 ensure_slices_exist($self->{imapd}, $z, $z->over->max);
412 $uid_base = $exists = 0;
415 ($ibx, $exists, $uidnext, $uid_base);
418 sub cmd_examine ($$$) {
419 my ($self, $tag, $mailbox) = @_;
420 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox);
421 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
422 $self->{uid_base} = $base;
424 # XXX: do we need this? RFC 5162/7162
425 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
431 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
432 * OK [UNSEEN $exists]\r
433 * OK [UIDNEXT $uidnext]\r
434 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
435 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
443 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
444 '{' . length($v) . "}\r\n" . $v;
445 } else { # quoted string
450 sub addr_envelope ($$;$) {
451 my ($eml, $x, $y) = @_;
452 my $v = $eml->header_raw($x) //
453 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
455 my @x = $Address->parse($v) or return 'NIL';
457 map { '(' . join(' ',
458 _esc($_->name), 'NIL',
459 _esc($_->user), _esc($_->host)
465 sub eml_envelope ($) {
468 _esc($eml->header_raw('Date')),
469 _esc($eml->header_raw('Subject')),
470 addr_envelope($eml, 'From'),
471 addr_envelope($eml, 'Sender', 'From'),
472 addr_envelope($eml, 'Reply-To', 'From'),
473 addr_envelope($eml, 'To'),
474 addr_envelope($eml, 'Cc'),
475 addr_envelope($eml, 'Bcc'),
476 _esc($eml->header_raw('In-Reply-To')),
477 _esc($eml->header_raw('Message-ID')),
483 if ($hash && scalar keys %$hash) {
484 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
485 '(' . join(' ', map { _esc($_) } @$hash) . ')';
491 sub body_disposition ($) {
493 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
494 $cd = parse_content_disposition($cd);
495 my $buf = '('._esc($cd->{type});
496 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
500 sub body_leaf ($$;$) {
501 my ($eml, $structure, $hold) = @_;
503 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
504 $buf .= eml_envelope($eml). ' ';
506 $buf .= '('._esc($ct->{type}).' ';
507 $buf .= _esc($ct->{subtype});
508 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
509 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
510 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
511 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
512 $buf .= ' ' . _esc($cte);
513 $buf .= ' ' . $eml->{imap_body_len};
514 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
516 # for message/(rfc822|global|news), $hold[0] should have envelope
517 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
520 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
521 $buf .= ' '. body_disposition($eml);
522 $buf .= ' '._esc($eml->header_raw('Content-Language'));
523 $buf .= ' '._esc($eml->header_raw('Content-Location'));
528 sub body_parent ($$$) {
529 my ($eml, $structure, $hold) = @_;
531 my $type = lc($ct->{type});
532 if ($type eq 'multipart') {
534 $buf .= @$hold ? join('', @$hold) : 'NIL';
535 $buf .= ' '._esc($ct->{subtype});
537 $buf .= ' '._esc_hash(delete $ct->{attributes});
538 $buf .= ' '.body_disposition($eml);
539 $buf .= ' '._esc($eml->header_raw('Content-Language'));
540 $buf .= ' '._esc($eml->header_raw('Content-Location'));
544 } else { # message/(rfc822|global|news)
545 @$hold = (body_leaf($eml, $structure, $hold));
549 # this is gross, but we need to process the parent part AFTER
550 # the child parts are done
551 sub bodystructure_prep {
553 my ($eml, $depth) = @$p; # ignore idx
554 # set length here, as $eml->{bdy} gets deleted for message/rfc822
555 $eml->{imap_body_len} = length($eml->body_raw);
556 push @$q, $eml, $depth;
559 # for FETCH BODY and FETCH BODYSTRUCTURE
560 sub fetch_body ($;$) {
561 my ($eml, $structure) = @_;
563 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
567 my ($part, $depth) = splice(@q, -2);
568 my $is_mp_parent = $depth == ($cur_depth - 1);
572 body_parent($part, $structure, \@hold);
574 unshift @hold, body_leaf($part, $structure);
580 sub requeue_once ($) {
582 # COMPRESS users all share the same DEFLATE context.
583 # Flush it here to ensure clients don't see
587 # no recursion, schedule another call ASAP,
588 # but only after all pending writes are done.
590 my $new_size = push(@{$self->{wbuf}}, \&long_step);
592 # wbuf may be populated by $cb, no need to rearm if so:
593 $self->requeue if $new_size == 1;
597 my ($self, $smsg, $bref, $ops, $partial) = @_;
598 my $uid = $smsg->{num};
599 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
601 for (my $i = 0; $i < @$ops;) {
603 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
605 partial_emit($self, $partial, $eml) if $partial;
606 $self->msg_more(")\r\n");
609 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
610 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
611 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
612 my $smsg = shift @$msgs or die 'BUG: no smsg';
613 if (!defined($oid)) {
614 # it's possible to have TOCTOU if an admin runs
615 # public-inbox-(edit|purge), just move onto the next message
616 return requeue_once($self);
618 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
620 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
625 my ($self, $k, undef, $bref) = @_;
626 $self->msg_more(" $k {" . length($$bref)."}\r\n");
627 $self->msg_more($$bref);
630 # Mail::IMAPClient::message_string cares about this by default,
631 # (->Ignoresizeerrors attribute). Admins are encouraged to
632 # --reindex for IMAP support, anyways.
633 sub emit_rfc822_size {
634 my ($self, $k, $smsg) = @_;
635 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
638 sub emit_internaldate {
639 my ($self, undef, $smsg) = @_;
640 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
643 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
646 my ($self, undef, undef, undef, $eml) = @_;
647 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
650 sub emit_rfc822_header {
651 my ($self, $k, undef, undef, $eml) = @_;
652 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
653 $self->msg_more(${$eml->{hdr}});
656 # n.b. this is sorted to be after any emit_eml_new ops
657 sub emit_rfc822_text {
658 my ($self, $k, undef, $bref) = @_;
659 $self->msg_more(" $k {".length($$bref)."}\r\n");
660 $self->msg_more($$bref);
663 sub emit_bodystructure {
664 my ($self, undef, undef, undef, $eml) = @_;
665 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
669 my ($self, undef, undef, undef, $eml) = @_;
670 $self->msg_more(' BODY '.fetch_body($eml));
673 # set $eml once ($_[4] == $eml, $_[3] == $bref)
674 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
676 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
678 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
679 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
682 sub op_crlf_bref { to_crlf_full($_[3]) }
684 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
686 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
688 sub uid_clamp ($$$) {
689 my ($self, $beg, $end) = @_;
690 my $uid_min = $self->{uid_base} + 1;
691 my $uid_end = $uid_min + UID_SLICE - 1;
692 $$beg = $uid_min if $$beg < $uid_min;
693 $$end = $uid_end if $$end > $uid_end;
696 sub range_step ($$) {
697 my ($self, $range_csv) = @_;
698 my ($beg, $end, $range);
699 if ($$range_csv =~ s/\A([^,]+),//) {
702 $range = $$range_csv;
705 my $uid_base = $self->{uid_base};
706 my $uid_end = $uid_base + UID_SLICE;
707 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
708 ($beg, $end) = ($1 + 0, $2 + 0);
709 uid_clamp($self, \$beg, \$end);
710 } elsif ($range =~ /\A([0-9]+):\*\z/) {
712 $end = $self->{ibx}->over->max;
713 $end = $uid_end if $end > $uid_end;
714 $beg = $end if $beg > $end;
715 uid_clamp($self, \$beg, \$end);
716 } elsif ($range =~ /\A[0-9]+\z/) {
717 $beg = $end = $range + 0;
718 # just let the caller do an out-of-range query if a single
719 # UID is out-of-range
720 ++$beg if ($beg <= $uid_base || $end > $uid_end);
722 return 'BAD fetch range';
724 [ $beg, $end, $$range_csv ];
727 sub refill_range ($$$) {
728 my ($self, $msgs, $range_info) = @_;
729 my ($beg, $end, $range_csv) = @$range_info;
730 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
731 $range_info->[0] = $msgs->[-1]->{num} + 1;
734 return 'OK Fetch done' if !$range_csv;
735 my $next_range = range_step($self, \$range_csv);
736 return $next_range if !ref($next_range); # error
737 @$range_info = @$next_range;
738 undef; # keep looping
741 sub fetch_blob { # long_response
742 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
743 while (!@$msgs) { # rare
744 if (my $end = refill_range($self, $msgs, $range_info)) {
745 $self->write(\"$tag $end\r\n");
749 uo2m_extend($self, $msgs->[-1]->{num});
750 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
751 \&fetch_blob_cb, \@_);
754 sub fetch_smsg { # long_response
755 my ($self, $tag, $msgs, $range_info, $ops) = @_;
756 while (!@$msgs) { # rare
757 if (my $end = refill_range($self, $msgs, $range_info)) {
758 $self->write(\"$tag $end\r\n");
762 uo2m_extend($self, $msgs->[-1]->{num});
763 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
768 sub refill_uids ($$$;$) {
769 my ($self, $uids, $range_info, $sql) = @_;
770 my ($beg, $end, $range_csv) = @$range_info;
771 my $over = $self->{ibx}->over;
773 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
774 $range_info->[0] = $uids->[-1] + 1; # update $beg
776 } elsif (!$range_csv) {
779 my $next_range = range_step($self, \$range_csv);
780 return $next_range if !ref($next_range); # error
781 ($beg, $end, $range_csv) = @$range_info = @$next_range;
787 sub fetch_uid { # long_response
788 my ($self, $tag, $uids, $range_info, $ops) = @_;
789 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
790 $err ||= 'OK Fetch done';
791 $self->write("$tag $err\r\n");
794 my $adj = $self->{uid_base} + 1;
795 my $uo2m = uo2m_extend($self, $uids->[-1]);
796 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
799 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
800 for ($i = 0; $i < @$ops;) {
802 $ops->[$i++]->($self, $k);
804 $self->msg_more(")\r\n");
810 sub cmd_status ($$$;@) {
811 my ($self, $tag, $mailbox, @items) = @_;
812 return "$tag BAD no items\r\n" if !scalar(@items);
813 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
814 return "$tag BAD invalid args\r\n";
815 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
816 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
818 for my $it (@items) {
821 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
823 } elsif ($it eq 'UIDNEXT') {
825 } elsif ($it eq 'UIDVALIDITY') {
826 push @it, $ibx->{uidvalidity};
828 return "$tag BAD invalid item\r\n";
831 return "$tag BAD no items\r\n" if !@it;
832 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
833 "$tag OK Status done\r\n";
836 my %patmap = ('*' => '.*', '%' => '[^\.]*');
837 sub cmd_list ($$$$) {
838 my ($self, $tag, $refname, $wildcard) = @_;
839 my $l = $self->{imapd}->{inboxlist};
840 if ($refname eq '' && $wildcard eq '') {
841 # request for hierarchy delimiter
842 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
843 } elsif ($refname ne '' || $wildcard ne '*') {
844 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
845 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
847 \(join('', @$l, "$tag OK List done\r\n"));
850 sub cmd_lsub ($$$$) {
851 my (undef, $tag) = @_; # same args as cmd_list
852 "$tag OK Lsub done\r\n";
855 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
857 my ($eml, undef, $idx) = @$p;
858 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
859 $eml->{imap_bdy} = $eml->{bdy} // \'';
861 $all->{$idx} = $eml; # $idx => Eml
864 # prepares an index for BODY[$SECTION_IDX] fetches
865 sub eml_body_idx ($$) {
866 my ($eml, $section_idx) = @_;
867 my $idx = $eml->{imap_all_parts} //= do {
869 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
870 # top-level of multipart, BODY[0] not allowed (nz-number)
874 $idx->{$section_idx};
877 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
879 my ($eml, $section_idx, $section_name) = @_;
880 if (defined $section_idx) {
881 $eml = eml_body_idx($eml, $section_idx) or return;
883 if (defined $section_name) {
884 if ($section_name eq 'MIME') {
885 # RFC 3501 6.4.5 states:
886 # The MIME part specifier MUST be prefixed
887 # by one or more numeric part specifiers
888 return unless defined $section_idx;
889 return $eml->header_obj->as_string . "\r\n";
891 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
892 $eml = PublicInbox::Eml->new($$bdy);
893 if ($section_name eq 'TEXT') {
894 return $eml->body_raw;
895 } elsif ($section_name eq 'HEADER') {
896 return $eml->header_obj->as_string . "\r\n";
898 die "BUG: bad section_name=$section_name";
901 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
904 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
905 # to avoid OOM with malicious users
906 sub hdrs_regexp ($) {
908 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
909 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
910 # continuation lines:
911 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
915 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
916 sub partial_hdr_not {
917 my ($eml, $section_idx, $hdrs_re) = @_;
918 if (defined $section_idx) {
919 $eml = eml_body_idx($eml, $section_idx) or return;
921 my $str = $eml->header_obj->as_string;
922 $str =~ s/$hdrs_re//g;
923 $str =~ s/(?<!\r)\n/\r\n/sg;
927 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
928 sub partial_hdr_get {
929 my ($eml, $section_idx, $hdrs_re) = @_;
930 if (defined $section_idx) {
931 $eml = eml_body_idx($eml, $section_idx) or return;
933 my $str = $eml->header_obj->as_string;
934 $str = join('', ($str =~ m/($hdrs_re)/g));
935 $str =~ s/(?<!\r)\n/\r\n/sg;
939 sub partial_prepare ($$$$) {
940 my ($need, $partial, $want, $att) = @_;
942 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
943 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
944 return unless $att =~ /\ABODY\[/s;
945 until (rindex($att, ']') >= 0) {
946 my $next = shift @$want or return;
947 $att .= ' ' . uc($next);
949 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
950 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
951 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
952 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
953 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
954 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
955 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
956 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
957 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
958 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
961 $tmp->[2] = hdrs_regexp($3);
963 # don't emit CRLF_HDR instruction, here, partial_hdr_*
964 # will do CRLF conversion with only the extracted result
965 # and not waste time converting lines we don't care about.
972 sub partial_emit ($$$) {
973 my ($self, $partial, $eml) = @_;
975 my ($k, $cb, @args) = @$_;
976 my ($offset, $len) = splice(@args, -2);
977 # $cb is partial_body|partial_hdr_get|partial_hdr_not
978 my $str = $cb->($eml, @args) // '';
979 if (defined $offset) {
981 $str = substr($str, $offset, $len);
982 $k =~ s/\.$len>\z/>/ or warn
983 "BUG: unable to remove `.$len>' from `$k'";
985 $str = substr($str, $offset);
991 $self->msg_more(" $k {$len}\r\n");
992 $self->msg_more($str);
996 sub fetch_compile ($) {
998 if ($want->[0] =~ s/\A\(//s) {
999 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1001 my (%partial, %seen, @op);
1003 while (defined(my $att = shift @$want)) {
1005 next if $att eq 'UID'; # always returned
1006 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1007 my $x = $FETCH_ATT{$att};
1009 while (my ($k, $fl_cb) = each %$x) {
1010 next if $seen{$k}++;
1011 $need |= $fl_cb->[0];
1012 push @op, [ @$fl_cb, $k ];
1014 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1015 return "BAD param: $att";
1020 # stabilize partial order for consistency and ease-of-debugging:
1021 if (scalar keys %partial) {
1023 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1026 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1028 # do we need CRLF conversion?
1029 if ($need & CRLF_BREF) {
1030 push @op, $OP_CRLF_BREF;
1031 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1032 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1033 push @op, $OP_CRLF_BREF;
1034 } elsif ($need & CRLF_HDR) {
1035 push @op, $OP_CRLF_HDR;
1037 push @op, $OP_CRLF_BDY;
1041 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1042 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1044 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1045 use sort 'stable'; # makes output more consistent
1046 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1050 sub cmd_uid_fetch ($$$$;@) {
1051 my ($self, $tag, $range_csv, @want) = @_;
1052 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1053 my ($cb, $ops, $partial) = fetch_compile(\@want);
1054 return "$tag $cb\r\n" unless $ops;
1056 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1057 $range_csv = 'bad' if $range_csv !~ $valid_range;
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 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1064 sub cmd_fetch ($$$$;@) {
1065 my ($self, $tag, $range_csv, @want) = @_;
1066 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1067 my ($cb, $ops, $partial) = fetch_compile(\@want);
1068 return "$tag $cb\r\n" unless $ops;
1070 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1071 $range_csv = 'bad' if $range_csv !~ $valid_range;
1072 msn_to_uid_range(msn2uid($self), $range_csv);
1073 my $range_info = range_step($self, \$range_csv);
1074 return "$tag $range_info\r\n" if !ref($range_info);
1075 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1076 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1079 sub parse_date ($) { # 02-Oct-1993
1080 my ($date_text) = @_;
1081 my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
1082 defined($yyyy) or return;
1083 my $mm = $MoY{$mon} // return;
1084 $dd =~ /\A[0123]?[0-9]\z/ or return;
1085 $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
1086 timegm(0, 0, 0, $dd, $mm, $yyyy);
1089 sub msn_convert ($$) {
1090 my ($self, $uids) = @_;
1091 my $adj = $self->{uid_base} + 1;
1092 my $uo2m = uo2m_extend($self, $uids->[-1]);
1093 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1094 $_ = $uo2m->[$_ - $adj] for @$uids;
1097 sub search_uid_range { # long_response
1098 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1100 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1101 $err ||= 'OK Search done';
1102 $self->write("\r\n$tag $err\r\n");
1105 msn_convert($self, $uids) if $want_msn;
1106 $self->msg_more(join(' ', '', @$uids));
1111 my ($q, $k, $d) = @_;
1112 my $sql = $q->{sql};
1115 if ($k eq 'SENTON') {
1116 my $end = $d + 86399; # no leap day...
1117 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1118 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1119 $q->{xap} .= " dt:$da..$db";
1120 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1121 } elsif ($k eq 'SENTBEFORE') {
1122 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1123 $$sql .= " AND ds <= $d" if defined($sql);
1124 } elsif ($k eq 'SENTSINCE') {
1125 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1126 $$sql .= " AND ds >= $d" if defined($sql);
1128 # INTERNALDATE (Received)
1129 } elsif ($k eq 'ON') {
1130 my $end = $d + 86399; # no leap day...
1131 $q->{xap} .= " ts:$d..$end";
1132 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1133 } elsif ($k eq 'BEFORE') {
1134 $q->{xap} .= " ts:..$d";
1135 $$sql .= " AND ts <= $d" if defined($sql);
1136 } elsif ($k eq 'SINCE') {
1137 $q->{xap} .= " ts:$d..";
1138 $$sql .= " AND ts >= $d" if defined($sql);
1140 die "BUG: $k not recognized";
1144 # IMAP to Xapian search key mapping
1149 TEXT => '', # n.b. does not include all headers
1152 # BCC => 'bcc:', # TODO
1153 # KEYWORD # TODO ? dfpre,dfpost,...
1156 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1157 # which gets silly expensive. We only allow the headers we already index.
1158 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1160 sub xap_append ($$$$) {
1161 my ($q, $rest, $k, $xk) = @_;
1162 delete $q->{sql}; # can't use over.sqlite3
1163 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1165 # AFAIK Xapian can't handle [*"] in probabilistic terms
1167 ${$q->{xap}} .= qq[ $xk"$arg"];
1172 my ($self, $rest) = @_;
1173 if (uc($rest->[0]) eq 'CHARSET') {
1175 defined(my $c = shift @$rest) or return 'BAD missing charset';
1176 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
1179 my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
1181 my $q = { sql => \$sql, xap => \$xap };
1184 my $k = uc(shift @$rest);
1186 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
1187 next if $k eq 'AND'; # the default, until we support OR
1188 if ($k =~ $valid_range) { # convert sequence numbers to UIDs
1189 msn_to_uid_range($msn2uid //= msn2uid($self), $k);
1190 push @{$q->{uid}}, $k;
1191 } elsif ($k eq 'UID') {
1192 $k = shift(@$rest) // '';
1193 $k =~ $valid_range or return 'BAD UID range';
1194 push @{$q->{uid}}, $k;
1195 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
1196 my $d = parse_date(shift(@$rest) // '');
1197 defined $d or return "BAD $k date format";
1198 date_search($q, $k, $d);
1199 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
1200 delete $q->{sql}; # can't use over.sqlite3
1201 my $bytes = shift(@$rest) // '';
1202 $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
1203 $xap .= ' bytes:' . ($k eq 'SMALLER' ?
1206 } elsif ($k eq 'HEADER') {
1207 $k = uc(shift(@$rest) // '');
1208 my $xk = $H2X{$k} or
1209 return "BAD HEADER $k not supported";
1210 my $err = xap_append($q, $rest, $k, $xk);
1211 return $err if $err;
1212 } elsif (defined(my $xk = $I2X{$k})) {
1213 my $err = xap_append($q, $rest, $k, $xk);
1214 return $err if $err;
1216 # TODO: parentheses, OR, NOT ...
1217 return "BAD $k not supported (yet?)";
1221 # favor using over.sqlite3 if possible, since Xapian is optional
1222 if (exists $q->{sql}) {
1224 delete($q->{sql}) if $sql eq '';
1225 } elsif (!$self->{ibx}->search) {
1226 return 'BAD Xapian not configured for mailbox';
1228 my $max = $self->{ibx}->over->max;
1229 if (my $uid = delete $q->{uid}) {
1230 my $range_csv = join(',', @$uid);
1232 my $nxt = range_step($self, \$range_csv);
1233 my ($beg, $end) = @$nxt;
1235 $xap .= " uid:$beg..$end";
1236 } elsif ($beg == $end) {
1237 $sql .= " AND num = $beg";
1239 $sql .= " AND num >= $beg AND num <= $end";
1241 } while ($range_csv);
1244 uid_clamp($self, \$beg, \$max);
1245 $q->{range_info} = [ $beg, $max ];
1249 sub refill_xap ($$$$) {
1250 my ($self, $uids, $range_info, $q) = @_;
1251 my ($beg, $end) = @$range_info;
1252 my $srch = $self->{ibx}->search;
1253 my $opt = { mset => 2, limit => 1000 };
1254 my $nshard = $srch->{nshard} // 1;
1256 my $mset = $srch->query("$$q uid:$beg..$end", $opt);
1257 @$uids = map { mdocid($nshard, $_) } $mset->items;
1259 $range_info->[0] = $uids->[-1] + 1; # update $beg
1267 sub search_xap_range { # long_response
1268 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1270 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1271 $err ||= 'OK Search done';
1272 $self->write("\r\n$tag $err\r\n");
1275 msn_convert($self, $uids) if $want_msn;
1276 $self->msg_more(join(' ', '', @$uids));
1281 my ($self, $tag, $rest, $want_msn) = @_;
1282 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1283 my $q = parse_query($self, $rest);
1284 return "$tag $q\r\n" if !ref($q);
1285 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1286 if (!scalar(keys %$q)) { # overview.sqlite3
1287 $self->msg_more('* SEARCH');
1288 long_response($self, \&search_uid_range,
1289 $tag, $sql, $range_info, $want_msn);
1290 } elsif ($q = $q->{xap}) {
1291 $self->msg_more('* SEARCH');
1292 long_response($self, \&search_xap_range,
1293 $tag, $q, $range_info, $want_msn);
1295 "$tag BAD Error\r\n";
1299 sub cmd_uid_search ($$$;) {
1300 my ($self, $tag) = splice(@_, 0, 2);
1301 search_common($self, $tag, \@_);
1304 sub cmd_search ($$$;) {
1305 my ($self, $tag) = splice(@_, 0, 2);
1306 search_common($self, $tag, \@_, 1);
1309 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1310 my ($cb, $argc) = @_;
1311 my $tot = prototype $cb;
1312 my ($nreq, undef) = split(';', $tot);
1313 $nreq = ($nreq =~ tr/$//) - 1;
1314 $tot = ($tot =~ tr/$//) - 1;
1315 ($argc <= $tot && $argc >= $nreq);
1318 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1319 sub process_line ($$) {
1320 my ($self, $l) = @_;
1322 # TODO: IMAP allows literals for big requests to upload messages
1323 # (which we don't support) but maybe some big search queries use it.
1324 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1325 pop(@args) if (@args && !defined($args[-1]));
1326 if (@args && uc($req) eq 'UID') {
1327 $req .= "_".(shift @args);
1330 if (defined(my $idle_tag = $self->{-idle_tag})) {
1331 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1332 idle_done($self, $tag) :
1333 "$idle_tag BAD expected DONE\r\n";
1334 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1335 $cmd->($self, $tag, @args);
1336 } else { # this is weird
1337 auth_challenge_ok($self) //
1339 ' BAD Error in IMAP command '.
1341 ": Unknown command\r\n";
1345 if ($err && $self->{sock}) {
1347 err($self, 'error from: %s (%s)', $l, $err);
1349 $res = "$tag BAD program fault - command not performed\r\n";
1351 return 0 unless defined $res;
1357 # wbuf is unset or empty, here; {long} may add to it
1358 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1359 my $more = eval { $cb->($self, @args) };
1360 if ($@ || !$self->{sock}) { # something bad happened...
1361 delete $self->{long_cb};
1362 my $elapsed = now() - $t0;
1365 "%s during long response[$fd] - %0.6f",
1368 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1370 } elsif ($more) { # $self->{wbuf}:
1371 $self->update_idle_time;
1373 # control passed to $more may be a GitAsyncCat object
1374 requeue_once($self) if !ref($more);
1375 } else { # all done!
1376 delete $self->{long_cb};
1377 my $elapsed = now() - $t0;
1378 my $fd = fileno($self->{sock});
1379 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1380 my $wbuf = $self->{wbuf}; # do NOT autovivify
1382 $self->requeue unless $wbuf && @$wbuf;
1387 my ($self, $fmt, @args) = @_;
1388 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1392 my ($self, $fmt, @args) = @_;
1393 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1396 sub long_response ($$;@) {
1397 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1399 my $sock = $self->{sock} or return;
1400 # make sure we disable reading during a long response,
1401 # clients should not be sending us stuff and making us do more
1402 # work while we are stream a response to them
1403 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1404 long_step($self); # kick off!
1408 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1412 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1414 $self->update_idle_time;
1415 # only read more requests if we've drained the write buffer,
1416 # otherwise we can be buffering infinitely w/o backpressure
1418 my $rbuf = $self->{rbuf} // \(my $x = '');
1419 my $line = index($$rbuf, "\n");
1421 if (length($$rbuf) >= LINE_MAX) {
1422 $self->write(\"\* BAD request too long\r\n");
1423 return $self->close;
1425 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1426 return uo2m_hibernate($self);
1427 $line = index($$rbuf, "\n");
1429 $line = substr($$rbuf, 0, $line + 1, '');
1430 $line =~ s/\r?\n\z//s;
1431 return $self->close if $line =~ /[[:cntrl:]]/s;
1433 my $fd = fileno($self->{sock});
1434 my $r = eval { process_line($self, $line) };
1435 my $pending = $self->{wbuf} ? ' pending' : '';
1436 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1438 return $self->close if $r < 0;
1439 $self->rbuf_idle($rbuf);
1440 $self->update_idle_time;
1442 # maybe there's more pipelined data, or we'll have
1443 # to register it for socket-readiness notifications
1444 $self->requeue unless $pending;
1447 sub compressed { undef }
1449 sub zflush {} # overridden by IMAPdeflate
1452 sub cmd_compress ($$$) {
1453 my ($self, $tag, $alg) = @_;
1454 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1455 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1457 # CRIME made TLS compression obsolete
1458 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1460 PublicInbox::IMAPdeflate->enable($self, $tag);
1465 sub cmd_starttls ($$) {
1466 my ($self, $tag) = @_;
1467 my $sock = $self->{sock} or return;
1468 if ($sock->can('stop_SSL') || $self->compressed) {
1469 return "$tag BAD TLS or compression already enabled\r\n";
1471 my $opt = $self->{imapd}->{accept_tls} or
1472 return "$tag BAD can not initiate TLS negotiation\r\n";
1473 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1474 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1475 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1479 # for graceful shutdown in PublicInbox::Daemon:
1481 my ($self, $now) = @_;
1482 if (defined($self->{-idle_tag})) {
1483 $self->write(\"* BYE server shutting down\r\n");
1484 return; # not busy anymore
1486 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1491 if (my $ibx = delete $self->{ibx}) {
1492 stop_idle($self, $ibx);
1494 $self->SUPER::close; # PublicInbox::DS::close
1497 # we're read-only, so SELECT and EXAMINE do the same thing
1499 *cmd_select = \&cmd_examine;
1501 package PublicInbox::IMAP_preauth;
1502 our @ISA = qw(PublicInbox::IMAP);