]> Sergey Matveev's repositories - public-inbox.git/log
public-inbox.git
3 years agowww*stream: gzip ->getline responses
Eric Wong [Sun, 5 Jul 2020 23:27:19 +0000 (23:27 +0000)]
www*stream: gzip ->getline responses

Our most common endpoints deserve to be gzipped.

3 years agowwwstream: oneshot: perform gzip without middleware
Eric Wong [Sun, 5 Jul 2020 23:27:18 +0000 (23:27 +0000)]
wwwstream: oneshot: perform gzip without middleware

Plack::Middleware::Deflater forces us to use a memory-intensive
closure.  Instead, work towards building compressed strings in
memory to reduce the overhead of buffering large HTML output.

3 years agogzipfilter: minor cleanups
Eric Wong [Sun, 5 Jul 2020 23:27:17 +0000 (23:27 +0000)]
gzipfilter: minor cleanups

We currently don't use bytes::length in ->write, so there's no
need to `use bytes'.  Favor `//=' to describe the intent of the
conditional assignment since the C::R::Z::Deflate object is
always truthy.  Also use the local $gz variable to avoid
unnecessary {gz} hash lookups.

3 years agogit_async_cat: unref pipes on EOF from git->cleanup
Eric Wong [Mon, 6 Jul 2020 06:11:02 +0000 (06:11 +0000)]
git_async_cat: unref pipes on EOF from git->cleanup

We avoided a managed circular reference in 10ee3548084c125f
but introduced a pipe FD leak, instead.  So handle the EOF
we get when the "git cat-file --batch" process exits and
closes its stdout FD.

v2: remove ->close entirely.  PublicInbox::Git->cleanup
handles all cleanup.  This prevents us from inadvertantly
deleting the {async_cat} field associated with a different
pipe than the one GAC is monitoring.

Fixes: 10ee3548084c125f ("git_async_cat: remove circular reference")
3 years agoinboxidle: warn on inotify_add_watch failures
Eric Wong [Mon, 6 Jul 2020 04:20:12 +0000 (04:20 +0000)]
inboxidle: warn on inotify_add_watch failures

inotify_add_watch(2), open(2), stat(2) may all fail due to
permissions errors, especially when running -nntpd/-imapd
as `nobody' as recommended.

3 years agot/import: test for nasty characters
Eric Wong [Sat, 4 Jul 2020 20:25:25 +0000 (20:25 +0000)]
t/import: test for nasty characters

Spammers may send emails with nasty characters which can throw
off git-fast-import.  Users with non-existent or weaker spam
filters may be susceptible to corruption in the fast-import
stream as a result.

This was actually quietly fixed in git on 2020-06-01 by
commit 9ab886546cc89f37819e1ef09cb49fd9325b3a41
("smsg: introduce ->populate method"), but no test case
was created.

Reported-by: Eric W. Biederman <ebiederm@xmission.com>
Link: https://public-inbox.org/meta/87imf4qn87.fsf@x220.int.ebiederm.org/
Link: https://public-inbox.org/meta/20200601100657.14700-6-e@yhbt.net/
3 years agowatch: don't burn CPU on IDLE failures
Eric Wong [Sat, 4 Jul 2020 21:33:13 +0000 (21:33 +0000)]
watch: don't burn CPU on IDLE failures

Network connections fail and need to be detected sooner rather
than later during IDLE to avoid backtrace floods.  In case the
IDLE process dies completely, don't respawn right away, either,
to avoid entering a respawn loop.

There's also a typo fix :P

3 years agospawn: drop unused sys/uio.h include
Eric Wong [Thu, 2 Jul 2020 20:12:40 +0000 (20:12 +0000)]
spawn: drop unused sys/uio.h include

We no longer use writev(2) in pi_fork_exec to emit errors.

3 years agooveridx: document why we don't use SQLite WAL
Eric Wong [Wed, 1 Jul 2020 21:06:19 +0000 (21:06 +0000)]
overidx: document why we don't use SQLite WAL

I was wondering about this myself the other day and had to read
up on it.  So make a note of it for future readers.

3 years agotests: add use/require statements for TEST_RUN_MODE=0
Eric Wong [Wed, 1 Jul 2020 21:06:18 +0000 (21:06 +0000)]
tests: add use/require statements for TEST_RUN_MODE=0

The default (and fast) TEST_RUN_MODE=2 preloads most modules,
but TEST_RUN_MODE=0 is more realistic and can catch some
problems which may show up in real-world use.

3 years agowatch: retry signals to kill IDLE and polling processes
Eric Wong [Wed, 1 Jul 2020 21:06:17 +0000 (21:06 +0000)]
watch: retry signals to kill IDLE and polling processes

To ensure reliable signal delivery in Perl, it seems we need to
repeatedly signal processes which aren't using signalfd (or
EVFILT_SIGNAL) with our event loop.

3 years agospawn: modernize with parent.pm, drop warnings.pm
Eric Wong [Wed, 1 Jul 2020 21:06:16 +0000 (21:06 +0000)]
spawn: modernize with parent.pm, drop warnings.pm

parent.pm is smaller than base.pm, and we'll also move
towards relying on `-w' (or not) to toggle process-wide
warnings during development.

3 years agospawn: make @RLIMITS an array
Eric Wong [Wed, 1 Jul 2020 21:06:15 +0000 (21:06 +0000)]
spawn: make @RLIMITS an array

Making the RLIMITS list a function doesn't allow constant
folding, so just make it an array accessible to other modules.

3 years agoinboxidle: avoid per-inbox anonymous subs
Eric Wong [Thu, 2 Jul 2020 03:32:56 +0000 (03:32 +0000)]
inboxidle: avoid per-inbox anonymous subs

