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