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