]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LEI.pm
lei up --all: send signals to workers, receive errors
[public-inbox.git] / lib / PublicInbox / LEI.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Backend for `lei' (local email interface).  Unlike the C10K-oriented
5 # PublicInbox::Daemon, this is designed exclusively to handle trusted
6 # local clients with read/write access to the FS and use as many
7 # system resources as the local user has access to.
8 package PublicInbox::LEI;
9 use strict;
10 use v5.10.1;
11 use parent qw(PublicInbox::DS PublicInbox::LeiExternal
12         PublicInbox::LeiQuery);
13 use Getopt::Long ();
14 use Socket qw(AF_UNIX SOCK_SEQPACKET MSG_EOR pack_sockaddr_un);
15 use Errno qw(EPIPE EAGAIN EINTR ECONNREFUSED ENOENT ECONNRESET);
16 use Cwd qw(getcwd);
17 use POSIX qw(strftime);
18 use IO::Handle ();
19 use Fcntl qw(SEEK_SET);
20 use PublicInbox::Config;
21 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
22 use PublicInbox::DS qw(now dwaitpid);
23 use PublicInbox::Spawn qw(spawn popen_rd);
24 use PublicInbox::Lock;
25 use PublicInbox::Eml;
26 use PublicInbox::Import;
27 use PublicInbox::ContentHash qw(git_sha);
28 use Time::HiRes qw(stat); # ctime comparisons for config cache
29 use File::Path qw(mkpath);
30 use File::Spec;
31 use Sys::Syslog qw(openlog syslog closelog);
32 our $quit = \&CORE::exit;
33 our ($current_lei, $errors_log, $listener, $oldset, $dir_idle,
34         $recv_cmd, $send_cmd);
35 my $GLP = Getopt::Long::Parser->new;
36 $GLP->configure(qw(gnu_getopt no_ignore_case auto_abbrev));
37 my $GLP_PASS = Getopt::Long::Parser->new;
38 $GLP_PASS->configure(qw(gnu_getopt no_ignore_case auto_abbrev pass_through));
39
40 our %PATH2CFG; # persistent for socket daemon
41 our $MDIR2CFGPATH; # /path/to/maildir => { /path/to/config => [ ino watches ] }
42
43 # TBD: this is a documentation mechanism to show a subcommand
44 # (may) pass options through to another command:
45 sub pass_through { $GLP_PASS }
46
47 my $OPT;
48 sub opt_dash ($$) {
49         my ($spec, $re_str) = @_; # 'limit|n=i', '([0-9]+)'
50         my ($key) = ($spec =~ m/\A([a-z]+)/g);
51         my $cb = sub { # Getopt::Long "<>" catch-all handler
52                 my ($arg) = @_;
53                 if ($arg =~ /\A-($re_str)\z/) {
54                         $OPT->{$key} = $1;
55                 } elsif ($arg eq '--') { # "--" arg separator, ignore first
56                         push @{$OPT->{-argv}}, $arg if $OPT->{'--'}++;
57                 # lone (single) dash is handled elsewhere
58                 } elsif (substr($arg, 0, 1) eq '-') {
59                         if ($OPT->{'--'}) {
60                                 push @{$OPT->{-argv}}, $arg;
61                         } else {
62                                 die "bad argument: $arg\n";
63                         }
64                 } else {
65                         push @{$OPT->{-argv}}, $arg;
66                 }
67         };
68         ($spec, '<>' => $cb, $GLP_PASS) # for Getopt::Long
69 }
70
71 # rel2abs preserves symlinks in parent, unlike abs_path
72 sub rel2abs {
73         my ($self, $p) = @_;
74         if (index($p, '/') == 0) { # already absolute
75                 $p =~ tr!/!/!s; # squeeze redundant slashes
76                 chop($p) if substr($p, -1, 1) eq '/';
77                 return $p;
78         }
79         my $pwd = $self->{env}->{PWD};
80         my $cwd;
81         if (defined $pwd) {
82                 my $xcwd = $self->{3} //
83                         ($cwd = getcwd() // die "getcwd(PWD=$pwd): $!");
84                 if (my @st_pwd = stat($pwd)) {
85                         my @st_cwd = stat($xcwd) or die "stat($xcwd): $!";
86                         "@st_pwd[1,0]" eq "@st_cwd[1,0]" or
87                                 $self->{env}->{PWD} = $pwd = undef;
88                 } else { # PWD was invalid
89                         $self->{env}->{PWD} = $pwd = undef;
90                 }
91         }
92         $pwd //= $self->{env}->{PWD} = $cwd // getcwd() // die "getcwd: $!";
93         File::Spec->rel2abs($p, $pwd);
94 }
95
96 # abs_path resolves symlinks in parent iff all parents exist
97 sub abs_path { Cwd::abs_path($_[1]) // rel2abs(@_) }
98
99 sub canonpath_harder {
100         my $p = $_[-1]; # $_[0] may be self
101         $p = File::Spec->canonpath($p);
102         $p =~ m!(?:/*|\A)\.\.(?:/*|\z)! && -e $p ? Cwd::abs_path($p) : $p;
103 }
104
105 sub share_path ($) { # $HOME/.local/share/lei/$FOO
106         my ($self) = @_;
107         rel2abs($self, ($self->{env}->{XDG_DATA_HOME} //
108                 ($self->{env}->{HOME} // '/nonexistent').'/.local/share')
109                 .'/lei');
110 }
111
112 sub store_path ($) { share_path($_[0]) . '/store' }
113
114 sub _config_path ($) {
115         my ($self) = @_;
116         rel2abs($self, ($self->{env}->{XDG_CONFIG_HOME} //
117                 ($self->{env}->{HOME} // '/nonexistent').'/.config')
118                 .'/lei/config');
119 }
120
121 sub cache_dir ($) {
122         my ($self) = @_;
123         rel2abs($self, ($self->{env}->{XDG_CACHE_HOME} //
124                 ($self->{env}->{HOME} // '/nonexistent').'/.cache')
125                 .'/lei');
126 }
127
128 sub url_folder_cache {
129         my ($self) = @_;
130         require PublicInbox::SharedKV; # URI => updated_at_sec_
131         PublicInbox::SharedKV->new(cache_dir($self).'/uri_folder');
132 }
133
134 sub ale {
135         my ($self) = @_;
136         $self->{ale} //= do {
137                 require PublicInbox::LeiALE;
138                 $self->_lei_cfg(1)->{ale} //= PublicInbox::LeiALE->new($self);
139         };
140 }
141
142 sub index_opt {
143         # TODO: drop underscore variants everywhere, they're undocumented
144         qw(fsync|sync! jobs|j=i indexlevel|L=s compact
145         max_size|max-size=s sequential-shard
146         batch_size|batch-size=s skip-docdata)
147 }
148
149 my @c_opt = qw(c=s@ C=s@ quiet|q);
150 my @net_opt = (qw(no-torsocks torsocks=s), PublicInbox::LeiQuery::curl_opt());
151 my @lxs_opt = qw(remote! local! external! include|I=s@ exclude=s@ only|O=s@
152         import-remote!);
153
154 # we don't support -C as an alias for --find-copies since it's already
155 # used for chdir
156 our @diff_opt = qw(unified|U=i output-indicator-new=s output-indicator-old=s
157         output-indicator-context=s indent-heuristic!
158         minimal patience histogram anchored=s@ diff-algorithm=s
159         color-moved:s color-moved-ws=s no-color-moved no-color-moved-ws
160         word-diff:s word-diff-regex=s color-words:s no-renames
161         rename-empty! check ws-error-highlight=s full-index binary
162         abbrev:i break-rewrites|B:s find-renames|M:s find-copies:s
163         find-copies-harder irreversible-delete|D l=i diff-filter=s
164         S=s G=s find-object=s pickaxe-all pickaxe-regex O=s R
165         relative:s text|a ignore-cr-at-eol ignore-space-at-eol
166         ignore-space-change|b ignore-all-space|w ignore-blank-lines
167         inter-hunk-context=i function-context|W exit-code ext-diff
168         no-ext-diff textconv! src-prefix=s dst-prefix=s no-prefix
169         line-prefix=s);
170
171 # we generate shell completion + help using %CMD and %OPTDESC,
172 # see lei__complete() and PublicInbox::LeiHelp
173 # command => [ positional_args, 1-line description, Getopt::Long option spec ]
174 our %CMD = ( # sorted in order of importance/use:
175 'q' => [ '--stdin|SEARCH_TERMS...', 'search for messages matching terms',
176         'stdin|', # /|\z/ must be first for lone dash
177         @lxs_opt, @net_opt,
178         qw(save! output|mfolder|o=s format|f=s dedupe|d=s threads|t+
179         sort|s=s reverse|r offset=i pretty jobs|j=s globoff|g augment|a
180         import-before! lock=s@ rsyncable alert=s@ mua=s verbose|v+
181         shared color! mail-sync!), @c_opt, opt_dash('limit|n=i', '[0-9]+') ],
182
183 'up' => [ 'OUTPUT...|--all', 'update saved search',
184         qw(jobs|j=s lock=s@ alert=s@ mua=s verbose|v+
185         remote-fudge-time=s all:s), @c_opt ],
186
187 'lcat' => [ '--stdin|MSGID_OR_URL...', 'display local copy of message(s)',
188         'stdin|', # /|\z/ must be first for lone dash
189         # some of these options are ridiculous for lcat
190         @lxs_opt, @net_opt,
191         qw(output|mfolder|o=s format|f=s dedupe|d=s threads|t+
192         sort|s=s reverse|r offset=i jobs|j=s globoff|g augment|a
193         import-before! lock=s@ rsyncable alert=s@ mua=s verbose|v+
194         color!), @c_opt, opt_dash('limit|n=i', '[0-9]+') ],
195
196 'blob' => [ 'OID', 'show a git blob, reconstructing from mail if necessary',
197         qw(git-dir=s@ cwd! verbose|v+ mail! oid-a|A=s path-a|a=s path-b|b=s),
198         @lxs_opt, @net_opt, @c_opt ],
199
200 'rediff' => [ '--stdin|LOCATION...',
201                 'regenerate a diff with different options',
202         'stdin|', # /|\z/ must be first for lone dash
203         qw(git-dir=s@ cwd! verbose|v+ color:s no-color drq:1 dequote-only:1),
204         @diff_opt, @lxs_opt, @net_opt, @c_opt ],
205
206 'mail-diff' => [ '--stdin|LOCATION...', 'diff the contents of emails',
207         'stdin|', # /|\z/ must be first for lone dash
208         qw(verbose|v+ color:s no-color raw-header),
209         @diff_opt, @net_opt, @c_opt ],
210
211 'add-external' => [ 'LOCATION',
212         'add/set priority of a publicinbox|extindex for extra matches',
213         qw(boost=i mirror=s inbox-version=i epoch=s verbose|v+),
214         @c_opt, index_opt(), @net_opt ],
215 'ls-external' => [ '[FILTER]', 'list publicinbox|extindex locations',
216         qw(format|f=s z|0 globoff|g invert-match|v local remote), @c_opt ],
217 'ls-label' => [ '', 'list labels', qw(z|0 stats:s), @c_opt ],
218 'ls-mail-sync' => [ '[FILTER]', 'list mail sync folders',
219                 qw(z|0 globoff|g invert-match|v local remote), @c_opt ],
220 'ls-mail-source' => [ 'URL', 'list IMAP or NNTP mail source folders',
221                 qw(z|0 ascii l pretty url), @c_opt ],
222 'forget-external' => [ 'LOCATION...|--prune',
223         'exclude further results from a publicinbox|extindex',
224         qw(prune), @c_opt ],
225
226 'ls-search' => [ '[PREFIX]', 'list saved search queries',
227                 qw(format|f=s pretty l ascii z|0), @c_opt ],
228 'forget-search' => [ 'OUTPUT', 'forget a saved search',
229                 qw(verbose|v+), @c_opt ],
230 'edit-search' => [ 'OUTPUT', "edit saved search via `git config --edit'",
231                         @c_opt ],
232 'rm' => [ '--stdin|LOCATION...',
233         'remove a message from the index and prevent reindexing',
234         'stdin|', # /|\z/ must be first for lone dash
235         qw(in-format|F=s lock=s@), @net_opt, @c_opt ],
236 'plonk' => [ '--threads|--from=IDENT',
237         'exclude mail matching From: or threads from non-Message-ID searches',
238         qw(stdin| threads|t from|f=s mid=s oid=s), @c_opt ],
239 'tag' => [ 'KEYWORDS...',
240         'set/unset keywords and/or labels on message(s)',
241         qw(stdin| in-format|F=s input|i=s@ oid=s@ mid=s@),
242         @net_opt, @c_opt, pass_through('-kw:foo for delete') ],
243
244 'purge-mailsource' => [ 'LOCATION|--all',
245         'remove imported messages from IMAP, Maildirs, and MH',
246         qw(exact! all jobs:i indexed), @c_opt ],
247
248 'add-watch' => [ 'LOCATION...', 'watch for new messages and flag changes',
249         qw(poll-interval=s state=s recursive|r), @c_opt ],
250 'rm-watch' => [ 'LOCATION...', 'remove specified watch(es)',
251         qw(recursive|r), @c_opt ],
252 'ls-watch' => [ '[FILTER...]', 'list active watches with numbers and status',
253                 qw(l z|0), @c_opt ],
254 'pause-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote), @c_opt ],
255 'resume-watch' => [ '[WATCH_NUMBER_OR_FILTER]', qw(all local remote), @c_opt ],
256 'forget-watch' => [ '{WATCH_NUMBER|--prune}', 'stop and forget a watch',
257         qw(prune), @c_opt ],
258
259 'index' => [ 'LOCATION...', 'one-time index from URL or filesystem',
260         qw(in-format|F=s kw! offset=i recursive|r exclude=s include|I=s
261         verbose|v+ incremental!), @net_opt, # mainly for --proxy=
262          @c_opt ],
263 'import' => [ 'LOCATION...|--stdin',
264         'one-time import/update from URL or filesystem',
265         qw(stdin| offset=i recursive|r exclude=s include|I=s new-only
266         lock=s@ in-format|F=s kw! verbose|v+ incremental! mail-sync!),
267         @net_opt, @c_opt ],
268 'forget-mail-sync' => [ 'LOCATION...',
269         'forget sync information for a mail folder', @c_opt ],
270 'refresh-mail-sync' => [ 'LOCATION...|--all',
271         'prune dangling sync data for a mail folder', 'all:s', @c_opt ],
272 'export-kw' => [ 'LOCATION...|--all',
273         'one-time export of keywords of sync sources',
274         qw(all:s mode=s), @net_opt, @c_opt ],
275 'convert' => [ 'LOCATION...|--stdin',
276         'one-time conversion from URL or filesystem to another format',
277         qw(stdin| in-format|F=s out-format|f=s output|mfolder|o=s lock=s@ kw!),
278         @net_opt, @c_opt ],
279 'p2q' => [ 'FILE|COMMIT_OID|--stdin',
280         "use a patch to generate a query for `lei q --stdin'",
281         qw(stdin| want|w=s@ uri debug), @c_opt ],
282 'config' => [ '[...]', sub {
283                 'git-config(1) wrapper for '._config_path($_[0]);
284         }, qw(config-file|system|global|file|f=s), # for conflict detection
285          qw(edit|e c=s@ C=s@), pass_through('git config') ],
286 'inspect' => [ 'ITEMS...|--stdin', 'inspect lei/store and/or local external',
287         qw(stdin| pretty ascii dir|d=s), @c_opt ],
288
289 'init' => [ '[DIRNAME]', sub {
290         "initialize storage, default: ".store_path($_[0]);
291         }, @c_opt ],
292 'daemon-kill' => [ '[-SIGNAL]', 'signal the lei-daemon',
293         # "-C DIR" conflicts with -CHLD, here, and chdir makes no sense, here
294         opt_dash('signal|s=s', '[0-9]+|(?:[A-Z][A-Z0-9]+)') ],
295 'daemon-pid' => [ '', 'show the PID of the lei-daemon' ],
296 'help' => [ '[SUBCOMMAND]', 'show help' ],
297
298 # TODO
299 #'reorder-local-store-and-break-history' => [ '[REFNAME]',
300 #       'rewrite git history in an attempt to improve compression',
301 #       qw(gc!), @c_opt ],
302 #'fuse-mount' => [ 'PATHNAME', 'expose lei/store as Maildir(s)', @c_opt ],
303 #
304 # internal commands are prefixed with '_'
305 '_complete' => [ '[...]', 'internal shell completion helper',
306                 pass_through('everything') ],
307 ); # @CMD
308
309 # switch descriptions, try to keep consistent across commands
310 # $spec: Getopt::Long option specification
311 # $spec => [@ALLOWED_VALUES (default is first), $description],
312 # $spec => $description
313 # "$SUB_COMMAND TAB $spec" => as above
314 my $stdin_formats = [ 'MAIL_FORMAT|eml|mboxrd|mboxcl2|mboxcl|mboxo',
315                         'specify message input format' ];
316 my $ls_format = [ 'OUT|plain|json|null', 'listing output format' ];
317
318 # we use \x{a0} (non-breaking SP) to avoid wrapping in PublicInbox::LeiHelp
319 my %OPTDESC = (
320 'help|h' => 'show this built-in help',
321 'c=s@' => [ 'NAME=VALUE', 'set config option' ],
322 'C=s@' => [ 'DIR', 'chdir to specify to directory' ],
323 'quiet|q' => 'be quiet',
324 'lock=s@' => [ 'METHOD|dotlock|fcntl|flock|none',
325         'mbox(5) locking method(s) to use (default: fcntl,dotlock)' ],
326
327 'incremental!   import' => 'import already seen IMAP and NNTP articles',
328 'globoff|g' => "do not match locations using '*?' wildcards ".
329                 "and\xa0'[]'\x{a0}ranges",
330 'invert-match|v' => 'select non-matching lines',
331 'color!' => 'disable color (for --format=text)',
332 'verbose|v+' => 'be more verbose',
333 'external!' => 'do not use externals',
334 'mail!' => 'do not look in mail storage for OID',
335 'cwd!' => 'do not look in git repo of current working directory',
336 'oid-a|A=s' => 'pre-image OID',
337 'path-a|a=s' => 'pre-image pathname associated with OID',
338 'path-b|b=s' => 'post-image pathname associated with OID',
339 'git-dir=s@' => 'additional git repository to scan',
340 'dir|d=s        inspect' =>
341         'specify a inboxdir, extindex topdir or Xapian shard',
342 'proxy=s' => [ 'PROTO://HOST[:PORT]', # shared with curl(1)
343         "proxy for (e.g. `socks5h://0:9050')" ],
344 'torsocks=s' => ['VAL|auto|no|yes',
345                 'whether or not to wrap git and curl commands with torsocks'],
346 'no-torsocks' => 'alias for --torsocks=no',
347 'save!' =>  "do not save a search for `lei up'",
348 'import-remote!' => 'do not memoize remote messages into local store',
349
350 'type=s' => [ 'any|mid|git', 'disambiguate type' ],
351
352 'dedupe|d=s' => ['STRATEGY|content|oid|mid|none',
353                 'deduplication strategy'],
354 'threads|t+' =>
355         'return all messages in the same threads as the actual match(es)',
356
357 'want|w=s@' => [ 'PREFIX|dfpost|dfn', # common ones in help...
358                 'search prefixes to extract (default: dfpost7)' ],
359
360 'alert=s@' => ['CMD,:WINCH,:bell,<any command>',
361         'run command(s) or perform ops when done writing to output ' .
362         '(default: ":WINCH,:bell" with --mua and Maildir/IMAP output, ' .
363         'nothing otherwise)' ],
364
365 'augment|a' => 'augment --output destination instead of clobbering',
366
367 'output|mfolder|o=s' => [ 'MFOLDER',
368         "destination (e.g.\xa0`/path/to/Maildir', ".
369         "or\xa0`-'\x{a0}for\x{a0}stdout)" ],
370 'mua=s' => [ 'CMD',
371         "MUA to run on --output Maildir or mbox (e.g.\xa0`mutt\xa0-f\xa0%f')" ],
372 'new-only       import' => 'only import new messages from IMAP source',
373
374 'inbox-version=i' => [ 'NUM|1|2',
375                 'force a public-inbox version with --mirror'],
376 'mirror=s' => [ 'URL', 'mirror a public-inbox'],
377
378 # public-inbox-index options
379 'fsync!' => 'speed up indexing after --mirror, risk index corruption',
380 'compact' => 'run compact index after mirroring',
381 'indexlevel|L=s' => [ 'LEVEL|full|medium|basic',
382         "indexlevel with --mirror (default: full)" ],
383 'max_size|max-size=s' => [ 'SIZE',
384         'do not index messages larger than SIZE (default: infinity)' ],
385 'batch_size|batch-size=s' => [ 'SIZE',
386         'flush changes to OS after given number of bytes (default: 1m)' ],
387 'sequential-shard' =>
388         'index Xapian shards sequentially for slow storage',
389 'skip-docdata' =>
390         'drop compatibility w/ public-inbox <1.6 to save ~1.5% space',
391
392 'format|f=s     q' => [
393         'OUT|maildir|mboxrd|mboxcl2|mboxcl|mboxo|html|json|jsonl|concatjson',
394                 'specify output format, default depends on --output'],
395 'exclude=s@     q' => [ 'LOCATION',
396                 'exclude specified external(s) from search' ],
397 'include|I=s@   q' => [ 'LOCATION',
398                 'include specified external(s) in search' ],
399 'only|O=s@      q' => [ 'LOCATION',
400                 'only use specified external(s) for search' ],
401 'jobs=s q' => [ '[SEARCH_JOBS][,WRITER_JOBS]',
402                 'control number of search and writer jobs' ],
403 'jobs|j=i       add-external' => 'set parallelism when indexing after --mirror',
404
405 'in-format|F=s' => $stdin_formats,
406 'format|f=s     ls-search' => ['OUT|json|jsonl|concatjson',
407                         'listing output format' ],
408 'l      ls-search' => 'long listing format',
409 'l      ls-watch' => 'long listing format',
410 'l      ls-mail-source' => 'long listing format',
411 'url    ls-mail-source' => 'show full URL of newsgroup or IMAP folder',
412 'format|f=s     ls-external' => $ls_format,
413
414 'limit|n=i@' => ['NUM', 'limit on number of matches (default: 10000)' ],
415 'offset=i' => ['OFF', 'search result offset (default: 0)'],
416
417 'sort|s=s' => [ 'VAL|received|relevance|docid',
418                 "order of results is `--output'-dependent"],
419 'reverse|r' => 'reverse search results', # like sort(1)
420
421 'boost=i' => 'increase/decrease priority of results (default: 0)',
422
423 'local' => 'limit operations to the local filesystem',
424 'local!' => 'exclude results from the local filesystem',
425 'remote' => 'limit operations to those requiring network access',
426 'remote!' => 'prevent operations requiring network access',
427
428 # up, refresh-mail-sync, export-kw
429 'all:s' => ['TYPE|local|remote', 'all remote or local folders' ],
430
431 'remote-fudge-time=s' => [ 'INTERVAL',
432         'look for mail INTERVAL older than the last successful query' ],
433
434 'mid=s' => 'specify the Message-ID of a message',
435 'oid=s' => 'specify the git object ID of a message',
436
437 'recursive|r' => 'scan directories/mailboxes/newsgroups recursively',
438 'exclude=s' => 'exclude mailboxes/newsgroups based on pattern',
439 'include=s' => 'include mailboxes/newsgroups based on pattern',
440
441 'exact' => 'operate on exact header matches only',
442 'exact!' => 'rely on content match instead of exact header matches',
443
444 'by-mid|mid:s' => [ 'MID', 'match only by Message-ID, ignoring contents' ],
445
446 'kw!' => 'disable/enable importing keywords (aka "flags")',
447
448 # xargs, env, use "-0", git(1) uses "-z".  We support z|0 everywhere
449 'z|0' => 'use NUL \\0 instead of newline (CR) to delimit lines',
450
451 'signal|s=s' => [ 'SIG', 'signal to send lei-daemon (default: TERM)' ],
452 ); # %OPTDESC
453
454 my %CONFIG_KEYS = (
455         'leistore.dir' => 'top-level storage location',
456 );
457
458 my @WQ_KEYS = qw(lxs l2m ikw pmd wq1 lne); # internal workers
459
460 sub _drop_wq {
461         my ($self) = @_;
462         for my $wq (grep(defined, delete(@$self{@WQ_KEYS}))) {
463                 if ($wq->wq_kill('-TERM')) {
464                         $wq->wq_close(0, undef, $self);
465                 } elsif ($wq->wq_kill_old('-TERM')) {
466                         $wq->wq_wait_old(undef, $self);
467                 }
468                 $wq->DESTROY;
469         }
470 }
471
472 # pronounced "exit": x_it(1 << 8) => exit(1); x_it(13) => SIGPIPE
473 sub x_it ($$) {
474         my ($self, $code) = @_;
475         local $current_lei = $self;
476         # make sure client sees stdout before exit
477         $self->{1}->autoflush(1) if $self->{1};
478         stop_pager($self);
479         if ($self->{pkt_op_p}) { # worker => lei-daemon
480                 $self->{pkt_op_p}->pkt_do('x_it', $code);
481         } elsif ($self->{sock}) { # lei->daemon => lei(1) client
482                 send($self->{sock}, "x_it $code", MSG_EOR);
483         } elsif ($quit == \&CORE::exit) { # an admin (one-shot) command
484                 exit($code >> 8);
485         } # else ignore if client disconnected
486 }
487
488 sub err ($;@) {
489         my $self = shift;
490         my $err = $self->{2} // ($self->{pgr} // [])->[2] // *STDERR{GLOB};
491         my @eor = (substr($_[-1]//'', -1, 1) eq "\n" ? () : ("\n"));
492         print $err @_, @eor and return;
493         my $old_err = delete $self->{2};
494         close($old_err) if $! == EPIPE && $old_err;
495         $err = $self->{2} = ($self->{pgr} // [])->[2] // *STDERR{GLOB};
496         print $err @_, @eor or print STDERR @_, @eor;
497 }
498
499 sub qerr ($;@) { $_[0]->{opt}->{quiet} or err(shift, @_) }
500
501 sub qfin { # show message on finalization (LeiFinmsg)
502         my ($lei, $msg) = @_;
503         return if $lei->{opt}->{quiet};
504         $lei->{fmsg} ? push(@{$lei->{fmsg}}, "$msg\n") : qerr($lei, $msg);
505 }
506
507 sub fail_handler ($;$$) {
508         my ($lei, $code, $io) = @_;
509         local $current_lei = $lei;
510         close($io) if $io; # needed to avoid warnings on SIGPIPE
511         _drop_wq($lei);
512         x_it($lei, $code // (1 << 8));
513 }
514
515 sub sigpipe_handler { # handles SIGPIPE from @WQ_KEYS workers
516         fail_handler($_[0], 13, delete $_[0]->{1});
517 }
518
519 sub fail ($$;$) {
520         my ($self, $buf, $exit_code) = @_;
521         local $current_lei = $self;
522         $self->{failed}++;
523         warn($buf, "\n") if defined $buf;
524         $self->{pkt_op_p}->pkt_do('fail_handler') if $self->{pkt_op_p};
525         x_it($self, ($exit_code // 1) << 8);
526         undef;
527 }
528
529 sub out ($;@) {
530         my $self = shift;
531         return if print { $self->{1} // return } @_; # likely
532         return note_sigpipe($self, 1) if $! == EPIPE;
533         my $err = "error writing to output: $!";
534         delete $self->{1};
535         fail($self, $err);
536 }
537
538 sub puts ($;@) { out(shift, map { "$_\n" } @_) }
539
540 sub child_error { # passes non-fatal curl exit codes to user
541         my ($self, $child_error, $msg) = @_; # child_error is $?
542         local $current_lei = $self;
543         $child_error ||= 1 << 8;
544         warn($msg, "\n") if defined $msg;
545         if ($self->{pkt_op_p}) { # to top lei-daemon
546                 $self->{pkt_op_p}->pkt_do('child_error', $child_error);
547         } elsif ($self->{sock}) { # to lei(1) client
548                 send($self->{sock}, "child_error $child_error", MSG_EOR);
549         } else { # non-lei admin command
550                 $self->{child_error} ||= $child_error;
551         } # else noop if client disconnected
552 }
553
554 sub note_sigpipe { # triggers sigpipe_handler
555         my ($self, $fd) = @_;
556         close(delete($self->{$fd})); # explicit close silences Perl warning
557         $self->{pkt_op_p}->pkt_do('sigpipe_handler') if $self->{pkt_op_p};
558         x_it($self, 13);
559 }
560
561 sub _lei_atfork_child {
562         my ($self, $persist) = @_;
563         # we need to explicitly close things which are on stack
564         if ($persist) {
565                 chdir '/' or die "chdir(/): $!";
566                 close($_) for (grep(defined, delete @$self{qw(0 1 2 sock)}));
567                 if (my $cfg = $self->{cfg}) {
568                         delete @$cfg{qw(-lei_store -watches -lei_note_event)};
569                 }
570         } else { # worker, Net::NNTP (Net::Cmd) uses STDERR directly
571                 open STDERR, '+>&='.fileno($self->{2}) or warn "open $!";
572                 STDERR->autoflush(1);
573                 POSIX::setpgid(0, $$) // die "setpgid(0, $$): $!";
574         }
575         close($_) for (grep(defined, delete @$self{qw(3 old_1 au_done)}));
576         delete $self->{-socks};
577         if (my $op_c = delete $self->{pkt_op_c}) {
578                 close(delete $op_c->{sock});
579         }
580         if (my $pgr = delete $self->{pgr}) {
581                 close($_) for (@$pgr[1,2]);
582         }
583         close $listener if $listener;
584         undef $listener;
585         $dir_idle->force_close if $dir_idle;
586         undef $dir_idle;
587         %PATH2CFG = ();
588         $MDIR2CFGPATH = {};
589         eval 'no warnings; undef $PublicInbox::LeiNoteEvent::to_flush';
590         undef $errors_log;
591         $quit = \&CORE::exit;
592         if (!$self->{-eml_noisy}) { # only "lei import" sets this atm
593                 my $cb = $SIG{__WARN__} // \&CORE::warn;
594                 $SIG{__WARN__} = sub {
595                         $cb->(@_) unless PublicInbox::Eml::warn_ignore(@_)
596                 };
597         }
598         $SIG{TERM} = sub { exit(128 + 15) };
599         $current_lei = $persist ? undef : $self; # for SIG{__WARN__}
600 }
601
602 sub _delete_pkt_op { # OnDestroy callback to prevent leaks on die
603         my ($self) = @_;
604         if (my $op = delete $self->{pkt_op_c}) { # in case of die
605                 $op->close; # PublicInbox::PktOp::close
606         }
607         my $pkt_op_p = delete($self->{pkt_op_p}) or return;
608         close $pkt_op_p->{op_p};
609 }
610
611 sub pkt_op_pair {
612         my ($self) = @_;
613         require PublicInbox::OnDestroy;
614         require PublicInbox::PktOp;
615         my $end = PublicInbox::OnDestroy->new($$, \&_delete_pkt_op, $self);
616         @$self{qw(pkt_op_c pkt_op_p)} = PublicInbox::PktOp->pair;
617         $end;
618 }
619
620 sub incr {
621         my ($self, $field, $nr) = @_;
622         $self->{counters}->{$field} += $nr;
623 }
624
625 sub pkt_ops {
626         my ($lei, $ops) = @_;
627         $ops->{fail_handler} = [ $lei ];
628         $ops->{sigpipe_handler} = [ $lei ];
629         $ops->{x_it} = [ $lei ];
630         $ops->{child_error} = [ $lei ];
631         $ops->{incr} = [ $lei ];
632         $ops;
633 }
634
635 sub workers_start {
636         my ($lei, $wq, $jobs, $ops, $flds) = @_;
637         $ops = pkt_ops($lei, { ($ops ? %$ops : ()) });
638         $ops->{''} //= [ $wq->can('_lei_wq_eof') || \&wq_eof, $lei ];
639         my $end = $lei->pkt_op_pair;
640         my $ident = $wq->{-wq_ident} // "lei-$lei->{cmd} worker";
641         $flds->{lei} = $lei;
642         $wq->wq_workers_start($ident, $jobs, $lei->oldset, $flds);
643         delete $lei->{pkt_op_p};
644         my $op_c = delete $lei->{pkt_op_c};
645         @$end = ();
646         $lei->event_step_init;
647         ($op_c, $ops);
648 }
649
650 # call this when we're ready to wait on events and yield to other clients
651 sub wait_wq_events {
652         my ($lei, $op_c, $ops) = @_;
653         for my $wq (grep(defined, @$lei{qw(ikw pmd)})) { # auxiliary WQs
654                 $wq->wq_close(1);
655         }
656         $op_c->{ops} = $ops;
657 }
658
659 sub _help {
660         require PublicInbox::LeiHelp;
661         PublicInbox::LeiHelp::call($_[0], $_[1], \%CMD, \%OPTDESC);
662 }
663
664 sub optparse ($$$) {
665         my ($self, $cmd, $argv) = @_;
666         # allow _complete --help to complete, not show help
667         return 1 if substr($cmd, 0, 1) eq '_';
668         $self->{cmd} = $cmd;
669         $OPT = $self->{opt} //= {};
670         my $info = $CMD{$cmd} // [ '[...]' ];
671         my ($proto, undef, @spec) = @$info;
672         my $glp = ref($spec[-1]) eq ref($GLP) ? pop(@spec) : $GLP;
673         push @spec, qw(help|h);
674         my $lone_dash;
675         if ($spec[0] =~ s/\|\z//s) { # "stdin|" or "clear|" allows "-" alias
676                 $lone_dash = $spec[0];
677                 $OPT->{$spec[0]} = \(my $var);
678                 push @spec, '' => \$var;
679         }
680         $glp->getoptionsfromarray($argv, $OPT, @spec) or
681                 return _help($self, "bad arguments or options for $cmd");
682         return _help($self) if $OPT->{help};
683
684         push @$argv, @{$OPT->{-argv}} if defined($OPT->{-argv});
685
686         # "-" aliases "stdin" or "clear"
687         $OPT->{$lone_dash} = ${$OPT->{$lone_dash}} if defined $lone_dash;
688
689         my $i = 0;
690         my $POS_ARG = '[A-Z][A-Z0-9_]+';
691         my ($err, $inf);
692         my @args = split(/ /, $proto);
693         for my $var (@args) {
694                 if ($var =~ /\A$POS_ARG\.\.\.\z/o) { # >= 1 args;
695                         $inf = defined($argv->[$i]) and last;
696                         $var =~ s/\.\.\.\z//;
697                         $err = "$var not supplied";
698                 } elsif ($var =~ /\A$POS_ARG\z/o) { # required arg at $i
699                         $argv->[$i++] // ($err = "$var not supplied");
700                 } elsif ($var =~ /\.\.\.\]\z/) { # optional args start
701                         $inf = 1;
702                         last;
703                 } elsif ($var =~ /\A\[-?$POS_ARG\]\z/) { # one optional arg
704                         $i++;
705                 } elsif ($var =~ /\A.+?\|/) { # required FOO|--stdin
706                         $inf = 1 if index($var, '...') > 0;
707                         my @or = split(/\|/, $var);
708                         my $ok;
709                         for my $o (@or) {
710                                 if ($o =~ /\A--([a-z0-9\-]+)/) {
711                                         my $sw = $1;
712                                         # assume pipe/regular file on stdin
713                                         # w/o args means stdin
714                                         if ($sw eq 'stdin' && !@$argv &&
715                                                         (-p $self->{0} ||
716                                                          -f _) && -r _) {
717                                                 $OPT->{stdin} //= 1;
718                                         }
719                                         $ok = defined($OPT->{$sw});
720                                         last if $ok;
721                                 } elsif (defined($argv->[$i])) {
722                                         $ok = 1;
723                                         $i++;
724                                         last;
725                                 } # else continue looping
726                         }
727                         last if $ok;
728                         my $last = pop @or;
729                         $err = join(', ', @or) . " or $last must be set";
730                 } else {
731                         warn "BUG: can't parse `$var' in $proto";
732                 }
733                 last if $err;
734         }
735         if (!$inf && scalar(@$argv) > scalar(@args)) {
736                 $err //= 'too many arguments';
737         }
738         $err ? fail($self, "usage: lei $cmd $proto\nE: $err") : 1;
739 }
740
741 sub _tmp_cfg { # for lei -c <name>=<value> ...
742         my ($self) = @_;
743         my $cfg = _lei_cfg($self, 1);
744         require File::Temp;
745         my $ft = File::Temp->new(TEMPLATE => 'lei_cfg-XXXX', TMPDIR => 1);
746         my $tmp = { '-f' => $ft->filename, -tmp => $ft };
747         $ft->autoflush(1);
748         print $ft <<EOM or return fail($self, "$tmp->{-f}: $!");
749 [include]
750         path = $cfg->{-f}
751 EOM
752         $tmp = $self->{cfg} = bless { %$cfg, %$tmp }, ref($cfg);
753         for (@{$self->{opt}->{c}}) {
754                 /\A([^=\.]+\.[^=]+)(?:=(.*))?\z/ or return fail($self, <<EOM);
755 `-c $_' is not of the form -c <name>=<value>'
756 EOM
757                 my $name = $1;
758                 my $value = $2 // 1;
759                 _config($self, '--add', $name, $value);
760                 if (defined(my $v = $tmp->{$name})) {
761                         if (ref($v) eq 'ARRAY') {
762                                 push @$v, $value;
763                         } else {
764                                 $tmp->{$name} = [ $v, $value ];
765                         }
766                 } else {
767                         $tmp->{$name} = $value;
768                 }
769         }
770 }
771
772 sub lazy_cb ($$$) {
773         my ($self, $cmd, $pfx) = @_;
774         my $ucmd = $cmd;
775         $ucmd =~ tr/-/_/;
776         my $cb;
777         $cb = $self->can($pfx.$ucmd) and return $cb;
778         my $base = $ucmd;
779         $base =~ s/_([a-z])/\u$1/g;
780         my $pkg = "PublicInbox::Lei\u$base";
781         ($INC{"PublicInbox/Lei\u$base.pm"} // eval("require $pkg")) ?
782                 $pkg->can($pfx.$ucmd) : undef;
783 }
784
785 sub dispatch {
786         my ($self, $cmd, @argv) = @_;
787         fchdir($self) or return;
788         local %ENV = %{$self->{env}};
789         local $current_lei = $self; # for __WARN__
790         $self->{2}->autoflush(1); # keep stdout buffered until x_it|DESTROY
791         return _help($self, 'no command given') unless defined($cmd);
792         # do not support Getopt bundling for this
793         while ($cmd eq '-C' || $cmd eq '-c') {
794                 my $v = shift(@argv) // return fail($self, $cmd eq '-C' ?
795                                         '-C DIRECTORY' : '-c <name>=<value>');
796                 push @{$self->{opt}->{substr($cmd, 1, 1)}}, $v;
797                 $cmd = shift(@argv) // return _help($self, 'no command given');
798         }
799         if (my $cb = lazy_cb(__PACKAGE__, $cmd, 'lei_')) {
800                 optparse($self, $cmd, \@argv) or return;
801                 $self->{opt}->{c} and (_tmp_cfg($self) // return);
802                 if (my $chdir = $self->{opt}->{C}) {
803                         for my $d (@$chdir) {
804                                 next if $d eq ''; # same as git(1)
805                                 chdir $d or return fail($self, "cd $d: $!");
806                         }
807                         open $self->{3}, '.' or return fail($self, "open . $!");
808                 }
809                 $cb->($self, @argv);
810         } elsif (grep(/\A-/, $cmd, @argv)) { # --help or -h only
811                 $GLP->getoptionsfromarray([$cmd, @argv], {}, qw(help|h C=s@))
812                         or return _help($self, 'bad arguments or options');
813                 _help($self);
814         } else {
815                 fail($self, "`$cmd' is not an lei command");
816         }
817 }
818
819 sub _lei_cfg ($;$) {
820         my ($self, $creat) = @_;
821         return $self->{cfg} if $self->{cfg};
822         my $f = _config_path($self);
823         my @st = stat($f);
824         my $cur_st = @st ? pack('dd', $st[10], $st[7]) : ''; # 10:ctime, 7:size
825         my ($sto, $sto_dir, $watches, $lne);
826         if (my $cfg = $PATH2CFG{$f}) { # reuse existing object in common case
827                 return ($self->{cfg} = $cfg) if $cur_st eq $cfg->{-st};
828                 ($sto, $sto_dir, $watches, $lne) =
829                                 @$cfg{qw(-lei_store leistore.dir -watches
830                                         -lei_note_event)};
831         }
832         if (!@st) {
833                 unless ($creat) {
834                         delete $self->{cfg};
835                         return bless {}, 'PublicInbox::Config';
836                 }
837                 my ($cfg_dir) = ($f =~ m!(.*?/)[^/]+\z!);
838                 -d $cfg_dir or mkpath($cfg_dir) or die "mkpath($cfg_dir): $!\n";
839                 open my $fh, '>>', $f or die "open($f): $!\n";
840                 @st = stat($fh) or die "fstat($f): $!\n";
841                 $cur_st = pack('dd', $st[10], $st[7]);
842                 qerr($self, "# $f created") if $self->{cmd} ne 'config';
843         }
844         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{2});
845         $cfg->{-st} = $cur_st;
846         $cfg->{'-f'} = $f;
847         if ($sto && canonpath_harder($sto_dir // store_path($self))
848                         eq canonpath_harder($cfg->{'leistore.dir'} //
849                                                 store_path($self))) {
850                 $cfg->{-lei_store} = $sto;
851                 $cfg->{-lei_note_event} = $lne;
852                 $cfg->{-watches} = $watches if $watches;
853         }
854         if (scalar(keys %PATH2CFG) > 5) {
855                 # FIXME: use inotify/EVFILT_VNODE to detect unlinked configs
856                 for my $k (keys %PATH2CFG) {
857                         delete($PATH2CFG{$k}) unless -f $k
858                 }
859         }
860         $self->{cfg} = $PATH2CFG{$f} = $cfg;
861         refresh_watches($self);
862         $cfg;
863 }
864
865 sub _lei_store ($;$) {
866         my ($self, $creat) = @_;
867         my $cfg = _lei_cfg($self, $creat) // return;
868         $cfg->{-lei_store} //= do {
869                 require PublicInbox::LeiStore;
870                 my $dir = $cfg->{'leistore.dir'} // store_path($self);
871                 return unless $creat || -d $dir;
872                 PublicInbox::LeiStore->new($dir, { creat => $creat });
873         };
874 }
875
876 sub _config {
877         my ($self, @argv) = @_;
878         my %env = (%{$self->{env}}, GIT_CONFIG => undef);
879         my $cfg = _lei_cfg($self, 1);
880         my $cmd = [ qw(git config -f), $cfg->{'-f'}, @argv ];
881         my %rdr = map { $_ => $self->{$_} } (0..2);
882         waitpid(spawn($cmd, \%env, \%rdr), 0);
883 }
884
885 sub lei_daemon_pid { puts shift, $$ }
886
887 sub lei_daemon_kill {
888         my ($self) = @_;
889         my $sig = $self->{opt}->{signal} // 'TERM';
890         kill($sig, $$) or fail($self, "kill($sig, $$): $!");
891 }
892
893 # Shell completion helper.  Used by lei-completion.bash and hopefully
894 # other shells.  Try to do as much here as possible to avoid redundancy
895 # and improve maintainability.
896 sub lei__complete {
897         my ($self, @argv) = @_; # argv = qw(lei and any other args...)
898         shift @argv; # ignore "lei", the entire command is sent
899         @argv or return puts $self, grep(!/^_/, keys %CMD), qw(--help -h -C);
900         my $cmd = shift @argv;
901         my $info = $CMD{$cmd} // do { # filter matching commands
902                 @argv or puts $self, grep(/\A\Q$cmd\E/, keys %CMD);
903                 return;
904         };
905         my ($proto, undef, @spec) = @$info;
906         my $cur = pop @argv;
907         my $re = defined($cur) ? qr/\A\Q$cur\E/ : qr/./;
908         if (substr(my $_cur = $cur // '-', 0, 1) eq '-') { # --switches
909                 # gross special case since the only git-config options
910                 # Consider moving to a table if we need more special cases
911                 # we use Getopt::Long for are the ones we reject, so these
912                 # are the ones we don't reject:
913                 if ($cmd eq 'config') {
914                         puts $self, grep(/$re/, keys %CONFIG_KEYS);
915                         @spec = qw(add z|null get get-all unset unset-all
916                                 replace-all get-urlmatch
917                                 remove-section rename-section
918                                 name-only list|l edit|e
919                                 get-color-name get-colorbool);
920                         # fall-through
921                 }
922                 # generate short/long names from Getopt::Long specs
923                 puts $self, grep(/$re/, qw(--help -h -C), map {
924                         if (s/[:=].+\z//) { # req/optional args, e.g output|o=i
925                         } elsif (s/\+\z//) { # verbose|v+
926                         } elsif (s/!\z//) {
927                                 # negation: mail! => no-mail|mail
928                                 s/([\w\-]+)/$1|no-$1/g
929                         }
930                         map {
931                                 my $x = length > 1 ? "--$_" : "-$_";
932                                 $x eq $_cur ? () : $x;
933                         } grep(!/_/, split(/\|/, $_, -1)) # help|h
934                 } grep { $OPTDESC{"$_\t$cmd"} || $OPTDESC{$_} } @spec);
935         } elsif ($cmd eq 'config' && !@argv && !$CONFIG_KEYS{$cur}) {
936                 puts $self, grep(/$re/, keys %CONFIG_KEYS);
937         }
938
939         # switch args (e.g. lei q -f mbox<TAB>)
940         if (($argv[-1] // $cur // '') =~ /\A--?([\w\-]+)\z/) {
941                 my $opt = quotemeta $1;
942                 puts $self, map {
943                         my $v = $OPTDESC{$_};
944                         my @v = ref($v) ? split(/\|/, $v->[0]) : ();
945                         # get rid of ALL CAPS placeholder (e.g "OUT")
946                         # (TODO: completion for external paths)
947                         shift(@v) if scalar(@v) && uc($v[0]) eq $v[0];
948                         @v;
949                 } grep(/\A(?:[\w-]+\|)*$opt\b.*?(?:\t$cmd)?\z/, keys %OPTDESC);
950         }
951         if (my $cb = lazy_cb($self, $cmd, '_complete_')) {
952                 puts $self, $cb->($self, @argv, $cur ? ($cur) : ());
953         }
954         # TODO: URLs, pathnames, OIDs, MIDs, etc...  See optparse() for
955         # proto parsing.
956 }
957
958 sub exec_buf ($$) {
959         my ($argv, $env) = @_;
960         my $argc = scalar @$argv;
961         my $buf = 'exec '.join("\0", scalar(@$argv), @$argv);
962         while (my ($k, $v) = each %$env) { $buf .= "\0$k=$v" };
963         $buf;
964 }
965
966 sub start_mua {
967         my ($self) = @_;
968         if ($self->{ovv}->{fmt} =~ /\A(?:maildir)\z/) { # TODO: IMAP
969                 refresh_watches($self);
970         }
971         my $mua = $self->{opt}->{mua} // return;
972         my $mfolder = $self->{ovv}->{dst};
973         my (@cmd, $replaced);
974         if ($mua =~ /\A(?:mutt|mailx|mail|neomutt)\z/) {
975                 @cmd = ($mua, '-f');
976         # TODO: help wanted: other common FOSS MUAs
977         } else {
978                 require Text::ParseWords;
979                 @cmd = Text::ParseWords::shellwords($mua);
980                 # mutt uses '%f' for open-hook with compressed mbox, we follow
981                 @cmd = map { $_ eq '%f' ? ($replaced = $mfolder) : $_ } @cmd;
982         }
983         push @cmd, $mfolder unless defined($replaced);
984         if ($self->{sock}) { # lei(1) client process runs it
985                 # restore terminal: echo $query | lei q --stdin --mua=...
986                 my $io = [];
987                 $io->[0] = $self->{1} if $self->{opt}->{stdin} && -t $self->{1};
988                 send_exec_cmd($self, $io, \@cmd, {});
989         }
990         if ($self->{lxs} && $self->{au_done}) { # kick wait_startq
991                 syswrite($self->{au_done}, 'q' x ($self->{lxs}->{jobs} // 0));
992         }
993         return unless -t $self->{2}; # XXX how to determine non-TUI MUAs?
994         $self->{opt}->{quiet} = 1;
995         delete $self->{-progress};
996         delete $self->{opt}->{verbose};
997 }
998
999 sub send_exec_cmd { # tell script/lei to execute a command
1000         my ($self, $io, $cmd, $env) = @_;
1001         my $sock = $self->{sock} // die 'lei client gone';
1002         my $fds = [ map { fileno($_) } @$io ];
1003         $send_cmd->($sock, $fds, exec_buf($cmd, $env), MSG_EOR);
1004 }
1005
1006 sub poke_mua { # forces terminal MUAs to wake up and hopefully notice new mail
1007         my ($self) = @_;
1008         my $alerts = $self->{opt}->{alert} // return;
1009         my $sock = $self->{sock};
1010         while (my $op = shift(@$alerts)) {
1011                 if ($op eq ':WINCH') {
1012                         # hit the process group that started the MUA
1013                         send($sock, '-WINCH', MSG_EOR) if $sock;
1014                 } elsif ($op eq ':bell') {
1015                         out($self, "\a");
1016                 } elsif ($op =~ /(?<!\\),/) { # bare ',' (not ',,')
1017                         push @$alerts, split(/(?<!\\),/, $op);
1018                 } elsif ($op =~ m!\A([/a-z0-9A-Z].+)!) {
1019                         my $cmd = $1; # run an arbitrary command
1020                         require Text::ParseWords;
1021                         $cmd = [ Text::ParseWords::shellwords($cmd) ];
1022                         send($sock, exec_buf($cmd, {}), MSG_EOR) if $sock;
1023                 } else {
1024                         warn("W: unsupported --alert=$op\n"); # non-fatal
1025                 }
1026         }
1027 }
1028
1029 my %path_to_fd = ('/dev/stdin' => 0, '/dev/stdout' => 1, '/dev/stderr' => 2);
1030 $path_to_fd{"/dev/fd/$_"} = $_ for (0..2);
1031
1032 # this also normalizes the path
1033 sub path_to_fd {
1034         my ($self, $path) = @_;
1035         $path = rel2abs($self, $path);
1036         $path =~ tr!/!/!s;
1037         $path_to_fd{$path} // (
1038                 ($path =~ m!\A/(?:dev|proc/self)/fd/[0-9]+\z!) ?
1039                         fail($self, "cannot open $path from daemon") : -1
1040         );
1041 }
1042
1043 # caller needs to "-t $self->{1}" to check if tty
1044 sub start_pager {
1045         my ($self, $new_env) = @_;
1046         my $fh = popen_rd([qw(git var GIT_PAGER)]);
1047         chomp(my $pager = <$fh> // '');
1048         close($fh) or warn "`git var PAGER' error: \$?=$?";
1049         return if $pager eq 'cat' || $pager eq '';
1050         $new_env //= {};
1051         $new_env->{LESS} //= 'FRX';
1052         $new_env->{LV} //= '-c';
1053         $new_env->{MORE} = $new_env->{LESS} if $^O eq 'freebsd';
1054         pipe(my ($r, $wpager)) or return warn "pipe: $!";
1055         my $rdr = { 0 => $r, 1 => $self->{1}, 2 => $self->{2} };
1056         my $pgr = [ undef, @$rdr{1, 2} ];
1057         my $env = $self->{env};
1058         if ($self->{sock}) { # lei(1) process runs it
1059                 delete @$new_env{keys %$env}; # only set iff unset
1060                 send_exec_cmd($self, [ @$rdr{0..2} ], [$pager], $new_env);
1061         } else {
1062                 die 'BUG: start_pager w/o socket';
1063         }
1064         $self->{1} = $wpager;
1065         $self->{2} = $wpager if -t $self->{2};
1066         $env->{GIT_PAGER_IN_USE} = 'true'; # we may spawn git
1067         $self->{pgr} = $pgr;
1068 }
1069
1070 # display a message for user before spawning full-screen $VISUAL
1071 sub pgr_err {
1072         my ($self, @msg) = @_;
1073         return warn(@msg) unless $self->{sock} && -t $self->{2};
1074         start_pager($self, { LESS => 'RX' }); # no 'F' so we prompt
1075         print { $self->{2} } @msg;
1076         $self->{2}->autoflush(1);
1077         stop_pager($self);
1078         send($self->{sock}, 'wait', MSG_EOR); # wait for user to quit pager
1079 }
1080
1081 sub stop_pager {
1082         my ($self) = @_;
1083         my $pgr = delete($self->{pgr}) or return;
1084         $self->{2} = $pgr->[2];
1085         close(delete($self->{1})) if $self->{1};
1086         $self->{1} = $pgr->[1];
1087 }
1088
1089 sub accept_dispatch { # Listener {post_accept} callback
1090         my ($sock) = @_; # ignore other
1091         $sock->autoflush(1);
1092         my $self = bless { sock => $sock }, __PACKAGE__;
1093         vec(my $rvec = '', fileno($sock), 1) = 1;
1094         select($rvec, undef, undef, 60) or
1095                 return send($sock, 'timed out waiting to recv FDs', MSG_EOR);
1096         # (4096 * 33) >MAX_ARG_STRLEN
1097         my @fds = $recv_cmd->($sock, my $buf, 4096 * 33) or return; # EOF
1098         if (!defined($fds[0])) {
1099                 warn(my $msg = "recv_cmd failed: $!");
1100                 return send($sock, $msg, MSG_EOR);
1101         } else {
1102                 my $i = 0;
1103                 for my $fd (@fds) {
1104                         open($self->{$i++}, '+<&=', $fd) and next;
1105                         send($sock, "open(+<&=$fd) (FD=$i): $!", MSG_EOR);
1106                 }
1107                 $i == 4 or return send($sock, 'not enough FDs='.($i-1), MSG_EOR)
1108         }
1109         # $ENV_STR = join('', map { "\0$_=$ENV{$_}" } keys %ENV);
1110         # $buf = "$argc\0".join("\0", @ARGV).$ENV_STR."\0\0";
1111         substr($buf, -2, 2, '') eq "\0\0" or  # s/\0\0\z//
1112                 return send($sock, 'request command truncated', MSG_EOR);
1113         my ($argc, @argv) = split(/\0/, $buf, -1);
1114         undef $buf;
1115         my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
1116         $self->{env} = \%env;
1117         eval { dispatch($self, @argv) };
1118         send($sock, $@, MSG_EOR) if $@;
1119 }
1120
1121 sub dclose {
1122         my ($self) = @_;
1123         local $current_lei = $self;
1124         delete $self->{-progress};
1125         _drop_wq($self) if $self->{failed};
1126         $self->close if $self->{-event_init_done}; # PublicInbox::DS::close
1127 }
1128
1129 # for long-running results
1130 sub event_step {
1131         my ($self) = @_;
1132         local %ENV = %{$self->{env}};
1133         local $current_lei = $self;
1134         eval {
1135                 my $buf;
1136                 while (my @fds = $recv_cmd->($self->{sock}, $buf, 4096)) {
1137                         if (scalar(@fds) == 1 && !defined($fds[0])) {
1138                                 return if $! == EAGAIN;
1139                                 next if $! == EINTR;
1140                                 last if $! == ECONNRESET;
1141                                 die "recvmsg: $!";
1142                         }
1143                         for (@fds) { open my $rfh, '+<&=', $_ }
1144                 }
1145                 if ($buf eq '') {
1146                         _drop_wq($self); # EOF, client disconnected
1147                         dclose($self);
1148                         $buf = 'TERM';
1149                 }
1150                 if ($buf =~ /\A(?:STOP|CONT|TERM)\z/) {
1151                         my $sig = "-$buf";
1152                         for my $wq (grep(defined, @$self{@WQ_KEYS})) {
1153                                 $wq->wq_kill($sig) or $wq->wq_kill_old($sig);
1154                         }
1155                 } else {
1156                         die "unrecognized client signal: $buf";
1157                 }
1158                 my $s = $self->{-socks} // []; # lei up --all
1159                 @$s = grep { send($_, $buf, MSG_EOR) } @$s;
1160         };
1161         if (my $err = $@) {
1162                 eval { $self->fail($err) };
1163                 dclose($self);
1164         }
1165 }
1166
1167 sub event_step_init {
1168         my ($self) = @_;
1169         my $sock = $self->{sock} or return;
1170         $self->{-event_init_done} //= do { # persist til $ops done
1171                 $sock->blocking(0);
1172                 $self->SUPER::new($sock, EPOLLIN|EPOLLET);
1173                 $sock;
1174         };
1175 }
1176
1177 sub noop {}
1178
1179 sub oldset { $oldset }
1180
1181 sub dump_and_clear_log {
1182         if (defined($errors_log) && -s STDIN && seek(STDIN, 0, SEEK_SET)) {
1183                 openlog('lei-daemon', 'pid,nowait,nofatal,ndelay', 'user');
1184                 chomp(my @lines = <STDIN>);
1185                 truncate(STDIN, 0) or
1186                         syslog('warning', "ftruncate (%s): %m", $errors_log);
1187                 for my $l (@lines) { syslog('warning', '%s', $l) }
1188                 closelog(); # don't share across fork
1189         }
1190 }
1191
1192 sub cfg2lei ($) {
1193         my ($cfg) = @_;
1194         my $lei = bless { env => { %{$cfg->{-env}} } }, __PACKAGE__;
1195         open($lei->{0}, '<&', \*STDIN) or die "dup 0: $!";
1196         open($lei->{1}, '>>&', \*STDOUT) or die "dup 1: $!";
1197         open($lei->{2}, '>>&', \*STDERR) or die "dup 2: $!";
1198         open($lei->{3}, '/') or die "open /: $!";
1199         my ($x, $y);
1200         socketpair($x, $y, AF_UNIX, SOCK_SEQPACKET, 0) or die "socketpair: $!";
1201         $lei->{sock} = $x;
1202         require PublicInbox::LeiSelfSocket;
1203         PublicInbox::LeiSelfSocket->new($y); # adds to event loop
1204         $lei;
1205 }
1206
1207 sub dir_idle_handler ($) { # PublicInbox::DirIdle callback
1208         my ($ev) = @_; # Linux::Inotify2::Event or duck type
1209         my $fn = $ev->fullname;
1210         if ($fn =~ m!\A(.+)/(new|cur)/([^/]+)\z!) { # Maildir file
1211                 my ($mdir, $nc, $bn) = ($1, $2, $3);
1212                 $nc = '' if $ev->IN_DELETE;
1213                 for my $f (keys %{$MDIR2CFGPATH->{$mdir} // {}}) {
1214                         my $cfg = $PATH2CFG{$f} // next;
1215                         eval {
1216                                 my $lei = cfg2lei($cfg);
1217                                 $lei->dispatch('note-event',
1218                                                 "maildir:$mdir", $nc, $bn, $fn);
1219                         };
1220                         warn "E: note-event $f: $@\n" if $@;
1221                 }
1222         }
1223         if ($ev->can('cancel') && ($ev->IN_IGNORE || $ev->IN_UNMOUNT)) {
1224                 $ev->cancel;
1225         }
1226         if ($fn =~ m!\A(.+)/(?:new|cur)\z! && !-e $fn) {
1227                 delete $MDIR2CFGPATH->{$1};
1228         }
1229         if (!-e $fn) { # config file or Maildir gone
1230                 for my $cfgpaths (values %$MDIR2CFGPATH) {
1231                         delete $cfgpaths->{$fn};
1232                 }
1233                 delete $PATH2CFG{$fn};
1234         }
1235 }
1236
1237 # lei(1) calls this when it can't connect
1238 sub lazy_start {
1239         my ($path, $errno, $narg) = @_;
1240         local ($errors_log, $listener);
1241         my ($sock_dir) = ($path =~ m!\A(.+?)/[^/]+\z!);
1242         $errors_log = "$sock_dir/errors.log";
1243         my $addr = pack_sockaddr_un($path);
1244         my $lk = bless { lock_path => $errors_log }, 'PublicInbox::Lock';
1245         umask(077) // die("umask(077): $!");
1246         $lk->lock_acquire;
1247         socket($listener, AF_UNIX, SOCK_SEQPACKET, 0) or die "socket: $!";
1248         if ($errno == ECONNREFUSED || $errno == ENOENT) {
1249                 return if connect($listener, $addr); # another process won
1250                 if ($errno == ECONNREFUSED && -S $path) {
1251                         unlink($path) or die "unlink($path): $!";
1252                 }
1253         } else {
1254                 $! = $errno; # allow interpolation to stringify in die
1255                 die "connect($path): $!";
1256         }
1257         bind($listener, $addr) or die "bind($path): $!";
1258         $lk->lock_release;
1259         undef $lk;
1260         my @st = stat($path) or die "stat($path): $!";
1261         my $dev_ino_expect = pack('dd', $st[0], $st[1]); # dev+ino
1262         local $oldset = PublicInbox::DS::block_signals();
1263         if ($narg == 5) {
1264                 $send_cmd = PublicInbox::Spawn->can('send_cmd4');
1265                 $recv_cmd = PublicInbox::Spawn->can('recv_cmd4') // do {
1266                         require PublicInbox::CmdIPC4;
1267                         $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4');
1268                         PublicInbox::CmdIPC4->can('recv_cmd4');
1269                 };
1270         }
1271         $recv_cmd or die <<"";
1272 (Socket::MsgHdr || Inline::C) missing/unconfigured (narg=$narg);
1273
1274         require PublicInbox::Listener;
1275         require PublicInbox::PktOp;
1276         (-p STDOUT) or die "E: stdout must be a pipe\n";
1277         open(STDIN, '+>>', $errors_log) or die "open($errors_log): $!";
1278         STDIN->autoflush(1);
1279         dump_and_clear_log();
1280         POSIX::setsid() > 0 or die "setsid: $!";
1281         my $pid = fork // die "fork: $!";
1282         return if $pid;
1283         $0 = "lei-daemon $path";
1284         local %PATH2CFG;
1285         local $MDIR2CFGPATH;
1286         $listener->blocking(0);
1287         my $exit_code;
1288         my $pil = PublicInbox::Listener->new($listener, \&accept_dispatch);
1289         local $quit = do {
1290                 my (undef, $eof_p) = PublicInbox::PktOp->pair;
1291                 sub {
1292                         $exit_code //= shift;
1293                         eval 'PublicInbox::LeiNoteEvent::flush_task()';
1294                         my $lis = $pil or exit($exit_code);
1295                         # closing eof_p triggers \&noop wakeup
1296                         $listener = $eof_p = $pil = $path = undef;
1297                         $lis->close; # DS::close
1298                         PublicInbox::DS->SetLoopTimeout(1000);
1299                 };
1300         };
1301         my $sig = {
1302                 CHLD => \&PublicInbox::DS::enqueue_reap,
1303                 QUIT => $quit,
1304                 INT => $quit,
1305                 TERM => $quit,
1306                 HUP => \&noop,
1307                 USR1 => \&noop,
1308                 USR2 => \&noop,
1309         };
1310         require PublicInbox::DirIdle;
1311         local $dir_idle = PublicInbox::DirIdle->new([$sock_dir], sub {
1312                 # just rely on wakeup to hit PostLoopCallback set below
1313                 dir_idle_handler($_[0]) if $_[0]->fullname ne $path;
1314         }, 1);
1315         PublicInbox::DS->SetPostLoopCallback(sub {
1316                 my ($dmap, undef) = @_;
1317                 if (@st = defined($path) ? stat($path) : ()) {
1318                         if ($dev_ino_expect ne pack('dd', $st[0], $st[1])) {
1319                                 warn "$path dev/ino changed, quitting\n";
1320                                 $path = undef;
1321                         }
1322                 } elsif (defined($path)) { # ENOENT is common
1323                         warn "stat($path): $!, quitting ...\n" if $! != ENOENT;
1324                         undef $path;
1325                         $quit->();
1326                 }
1327                 return 1 if defined($path);
1328                 my $now = now();
1329                 my $n = 0;
1330                 for my $s (values %$dmap) {
1331                         $s->can('busy') or next;
1332                         if ($s->busy($now)) {
1333                                 ++$n;
1334                         } else {
1335                                 $s->close;
1336                         }
1337                 }
1338                 $n; # true: continue, false: stop
1339         });
1340
1341         # STDIN was redirected to /dev/null above, closing STDERR and
1342         # STDOUT will cause the calling `lei' client process to finish
1343         # reading the <$daemon> pipe.
1344         local $SIG{__WARN__} = sub {
1345                 $current_lei ? err($current_lei, @_) : warn(
1346                   strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time))," $$ ", @_);
1347         };
1348         open STDERR, '>&STDIN' or die "redirect stderr failed: $!";
1349         open STDOUT, '>&STDIN' or die "redirect stdout failed: $!";
1350         # $daemon pipe to `lei' closed, main loop begins:
1351         eval { PublicInbox::DS::event_loop($sig, $oldset) };
1352         warn "event loop error: $@\n" if $@;
1353         # exit() may trigger waitpid via various DESTROY, ensure interruptible
1354         PublicInbox::DS::sig_setmask($oldset);
1355         dump_and_clear_log();
1356         exit($exit_code // 0);
1357 }
1358
1359 sub busy { 1 } # prevent daemon-shutdown if client is connected
1360
1361 # ensures stdout hits the FS before sock disconnects so a client
1362 # can immediately reread it
1363 sub DESTROY {
1364         my ($self) = @_;
1365         if (my $counters = delete $self->{counters}) {
1366                 for my $k (sort keys %$counters) {
1367                         my $nr = $counters->{$k};
1368                         $self->child_error(0, "$nr $k messages");
1369                 }
1370         }
1371         $self->{1}->autoflush(1) if $self->{1};
1372         stop_pager($self);
1373         dump_and_clear_log();
1374         # preserve $? for ->fail or ->x_it code
1375 }
1376
1377 sub wq_done_wait { # dwaitpid callback
1378         my ($arg, $pid) = @_;
1379         my ($wq, $lei) = @$arg;
1380         local $current_lei = $lei;
1381         my $err_type = $lei->{-err_type};
1382         $? and $lei->child_error($?,
1383                         $err_type ? "$err_type errors during $lei->{cmd}" : ());
1384         $lei->dclose;
1385 }
1386
1387 sub fchdir {
1388         my ($lei) = @_;
1389         my $dh = $lei->{3} // die 'BUG: lei->{3} (CWD) gone';
1390         chdir($dh) || $lei->fail("fchdir: $!");
1391 }
1392
1393 sub wq_eof { # EOF callback for main daemon
1394         my ($lei) = @_;
1395         local $current_lei = $lei;
1396         my $wq1 = delete $lei->{wq1} // return $lei->fail; # already failed
1397         $wq1->wq_wait_old($wq1->can('_wq_done_wait') // \&wq_done_wait, $lei);
1398 }
1399
1400 sub watch_state_ok ($) {
1401         my ($state) = $_[-1]; # $_[0] may be $self
1402         $state =~ /\Apause|(?:import|index|tag)-(?:ro|rw)\z/;
1403 }
1404
1405 sub cancel_maildir_watch ($$) {
1406         my ($d, $cfg_f) = @_;
1407         my $w = delete $MDIR2CFGPATH->{$d}->{$cfg_f};
1408         scalar(keys %{$MDIR2CFGPATH->{$d}}) or
1409                 delete $MDIR2CFGPATH->{$d};
1410         for my $x (@{$w // []}) { $x->cancel }
1411 }
1412
1413 sub add_maildir_watch ($$) {
1414         my ($d, $cfg_f) = @_;
1415         if (!exists($MDIR2CFGPATH->{$d}->{$cfg_f})) {
1416                 my @w = $dir_idle->add_watches(["$d/cur", "$d/new"], 1);
1417                 push @{$MDIR2CFGPATH->{$d}->{$cfg_f}}, @w if @w;
1418         }
1419 }
1420
1421 sub refresh_watches {
1422         my ($lei) = @_;
1423         $dir_idle or return;
1424         my $cfg = _lei_cfg($lei) or return;
1425         my $old = $cfg->{-watches};
1426         my $watches = $cfg->{-watches} //= {};
1427         my %seen;
1428         my $cfg_f = $cfg->{'-f'};
1429         for my $w (grep(/\Awatch\..+\.state\z/, keys %$cfg)) {
1430                 my $url = substr($w, length('watch.'), -length('.state'));
1431                 require PublicInbox::LeiWatch;
1432                 $watches->{$url} //= PublicInbox::LeiWatch->new($url);
1433                 $seen{$url} = undef;
1434                 my $state = $cfg->get_1("watch.$url.state");
1435                 if (!watch_state_ok($state)) {
1436                         warn("watch.$url.state=$state not supported\n");
1437                         next;
1438                 }
1439                 if ($url =~ /\Amaildir:(.+)/i) {
1440                         my $d = canonpath_harder($1);
1441                         if ($state eq 'pause') {
1442                                 cancel_maildir_watch($d, $cfg_f);
1443                         } else {
1444                                 add_maildir_watch($d, $cfg_f);
1445                         }
1446                 } else { # TODO: imap/nntp/jmap
1447                         $lei->child_error(0, "E: watch $url not supported, yet")
1448                 }
1449         }
1450
1451         # add all known Maildir folders as implicit watches
1452         my $lms = $lei->lms;
1453         if ($lms) {
1454                 $lms->lms_write_prepare;
1455                 for my $d ($lms->folders('maildir:')) {
1456                         substr($d, 0, length('maildir:')) = '';
1457
1458                         # fixup old bugs while we're iterating:
1459                         my $cd = canonpath_harder($d);
1460                         my $f = "maildir:$cd";
1461                         $lms->rename_folder("maildir:$d", $f) if $d ne $cd;
1462                         next if $watches->{$f}; # may be set to pause
1463                         require PublicInbox::LeiWatch;
1464                         $watches->{$f} = PublicInbox::LeiWatch->new($f);
1465                         $seen{$f} = undef;
1466                         add_maildir_watch($cd, $cfg_f);
1467                 }
1468         }
1469         if ($old) { # cull old non-existent entries
1470                 for my $url (keys %$old) {
1471                         next if exists $seen{$url};
1472                         delete $old->{$url};
1473                         if ($url =~ /\Amaildir:(.+)/i) {
1474                                 my $d = canonpath_harder($1);
1475                                 cancel_maildir_watch($d, $cfg_f);
1476                         } else { # TODO: imap/nntp/jmap
1477                                 $lei->child_error(0, "E: watch $url TODO");
1478                         }
1479                 }
1480         }
1481         if (scalar keys %$watches) {
1482                 $cfg->{-env} //= { %{$lei->{env}}, PWD => '/' }; # for cfg2lei
1483         } else {
1484                 delete $cfg->{-watches};
1485         }
1486 }
1487
1488 # TODO: support SHA-256
1489 sub git_oid {
1490         my $eml = $_[-1];
1491         $eml->header_set($_) for @PublicInbox::Import::UNWANTED_HEADERS;
1492         git_sha(1, $eml);
1493 }
1494
1495 sub lms {
1496         my ($lei, $rw) = @_;
1497         my $sto = $lei->{sto} // _lei_store($lei) // return;
1498         require PublicInbox::LeiMailSync;
1499         my $f = "$sto->{priv_eidx}->{topdir}/mail_sync.sqlite3";
1500         (-f $f || $rw) ? PublicInbox::LeiMailSync->new($f) : undef;
1501 }
1502
1503 sub sto_done_request {
1504         my ($lei, $sock) = @_;
1505         local $current_lei = $lei;
1506         eval {
1507                 if ($sock //= $lei->{sock}) { # issue, async wait
1508                         $lei->{sto}->wq_io_do('done', [ $sock ]);
1509                 } else { # forcibly wait
1510                         my $wait = $lei->{sto}->wq_do('done');
1511                 }
1512         };
1513         warn($@) if $@;
1514 }
1515
1516 sub cfg_dump ($$) {
1517         my ($lei, $f) = @_;
1518         my $ret = eval { PublicInbox::Config->git_config_dump($f, $lei->{2}) };
1519         return $ret if !$@;
1520         warn($@);
1521         undef;
1522 }
1523
1524 sub request_umask {
1525         my ($lei) = @_;
1526         my $s = $lei->{sock} // return;
1527         send($s, 'umask', MSG_EOR) // die "send: $!";
1528         vec(my $rvec = '', fileno($s), 1) = 1;
1529         select($rvec, undef, undef, 2) or die 'timeout waiting for umask';
1530         recv($s, my $v, 5, 0) // die "recv: $!";
1531         (my $u, $lei->{client_umask}) = unpack('AV', $v);
1532         $u eq 'u' or warn "E: recv $v has no umask";
1533 }
1534
1535 1;