Anonymous subs cost over 5K each on x86-64.  So prefer the
less-recommended-but-still-documented way of using
Linux::Inotify2::watch to register watchers.

This also updates FakeInotify to detect modifications correctly
when used on systems with neither IO::KQueue nor
Linux::Inotify2.

3 years agot/run: show unexpected output lines in logs
Eric Wong [Mon, 29 Jun 2020 00:30:52 +0000 (00:30 +0000)]
t/run: show unexpected output lines in logs

This will help us catch warnings in new code and notice
inadvertantly skipped tests.

3 years agowatch: make waitpid() synchronous for Maildir scans
Eric Wong [Mon, 29 Jun 2020 10:34:21 +0000 (10:34 +0000)]
watch: make waitpid() synchronous for Maildir scans

Maildir scanning still happens in the main process.  Scanning
dozens of Maildirs is still time-consuming and monopolizes the
event loop during WatchMaildir::event_step.  This can cause
cause zombies to accumulate before Sigfd::event_step triggers
DS::reap_pids.

3 years agospawn: unblock SIGCHLD in subprocess
Eric Wong [Mon, 29 Jun 2020 10:34:20 +0000 (10:34 +0000)]
spawn: unblock SIGCHLD in subprocess

Subprocess we spawn may want to use SIGCHLD for themselves.
This also ensures we restore default signal handlers
in the pure Perl version.

3 years agowatch: ensure SIGCHLD works in forked children
Eric Wong [Mon, 29 Jun 2020 10:34:19 +0000 (10:34 +0000)]
watch: ensure SIGCHLD works in forked children

In case our git or spam checker subprocesses spawn
subprocesses of their own.  We'll also ensure signal
handlers are properly setup before unblocking them.

3 years agowatch: show path for warnings from spam messages
Eric Wong [Mon, 29 Jun 2020 10:34:18 +0000 (10:34 +0000)]
watch: show path for warnings from spam messages

It could be useful to see warnings generated for known problematic
messages just as it is for possibly non-problematic ones.

3 years agowatch: check for duplicates in ->over before spamcheck
Eric Wong [Mon, 29 Jun 2020 10:34:17 +0000 (10:34 +0000)]
watch: check for duplicates in ->over before spamcheck

It's cheaper to check for duplicates than run `spamc'
repeatedly when rechecking.  We already do this for
v1 with by using the "ls" command with fast-import,
but v2 requires checking against over.sqlite3.

3 years agowatch: simplify internal structures
Eric Wong [Sat, 27 Jun 2020 10:04:00 +0000 (10:04 +0000)]
watch: simplify internal structures

We won't be attempting to reuse Mail::IMAPConnections used to
check authentication info, for now, so stop storing
$self->{mics}.

We can also combine $poll initialization for IMAP and NNTP
to avoid data structure duplication.  Furthermore, rely on
autovivification to create {idle_pids} and {poll_pids}.

3 years agoimaptracker: use flock(2) around writes
Eric Wong [Sat, 27 Jun 2020 10:03:59 +0000 (10:03 +0000)]
imaptracker: use flock(2) around writes

SQLite only issues non-blocking F_SETLK ops (not F_SETLKW) and
retries failures using a configurable busy_timeout.  SQLite's
busy loop sleeps for a millisecond and retries the lock until
the configured busy_timeout is hit.

Trying to set ->sqlite_busy_timeout to larger values (e.g. 30000
milliseconds) still leads to failure when running the new stress
test with 8 processes with TMPDIR on a 7200 RPM HDD.

Inspection of SQLite source reveals there's no built-in way to
use F_SETLKW, so tack on the existing flock(2) support we use to
synchronize git + SQLite + Xapian for inbox writing.  We use
flock(2) instead of POSIX fcntl(2) locks since Perl doesn't
provide a way to manipulate "struct flock" portably.

3 years agowatch: support ~/.netrc via Net::Netrc
Eric Wong [Sat, 27 Jun 2020 10:03:58 +0000 (10:03 +0000)]
watch: support ~/.netrc via Net::Netrc

While git-credential-netrc exists in git.git contrib/, it may
not be widely known or installed.  Net::Netrc is already a
standard part of most (if not all) Perl installations, so use it
directly if available.

3 years agowatch: use our own "git credential" wrapper
Eric Wong [Sat, 27 Jun 2020 10:03:57 +0000 (10:03 +0000)]
watch: use our own "git credential" wrapper

Git.pm may not be installed on some systems; or some users have
multiple Perl installations and Git.pm is not available to the
Perl running -watch.  Accomodate both those types of users by
providing our own "git credential" wrapper.

3 years agowatch: enable autoflush for STDOUT and STDERR
Eric Wong [Sat, 27 Jun 2020 10:03:56 +0000 (10:03 +0000)]
watch: enable autoflush for STDOUT and STDERR

In case output is redirected to a pipe, ensure stdout and stderr
are always unbuffered, as -watch may go long periods without
any output to fill up buffers.

3 years agowatch: show user-specified URL consistently.
Eric Wong [Sat, 27 Jun 2020 10:03:55 +0000 (10:03 +0000)]
watch: show user-specified URL consistently.

Since we use the non-ref scalar URL in many error messages,
favor keeping the unblessed URL in the long-lived process.

This avoids showing "snews://" to users who've specified
"nntps://" URLs, since "nntps" is IANA-registered nowadays and
what we show in our documentation, while "snews" was just a
draft the URI package picked up decades ago.

3 years agowatch: add NNTP support
Eric Wong [Sat, 27 Jun 2020 10:03:54 +0000 (10:03 +0000)]
watch: add NNTP support

This is similar to IMAP support, but only supports polling.
Automatic altid support is not yet supported, yet; but may
be in the future.

