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
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::Syscall qw(EPOLLIN EPOLLONESHOT);
40 use PublicInbox::GitAsyncCat;
41 use Text::ParseWords qw(parse_line);
43 use PublicInbox::IMAPsearchqp;
46 for my $mod (qw(Email::Address::XS Mail::Address)) {
47 eval "require $mod" or next;
48 $Address = $mod and last;
50 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
52 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
54 # Changing UID_SLICE will cause grief for clients which cache.
55 # This also needs to be <64K: we pack it into a uint16_t
56 # for long_response UID (offset) => MSN mappings
57 sub UID_SLICE () { 50_000 }
59 # these values area also used for sorting
60 sub NEED_SMSG () { 1 }
61 sub NEED_BLOB () { NEED_SMSG|2 }
62 sub CRLF_BREF () { 4 }
64 sub CRLF_HDR () { 16 }
66 sub CRLF_BDY () { 64 }
67 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
68 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
69 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
70 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
73 'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
74 'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
75 'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
76 'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
77 'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
78 'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
79 RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
80 BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
81 BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
82 ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
83 FLAGS => [ 0, \&emit_flags ],
84 INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
86 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
88 # aliases (RFC 3501 section 6.4.5)
89 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
90 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
91 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
93 for my $att (keys %FETCH_ATT) {
94 my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
95 $FETCH_ATT{$att} = \%h;
99 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
100 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
102 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
103 $PublicInbox::DS::EXPTIME = 60 * 30;
107 my $capa = capa($self);
108 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
112 my ($class, $sock, $imapd) = @_;
113 my $self = bless { imapd => $imapd }, 'PublicInbox::IMAP_preauth';
116 if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
117 return CORE::close($sock) if $! != EAGAIN;
118 $ev = PublicInbox::TLS::epollbit();
119 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
121 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
123 $self->{wbuf} = $wbuf;
127 $self->update_idle_time;
136 # dovecot advertises IDLE pre-login; perhaps because some clients
137 # depend on it, so we'll do the same
138 my $capa = 'CAPABILITY IMAP4rev1 IDLE';
139 if ($self->logged_in) {
140 $capa .= ' COMPRESS=DEFLATE';
142 if (!($self->{sock} // $self)->can('accept_SSL') &&
143 $self->{imapd}->{accept_tls}) {
144 $capa .= ' STARTTLS';
146 $capa .= ' AUTH=ANONYMOUS';
150 sub login_success ($$) {
151 my ($self, $tag) = @_;
152 bless $self, 'PublicInbox::IMAP';
153 my $capa = capa($self);
154 "$tag OK [$capa] Logged in\r\n";
157 sub auth_challenge_ok ($) {
159 my $tag = delete($self->{-login_tag}) or return;
160 login_success($self, $tag);
163 sub cmd_login ($$$$) {
164 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
165 login_success($self, $tag);
169 my ($self, $tag) = @_;
170 delete @$self{qw(uid_base uo2m)};
171 delete $self->{ibx} ? "$tag OK Close done\r\n"
172 : "$tag BAD No mailbox\r\n";
175 sub cmd_logout ($$) {
176 my ($self, $tag) = @_;
177 delete $self->{-idle_tag};
178 $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
179 $self->shutdn; # PublicInbox::DS::shutdn
183 sub cmd_authenticate ($$$) {
184 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
185 $self->{-login_tag} = $tag;
189 sub cmd_capability ($$) {
190 my ($self, $tag) = @_;
191 '* '.capa($self)."\r\n$tag OK Capability done\r\n";
194 # uo2m: UID Offset to MSN, this is an arrayref by default,
195 # but uo2m_hibernate can compact and deduplicate it
196 sub uo2m_ary_new ($;$) {
197 my ($self, $exists) = @_;
198 my $base = $self->{uid_base};
199 my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
201 # convert UIDs to offsets from {base}
202 my @tmp; # [$UID_OFFSET] => $MSN
205 $tmp[$_ - $base] = ++$msn for @$uids;
206 $$exists = $msn if $exists;
210 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
211 # uint16_t uo2m[UID_SLICE].
212 # May be swapped out for idle clients if THP is disabled.
213 sub uo2m_hibernate ($) {
215 ref(my $uo2m = $self->{uo2m}) or return;
216 my %dedupe = ( uo2m_pack($uo2m) => undef );
217 $self->{uo2m} = (keys(%dedupe))[0];
221 sub uo2m_last_uid ($) {
223 defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
224 (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
228 # $_[0] is an arrayref of MSNs, it may have undef gaps if there
229 # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
230 no warnings 'uninitialized';
231 pack('S*', @{$_[0]});
234 # extend {uo2m} to account for new messages which arrived since
235 # {uo2m} was created.
236 sub uo2m_extend ($$;$) {
237 my ($self, $new_uid_max) = @_;
238 defined(my $uo2m = $self->{uo2m}) or
239 return($self->{uo2m} = uo2m_ary_new($self));
240 my $beg = uo2m_last_uid($self); # last UID we've learned
241 return $uo2m if $beg >= $new_uid_max; # fast path
243 # need to extend the current range:
244 my $base = $self->{uid_base};
246 my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
247 return $uo2m if !scalar(@$uids);
248 my @tmp; # [$UID_OFFSET] => $MSN
249 my $write_method = $_[2] // 'msg_more';
251 my $msn = $uo2m->[-1];
252 $tmp[$_ - $beg] = ++$msn for @$uids;
253 $self->$write_method("* $msn EXISTS\r\n");
257 my $msn = unpack('S', substr($uo2m, -2, 2));
258 $tmp[$_ - $beg] = ++$msn for @$uids;
259 $self->$write_method("* $msn EXISTS\r\n");
260 $uo2m .= uo2m_pack(\@tmp);
261 my %dedupe = ($uo2m => undef);
262 $self->{uo2m} = (keys %dedupe)[0];
267 my ($self, $tag) = @_;
268 defined($self->{uid_base}) and
269 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
270 \"$tag OK Noop done\r\n";
273 # the flexible version which works on scalars and array refs.
274 # Must call uo2m_extend before this
276 my ($self, $uid) = @_;
277 my $uo2m = $self->{uo2m};
278 my $off = $uid - $self->{uid_base} - 1;
279 ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
282 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
283 # $msn2uid->[$MSN-1] => $UID. The result of this is always ephemeral
284 # and does not live beyond the event loop.
287 my $base = $self->{uid_base};
288 my $uo2m = uo2m_extend($self, $base + UID_SLICE);
289 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
293 for my $msn (@$uo2m) {
295 $msn2uid[$msn - 1] = $uo + $base if $msn;
300 # converts a set of message sequence numbers in requests to UIDs:
301 sub msn_to_uid_range ($$) {
303 $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
306 # called by PublicInbox::InboxIdle
307 sub on_inbox_unlock {
308 my ($self, $ibx) = @_;
309 my $uid_end = $self->{uid_base} + UID_SLICE;
310 uo2m_extend($self, $uid_end, 'write');
311 my $new = uo2m_last_uid($self);
312 if ($new == $uid_end) { # max exceeded $uid_end
313 # continue idling w/o inotify
314 my $sock = $self->{sock} or return;
315 $ibx->unsubscribe_unlock(fileno($sock));
319 # called every X minute(s) or so by PublicInbox::DS::later
325 for my $i (values %$old) {
326 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
327 $i->update_idle_time or next;
328 $IDLERS->{fileno($i->{sock})} = $i;
329 $i->write(\"* OK Still here\r\n");
331 $idle_timer = scalar keys %$IDLERS ?
332 PublicInbox::DS::later(\&idle_tick_all) : undef;
336 my ($self, $tag) = @_;
337 # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
338 my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
339 my $uid_end = $self->{uid_base} + UID_SLICE;
340 uo2m_extend($self, $uid_end);
341 my $sock = $self->{sock} or return;
342 my $fd = fileno($sock);
343 $self->{-idle_tag} = $tag;
344 # only do inotify on most recent slice
345 if ($ibx->over->max < $uid_end) {
346 $ibx->subscribe_unlock($fd, $self);
347 $self->{imapd}->idler_start;
349 $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
350 $IDLERS->{$fd} = $self;
355 my ($self, $ibx) = @_;
356 my $sock = $self->{sock} or return;
357 my $fd = fileno($sock);
358 delete $IDLERS->{$fd};
359 $ibx->unsubscribe_unlock($fd);
363 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
364 defined(my $idle_tag = delete $self->{-idle_tag}) or
365 return "$tag BAD not idle\r\n";
366 my $ibx = $self->{ibx} or do {
367 warn "BUG: idle_tag set w/o inbox";
368 return "$tag BAD internal bug\r\n";
370 stop_idle($self, $ibx);
371 "$idle_tag OK Idle done\r\n";
374 sub ensure_slices_exist ($$$) {
375 my ($imapd, $ibx, $max) = @_;
376 defined(my $mb_top = $ibx->{newsgroup}) or return;
377 my $mailboxes = $imapd->{mailboxes};
379 for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
380 my $sub_mailbox = "$mb_top.$i";
381 last if exists $mailboxes->{$sub_mailbox};
382 $mailboxes->{$sub_mailbox} = $ibx;
383 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
384 push @created, $sub_mailbox;
386 return unless @created;
387 my $l = $imapd->{inboxlist} or return;
388 push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
391 sub inbox_lookup ($$;$) {
392 my ($self, $mailbox, $examine) = @_;
393 my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
394 $mailbox = lc $mailbox;
395 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
396 my $over = $ibx->over;
397 if ($over != $ibx) { # not a dummy
398 $mailbox =~ /\.([0-9]+)\z/ or
399 die "BUG: unexpected dummy mailbox: $mailbox\n";
400 $uid_base = $1 * UID_SLICE;
402 # ->num_highwater caches for writers, so use ->meta_accessor
403 $uidmax = $ibx->mm->meta_accessor('num_highwater') // 0;
405 $self->{uid_base} = $uid_base;
407 $self->{uo2m} = uo2m_ary_new($self, \$exists);
409 $exists = $over->imap_exists;
411 ensure_slices_exist($self->{imapd}, $ibx, $over->max);
414 $self->{uid_base} = $uid_base;
416 delete $self->{uo2m};
418 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
419 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
420 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
421 ensure_slices_exist($self->{imapd}, $z, $z->over->max);
424 ($ibx, $exists, $uidmax + 1, $uid_base);
427 sub cmd_examine ($$$) {
428 my ($self, $tag, $mailbox) = @_;
429 # XXX: do we need this? RFC 5162/7162
430 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
431 my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox, 1);
432 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
437 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
438 * OK [UNSEEN $exists]\r
439 * OK [UIDNEXT $uidnext]\r
440 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
441 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
449 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
450 '{' . length($v) . "}\r\n" . $v;
451 } else { # quoted string
456 sub addr_envelope ($$;$) {
457 my ($eml, $x, $y) = @_;
458 my $v = $eml->header_raw($x) //
459 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
461 my @x = $Address->parse($v) or return 'NIL';
463 map { '(' . join(' ',
464 _esc($_->name), 'NIL',
465 _esc($_->user), _esc($_->host)
471 sub eml_envelope ($) {
474 _esc($eml->header_raw('Date')),
475 _esc($eml->header_raw('Subject')),
476 addr_envelope($eml, 'From'),
477 addr_envelope($eml, 'Sender', 'From'),
478 addr_envelope($eml, 'Reply-To', 'From'),
479 addr_envelope($eml, 'To'),
480 addr_envelope($eml, 'Cc'),
481 addr_envelope($eml, 'Bcc'),
482 _esc($eml->header_raw('In-Reply-To')),
483 _esc($eml->header_raw('Message-ID')),
489 if ($hash && scalar keys %$hash) {
490 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
491 '(' . join(' ', map { _esc($_) } @$hash) . ')';
497 sub body_disposition ($) {
499 my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
500 $cd = parse_content_disposition($cd);
501 my $buf = '('._esc($cd->{type});
502 $buf .= ' ' . _esc_hash(delete $cd->{attributes});
506 sub body_leaf ($$;$) {
507 my ($eml, $structure, $hold) = @_;
509 $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
510 $buf .= eml_envelope($eml). ' ';
512 $buf .= '('._esc($ct->{type}).' ';
513 $buf .= _esc($ct->{subtype});
514 $buf .= ' ' . _esc_hash(delete $ct->{attributes});
515 $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
516 $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
517 my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
518 $buf .= ' ' . _esc($cte);
519 $buf .= ' ' . $eml->{imap_body_len};
520 $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
522 # for message/(rfc822|global|news), $hold[0] should have envelope
523 $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
526 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
527 $buf .= ' '. body_disposition($eml);
528 $buf .= ' '._esc($eml->header_raw('Content-Language'));
529 $buf .= ' '._esc($eml->header_raw('Content-Location'));
534 sub body_parent ($$$) {
535 my ($eml, $structure, $hold) = @_;
537 my $type = lc($ct->{type});
538 if ($type eq 'multipart') {
540 $buf .= @$hold ? join('', @$hold) : 'NIL';
541 $buf .= ' '._esc($ct->{subtype});
543 $buf .= ' '._esc_hash(delete $ct->{attributes});
544 $buf .= ' '.body_disposition($eml);
545 $buf .= ' '._esc($eml->header_raw('Content-Language'));
546 $buf .= ' '._esc($eml->header_raw('Content-Location'));
550 } else { # message/(rfc822|global|news)
551 @$hold = (body_leaf($eml, $structure, $hold));
555 # this is gross, but we need to process the parent part AFTER
556 # the child parts are done
557 sub bodystructure_prep {
559 my ($eml, $depth) = @$p; # ignore idx
560 # set length here, as $eml->{bdy} gets deleted for message/rfc822
561 $eml->{imap_body_len} = length($eml->body_raw);
562 push @$q, $eml, $depth;
565 # for FETCH BODY and FETCH BODYSTRUCTURE
566 sub fetch_body ($;$) {
567 my ($eml, $structure) = @_;
569 $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
573 my ($part, $depth) = splice(@q, -2);
574 my $is_mp_parent = $depth == ($cur_depth - 1);
578 body_parent($part, $structure, \@hold);
580 unshift @hold, body_leaf($part, $structure);
586 sub requeue_once ($) {
588 # COMPRESS users all share the same DEFLATE context.
589 # Flush it here to ensure clients don't see
593 # no recursion, schedule another call ASAP,
594 # but only after all pending writes are done.
596 my $new_size = push(@{$self->{wbuf}}, \&long_step);
598 # wbuf may be populated by $cb, no need to rearm if so:
599 $self->requeue if $new_size == 1;
603 my ($self, $smsg, $bref, $ops, $partial) = @_;
604 my $uid = $smsg->{num};
605 $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
607 for (my $i = 0; $i < @$ops;) {
609 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
611 partial_emit($self, $partial, $eml) if $partial;
612 $self->msg_more(")\r\n");
615 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
616 my ($bref, $oid, $type, $size, $fetch_arg) = @_;
617 my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
618 my $smsg = shift @$msgs or die 'BUG: no smsg';
619 if (!defined($oid)) {
620 # it's possible to have TOCTOU if an admin runs
621 # public-inbox-(edit|purge), just move onto the next message
622 warn "E: $smsg->{blob} missing in $self->{ibx}->{inboxdir}\n";
623 return requeue_once($self);
625 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
628 if (!$self->{wbuf} && (my $nxt = $msgs->[0])) {
629 $pre = $self->{ibx}->git->async_prefetch($nxt->{blob},
630 \&fetch_blob_cb, $fetch_arg);
632 fetch_run_ops($self, $smsg, $bref, $ops, $partial);
633 $pre ? $self->zflush : requeue_once($self);
637 my ($self, $k, undef, $bref) = @_;
638 $self->msg_more(" $k {" . length($$bref)."}\r\n");
639 $self->msg_more($$bref);
642 # Mail::IMAPClient::message_string cares about this by default,
643 # (->Ignoresizeerrors attribute). Admins are encouraged to
644 # --reindex for IMAP support, anyways.
645 sub emit_rfc822_size {
646 my ($self, $k, $smsg) = @_;
647 $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
650 sub emit_internaldate {
651 my ($self, undef, $smsg) = @_;
652 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
655 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
658 my ($self, undef, undef, undef, $eml) = @_;
659 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
662 sub emit_rfc822_header {
663 my ($self, $k, undef, undef, $eml) = @_;
664 $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
665 $self->msg_more(${$eml->{hdr}});
668 # n.b. this is sorted to be after any emit_eml_new ops
669 sub emit_rfc822_text {
670 my ($self, $k, undef, $bref) = @_;
671 $self->msg_more(" $k {".length($$bref)."}\r\n");
672 $self->msg_more($$bref);
675 sub emit_bodystructure {
676 my ($self, undef, undef, undef, $eml) = @_;
677 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
681 my ($self, undef, undef, undef, $eml) = @_;
682 $self->msg_more(' BODY '.fetch_body($eml));
685 # set $eml once ($_[4] == $eml, $_[3] == $bref)
686 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
688 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
690 ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
691 ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
694 sub op_crlf_bref { to_crlf_full($_[3]) }
696 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
698 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
700 sub uid_clamp ($$$) {
701 my ($self, $beg, $end) = @_;
702 my $uid_min = $self->{uid_base} + 1;
703 my $uid_end = $uid_min + UID_SLICE - 1;
704 $$beg = $uid_min if $$beg < $uid_min;
705 $$end = $uid_end if $$end > $uid_end;
708 sub range_step ($$) {
709 my ($self, $range_csv) = @_;
710 my ($beg, $end, $range);
711 if ($$range_csv =~ s/\A([^,]+),//) {
714 $range = $$range_csv;
717 my $uid_base = $self->{uid_base};
718 my $uid_end = $uid_base + UID_SLICE;
719 if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
720 ($beg, $end) = ($1 + 0, $2 + 0);
721 uid_clamp($self, \$beg, \$end);
722 } elsif ($range =~ /\A([0-9]+):\*\z/) {
724 $end = $self->{ibx}->over->max;
725 $end = $uid_end if $end > $uid_end;
726 $beg = $end if $beg > $end;
727 uid_clamp($self, \$beg, \$end);
728 } elsif ($range =~ /\A[0-9]+\z/) {
729 $beg = $end = $range + 0;
730 # just let the caller do an out-of-range query if a single
731 # UID is out-of-range
732 ++$beg if ($beg <= $uid_base || $end > $uid_end);
734 return 'BAD fetch range';
736 [ $beg, $end, $$range_csv ];
739 sub refill_range ($$$) {
740 my ($self, $msgs, $range_info) = @_;
741 my ($beg, $end, $range_csv) = @$range_info;
742 if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
743 $range_info->[0] = $msgs->[-1]->{num} + 1;
746 return 'OK Fetch done' if !$range_csv;
747 my $next_range = range_step($self, \$range_csv);
748 return $next_range if !ref($next_range); # error
749 @$range_info = @$next_range;
750 undef; # keep looping
753 sub fetch_blob { # long_response
754 my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
755 while (!@$msgs) { # rare
756 if (my $end = refill_range($self, $msgs, $range_info)) {
757 $self->write(\"$tag $end\r\n");
761 uo2m_extend($self, $msgs->[-1]->{num});
762 git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
763 \&fetch_blob_cb, \@_);
766 sub fetch_smsg { # long_response
767 my ($self, $tag, $msgs, $range_info, $ops) = @_;
768 while (!@$msgs) { # rare
769 if (my $end = refill_range($self, $msgs, $range_info)) {
770 $self->write(\"$tag $end\r\n");
774 uo2m_extend($self, $msgs->[-1]->{num});
775 fetch_run_ops($self, $_, undef, $ops) for @$msgs;
780 sub refill_uids ($$$;$) {
781 my ($self, $uids, $range_info, $sql) = @_;
782 my ($beg, $end, $range_csv) = @$range_info;
783 my $over = $self->{ibx}->over;
785 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
786 $range_info->[0] = $uids->[-1] + 1; # update $beg
788 } elsif (!$range_csv) {
791 my $next_range = range_step($self, \$range_csv);
792 return $next_range if !ref($next_range); # error
793 ($beg, $end, $range_csv) = @$range_info = @$next_range;
799 sub fetch_uid { # long_response
800 my ($self, $tag, $uids, $range_info, $ops) = @_;
801 if (defined(my $err = refill_uids($self, $uids, $range_info))) {
802 $err ||= 'OK Fetch done';
803 $self->write("$tag $err\r\n");
806 my $adj = $self->{uid_base} + 1;
807 my $uo2m = uo2m_extend($self, $uids->[-1]);
808 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
811 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
812 for ($i = 0; $i < @$ops;) {
814 $ops->[$i++]->($self, $k);
816 $self->msg_more(")\r\n");
822 sub cmd_status ($$$;@) {
823 my ($self, $tag, $mailbox, @items) = @_;
824 return "$tag BAD no items\r\n" if !scalar(@items);
825 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
826 return "$tag BAD invalid args\r\n";
827 my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
828 return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
830 for my $it (@items) {
833 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
835 } elsif ($it eq 'UIDNEXT') {
837 } elsif ($it eq 'UIDVALIDITY') {
838 push @it, $ibx->{uidvalidity};
840 return "$tag BAD invalid item\r\n";
843 return "$tag BAD no items\r\n" if !@it;
844 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
845 "$tag OK Status done\r\n";
848 my %patmap = ('*' => '.*', '%' => '[^\.]*');
849 sub cmd_list ($$$$) {
850 my ($self, $tag, $refname, $wildcard) = @_;
851 my $l = $self->{imapd}->{inboxlist};
852 if ($refname eq '' && $wildcard eq '') {
853 # request for hierarchy delimiter
854 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
855 } elsif ($refname ne '' || $wildcard ne '*') {
856 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
857 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
859 \(join('', @$l, "$tag OK List done\r\n"));
862 sub cmd_lsub ($$$$) {
863 my (undef, $tag) = @_; # same args as cmd_list
864 "$tag OK Lsub done\r\n";
867 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
869 my ($eml, undef, $idx) = @$p;
870 if ($idx && lc($eml->ct->{type}) eq 'multipart') {
871 $eml->{imap_bdy} = $eml->{bdy} // \'';
873 $all->{$idx} = $eml; # $idx => Eml
876 # prepares an index for BODY[$SECTION_IDX] fetches
877 sub eml_body_idx ($$) {
878 my ($eml, $section_idx) = @_;
879 my $idx = $eml->{imap_all_parts} //= do {
881 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
882 # top-level of multipart, BODY[0] not allowed (nz-number)
886 $idx->{$section_idx};
889 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
891 my ($eml, $section_idx, $section_name) = @_;
892 if (defined $section_idx) {
893 $eml = eml_body_idx($eml, $section_idx) or return;
895 if (defined $section_name) {
896 if ($section_name eq 'MIME') {
897 # RFC 3501 6.4.5 states:
898 # The MIME part specifier MUST be prefixed
899 # by one or more numeric part specifiers
900 return unless defined $section_idx;
901 return $eml->header_obj->as_string . "\r\n";
903 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
904 $eml = PublicInbox::Eml->new($$bdy);
905 if ($section_name eq 'TEXT') {
906 return $eml->body_raw;
907 } elsif ($section_name eq 'HEADER') {
908 return $eml->header_obj->as_string . "\r\n";
910 die "BUG: bad section_name=$section_name";
913 ${$eml->{bdy} // $eml->{imap_bdy} // \''};
916 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
917 # to avoid OOM with malicious users
918 sub hdrs_regexp ($) {
920 my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
921 qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
922 # continuation lines:
923 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
927 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
928 sub partial_hdr_not {
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 =~ s/$hdrs_re//g;
935 $str =~ s/(?<!\r)\n/\r\n/sg;
939 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
940 sub partial_hdr_get {
941 my ($eml, $section_idx, $hdrs_re) = @_;
942 if (defined $section_idx) {
943 $eml = eml_body_idx($eml, $section_idx) or return;
945 my $str = $eml->header_obj->as_string;
946 $str = join('', ($str =~ m/($hdrs_re)/g));
947 $str =~ s/(?<!\r)\n/\r\n/sg;
951 sub partial_prepare ($$$$) {
952 my ($need, $partial, $want, $att) = @_;
954 # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
955 # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
956 return unless $att =~ /\ABODY\[/s;
957 until (rindex($att, ']') >= 0) {
958 my $next = shift @$want or return;
959 $att .= ' ' . uc($next);
961 if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
962 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
963 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
964 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
965 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
966 } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
967 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
968 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
969 \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
970 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
973 $tmp->[2] = hdrs_regexp($3);
975 # don't emit CRLF_HDR instruction, here, partial_hdr_*
976 # will do CRLF conversion with only the extracted result
977 # and not waste time converting lines we don't care about.
984 sub partial_emit ($$$) {
985 my ($self, $partial, $eml) = @_;
987 my ($k, $cb, @args) = @$_;
988 my ($offset, $len) = splice(@args, -2);
989 # $cb is partial_body|partial_hdr_get|partial_hdr_not
990 my $str = $cb->($eml, @args) // '';
991 if (defined $offset) {
993 $str = substr($str, $offset, $len);
994 $k =~ s/\.$len>\z/>/ or warn
995 "BUG: unable to remove `.$len>' from `$k'";
997 $str = substr($str, $offset);
1001 $len = length($str);
1003 $self->msg_more(" $k {$len}\r\n");
1004 $self->msg_more($str);
1008 sub fetch_compile ($) {
1010 if ($want->[0] =~ s/\A\(//s) {
1011 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1013 my (%partial, %seen, @op);
1015 while (defined(my $att = shift @$want)) {
1017 next if $att eq 'UID'; # always returned
1018 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1019 my $x = $FETCH_ATT{$att};
1021 while (my ($k, $fl_cb) = each %$x) {
1022 next if $seen{$k}++;
1023 $need |= $fl_cb->[0];
1024 push @op, [ @$fl_cb, $k ];
1026 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1027 return "BAD param: $att";
1032 # stabilize partial order for consistency and ease-of-debugging:
1033 if (scalar keys %partial) {
1035 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1038 push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1040 # do we need CRLF conversion?
1041 if ($need & CRLF_BREF) {
1042 push @op, $OP_CRLF_BREF;
1043 } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1044 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1045 push @op, $OP_CRLF_BREF;
1046 } elsif ($need & CRLF_HDR) {
1047 push @op, $OP_CRLF_HDR;
1049 push @op, $OP_CRLF_BDY;
1053 $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1054 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1056 # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1057 use sort 'stable'; # makes output more consistent
1058 $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1062 sub cmd_uid_fetch ($$$$;@) {
1063 my ($self, $tag, $range_csv, @want) = @_;
1064 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1065 my ($cb, $ops, $partial) = fetch_compile(\@want);
1066 return "$tag $cb\r\n" unless $ops;
1068 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1069 $range_csv = 'bad' if $range_csv !~ $valid_range;
1070 my $range_info = range_step($self, \$range_csv);
1071 return "$tag $range_info\r\n" if !ref($range_info);
1072 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1073 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1076 sub cmd_fetch ($$$$;@) {
1077 my ($self, $tag, $range_csv, @want) = @_;
1078 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1079 my ($cb, $ops, $partial) = fetch_compile(\@want);
1080 return "$tag $cb\r\n" unless $ops;
1082 # cb is one of fetch_blob, fetch_smsg, fetch_uid
1083 $range_csv = 'bad' if $range_csv !~ $valid_range;
1084 msn_to_uid_range(msn2uid($self), $range_csv);
1085 my $range_info = range_step($self, \$range_csv);
1086 return "$tag $range_info\r\n" if !ref($range_info);
1087 uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1088 long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1091 sub msn_convert ($$) {
1092 my ($self, $uids) = @_;
1093 my $adj = $self->{uid_base} + 1;
1094 my $uo2m = uo2m_extend($self, $uids->[-1]);
1095 $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1096 $_ = $uo2m->[$_ - $adj] for @$uids;
1099 sub search_uid_range { # long_response
1100 my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1102 if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1103 $err ||= 'OK Search done';
1104 $self->write("\r\n$tag $err\r\n");
1107 msn_convert($self, $uids) if $want_msn;
1108 $self->msg_more(join(' ', '', @$uids));
1113 my ($q, $k, $d) = @_;
1114 my $sql = $q->{sql};
1117 if ($k eq 'SENTON') {
1118 my $end = $d + 86399; # no leap day...
1119 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1120 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1121 $q->{xap} .= " dt:$da..$db";
1122 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1123 } elsif ($k eq 'SENTBEFORE') {
1124 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1125 $$sql .= " AND ds <= $d" if defined($sql);
1126 } elsif ($k eq 'SENTSINCE') {
1127 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1128 $$sql .= " AND ds >= $d" if defined($sql);
1130 # INTERNALDATE (Received)
1131 } elsif ($k eq 'ON') {
1132 my $end = $d + 86399; # no leap day...
1133 $q->{xap} .= " ts:$d..$end";
1134 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1135 } elsif ($k eq 'BEFORE') {
1136 $q->{xap} .= " ts:..$d";
1137 $$sql .= " AND ts <= $d" if defined($sql);
1138 } elsif ($k eq 'SINCE') {
1139 $q->{xap} .= " ts:$d..";
1140 $$sql .= " AND ts >= $d" if defined($sql);
1142 die "BUG: $k not recognized";
1146 # IMAP to Xapian search key mapping
1151 TEXT => '', # n.b. does not include all headers
1154 # BCC => 'bcc:', # TODO
1155 # KEYWORD # TODO ? dfpre,dfpost,...
1158 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1159 # which gets silly expensive. We only allow the headers we already index.
1160 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1162 sub xap_append ($$$$) {
1163 my ($q, $rest, $k, $xk) = @_;
1164 delete $q->{sql}; # can't use over.sqlite3
1165 defined(my $arg = shift @$rest) or return "BAD $k no arg";
1167 # AFAIK Xapian can't handle [*"] in probabilistic terms
1169 ${$q->{xap}} .= qq[ $xk"$arg"];
1173 sub parse_query ($$) {
1174 my ($self, $query) = @_;
1175 my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1177 my $max = $self->{ibx}->over->max;
1179 uid_clamp($self, \$beg, \$max);
1180 $q->{range_info} = [ $beg, $max ];
1185 sub refill_xap ($$$$) {
1186 my ($self, $uids, $range_info, $q) = @_;
1187 my ($beg, $end) = @$range_info;
1188 my $srch = $self->{ibx}->search;
1189 my $opt = { mset => 2, limit => 1000 };
1190 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1191 @$uids = @{$srch->mset_to_artnums($mset)};
1193 $range_info->[0] = $uids->[-1] + 1; # update $beg
1194 return; # possibly more
1199 sub search_xap_range { # long_response
1200 my ($self, $tag, $q, $range_info, $want_msn) = @_;
1202 if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1203 $err ||= 'OK Search done';
1204 $self->write("\r\n$tag $err\r\n");
1207 msn_convert($self, $uids) if $want_msn;
1208 $self->msg_more(join(' ', '', @$uids));
1213 my ($self, $tag, $query, $want_msn) = @_;
1214 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1215 my $q = parse_query($self, $query);
1216 return "$tag $q\r\n" if !ref($q);
1217 my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1218 if (!scalar(keys %$q)) { # overview.sqlite3
1219 $self->msg_more('* SEARCH');
1220 long_response($self, \&search_uid_range,
1221 $tag, $sql, $range_info, $want_msn);
1222 } elsif ($q = $q->{xap}) {
1223 $self->{ibx}->search or
1224 return "$tag BAD search not available for mailbox\r\n";
1225 $self->msg_more('* SEARCH');
1226 long_response($self, \&search_xap_range,
1227 $tag, $q, $range_info, $want_msn);
1229 "$tag BAD Error\r\n";
1233 sub cmd_uid_search ($$$) {
1234 my ($self, $tag, $query) = @_;
1235 search_common($self, $tag, $query);
1238 sub cmd_search ($$$;) {
1239 my ($self, $tag, $query) = @_;
1240 search_common($self, $tag, $query, 1);
1243 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1244 my ($cb, $argc) = @_;
1245 my $tot = prototype $cb;
1246 my ($nreq, undef) = split(';', $tot);
1247 $nreq = ($nreq =~ tr/$//) - 1;
1248 $tot = ($tot =~ tr/$//) - 1;
1249 ($argc <= $tot && $argc >= $nreq);
1252 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1253 sub process_line ($$) {
1254 my ($self, $l) = @_;
1256 # TODO: IMAP allows literals for big requests to upload messages
1257 # (which we don't support) but maybe some big search queries use it.
1258 # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1259 my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1260 pop(@args) if (@args && !defined($args[-1]));
1261 if (@args && uc($req) eq 'UID') {
1262 $req .= "_".(shift @args);
1265 if (defined(my $idle_tag = $self->{-idle_tag})) {
1266 (uc($tag // '') eq 'DONE' && !defined($req)) ?
1267 idle_done($self, $tag) :
1268 "$idle_tag BAD expected DONE\r\n";
1269 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1270 if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1271 # preserve user-supplied quotes for search
1272 (undef, @args) = split(/ search /i, $l, 2);
1274 $cmd->($self, $tag, @args);
1275 } else { # this is weird
1276 auth_challenge_ok($self) //
1278 ' BAD Error in IMAP command '.
1280 ": Unknown command\r\n";
1284 if ($err && $self->{sock}) {
1286 err($self, 'error from: %s (%s)', $l, $err);
1288 $res = "$tag BAD program fault - command not performed\r\n";
1290 return 0 unless defined $res;
1296 # wbuf is unset or empty, here; {long} may add to it
1297 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1298 my $more = eval { $cb->($self, @args) };
1299 if ($@ || !$self->{sock}) { # something bad happened...
1300 delete $self->{long_cb};
1301 my $elapsed = now() - $t0;
1304 "%s during long response[$fd] - %0.6f",
1307 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1309 } elsif ($more) { # $self->{wbuf}:
1310 $self->update_idle_time;
1312 # control passed to git_async_cat if $more == \undef
1313 requeue_once($self) if !ref($more);
1314 } else { # all done!
1315 delete $self->{long_cb};
1316 my $elapsed = now() - $t0;
1317 my $fd = fileno($self->{sock});
1318 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1319 my $wbuf = $self->{wbuf}; # do NOT autovivify
1321 $self->requeue unless $wbuf && @$wbuf;
1326 my ($self, $fmt, @args) = @_;
1327 printf { $self->{imapd}->{err} } $fmt."\n", @args;
1331 my ($self, $fmt, @args) = @_;
1332 printf { $self->{imapd}->{out} } $fmt."\n", @args;
1335 sub long_response ($$;@) {
1336 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1338 my $sock = $self->{sock} or return;
1339 # make sure we disable reading during a long response,
1340 # clients should not be sending us stuff and making us do more
1341 # work while we are stream a response to them
1342 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1343 long_step($self); # kick off!
1347 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1351 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1353 $self->update_idle_time;
1354 # only read more requests if we've drained the write buffer,
1355 # otherwise we can be buffering infinitely w/o backpressure
1357 my $rbuf = $self->{rbuf} // \(my $x = '');
1358 my $line = index($$rbuf, "\n");
1360 if (length($$rbuf) >= LINE_MAX) {
1361 $self->write(\"\* BAD request too long\r\n");
1362 return $self->close;
1364 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1365 return uo2m_hibernate($self);
1366 $line = index($$rbuf, "\n");
1368 $line = substr($$rbuf, 0, $line + 1, '');
1369 $line =~ s/\r?\n\z//s;
1370 return $self->close if $line =~ /[[:cntrl:]]/s;
1372 my $fd = fileno($self->{sock});
1373 my $r = eval { process_line($self, $line) };
1374 my $pending = $self->{wbuf} ? ' pending' : '';
1375 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1377 return $self->close if $r < 0;
1378 $self->rbuf_idle($rbuf);
1379 $self->update_idle_time;
1381 # maybe there's more pipelined data, or we'll have
1382 # to register it for socket-readiness notifications
1383 $self->requeue unless $pending;
1386 sub compressed { undef }
1388 sub zflush {} # overridden by IMAPdeflate
1391 sub cmd_compress ($$$) {
1392 my ($self, $tag, $alg) = @_;
1393 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1394 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1396 # CRIME made TLS compression obsolete
1397 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1399 PublicInbox::IMAPdeflate->enable($self, $tag);
1404 sub cmd_starttls ($$) {
1405 my ($self, $tag) = @_;
1406 my $sock = $self->{sock} or return;
1407 if ($sock->can('stop_SSL') || $self->compressed) {
1408 return "$tag BAD TLS or compression already enabled\r\n";
1410 my $opt = $self->{imapd}->{accept_tls} or
1411 return "$tag BAD can not initiate TLS negotiation\r\n";
1412 $self->write(\"$tag OK begin TLS negotiation now\r\n");
1413 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1414 $self->requeue if PublicInbox::DS::accept_tls_step($self);
1418 # for graceful shutdown in PublicInbox::Daemon:
1420 my ($self, $now) = @_;
1421 if (defined($self->{-idle_tag})) {
1422 $self->write(\"* BYE server shutting down\r\n");
1423 return; # not busy anymore
1425 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1430 if (my $ibx = delete $self->{ibx}) {
1431 stop_idle($self, $ibx);
1433 $self->SUPER::close; # PublicInbox::DS::close
1436 # we're read-only, so SELECT and EXAMINE do the same thing
1438 *cmd_select = \&cmd_examine;
1440 package PublicInbox::IMAP_preauth;
1441 our @ISA = qw(PublicInbox::IMAP);