]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LEI.pm
lei: TSTP affects all curl and related subprocesses
[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         if (my $op_c = delete $self->{pkt_op_c}) {
577                 close(delete $op_c->{sock});
578         }
579         if (my $pgr = delete $self->{pgr}) {
580                 close($_) for (@$pgr[1,2]);
581         }
582         close $listener if $listener;
583         undef $listener;
584         $dir_idle->force_close if $dir_idle;
585         undef $dir_idle;
586         %PATH2CFG = ();
587         $MDIR2CFGPATH = {};
588         eval 'no warnings; undef $PublicInbox::LeiNoteEvent::to_flush';
589         undef $errors_log;
590         $quit = \&CORE::exit;
591         if (!$self->{-eml_noisy}) { # only "lei import" sets this atm
592                 my $cb = $SIG{__WARN__} // \&CORE::warn;
593                 $SIG{__WARN__} = sub {
594                         $cb->(@_) unless PublicInbox::Eml::warn_ignore(@_)
595                 };
596         }
597         $SIG{TERM} = sub { exit(128 + 15) };
598         $current_lei = $persist ? undef : $self; # for SIG{__WARN__}
599 }
600
601 sub _delete_pkt_op { # OnDestroy callback to prevent leaks on die
602         my ($self) = @_;
603         if (my $op = delete $self->{pkt_op_c}) { # in case of die
604                 $op->close; # PublicInbox::PktOp::close
605         }
606         my $pkt_op_p = delete($self->{pkt_op_p}) or return;
607         close $pkt_op_p->{op_p};
608 }
609
610 sub pkt_op_pair {
611         my ($self) = @_;
612         require PublicInbox::OnDestroy;
613         require PublicInbox::PktOp;
614         my $end = PublicInbox::OnDestroy->new($$, \&_delete_pkt_op, $self);
615         @$self{qw(pkt_op_c pkt_op_p)} = PublicInbox::PktOp->pair;
616         $end;
617 }
618
619 sub incr {
620         my ($self, $field, $nr) = @_;
621         $self->{counters}->{$field} += $nr;
622 }
623
624 sub pkt_ops {
625         my ($lei, $ops) = @_;
626         $ops->{fail_handler} = [ $lei ];
627         $ops->{sigpipe_handler} = [ $lei ];
628         $ops->{x_it} = [ $lei ];
629         $ops->{child_error} = [ $lei ];
630         $ops->{incr} = [ $lei ];
631         $ops;
632 }
633
634 sub workers_start {
635         my ($lei, $wq, $jobs, $ops, $flds) = @_;
636         $ops = pkt_ops($lei, { ($ops ? %$ops : ()) });
637         $ops->{''} //= [ $wq->can('_lei_wq_eof') || \&wq_eof, $lei ];
638         my $end = $lei->pkt_op_pair;
639         my $ident = $wq->{-wq_ident} // "lei-$lei->{cmd} worker";
640         $flds->{lei} = $lei;
641         $wq->wq_workers_start($ident, $jobs, $lei->oldset, $flds);
642         delete $lei->{pkt_op_p};
643         my $op_c = delete $lei->{pkt_op_c};
644         @$end = ();
645         $lei->event_step_init;
646         ($op_c, $ops);
647 }
648
649 # call this when we're ready to wait on events and yield to other clients
650 sub wait_wq_events {
651         my ($lei, $op_c, $ops) = @_;
652         for my $wq (grep(defined, @$lei{qw(ikw pmd)})) { # auxiliary WQs
653                 $wq->wq_close(1);
654         }
655         $op_c->{ops} = $ops;
656 }
657
658 sub _help {
659         require PublicInbox::LeiHelp;
660         PublicInbox::LeiHelp::call($_[0], $_[1], \%CMD, \%OPTDESC);
661 }
662
663 sub optparse ($$$) {
664         my ($self, $cmd, $argv) = @_;
665         # allow _complete --help to complete, not show help
666         return 1 if substr($cmd, 0, 1) eq '_';
667         $self->{cmd} = $cmd;
668         $OPT = $self->{opt} //= {};
669         my $info = $CMD{$cmd} // [ '[...]' ];
670         my ($proto, undef, @spec) = @$info;
671         my $glp = ref($spec[-1]) eq ref($GLP) ? pop(@spec) : $GLP;
672         push @spec, qw(help|h);
673         my $lone_dash;
674         if ($spec[0] =~ s/\|\z//s) { # "stdin|" or "clear|" allows "-" alias
675                 $lone_dash = $spec[0];
676                 $OPT->{$spec[0]} = \(my $var);
677                 push @spec, '' => \$var;
678         }
679         $glp->getoptionsfromarray($argv, $OPT, @spec) or
680                 return _help($self, "bad arguments or options for $cmd");
681         return _help($self) if $OPT->{help};
682
683         push @$argv, @{$OPT->{-argv}} if defined($OPT->{-argv});
684
685         # "-" aliases "stdin" or "clear"
686         $OPT->{$lone_dash} = ${$OPT->{$lone_dash}} if defined $lone_dash;
687
688         my $i = 0;
689         my $POS_ARG = '[A-Z][A-Z0-9_]+';
690         my ($err, $inf);
691         my @args = split(/ /, $proto);
692         for my $var (@args) {
693                 if ($var =~ /\A$POS_ARG\.\.\.\z/o) { # >= 1 args;
694                         $inf = defined($argv->[$i]) and last;
695                         $var =~ s/\.\.\.\z//;
696                         $err = "$var not supplied";
697                 } elsif ($var =~ /\A$POS_ARG\z/o) { # required arg at $i
698                         $argv->[$i++] // ($err = "$var not supplied");
699                 } elsif ($var =~ /\.\.\.\]\z/) { # optional args start
700                         $inf = 1;
701                         last;
702                 } elsif ($var =~ /\A\[-?$POS_ARG\]\z/) { # one optional arg
703                         $i++;
704                 } elsif ($var =~ /\A.+?\|/) { # required FOO|--stdin
705                         $inf = 1 if index($var, '...') > 0;
706                         my @or = split(/\|/, $var);
707                         my $ok;
708                         for my $o (@or) {
709                                 if ($o =~ /\A--([a-z0-9\-]+)/) {
710                                         my $sw = $1;
711                                         # assume pipe/regular file on stdin
712                                         # w/o args means stdin
713                                         if ($sw eq 'stdin' && !@$argv &&
714                                                         (-p $self->{0} ||
715                                                          -f _) && -r _) {
716                                                 $OPT->{stdin} //= 1;
717                                         }
718                                         $ok = defined($OPT->{$sw});
719                                         last if $ok;
720                                 } elsif (defined($argv->[$i])) {
721                                         $ok = 1;
722                                         $i++;
723                                         last;
724                                 } # else continue looping
725                         }
726                         last if $ok;
727                         my $last = pop @or;
728                         $err = join(', ', @or) . " or $last must be set";
729                 } else {
730                         warn "BUG: can't parse `$var' in $proto";
731                 }
732                 last if $err;
733         }
734         if (!$inf && scalar(@$argv) > scalar(@args)) {
735                 $err //= 'too many arguments';
736         }
737         $err ? fail($self, "usage: lei $cmd $proto\nE: $err") : 1;
738 }
739
740 sub _tmp_cfg { # for lei -c <name>=<value> ...
741         my ($self) = @_;
742         my $cfg = _lei_cfg($self, 1);
743         require File::Temp;
744         my $ft = File::Temp->new(TEMPLATE => 'lei_cfg-XXXX', TMPDIR => 1);
745         my $tmp = { '-f' => $ft->filename, -tmp => $ft };
746         $ft->autoflush(1);
747         print $ft <<EOM or return fail($self, "$tmp->{-f}: $!");
748 [include]
749         path = $cfg->{-f}
750 EOM
751         $tmp = $self->{cfg} = bless { %$cfg, %$tmp }, ref($cfg);
752         for (@{$self->{opt}->{c}}) {
753                 /\A([^=\.]+\.[^=]+)(?:=(.*))?\z/ or return fail($self, <<EOM);
754 `-c $_' is not of the form -c <name>=<value>'
755 EOM
756                 my $name = $1;
757                 my $value = $2 // 1;
758                 _config($self, '--add', $name, $value);
759                 if (defined(my $v = $tmp->{$name})) {
760                         if (ref($v) eq 'ARRAY') {
761                                 push @$v, $value;
762                         } else {
763                                 $tmp->{$name} = [ $v, $value ];
764                         }
765                 } else {
766                         $tmp->{$name} = $value;
767                 }
768         }
769 }
770
771 sub lazy_cb ($$$) {
772         my ($self, $cmd, $pfx) = @_;
773         my $ucmd = $cmd;
774         $ucmd =~ tr/-/_/;
775         my $cb;
776         $cb = $self->can($pfx.$ucmd) and return $cb;
777         my $base = $ucmd;
778         $base =~ s/_([a-z])/\u$1/g;
779         my $pkg = "PublicInbox::Lei\u$base";
780         ($INC{"PublicInbox/Lei\u$base.pm"} // eval("require $pkg")) ?
781                 $pkg->can($pfx.$ucmd) : undef;
782 }
783
784 sub dispatch {
785         my ($self, $cmd, @argv) = @_;
786         fchdir($self) or return;
787         local %ENV = %{$self->{env}};
788         local $current_lei = $self; # for __WARN__
789         $self->{2}->autoflush(1); # keep stdout buffered until x_it|DESTROY
790         return _help($self, 'no command given') unless defined($cmd);
791         # do not support Getopt bundling for this
792         while ($cmd eq '-C' || $cmd eq '-c') {
793                 my $v = shift(@argv) // return fail($self, $cmd eq '-C' ?
794                                         '-C DIRECTORY' : '-c <name>=<value>');
795                 push @{$self->{opt}->{substr($cmd, 1, 1)}}, $v;
796                 $cmd = shift(@argv) // return _help($self, 'no command given');
797         }
798         if (my $cb = lazy_cb(__PACKAGE__, $cmd, 'lei_')) {
799                 optparse($self, $cmd, \@argv) or return;
800                 $self->{opt}->{c} and (_tmp_cfg($self) // return);
801                 if (my $chdir = $self->{opt}->{C}) {
802                         for my $d (@$chdir) {
803                                 next if $d eq ''; # same as git(1)
804                                 chdir $d or return fail($self, "cd $d: $!");
805                         }
806                         open $self->{3}, '.' or return fail($self, "open . $!");
807                 }
808                 $cb->($self, @argv);
809         } elsif (grep(/\A-/, $cmd, @argv)) { # --help or -h only
810                 $GLP->getoptionsfromarray([$cmd, @argv], {}, qw(help|h C=s@))
811                         or return _help($self, 'bad arguments or options');
812                 _help($self);
813         } else {
814                 fail($self, "`$cmd' is not an lei command");
815         }
816 }
817
818 sub _lei_cfg ($;$) {
819         my ($self, $creat) = @_;
820         return $self->{cfg} if $self->{cfg};
821         my $f = _config_path($self);
822         my @st = stat($f);
823         my $cur_st = @st ? pack('dd', $st[10], $st[7]) : ''; # 10:ctime, 7:size
824         my ($sto, $sto_dir, $watches, $lne);
825         if (my $cfg = $PATH2CFG{$f}) { # reuse existing object in common case
826                 return ($self->{cfg} = $cfg) if $cur_st eq $cfg->{-st};
827                 ($sto, $sto_dir, $watches, $lne) =
828                                 @$cfg{qw(-lei_store leistore.dir -watches
829                                         -lei_note_event)};
830         }
831         if (!@st) {
832                 unless ($creat) {
833                         delete $self->{cfg};
834                         return bless {}, 'PublicInbox::Config';
835                 }
836                 my ($cfg_dir) = ($f =~ m!(.*?/)[^/]+\z!);
837                 -d $cfg_dir or mkpath($cfg_dir) or die "mkpath($cfg_dir): $!\n";
838                 open my $fh, '>>', $f or die "open($f): $!\n";
839                 @st = stat($fh) or die "fstat($f): $!\n";
840                 $cur_st = pack('dd', $st[10], $st[7]);
841                 qerr($self, "# $f created") if $self->{cmd} ne 'config';
842         }
843         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{2});
844         $cfg->{-st} = $cur_st;
845         $cfg->{'-f'} = $f;
846         if ($sto && canonpath_harder($sto_dir // store_path($self))
847                         eq canonpath_harder($cfg->{'leistore.dir'} //
848                                                 store_path($self))) {
849                 $cfg->{-lei_store} = $sto;
850                 $cfg->{-lei_note_event} = $lne;
851                 $cfg->{-watches} = $watches if $watches;
852         }
853         if (scalar(keys %PATH2CFG) > 5) {
854                 # FIXME: use inotify/EVFILT_VNODE to detect unlinked configs
855                 for my $k (keys %PATH2CFG) {
856                         delete($PATH2CFG{$k}) unless -f $k
857                 }
858         }
859         $self->{cfg} = $PATH2CFG{$f} = $cfg;
860         refresh_watches($self);
861         $cfg;
862 }
863
864 sub _lei_store ($;$) {
865         my ($self, $creat) = @_;
866         my $cfg = _lei_cfg($self, $creat) // return;
867         $cfg->{-lei_store} //= do {
868                 require PublicInbox::LeiStore;
869                 my $dir = $cfg->{'leistore.dir'} // store_path($self);
870                 return unless $creat || -d $dir;
871                 PublicInbox::LeiStore->new($dir, { creat => $creat });
872         };
873 }
874
875 sub _config {
876         my ($self, @argv) = @_;
877         my %env = (%{$self->{env}}, GIT_CONFIG => undef);
878         my $cfg = _lei_cfg($self, 1);
879         my $cmd = [ qw(git config -f), $cfg->{'-f'}, @argv ];
880         my %rdr = map { $_ => $self->{$_} } (0..2);
881         waitpid(spawn($cmd, \%env, \%rdr), 0);
882 }
883
884 sub lei_daemon_pid { puts shift, $$ }
885
886 sub lei_daemon_kill {
887         my ($self) = @_;
888         my $sig = $self->{opt}->{signal} // 'TERM';
889         kill($sig, $$) or fail($self, "kill($sig, $$): $!");
890 }
891
892 # Shell completion helper.  Used by lei-completion.bash and hopefully
893 # other shells.  Try to do as much here as possible to avoid redundancy
894 # and improve maintainability.
895 sub lei__complete {
896         my ($self, @argv) = @_; # argv = qw(lei and any other args...)
897         shift @argv; # ignore "lei", the entire command is sent
898         @argv or return puts $self, grep(!/^_/, keys %CMD), qw(--help -h -C);
899         my $cmd = shift @argv;
900         my $info = $CMD{$cmd} // do { # filter matching commands
901                 @argv or puts $self, grep(/\A\Q$cmd\E/, keys %CMD);
902                 return;
903         };
904         my ($proto, undef, @spec) = @$info;
905         my $cur = pop @argv;
906         my $re = defined($cur) ? qr/\A\Q$cur\E/ : qr/./;
907         if (substr(my $_cur = $cur // '-', 0, 1) eq '-') { # --switches
908                 # gross special case since the only git-config options
909                 # Consider moving to a table if we need more special cases
910                 # we use Getopt::Long for are the ones we reject, so these
911                 # are the ones we don't reject:
912                 if ($cmd eq 'config') {
913                         puts $self, grep(/$re/, keys %CONFIG_KEYS);
914                         @spec = qw(add z|null get get-all unset unset-all
915                                 replace-all get-urlmatch
916                                 remove-section rename-section
917                                 name-only list|l edit|e
918                                 get-color-name get-colorbool);
919                         # fall-through
920                 }
921                 # generate short/long names from Getopt::Long specs
922                 puts $self, grep(/$re/, qw(--help -h -C), map {
923                         if (s/[:=].+\z//) { # req/optional args, e.g output|o=i
924                         } elsif (s/\+\z//) { # verbose|v+
925                         } elsif (s/!\z//) {
926                                 # negation: mail! => no-mail|mail
927                                 s/([\w\-]+)/$1|no-$1/g
928                         }
929                         map {
930                                 my $x = length > 1 ? "--$_" : "-$_";
931                                 $x eq $_cur ? () : $x;
932                         } grep(!/_/, split(/\|/, $_, -1)) # help|h
933                 } grep { $OPTDESC{"$_\t$cmd"} || $OPTDESC{$_} } @spec);
934         } elsif ($cmd eq 'config' && !@argv && !$CONFIG_KEYS{$cur}) {
935                 puts $self, grep(/$re/, keys %CONFIG_KEYS);
936         }
937
938         # switch args (e.g. lei q -f mbox<TAB>)
939         if (($argv[-1] // $cur // '') =~ /\A--?([\w\-]+)\z/) {
940                 my $opt = quotemeta $1;
941                 puts $self, map {
942                         my $v = $OPTDESC{$_};
943                         my @v = ref($v) ? split(/\|/, $v->[0]) : ();
944                         # get rid of ALL CAPS placeholder (e.g "OUT")
945                         # (TODO: completion for external paths)
946                         shift(@v) if scalar(@v) && uc($v[0]) eq $v[0];
947                         @v;
948                 } grep(/\A(?:[\w-]+\|)*$opt\b.*?(?:\t$cmd)?\z/, keys %OPTDESC);
949         }
950         if (my $cb = lazy_cb($self, $cmd, '_complete_')) {
951                 puts $self, $cb->($self, @argv, $cur ? ($cur) : ());
952         }
953         # TODO: URLs, pathnames, OIDs, MIDs, etc...  See optparse() for
954         # proto parsing.
955 }
956
957 sub exec_buf ($$) {
958         my ($argv, $env) = @_;
959         my $argc = scalar @$argv;
960         my $buf = 'exec '.join("\0", scalar(@$argv), @$argv);
961         while (my ($k, $v) = each %$env) { $buf .= "\0$k=$v" };
962         $buf;
963 }
964
965 sub start_mua {
966         my ($self) = @_;
967         if ($self->{ovv}->{fmt} =~ /\A(?:maildir)\z/) { # TODO: IMAP
968                 refresh_watches($self);
969         }
970         my $mua = $self->{opt}->{mua} // return;
971         my $mfolder = $self->{ovv}->{dst};
972         my (@cmd, $replaced);
973         if ($mua =~ /\A(?:mutt|mailx|mail|neomutt)\z/) {
974                 @cmd = ($mua, '-f');
975         # TODO: help wanted: other common FOSS MUAs
976         } else {
977                 require Text::ParseWords;
978                 @cmd = Text::ParseWords::shellwords($mua);
979                 # mutt uses '%f' for open-hook with compressed mbox, we follow
980                 @cmd = map { $_ eq '%f' ? ($replaced = $mfolder) : $_ } @cmd;
981         }
982         push @cmd, $mfolder unless defined($replaced);
983         if ($self->{sock}) { # lei(1) client process runs it
984                 # restore terminal: echo $query | lei q --stdin --mua=...
985                 my $io = [];
986                 $io->[0] = $self->{1} if $self->{opt}->{stdin} && -t $self->{1};
987                 send_exec_cmd($self, $io, \@cmd, {});
988         }
989         if ($self->{lxs} && $self->{au_done}) { # kick wait_startq
990                 syswrite($self->{au_done}, 'q' x ($self->{lxs}->{jobs} // 0));
991         }
992         return unless -t $self->{2}; # XXX how to determine non-TUI MUAs?
993         $self->{opt}->{quiet} = 1;
994         delete $self->{-progress};
995         delete $self->{opt}->{verbose};
996 }
997
998 sub send_exec_cmd { # tell script/lei to execute a command
999         my ($self, $io, $cmd, $env) = @_;
1000         my $sock = $self->{sock} // die 'lei client gone';
1001         my $fds = [ map { fileno($_) } @$io ];
1002         $send_cmd->($sock, $fds, exec_buf($cmd, $env), MSG_EOR);
1003 }
1004
1005 sub poke_mua { # forces terminal MUAs to wake up and hopefully notice new mail
1006         my ($self) = @_;
1007         my $alerts = $self->{opt}->{alert} // return;
1008         my $sock = $self->{sock};
1009         while (my $op = shift(@$alerts)) {
1010                 if ($op eq ':WINCH') {
1011                         # hit the process group that started the MUA
1012                         send($sock, '-WINCH', MSG_EOR) if $sock;
1013                 } elsif ($op eq ':bell') {
1014                         out($self, "\a");
1015                 } elsif ($op =~ /(?<!\\),/) { # bare ',' (not ',,')
1016                         push @$alerts, split(/(?<!\\),/, $op);
1017                 } elsif ($op =~ m!\A([/a-z0-9A-Z].+)!) {
1018                         my $cmd = $1; # run an arbitrary command
1019                         require Text::ParseWords;
1020                         $cmd = [ Text::ParseWords::shellwords($cmd) ];
1021                         send($sock, exec_buf($cmd, {}), MSG_EOR) if $sock;
1022                 } else {
1023                         warn("W: unsupported --alert=$op\n"); # non-fatal
1024                 }
1025         }
1026 }
1027
1028 my %path_to_fd = ('/dev/stdin' => 0, '/dev/stdout' => 1, '/dev/stderr' => 2);
1029 $path_to_fd{"/dev/fd/$_"} = $_ for (0..2);
1030
1031 # this also normalizes the path
1032 sub path_to_fd {
1033         my ($self, $path) = @_;
1034         $path = rel2abs($self, $path);
1035         $path =~ tr!/!/!s;
1036         $path_to_fd{$path} // (
1037                 ($path =~ m!\A/(?:dev|proc/self)/fd/[0-9]+\z!) ?
1038                         fail($self, "cannot open $path from daemon") : -1
1039         );
1040 }
1041
1042 # caller needs to "-t $self->{1}" to check if tty
1043 sub start_pager {
1044         my ($self, $new_env) = @_;
1045         my $fh = popen_rd([qw(git var GIT_PAGER)]);
1046         chomp(my $pager = <$fh> // '');
1047         close($fh) or warn "`git var PAGER' error: \$?=$?";
1048         return if $pager eq 'cat' || $pager eq '';
1049         $new_env //= {};
1050         $new_env->{LESS} //= 'FRX';
1051         $new_env->{LV} //= '-c';
1052         $new_env->{MORE} = $new_env->{LESS} if $^O eq 'freebsd';
1053         pipe(my ($r, $wpager)) or return warn "pipe: $!";
1054         my $rdr = { 0 => $r, 1 => $self->{1}, 2 => $self->{2} };
1055         my $pgr = [ undef, @$rdr{1, 2} ];
1056         my $env = $self->{env};
1057         if ($self->{sock}) { # lei(1) process runs it
1058                 delete @$new_env{keys %$env}; # only set iff unset
1059                 send_exec_cmd($self, [ @$rdr{0..2} ], [$pager], $new_env);
1060         } else {
1061                 die 'BUG: start_pager w/o socket';
1062         }
1063         $self->{1} = $wpager;
1064         $self->{2} = $wpager if -t $self->{2};
1065         $env->{GIT_PAGER_IN_USE} = 'true'; # we may spawn git
1066         $self->{pgr} = $pgr;
1067 }
1068
1069 # display a message for user before spawning full-screen $VISUAL
1070 sub pgr_err {
1071         my ($self, @msg) = @_;
1072         return warn(@msg) unless $self->{sock} && -t $self->{2};
1073         start_pager($self, { LESS => 'RX' }); # no 'F' so we prompt
1074         print { $self->{2} } @msg;
1075         $self->{2}->autoflush(1);
1076         stop_pager($self);
1077         send($self->{sock}, 'wait', MSG_EOR); # wait for user to quit pager
1078 }
1079
1080 sub stop_pager {
1081         my ($self) = @_;
1082         my $pgr = delete($self->{pgr}) or return;
1083         $self->{2} = $pgr->[2];
1084         close(delete($self->{1})) if $self->{1};
1085         $self->{1} = $pgr->[1];
1086 }
1087
1088 sub accept_dispatch { # Listener {post_accept} callback
1089         my ($sock) = @_; # ignore other
1090         $sock->autoflush(1);
1091         my $self = bless { sock => $sock }, __PACKAGE__;
1092         vec(my $rvec = '', fileno($sock), 1) = 1;
1093         select($rvec, undef, undef, 60) or
1094                 return send($sock, 'timed out waiting to recv FDs', MSG_EOR);
1095         # (4096 * 33) >MAX_ARG_STRLEN
1096         my @fds = $recv_cmd->($sock, my $buf, 4096 * 33) or return; # EOF
1097         if (!defined($fds[0])) {
1098                 warn(my $msg = "recv_cmd failed: $!");
1099                 return send($sock, $msg, MSG_EOR);
1100         } else {
1101                 my $i = 0;
1102                 for my $fd (@fds) {
1103                         open($self->{$i++}, '+<&=', $fd) and next;
1104                         send($sock, "open(+<&=$fd) (FD=$i): $!", MSG_EOR);
1105                 }
1106                 $i == 4 or return send($sock, 'not enough FDs='.($i-1), MSG_EOR)
1107         }
1108         # $ENV_STR = join('', map { "\0$_=$ENV{$_}" } keys %ENV);
1109         # $buf = "$argc\0".join("\0", @ARGV).$ENV_STR."\0\0";
1110         substr($buf, -2, 2, '') eq "\0\0" or  # s/\0\0\z//
1111                 return send($sock, 'request command truncated', MSG_EOR);
1112         my ($argc, @argv) = split(/\0/, $buf, -1);
1113         undef $buf;
1114         my %env = map { split(/=/, $_, 2) } splice(@argv, $argc);
1115         $self->{env} = \%env;
1116         eval { dispatch($self, @argv) };
1117         send($sock, $@, MSG_EOR) if $@;
1118 }
1119
1120 sub dclose {
1121         my ($self) = @_;
1122         local $current_lei = $self;
1123         delete $self->{-progress};
1124         _drop_wq($self) if $self->{failed};
1125         $self->close if $self->{-event_init_done}; # PublicInbox::DS::close
1126 }
1127
1128 # for long-running results
1129 sub event_step {
1130         my ($self) = @_;
1131         local %ENV = %{$self->{env}};
1132         local $current_lei = $self;
1133         eval {
1134                 my $buf;
1135                 while (my @fds = $recv_cmd->($self->{sock}, $buf, 4096)) {
1136                         if (scalar(@fds) == 1 && !defined($fds[0])) {
1137                                 return if $! == EAGAIN;
1138                                 next if $! == EINTR;
1139                                 last if $! == ECONNRESET;
1140                                 die "recvmsg: $!";
1141                         }
1142                         for (@fds) { open my $rfh, '+<&=', $_ }
1143                 }
1144                 if ($buf eq '') {
1145                         _drop_wq($self); # EOF, client disconnected
1146                         dclose($self);
1147                 } elsif ($buf =~ /\A(?:STOP|CONT)\z/) {
1148                         my $sig = "-$buf";
1149                         for my $wq (grep(defined, @$self{@WQ_KEYS})) {
1150                                 $wq->wq_kill($sig) or $wq->wq_kill_old($sig);
1151                         }
1152                 } else {
1153                         die "unrecognized client signal: $buf";
1154                 }
1155         };
1156         if (my $err = $@) {
1157                 eval { $self->fail($err) };
1158                 dclose($self);
1159         }
1160 }
1161
1162 sub event_step_init {
1163         my ($self) = @_;
1164         my $sock = $self->{sock} or return;
1165         $self->{-event_init_done} //= do { # persist til $ops done
1166                 $sock->blocking(0);
1167                 $self->SUPER::new($sock, EPOLLIN|EPOLLET);
1168                 $sock;
1169         };
1170 }
1171
1172 sub noop {}
1173
1174 sub oldset { $oldset }
1175
1176 sub dump_and_clear_log {
1177         if (defined($errors_log) && -s STDIN && seek(STDIN, 0, SEEK_SET)) {
1178                 openlog('lei-daemon', 'pid,nowait,nofatal,ndelay', 'user');
1179                 chomp(my @lines = <STDIN>);
1180                 truncate(STDIN, 0) or
1181                         syslog('warning', "ftruncate (%s): %m", $errors_log);
1182                 for my $l (@lines) { syslog('warning', '%s', $l) }
1183                 closelog(); # don't share across fork
1184         }
1185 }
1186
1187 sub cfg2lei ($) {
1188         my ($cfg) = @_;
1189         my $lei = bless { env => { %{$cfg->{-env}} } }, __PACKAGE__;
1190         open($lei->{0}, '<&', \*STDIN) or die "dup 0: $!";
1191         open($lei->{1}, '>>&', \*STDOUT) or die "dup 1: $!";
1192         open($lei->{2}, '>>&', \*STDERR) or die "dup 2: $!";
1193         open($lei->{3}, '/') or die "open /: $!";
1194         my ($x, $y);
1195         socketpair($x, $y, AF_UNIX, SOCK_SEQPACKET, 0) or die "socketpair: $!";
1196         $lei->{sock} = $x;
1197         require PublicInbox::LeiSelfSocket;
1198         PublicInbox::LeiSelfSocket->new($y); # adds to event loop
1199         $lei;
1200 }
1201
1202 sub dir_idle_handler ($) { # PublicInbox::DirIdle callback
1203         my ($ev) = @_; # Linux::Inotify2::Event or duck type
1204         my $fn = $ev->fullname;
1205         if ($fn =~ m!\A(.+)/(new|cur)/([^/]+)\z!) { # Maildir file
1206                 my ($mdir, $nc, $bn) = ($1, $2, $3);
1207                 $nc = '' if $ev->IN_DELETE;
1208                 for my $f (keys %{$MDIR2CFGPATH->{$mdir} // {}}) {
1209                         my $cfg = $PATH2CFG{$f} // next;
1210                         eval {
1211                                 my $lei = cfg2lei($cfg);
1212                                 $lei->dispatch('note-event',
1213                                                 "maildir:$mdir", $nc, $bn, $fn);
1214                         };
1215                         warn "E: note-event $f: $@\n" if $@;
1216                 }
1217         }
1218         if ($ev->can('cancel') && ($ev->IN_IGNORE || $ev->IN_UNMOUNT)) {
1219                 $ev->cancel;
1220         }
1221         if ($fn =~ m!\A(.+)/(?:new|cur)\z! && !-e $fn) {
1222                 delete $MDIR2CFGPATH->{$1};
1223         }
1224         if (!-e $fn) { # config file or Maildir gone
1225                 for my $cfgpaths (values %$MDIR2CFGPATH) {
1226                         delete $cfgpaths->{$fn};
1227                 }
1228                 delete $PATH2CFG{$fn};
1229         }
1230 }
1231
1232 # lei(1) calls this when it can't connect
1233 sub lazy_start {
1234         my ($path, $errno, $narg) = @_;
1235         local ($errors_log, $listener);
1236         my ($sock_dir) = ($path =~ m!\A(.+?)/[^/]+\z!);
1237         $errors_log = "$sock_dir/errors.log";
1238         my $addr = pack_sockaddr_un($path);
1239         my $lk = bless { lock_path => $errors_log }, 'PublicInbox::Lock';
1240         umask(077) // die("umask(077): $!");
1241         $lk->lock_acquire;
1242         socket($listener, AF_UNIX, SOCK_SEQPACKET, 0) or die "socket: $!";
1243         if ($errno == ECONNREFUSED || $errno == ENOENT) {
1244                 return if connect($listener, $addr); # another process won
1245                 if ($errno == ECONNREFUSED && -S $path) {
1246                         unlink($path) or die "unlink($path): $!";
1247                 }
1248         } else {
1249                 $! = $errno; # allow interpolation to stringify in die
1250                 die "connect($path): $!";
1251         }
1252         bind($listener, $addr) or die "bind($path): $!";
1253         $lk->lock_release;
1254         undef $lk;
1255         my @st = stat($path) or die "stat($path): $!";
1256         my $dev_ino_expect = pack('dd', $st[0], $st[1]); # dev+ino
1257         local $oldset = PublicInbox::DS::block_signals();
1258         if ($narg == 5) {
1259                 $send_cmd = PublicInbox::Spawn->can('send_cmd4');
1260                 $recv_cmd = PublicInbox::Spawn->can('recv_cmd4') // do {
1261                         require PublicInbox::CmdIPC4;
1262                         $send_cmd = PublicInbox::CmdIPC4->can('send_cmd4');
1263                         PublicInbox::CmdIPC4->can('recv_cmd4');
1264                 };
1265         }
1266         $recv_cmd or die <<"";
1267 (Socket::MsgHdr || Inline::C) missing/unconfigured (narg=$narg);
1268
1269         require PublicInbox::Listener;
1270         require PublicInbox::PktOp;
1271         (-p STDOUT) or die "E: stdout must be a pipe\n";
1272         open(STDIN, '+>>', $errors_log) or die "open($errors_log): $!";
1273         STDIN->autoflush(1);
1274         dump_and_clear_log();
1275         POSIX::setsid() > 0 or die "setsid: $!";
1276         my $pid = fork // die "fork: $!";
1277         return if $pid;
1278         $0 = "lei-daemon $path";
1279         local %PATH2CFG;
1280         local $MDIR2CFGPATH;
1281         $listener->blocking(0);
1282         my $exit_code;
1283         my $pil = PublicInbox::Listener->new($listener, \&accept_dispatch);
1284         local $quit = do {
1285                 my (undef, $eof_p) = PublicInbox::PktOp->pair;
1286                 sub {
1287                         $exit_code //= shift;
1288                         eval 'PublicInbox::LeiNoteEvent::flush_task()';
1289                         my $lis = $pil or exit($exit_code);
1290                         # closing eof_p triggers \&noop wakeup
1291                         $listener = $eof_p = $pil = $path = undef;
1292                         $lis->close; # DS::close
1293                         PublicInbox::DS->SetLoopTimeout(1000);
1294                 };
1295         };
1296         my $sig = {
1297                 CHLD => \&PublicInbox::DS::enqueue_reap,
1298                 QUIT => $quit,
1299                 INT => $quit,
1300                 TERM => $quit,
1301                 HUP => \&noop,
1302                 USR1 => \&noop,
1303                 USR2 => \&noop,
1304         };
1305         require PublicInbox::DirIdle;
1306         local $dir_idle = PublicInbox::DirIdle->new([$sock_dir], sub {
1307                 # just rely on wakeup to hit PostLoopCallback set below
1308                 dir_idle_handler($_[0]) if $_[0]->fullname ne $path;
1309         }, 1);
1310         PublicInbox::DS->SetPostLoopCallback(sub {
1311                 my ($dmap, undef) = @_;
1312                 if (@st = defined($path) ? stat($path) : ()) {
1313                         if ($dev_ino_expect ne pack('dd', $st[0], $st[1])) {
1314                                 warn "$path dev/ino changed, quitting\n";
1315                                 $path = undef;
1316                         }
1317                 } elsif (defined($path)) { # ENOENT is common
1318                         warn "stat($path): $!, quitting ...\n" if $! != ENOENT;
1319                         undef $path;
1320                         $quit->();
1321                 }
1322                 return 1 if defined($path);
1323                 my $now = now();
1324                 my $n = 0;
1325                 for my $s (values %$dmap) {
1326                         $s->can('busy') or next;
1327                         if ($s->busy($now)) {
1328                                 ++$n;
1329                         } else {
1330                                 $s->close;
1331                         }
1332                 }
1333                 $n; # true: continue, false: stop
1334         });
1335
1336         # STDIN was redirected to /dev/null above, closing STDERR and
1337         # STDOUT will cause the calling `lei' client process to finish
1338         # reading the <$daemon> pipe.
1339         local $SIG{__WARN__} = sub {
1340                 $current_lei ? err($current_lei, @_) : warn(
1341                   strftime('%Y-%m-%dT%H:%M:%SZ', gmtime(time))," $$ ", @_);
1342         };
1343         open STDERR, '>&STDIN' or die "redirect stderr failed: $!";
1344         open STDOUT, '>&STDIN' or die "redirect stdout failed: $!";
1345         # $daemon pipe to `lei' closed, main loop begins:
1346         eval { PublicInbox::DS::event_loop($sig, $oldset) };
1347         warn "event loop error: $@\n" if $@;
1348         # exit() may trigger waitpid via various DESTROY, ensure interruptible
1349         PublicInbox::DS::sig_setmask($oldset);
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         local $current_lei = $lei;
1376         my $err_type = $lei->{-err_type};
1377         $? and $lei->child_error($?,
1378                         $err_type ? "$err_type errors during $lei->{cmd}" : ());
1379         $lei->dclose;
1380 }
1381
1382 sub fchdir {
1383         my ($lei) = @_;
1384         my $dh = $lei->{3} // die 'BUG: lei->{3} (CWD) gone';
1385         chdir($dh) || $lei->fail("fchdir: $!");
1386 }
1387
1388 sub wq_eof { # EOF callback for main daemon
1389         my ($lei) = @_;
1390         local $current_lei = $lei;
1391         my $wq1 = delete $lei->{wq1} // return $lei->fail; # already failed
1392         $wq1->wq_wait_old($wq1->can('_wq_done_wait') // \&wq_done_wait, $lei);
1393 }
1394
1395 sub watch_state_ok ($) {
1396         my ($state) = $_[-1]; # $_[0] may be $self
1397         $state =~ /\Apause|(?:import|index|tag)-(?:ro|rw)\z/;
1398 }
1399
1400 sub cancel_maildir_watch ($$) {
1401         my ($d, $cfg_f) = @_;
1402         my $w = delete $MDIR2CFGPATH->{$d}->{$cfg_f};
1403         scalar(keys %{$MDIR2CFGPATH->{$d}}) or
1404                 delete $MDIR2CFGPATH->{$d};
1405         for my $x (@{$w // []}) { $x->cancel }
1406 }
1407
1408 sub add_maildir_watch ($$) {
1409         my ($d, $cfg_f) = @_;
1410         if (!exists($MDIR2CFGPATH->{$d}->{$cfg_f})) {
1411                 my @w = $dir_idle->add_watches(["$d/cur", "$d/new"], 1);
1412                 push @{$MDIR2CFGPATH->{$d}->{$cfg_f}}, @w if @w;
1413         }
1414 }
1415
1416 sub refresh_watches {
1417         my ($lei) = @_;
1418         $dir_idle or return;
1419         my $cfg = _lei_cfg($lei) or return;
1420         my $old = $cfg->{-watches};
1421         my $watches = $cfg->{-watches} //= {};
1422         my %seen;
1423         my $cfg_f = $cfg->{'-f'};
1424         for my $w (grep(/\Awatch\..+\.state\z/, keys %$cfg)) {
1425                 my $url = substr($w, length('watch.'), -length('.state'));
1426                 require PublicInbox::LeiWatch;
1427                 $watches->{$url} //= PublicInbox::LeiWatch->new($url);
1428                 $seen{$url} = undef;
1429                 my $state = $cfg->get_1("watch.$url.state");
1430                 if (!watch_state_ok($state)) {
1431                         warn("watch.$url.state=$state not supported\n");
1432                         next;
1433                 }
1434                 if ($url =~ /\Amaildir:(.+)/i) {
1435                         my $d = canonpath_harder($1);
1436                         if ($state eq 'pause') {
1437                                 cancel_maildir_watch($d, $cfg_f);
1438                         } else {
1439                                 add_maildir_watch($d, $cfg_f);
1440                         }
1441                 } else { # TODO: imap/nntp/jmap
1442                         $lei->child_error(0, "E: watch $url not supported, yet")
1443                 }
1444         }
1445
1446         # add all known Maildir folders as implicit watches
1447         my $lms = $lei->lms;
1448         if ($lms) {
1449                 $lms->lms_write_prepare;
1450                 for my $d ($lms->folders('maildir:')) {
1451                         substr($d, 0, length('maildir:')) = '';
1452
1453                         # fixup old bugs while we're iterating:
1454                         my $cd = canonpath_harder($d);
1455                         my $f = "maildir:$cd";
1456                         $lms->rename_folder("maildir:$d", $f) if $d ne $cd;
1457                         next if $watches->{$f}; # may be set to pause
1458                         require PublicInbox::LeiWatch;
1459                         $watches->{$f} = PublicInbox::LeiWatch->new($f);
1460                         $seen{$f} = undef;
1461                         add_maildir_watch($cd, $cfg_f);
1462                 }
1463         }
1464         if ($old) { # cull old non-existent entries
1465                 for my $url (keys %$old) {
1466                         next if exists $seen{$url};
1467                         delete $old->{$url};
1468                         if ($url =~ /\Amaildir:(.+)/i) {
1469                                 my $d = canonpath_harder($1);
1470                                 cancel_maildir_watch($d, $cfg_f);
1471                         } else { # TODO: imap/nntp/jmap
1472                                 $lei->child_error(0, "E: watch $url TODO");
1473                         }
1474                 }
1475         }
1476         if (scalar keys %$watches) {
1477                 $cfg->{-env} //= { %{$lei->{env}}, PWD => '/' }; # for cfg2lei
1478         } else {
1479                 delete $cfg->{-watches};
1480         }
1481 }
1482
1483 # TODO: support SHA-256
1484 sub git_oid {
1485         my $eml = $_[-1];
1486         $eml->header_set($_) for @PublicInbox::Import::UNWANTED_HEADERS;
1487         git_sha(1, $eml);
1488 }
1489
1490 sub lms {
1491         my ($lei, $rw) = @_;
1492         my $sto = $lei->{sto} // _lei_store($lei) // return;
1493         require PublicInbox::LeiMailSync;
1494         my $f = "$sto->{priv_eidx}->{topdir}/mail_sync.sqlite3";
1495         (-f $f || $rw) ? PublicInbox::LeiMailSync->new($f) : undef;
1496 }
1497
1498 sub sto_done_request {
1499         my ($lei, $sock) = @_;
1500         local $current_lei = $lei;
1501         eval {
1502                 if ($sock //= $lei->{sock}) { # issue, async wait
1503                         $lei->{sto}->wq_io_do('done', [ $sock ]);
1504                 } else { # forcibly wait
1505                         my $wait = $lei->{sto}->wq_do('done');
1506                 }
1507         };
1508         warn($@) if $@;
1509 }
1510
1511 sub cfg_dump ($$) {
1512         my ($lei, $f) = @_;
1513         my $ret = eval { PublicInbox::Config->git_config_dump($f, $lei->{2}) };
1514         return $ret if !$@;
1515         warn($@);
1516         undef;
1517 }
1518
1519 sub request_umask {
1520         my ($lei) = @_;
1521         my $s = $lei->{sock} // return;
1522         send($s, 'umask', MSG_EOR) // die "send: $!";
1523         vec(my $rvec = '', fileno($s), 1) = 1;
1524         select($rvec, undef, undef, 2) or die 'timeout waiting for umask';
1525         recv($s, my $v, 5, 0) // die "recv: $!";
1526         (my $u, $lei->{client_umask}) = unpack('AV', $v);
1527         $u eq 'u' or warn "E: recv $v has no umask";
1528 }
1529
1530 1;