v2: small grammar fix by Kyle Meyer
Link: https://public-inbox.org/meta/87sgeg5nxf.fsf@kyleam.com/
3 years agotestcommon: $ENV{TAIL} supports non-@ARGV redirects
Eric Wong [Sat, 27 Jun 2020 10:03:53 +0000 (10:03 +0000)]
testcommon: $ENV{TAIL} supports non-@ARGV redirects

Existing use of the $ENV{TAIL} relied on parsing --std{out,err},
which was only usable for read-only daemons.  However, -watch
doesn't use PublicInbox::Daemon code(*), so attempt to figure
out redirects.

(*) -watch won't able to run as a daemon in cases when
    git-credential prompts for IMAP/NNTP passwords.
    PublicInbox::Daemon is also designed for read-only
    parallelism where all worker processes are the same.
    Any subprocesses spawned by -watch are to do specific
    tasks for a particular set of inboxes.

3 years agowatch: just use ->urlmatch
Eric Wong [Sat, 27 Jun 2020 10:03:52 +0000 (10:03 +0000)]
watch: just use ->urlmatch

We may just modify PublicInbox::Config->urlmatch in the future
to support git <1.8.5, but I wonder if there's enough users on
git <1.8.5 to justify it.

3 years agowatch: remove {mdir} array
Eric Wong [Sat, 27 Jun 2020 10:03:51 +0000 (10:03 +0000)]
watch: remove {mdir} array

Since we store all watched directory names as keys in %mdmap,
there should be no need to keep an array of those directories
around.

t/watch_maildir*.t required changes to remove trained spam.
Once we've trained something as spam, there shouldn't be
a need to rescan it.

3 years agowatch: support multiple watch: directives per-inbox
Eric Wong [Sat, 27 Jun 2020 10:03:50 +0000 (10:03 +0000)]
watch: support multiple watch: directives per-inbox

Some users will find it useful to merge several Maildir or
IMAP mailboxes into one public-inbox.  Let them do it, since
we've always supported multi-address inboxes.

3 years agowatch: imap: be quiet about disconnecting on quit
Eric Wong [Sat, 27 Jun 2020 10:03:49 +0000 (10:03 +0000)]
watch: imap: be quiet about disconnecting on quit

If ->idle_done was handled successfully, we can just
let normal ->DESTROY disconnect and avoid ugly backtraces
when a user hits Ctrl-C to take down the process group.

3 years agowatch: support imap.fetchBatchSize parameter
Eric Wong [Sat, 27 Jun 2020 10:03:48 +0000 (10:03 +0000)]
watch: support imap.fetchBatchSize parameter

IMAP allows retrieving multiple messages with a single command,
and Mail::IMAPClient supports that.  Unfortunately, it means we
slurp multiple messages into memory at once.  This option allows
users to trade off memory usage to reduce network round-trips.

Ideally, we'd support pipelining; but AFAIK no widely installed
Perl IMAP library supports it.

3 years agowatch: avoid long transaction to IMAPTracker
Eric Wong [Sat, 27 Jun 2020 10:03:47 +0000 (10:03 +0000)]
watch: avoid long transaction to IMAPTracker

With different polling intervals, multiple processes may
simultaneously write to IMAPtracker.  This ought to reduce
SQLite busy waiting and contention issues when importing
many inboxes in parallel.

3 years agoimaptracker: drop {dbname} field
Eric Wong [Sat, 27 Jun 2020 10:03:46 +0000 (10:03 +0000)]
imaptracker: drop {dbname} field

It's not used anywhere since the IMAPTracker object doesn't
disconnect and reconnect.  If we ever need the filename,
{dbh}->sqlite_db_filename may be used.

Cc: Eric W. Biederman <ebiederm@xmission.com>
3 years agoimaptracker: add {url} field to reduce args
Eric Wong [Sat, 27 Jun 2020 10:03:45 +0000 (10:03 +0000)]
imaptracker: add {url} field to reduce args

Passing a $url parameter to every function was error-prone
and having {url} field for a short-lived object is appropriate.

This matches the version of IMAPTracker posted by
Eric W. Biederman on 2020-05-15 at:
https://public-inbox.org/meta/87ftc0c3r4.fsf_-_@x220.int.ebiederm.org/

The version I originally imported was based on the one
posted on 2019-10-09:
https://public-inbox.org/meta/874l0i9vhc.fsf_-_@x220.int.ebiederm.org/

Cc: Eric W. Biederman <ebiederm@xmission.com>
3 years agods: add_timer: allow passing arg to callback.
Eric Wong [Sat, 27 Jun 2020 10:03:44 +0000 (10:03 +0000)]
ds: add_timer: allow passing arg to callback.

This allows callers to avoid creating expensive closures.
We no longer pass the `$now' value to callers, as none of
the callers used it.

3 years agowatch: use UID SEARCH to avoid empty UID FETCH
Eric Wong [Sat, 27 Jun 2020 10:03:43 +0000 (10:03 +0000)]
watch: use UID SEARCH to avoid empty UID FETCH

For mailboxes with many gaps in the UID sequence,
performing a UID SEARCH beforehand can reduce the
number of articles to fetch.

However, the downside to this is we may end up with
an arbitrarly large list of UIDs from the server.

3 years agowatch: stop importers before forking
Eric Wong [Sat, 27 Jun 2020 10:03:42 +0000 (10:03 +0000)]
watch: stop importers before forking

This fixes cases where watch is handling both Maildirs and IMAP
connections.  While we're at it, close open directories in the
IMAP children to save FDs.

3 years agoconfig: support ->urlmatch method for -watch
Eric Wong [Sat, 27 Jun 2020 10:03:41 +0000 (10:03 +0000)]
config: support ->urlmatch method for -watch

Since we have IMAP client support in -watch; make sure per-URL
settings are familiar to git users by taking advantage of git's
URL matching abilities.

This requires git 1.8.5+, which most users ought to have
(though base CentOS 7 is on 1.8.3).

3 years agowatch: support IMAP polling
Eric Wong [Sat, 27 Jun 2020 10:03:40 +0000 (10:03 +0000)]
watch: support IMAP polling

Not all IMAP servers support IDLE, and IDLE may be prohibitively
expensive for some IMAP servers with many inboxes.  So allow
configuring a imap.$IMAP_URL.pollInterval=SECONDS to poll
mailboxes.

We'll also need to poll for NNTP servers in the future.

3 years agowatch: wire up IMAP IDLE reapers to DS
Eric Wong [Sat, 27 Jun 2020 10:03:39 +0000 (10:03 +0000)]
watch: wire up IMAP IDLE reapers to DS

We can avoid synchronous `waitpid(-1, 0)' and save a process
when simultaneously watching Maildirs.

One DS bug is fixed: ->Reset needs to clear the DS $in_loop flag
in forked children so dwaitpid() fails and allows git processes
to be reaped synchronously.  TestCommon also calls DS->Reset
when spawning new processes, since t/imapd.t uses DS->EventLoop
while waiting on -watch to write.

3 years agods: remove fields.pm usage
Eric Wong [Sat, 27 Jun 2020 10:03:38 +0000 (10:03 +0000)]
ds: remove fields.pm usage

Since the removal of pseudo-hash support in Perl 5.10, the
"fields" module no longer provides the space or speed benefits
it did in 5.8.  It also does not allow for compile-time checks,
only run-time checks.

To me, the extra developer overhead in maintaining "use fields"
args has become a hassle.  None of our non-DS-related code uses
fields.pm, nor do any of our current dependencies.  In fact,
Danga::Socket (which DS was originally forked from) and its
subclasses are the only fields.pm users I've ever encountered in
the wild.  Removing fields may make our code more approachable
to other Perl hackers.

So stop using fields.pm and locked hashes, but continue to
document what fields do for non-trivial classes.

3 years agowatch: use signalfd for Maildir watching
Eric Wong [Sat, 27 Jun 2020 10:03:37 +0000 (10:03 +0000)]
watch: use signalfd for Maildir watching

We can get rid of the janky wannabe
self-using-a-directory-instead-of-pipe thing we needed to
workaround Filesys::Notify::Simple being blocking.

For existing Maildir users, this should be more robust and
immune to missed wakeups for signalfd and kqueue-enabled
systems; as well as being immune to BOFHs clearing $TMPDIR
and preventing notifications from firing.

The IMAP IDLE code still uses normal Perl signals, so it's still
vulnerable to missed wakeups.  That will be addressed in future
commits.

3 years agowatch: remove Filesys::Notify::Simple dependency
Eric Wong [Sat, 27 Jun 2020 10:03:36 +0000 (10:03 +0000)]
watch: remove Filesys::Notify::Simple dependency

Since we already use inotify and EVFILT_VNODE (kqueue)
in -imapd, we might as well use them directly in -watch,
too.

This will allow public-inbox-watch to use PublicInbox::DS
for timers to watch newsgroups/mailboxes and have saner
signal handling in future commits.

3 years agokqnotify|fake_inotify: detect Maildir write ops
Eric Wong [Sat, 27 Jun 2020 10:03:35 +0000 (10:03 +0000)]
kqnotify|fake_inotify: detect Maildir write ops

We need to detect link(2) and rename(2) in other apps
writing to the Maildir.

We'll be removing the Filesys::Notify::Simple from -watch
in favor of using IO::KQueue or Linux::Inotify2 directly.
Ensure non-inotify emulations can support everything we
expect for Maildir writers.

3 years agowatch: preliminary IMAP support
Eric Wong [Sat, 27 Jun 2020 10:03:34 +0000 (10:03 +0000)]
watch: preliminary IMAP support

Only servers with IDLE are supported, for now.  Polling will
be needed since users may need to watch many inboxes with
a few active connections due to IMAP server limitations.

3 years agoURI IMAP support
Eric Wong [Sat, 27 Jun 2020 10:03:33 +0000 (10:03 +0000)]
URI IMAP support

We'll be supporting the IMAP URL scheme described in RFC 5092
for -watch, so add this module to fill in what the `URI' package
lacks.

3 years agowatchmaildir: fix check for spam vs ham inbox conflicts
Eric Wong [Sat, 27 Jun 2020 10:03:32 +0000 (10:03 +0000)]
watchmaildir: fix check for spam vs ham inbox conflicts

The old check was ineffective since we process the spam folder
config before ham inboxes; and would only fail when attempting
to treat the scalar "watchspam" string as an array ref.

3 years agowatchmaildir: hoist out compile_watchheaders
Eric Wong [Sat, 27 Jun 2020 10:03:31 +0000 (10:03 +0000)]
watchmaildir: hoist out compile_watchheaders

It's too deeply indented, and we will be using it for IMAP, too.

3 years agoimaptracker: use ~/.local/share/public-inbox/imap.sqlite3
Eric Wong [Sat, 27 Jun 2020 10:03:30 +0000 (10:03 +0000)]
imaptracker: use ~/.local/share/public-inbox/imap.sqlite3

Respect XDG_DATA_HOME to avoid cluttering ~/.public-inbox/.
Existing users of ~/.public-inbox/imap.sqlite3 will remain
supported, but the preference for new data is to use
~/.local/share and other paths standardized by XDG.

Cc: "Eric W. Biederman" <ebiederm@xmission.com>
3 years agoIMAPTracker: Add a helper to track our place in reading imap mailboxes
Eric W. Biederman [Sat, 27 Jun 2020 10:03:29 +0000 (10:03 +0000)]
IMAPTracker: Add a helper to track our place in reading imap mailboxes

This removes the need to delete from an imap mailbox when
downloading it's messages.

[ew: minor style changes]

Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>
3 years agoinbox: warn on ->on_inbox_unlock exception
Eric Wong [Sat, 27 Jun 2020 10:03:28 +0000 (10:03 +0000)]
inbox: warn on ->on_inbox_unlock exception

Otherwise, we may never know what went wrong.

3 years agoinboxwritable: ensure ssoma.lock exists on init
Eric Wong [Sat, 27 Jun 2020 10:03:27 +0000 (10:03 +0000)]
inboxwritable: ensure ssoma.lock exists on init

This will allow us to use InboxIdle on empty/unindexed v1 inboxes.

3 years agoeml: header_str_set: correctly encode UTF-8 headers
Eric Wong [Sun, 28 Jun 2020 07:14:40 +0000 (07:14 +0000)]
eml: header_str_set: correctly encode UTF-8 headers

Apparently, using $1 from an octet string still results in a
multi-byte string.  Thus we need to perform utf8::encode after
the regexp character match to ensure wide characters don't get
passed to encode_base64.

This fixes a bug in which caused -watch to crash when using
PublicInbox::Filter::SubjectTag to remove "[list prefix]"
tags from Subject: lines.

I only found this bug because the proposed -watch updates for
NNTP/IMAP support introduced a possible bug which triggered a
full rescan of old archives:

  https://public-inbox.org/meta/20200627100400.9871-1-e@yhbt.net/

3 years agolinkify: support imap, imaps, news, and snews URIs
Eric Wong [Fri, 26 Jun 2020 23:26:18 +0000 (23:26 +0000)]
linkify: support imap, imaps, news, and snews URIs

Since we'll have an IMAP server released soon, maybe imaps://
and imap:// URLs can become popular.

news:// is defined with nntp:// in RFC 5538, and we can at least
support the news:// form in rendered HTML.  snews:// may appear
in old mail archives, too, so we'll attempt to support it in
case clients do.

3 years agoimap: EXAMINE: avoid potential race conditions
Eric Wong [Thu, 25 Jun 2020 10:09:37 +0000 (10:09 +0000)]
imap: EXAMINE: avoid potential race conditions

We need to rely on num_highwater for UIDNEXT since the
highest `num' stored in over.sqlite3 may be rolled back
if the most recent messages were spam.

We also need to load the uo2m immediately on EXAMINE to ensure
EXISTS responses are always consistent with regard to future
updates.

3 years agoimap: always send EXISTS on uo2m_extend
Eric Wong [Thu, 25 Jun 2020 10:09:36 +0000 (10:09 +0000)]
imap: always send EXISTS on uo2m_extend

Clients which are NOT in an IDLE state still need to be
notified of message existence.  Unlike the EXPUNGE response,
untagged EXISTS responses seem to be allowed at any time
according to RFC 3501.

We'll also perform uo2m_extend on the NOOP command, since
NOOP is the recommended command for message polling.

3 years agods: flush_write: early return on closed socket
Eric Wong [Tue, 23 Jun 2020 18:09:06 +0000 (18:09 +0000)]
ds: flush_write: early return on closed socket

This quiets warnings from IMAP::fetch_blob (called via
long_response) failing to access `$self->{ibx}->git'
because ->{ibx} gets deleted by IMAP::close.

3 years agogit_async_cat: remove circular reference
Eric Wong [Tue, 23 Jun 2020 23:21:12 +0000 (23:21 +0000)]
git_async_cat: remove circular reference

While this circular reference was carefully managed to not leak
memory; it was still triggering a warning at -imapd/-nntpd
shutdown due to the EPOLL_CTL_DEL op failing after the $Epoll FD
gets closed.

So remove the circular reference by providing a ref to `undef',
instead.

3 years agolock: reduce inotify wakeups
Eric Wong [Wed, 24 Jun 2020 18:45:07 +0000 (18:45 +0000)]
lock: reduce inotify wakeups

We can reduce the amount of platform-specific code by always
relying on IN_MODIFY/NOTE_WRITE notifications from lock release.
This reduces the number of times our read-only daemons will
need to wake up when -watch sees no-op message changes
(e.g. replied, seen, recent flag changes).

3 years agotestcommon: DS->Reset when using fork-only subprocess
Eric Wong [Tue, 23 Jun 2020 20:51:49 +0000 (20:51 +0000)]
testcommon: DS->Reset when using fork-only subprocess

This fixes a bug on FreeBSD 11 here -nntpd + TEST_RUN_MODE=2
(default) was occasionally causing failures in t/v2writable.t
due to the kqueue descriptor being auto-closed by the OS on fork.

3 years agot/init: remove leftover find(1) call
Eric Wong [Tue, 23 Jun 2020 18:34:29 +0000 (18:34 +0000)]
t/init: remove leftover find(1) call

I used find(1) here for debugging.  The "make check-run" test
target needs to be updated to make stderr spew more obvious.

3 years agoinit: add --skip-artnum parameter
Eric Wong [Sun, 21 Jun 2020 00:21:33 +0000 (00:21 +0000)]
init: add --skip-artnum parameter

For archivists with only newer mail archives, this option allows
reserving reserve NNTP article numbers for yet-to-be-archived
old messages.  Indexers will need to be updated to support this
feature in future commits.

-V1 inboxes will now be initialized with SQLite and Xapian
support if this option is used, or if --indexlevel= is
specified.

3 years agoinit: refer to inboxes as "inbox" or "inboxes" in errors
Eric Wong [Sun, 21 Jun 2020 00:21:32 +0000 (00:21 +0000)]
init: refer to inboxes as "inbox" or "inboxes" in errors

Since V2 uses multiple git repositories, stop using
the word "repo" when referring to inboxes.

3 years agoinit: add -j / --jobs parameter
Eric Wong [Sun, 21 Jun 2020 00:21:31 +0000 (00:21 +0000)]
init: add -j / --jobs parameter

On a powerful (by my standards) machine with 16GB RAM and an
7200 RPM HDD marketed for "enterprise" use, indexing a 8.1G (in
git) LKML snapshot from Sep 2019 did not finish after 7 days
with the default number (3) of Xapian shards (`--jobs=4') and
`--batch-size=10m'.

Indexing starts off fast, but progressively get slower as
contents of the inbox (including Xapian + SQLite DBs) could no
longer be cached by the kernel.  Once the on-disk size
increased, HDD seek contention between the Xapian shard workers
slowed the process down to a crawl.

With a single shard, it still took around 3.5 days to index on
the HDD.  That's not good, but it's far better than not
finishing after 7 days.  So allow unfortunate HDD users to
easily specify a single shard on public-inbox-init.

For reference, a freshly TRIM-ed low-end TLC SSD on the SATA II
bus on the same machine indexes that same snapshot of LKML in
~7 hours with 3 shards and the same 10m batch size.  In the past,
a higher-end consumer grade MLC SSDs on similar hardware indexed
a similarly sized-data set in ~4 hours.

3 years agoimap: refill_xap: remove needless loop
Eric Wong [Sun, 21 Jun 2020 19:23:25 +0000 (19:23 +0000)]
imap: refill_xap: remove needless loop

There's no need to loop when the first iteration guarantees
a `return'.

3 years agotests: require git 2.6+ in more places
Eric Wong [Sat, 20 Jun 2020 00:13:02 +0000 (00:13 +0000)]
tests: require git 2.6+ in more places

We also need to check for git 2.6 earlier in each test case,
before any other TAP output is emitted to avoid confusing the
TAP consumers.

3 years agotestcommon: require IO::Socket::SSL >= 2.007
Eric Wong [Sat, 20 Jun 2020 00:13:01 +0000 (00:13 +0000)]
testcommon: require IO::Socket::SSL >= 2.007

Net::NNTP does not support older IO::Socket::SSL.  1.94 on
CentOS 7.x fails HTTPS and IMAPS tests, too.

cf. https://rt.cpan.org/Ticket/Display.html?id=100529

3 years agonntp: support slow blob retrievals
Eric Wong [Tue, 16 Jun 2020 22:31:22 +0000 (22:31 +0000)]
nntp: support slow blob retrievals

Having `git cat-file' as a separate process naturally lends
itself to asynchronous dispatch.  Our event loop for -nntpd no
longer blocks on slow git storage.

Pipelining in -imapd was tricky and bugs were exposed by
mbsync(1).  Update t/nntpd.t to support pipelining ARTICLE
requests to ensure we don't have the same problems -imapd
did during development.

3 years agonntp: event_step: prepare for async git reads
Eric Wong [Tue, 16 Jun 2020 22:31:21 +0000 (22:31 +0000)]
nntp: event_step: prepare for async git reads

This matches PublicInbox::IMAP::event_step and will allow us to
handle blob retrievals from git asynchronously without falling
over on pipelined requests.

3 years agodaemon: use ->can to check for IO::Socket::SSL
Eric Wong [Tue, 16 Jun 2020 22:31:20 +0000 (22:31 +0000)]
daemon: use ->can to check for IO::Socket::SSL

Doing a ref($obj) string comparison ties us to IO::Socket::SSL
(and OpenSSL) In the future, we may support GnuTLS or other TLS
implementations.  This was already done in the IMAP code.

3 years agoimap: fix UID-offset-to-MSN mapping bugs
Eric Wong [Tue, 16 Jun 2020 06:19:08 +0000 (06:19 +0000)]
imap: fix UID-offset-to-MSN mapping bugs

We need to clear the UID-offset-to-MSN mapping when
leaving mailboxes via EXAMINE/SELECT/CLOSE.

Furthermore, uo2m_last_uid() needs to account for tiny mailboxes
where the scalar representation of {uo2m} may be evaluated to
`false' in a boolean context.

3 years agoimap: *SEARCH: reinstate "TEXT" search-key
Eric Wong [Tue, 16 Jun 2020 07:05:06 +0000 (07:05 +0000)]
imap: *SEARCH: reinstate "TEXT" search-key

I accidentally dropped "TEXT" handling while porting
the IMAP search query parser to Parse::RecDescent.
This reinstates it and adds a test to prevent future
regression, and the additional test fixes a counting
error for non-Xapian-enabled systems.

3 years agoimap: *SEARCH: fix CHARSET handling
Eric Wong [Tue, 16 Jun 2020 07:04:26 +0000 (07:04 +0000)]
imap: *SEARCH: fix CHARSET handling

We no longer pass an arrayref to search_common() or
parse_query(), so handle the CHARSET directive in
the Parse::RecDescent-generated parser directly.

3 years agoimap: *SEARCH: use Parse::RecDescent
Eric Wong [Tue, 16 Jun 2020 05:05:40 +0000 (05:05 +0000)]
imap: *SEARCH: use Parse::RecDescent

For properly parsing IMAP search requests, it's easier to use a
recursive descent parser generator to deal with subqueries and
the "OR" statement.

Parse::RecDescent was chosen since it's mature, well-known,
widely available and already used by our optional dependencies:
Inline::C and Mail::IMAPClient.  While it's possible to build
Xapian queries without using the Xapian string query parser;
this iteration of the IMAP parser still builds a string which is
passed to Xapian's query parser for ease-of-diagnostics.

Since this is a recursive descent parser dealing with untrusted
inputs, subqueries have a nesting limit of 10.  I expect that is
more than adequate for real-world use.

3 years agoimap: reinstate non-UID SEARCH
Eric Wong [Tue, 16 Jun 2020 05:05:39 +0000 (05:05 +0000)]
imap: reinstate non-UID SEARCH

Since we support MSNs properly, now, it seems acceptable
to support regular SEARCH requests in case there are any
clients which still use non-UID SEARCH.

3 years agoMANIFEST: add missing 1.6.0 release notes entry
Eric Wong [Tue, 16 Jun 2020 00:33:17 +0000 (00:33 +0000)]
MANIFEST: add missing 1.6.0 release notes entry

3 years agoimap: stop_idle: fix parameter parsing :x
Eric Wong [Mon, 15 Jun 2020 09:17:28 +0000 (09:17 +0000)]
imap: stop_idle: fix parameter parsing :x

stop_idle was a noop when the client issues a "DONE"
continuation or just disconnects.  This would not have
led to a long term memory leak since FDs get closed and
reused, anyways, and all of our InboxIdle mappings are
keyed by FD.

3 years agoimap: improve IDLE handling at graceful shutdown
Eric Wong [Mon, 15 Jun 2020 07:43:17 +0000 (07:43 +0000)]
imap: improve IDLE handling at graceful shutdown

Since IMAP IDLE users aren't expected to issue any commands, we
can terminate their connections immediately on graceful
shutdown.

Furthermore, we need to drop the inotify FD from the epoll set
to avoid warnings during global destruction.  Embarassingly,
this required fixing wacky test ordering from 2a717d13f10fcdc6
("nntpd+imapd: detect replaced over.sqlite3")

3 years agoimap: clarify "DONE" usage with IDLE
Eric Wong [Mon, 15 Jun 2020 03:30:03 +0000 (03:30 +0000)]
imap: clarify "DONE" usage with IDLE

"DONE" is a continuation and not a normal IMAP command, so
ensure it can't be called like a normal IMAP command which
has a tag.

3 years agot/imapd: quiet overload warning from Mail::IMAPClient
Eric Wong [Sat, 13 Jun 2020 20:27:04 +0000 (20:27 +0000)]
t/imapd: quiet overload warning from Mail::IMAPClient

Mail::IMAPClient understandably stumbles into a warning
by our bogus test request.  Just silence it on our end
since it's not normal operation for Mail::IMAPClient.

3 years agot/imapd*.t: support older Mail::IMAPClient
Eric Wong [Sun, 14 Jun 2020 00:25:05 +0000 (00:25 +0000)]
t/imapd*.t: support older Mail::IMAPClient

->has_capability on Mail::IMAPClient 3.37 (tested on CentOS 7.x)
only returned boolean values, and not the value of the capability.

3 years agoinboxidle: support Linux::Inotify2 1.x
Eric Wong [Sun, 14 Jun 2020 00:25:04 +0000 (00:25 +0000)]
inboxidle: support Linux::Inotify2 1.x

Linux::Inotify2 1.x lacked ->on_overflow and ->broadcast
methods.  Just don't use them for now.  We may eventually
provide a pure Perl alternative which doesn't require closures,
XS, or the common::sense dependency.

Overflowing the inotify queue seems difficult to trigger at
the moment: /proc/sys/fs/inotify/max_queued_events defaults
to 16384 on a my CentOS 7.x VM with 2GB RAM.

3 years agotestcommon: allow OR-ing module dependencies
Eric Wong [Sun, 14 Jun 2020 00:25:03 +0000 (00:25 +0000)]
testcommon: allow OR-ing module dependencies

IMAP requires either the Email::Address::XS or Mail::Address
package (part of perl-MailTools RPM or libmailtools-perl deb);
and Email::Address::XS is not officially packaged for some older
distros, most notably CentOS 7.x.

3 years agodoc: update TODO and WIP 1.6.0 release notes
Eric Wong [Wed, 10 Jun 2020 18:39:09 +0000 (18:39 +0000)]
doc: update TODO and WIP 1.6.0 release notes

Lots of big changes coming   Thanks to The Linux Foundation for
sponsoring me to hack on this in 2020 :)

3 years agonntpd+imapd: detect replaced over.sqlite3
Eric Wong [Thu, 11 Jun 2020 00:57:53 +0000 (00:57 +0000)]
nntpd+imapd: detect replaced over.sqlite3

For v1 inboxes (and possibly v2 in the future, for VACUUM),
public-inbox-compact replaces over.sqlite3 with a new file.

This currently doesn't need an extra inotify watch descriptor
(or FD for kevent) at the moment, so it can coexist nicely for
systems w/o IO::KQueue or Linux::Inotify2.

3 years agoimap: introduce memory-efficient uo2m mapping
Eric Wong [Fri, 12 Jun 2020 23:49:24 +0000 (23:49 +0000)]
imap: introduce memory-efficient uo2m mapping

Since we limit our mailboxes slices to 50K and can guarantee a
contiguous UID space for those mailboxes, we can store a mapping
of "UID offsets" (not full UIDs) to Message Sequence Numbers as
an array of 16-bit unsigned integers in a 100K scalar.

For UID-only FETCH responses, we can momentarily unpack the
compact 100K representation to a ~1.6M Perl array of IV/UV
elements for a slight speedup.

Furthermore, we can (ab)use hash key deduplication in Perl5 to
deduplicate this 100K scalar across all clients with the same
mailbox slice open.

Technically we can increase our slice size to 64K w/o increasing
our storage overhead, but I suspect humans are more accustomed
to slices easily divisible by 10.

3 years agoimap: FETCH: proper MSN => UID mapping for requests
Eric Wong [Wed, 10 Jun 2020 07:05:19 +0000 (07:05 +0000)]
imap: FETCH: proper MSN => UID mapping for requests

This finally seems to make mutt header caching behave properly.

We expect to be able to safely load 50K IV/UVs in memory without
OOM, since that's "only" 1.6 MB that won't live beyond a single
event loop iteration.  So create a simple array which can
quickly map MSNs in requests to UIDs and not leave out messages.

MSNs in the FETCH response will NOT be correct, since it's
inefficient to implement properly and mutt doesn't seem to
care.

Since the conversion code is easily shared, "UID SEARCH" can
allow the same MSN => UID mapping non-UID "FETCH" does.

3 years agoover: uid_range: remove LIMIT
Eric Wong [Wed, 10 Jun 2020 07:05:18 +0000 (07:05 +0000)]
over: uid_range: remove LIMIT

The IMAP code already limits the range to UID_SLICE (50K),
so that's about 1.6MB of of IVs for an ephemeral allocation
that won't live beyond one iteration of the event loop.

3 years agoimap: remove non-UID SEARCH for now
Eric Wong [Wed, 10 Jun 2020 07:05:17 +0000 (07:05 +0000)]
imap: remove non-UID SEARCH for now

Supporting MSNs in long-lived connections beyond the lifetime of
a single request/response cycle is not scalable to a C10K
scenario.  It's probably not needed, since most clients seem to
use UIDs.

A somewhat efficient implementation I can come up uses
pack("S*" ...) (AKA "uint16_t mapping[50000]") has an overhead
of 100K per-client socket on a mailbox with 50K messages.  The
100K is a contiguous scalar, so it could be swapped out for
idle clients on most architectures if THP is disabled.

An alternative could be to use a tempfile as an allocator
partitioned into 100K chunks (or SQLite); but I'll only do that
if somebody presents a compelling case to support MSN SEARCH.

3 years agoimapd: don't bother sorting LIST output
Eric Wong [Wed, 10 Jun 2020 07:05:16 +0000 (07:05 +0000)]
imapd: don't bother sorting LIST output

The sort was unstable on my test instance anyways, and
clients don't seem to mind.  So stop wasting CPU cycles.

3 years agoimap: misc cleanups and notes
Eric Wong [Wed, 10 Jun 2020 07:05:15 +0000 (07:05 +0000)]
imap: misc cleanups and notes

Note some of our limitations for potential hackers.

We'll be renaming "UID_BLOCK" to "UID_SLICE", since "block" is
overused term and "slice" isn't used in our codebase.  Also,
document how "slice" and "epochs" are similar concepts for
different clients.

3 years agoimap: wire up Xapian, MSN SEARCH and multi sequence-sets
Eric Wong [Wed, 10 Jun 2020 07:05:14 +0000 (07:05 +0000)]
imap: wire up Xapian, MSN SEARCH and multi sequence-sets

Simple queries work, more complex queries involving parentheses,
"OR", "NOT" don't work, yet.

Tested with "=b", "=B", and "=H" search and limits in mutt
on both v1 and v2 with multiple Xapian shards.

3 years agoimap: UID SEARCH: support multiple ranges
Eric Wong [Wed, 10 Jun 2020 07:05:13 +0000 (07:05 +0000)]
imap: UID SEARCH: support multiple ranges

We can share a bit of code with FETCH to refill UID
ranges which hit the SQLite overview.

3 years agoimap: STATUS/EXAMINE: rely on SQLite overview
Eric Wong [Wed, 10 Jun 2020 07:05:12 +0000 (07:05 +0000)]
imap: STATUS/EXAMINE: rely on SQLite overview

We can get exact values for EXISTS, UIDNEXT using SQLite
rather than calculating off $ibx->mm->max ourselves.

Furthermore, $ibx->mm is less useful than $ibx->over for IMAP
(and for our read-only daemons in general) so do not depend on
$ibx->mm outside of startup/reload to save FDs and reduce kernel
page cache footprint.

3 years agoimap: FETCH: try to make fake MSNs sequentially
Eric Wong [Wed, 10 Jun 2020 07:05:11 +0000 (07:05 +0000)]
imap: FETCH: try to make fake MSNs sequentially

This appears to significantly improve header caching behavior
with mutt.  With the current public-inbox.org/git mirror(*),
mutt will only re-FETCH the last ~300 or so messages in the
final "inbox.comp.version-control.git.7" mailbox, instead of
~49,000 messages every time.

It's not perfect, but a 500ms query is better than a >10s query
and mutt itself spends as much time loading its header cache.

(*) there are many gaps in NNTP article numbers (UIDs) due to
    spam removal from public-inbox-learn.

3 years agoimap: further speed up HEADER.FIELDS FETCH requests
Eric Wong [Wed, 10 Jun 2020 07:05:10 +0000 (07:05 +0000)]
imap: further speed up HEADER.FIELDS FETCH requests

Since headers are big and include a lot of lines MUAs don't
care about, we can skip the CRLF_HDR ops and just do the
CRLF conversion in partial_hdr_get and partial_hdr_not.
This is another 10-15% speedup for mutt w/o header caching.

3 years agoimap: FETCH: more granular CRLF conversion
Eric Wong [Wed, 10 Jun 2020 07:05:09 +0000 (07:05 +0000)]
imap: FETCH: more granular CRLF conversion

This speeds up requests from mutt for HEADER.FIELDS by around 10%
since we don't waste time doing CRLF conversion on large message
bodies that get discarded, anyways.

3 years agoimap: cleanup ->{uid_base} usage
Eric Wong [Wed, 10 Jun 2020 07:05:08 +0000 (07:05 +0000)]
imap: cleanup ->{uid_base} usage

Ensure {uid_base} is always set, so we don't need to add `//'
checks everywhere.  Furthermore, this fixes a hard-to-test bug
where the STATUS command would inadvertantly clobber {uid_base}.