NEWS: adjust for v14.8.1
[s-mailx.git] / main.c
blob37841ec24b641a6755f2787ba1de4d6863fb8df3
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Startup -- interface with user.
3 *@ This file is also used to materialize externals.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
40 #undef n_FILE
41 #define n_FILE main
43 #ifndef HAVE_AMALGAMATION
44 # define _MAIN_SOURCE
45 # include "nail.h"
46 #endif
48 #include <sys/ioctl.h>
50 #include <pwd.h>
52 #ifdef HAVE_NL_LANGINFO
53 # include <langinfo.h>
54 #endif
55 #ifdef HAVE_SETLOCALE
56 # include <locale.h>
57 #endif
59 /* Verify that our size_t PRI[du]Z format string has the correct type size */
60 PRIxZ_FMT_CTA();
62 struct a_arg {
63 struct a_arg *aa_next;
64 char *aa_file;
67 struct X_arg {
68 struct X_arg *xa_next;
69 size_t xa_cmd_len;
70 char xa_cmd_buf[VFIELD_SIZE(sizeof(size_t))];
73 /* (extern, but not with amalgamation, so define here) */
74 VL char const weekday_names[7 + 1][4] = {
75 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ""
77 VL char const month_names[12 + 1][4] = {
78 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
79 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""
81 VL char const uagent[] = UAGENT;
82 VL uc_i const class_char[] = {
83 /* 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel */
84 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
85 /* 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si */
86 C_CNTRL, C_BLANK, C_WHITE, C_SPACE, C_SPACE, C_SPACE, C_CNTRL, C_CNTRL,
87 /* 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb */
88 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
89 /* 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us */
90 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
91 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
92 C_BLANK, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
93 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
94 C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
95 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
96 C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL,
97 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
98 C_DIGIT, C_DIGIT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
99 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
100 C_PUNCT, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
101 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
102 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
103 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
104 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
105 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
106 C_UPPER, C_UPPER, C_UPPER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
107 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
108 C_PUNCT, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
109 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
110 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
111 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
112 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
113 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
114 C_LOWER, C_LOWER, C_LOWER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_CNTRL
117 /* Our own little getopt(3) */
118 static char *_oarg;
119 static int _oind, /*_oerr,*/ _oopt;
121 /* Our own little getopt(3); note --help is special treated as 'h' */
122 static int _getopt(int argc, char * const argv[], char const *optstring);
124 /* Perform basic startup initialization */
125 static void _startup(void);
127 /* Grow a char** */
128 static size_t _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt);
130 /* Initialize *tempdir*, *myname*, *homedir* */
131 static void _setup_vars(void);
133 /* We're in an interactive session - compute what the screen size for printing
134 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
135 * We use the following algorithm for the height:
136 * If baud rate < 1200, use 9
137 * If baud rate = 1200, use 14
138 * If baud rate > 1200, use 24 or ws_row
139 * Width is either 80 or ws_col */
140 static void _setscreensize(int is_sighdl);
142 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
143 * the system mailbox, and open up the right stuff */
144 static int _rcv_mode(char const *folder, char const *Larg,
145 struct X_arg *xhp);
147 /* Interrupt printing of the headers */
148 static void _hdrstop(int signo);
150 /* -X arg given at least once, evaluate the list in order */
151 static bool_t _X_arg_eval(struct X_arg *xhp);
153 static int
154 _getopt(int argc, char * const argv[], char const *optstring)
156 static char const *lastp;
158 int rv = -1, colon;
159 char const *curp;
160 NYD_ENTER;
162 _oarg = NULL;
164 if ((colon = (optstring[0] == ':')))
165 ++optstring;
166 if (lastp != NULL) {
167 curp = lastp;
168 lastp = 0;
169 } else {
170 if (_oind >= argc || argv[_oind] == NULL || argv[_oind][0] != '-' ||
171 argv[_oind][1] == '\0')
172 goto jleave;
173 if (argv[_oind][1] == '-' && argv[_oind][2] == '\0') {
174 /* We need this in for MTA arg detection (easier) ++_oind;*/
175 goto jleave;
177 curp = &argv[_oind][1];
180 _oopt = curp[0];
181 while (optstring[0] != '\0') {
182 if (optstring[0] == ':' || optstring[0] != _oopt) {
183 ++optstring;
184 continue;
186 if (optstring[1] == ':') {
187 if (curp[1] != '\0') {
188 _oarg = UNCONST(curp + 1);
189 ++_oind;
190 } else {
191 if ((_oind += 2) > argc) {
192 if (!colon /*&& _oerr*/) {
193 fprintf(stderr,
194 _("%s: option requires an argument -- %c\n"),
195 argv[0], (char)_oopt);
197 rv = (colon ? ':' : '?');
198 goto jleave;
200 _oarg = argv[_oind - 1];
202 } else {
203 if (curp[1] != '\0')
204 lastp = curp + 1;
205 else
206 ++_oind;
208 rv = _oopt;
209 goto jleave;
212 /* Special support for --help, which is quite common */
213 if (_oopt == '-' && !strcmp(curp, "-help")) {
214 ++_oind;
215 rv = 'h';
216 goto jleave;
219 /* Definitive error */
220 if (!colon /*&& opterr*/)
221 fprintf(stderr, _("%s: invalid option -- %c\n"), argv[0], _oopt);
222 if (curp[1] != '\0')
223 lastp = curp + 1;
224 else
225 ++_oind;
226 _oarg = 0;
227 rv = '?';
228 jleave:
229 NYD_LEAVE;
230 return rv;
233 static void
234 _startup(void)
236 char *cp;
237 NYD_ENTER;
239 /* Absolutely the first thing we do is save our egid and set it to the rgid,
240 * so that we can safely run setgid. We use the sgid (saved set-gid) to
241 * allow ourselves to revert to the egid if we want (temporarily) to become
242 * privileged XXX (s-nail-)*dotlock(-program)* [maybe forked<->Unix IPC?] */
243 effectivegid = getegid();
244 realgid = getgid();
245 if (setgid(realgid) == -1) {
246 perror("setgid");
247 exit(1);
250 image = -1;
251 dflpipe = SIG_DFL;
252 _oind = /*_oerr =*/ 1;
254 if ((cp = strrchr(progname, '/')) != NULL)
255 progname = ++cp;
257 /* Set up a reasonable environment */
259 #ifdef HAVE_NYD
260 safe_signal(SIGABRT, &_nyd_oncrash);
261 # ifdef SIGBUS
262 safe_signal(SIGBUS, &_nyd_oncrash);
263 # endif
264 safe_signal(SIGFPE, &_nyd_oncrash);
265 safe_signal(SIGILL, &_nyd_oncrash);
266 safe_signal(SIGSEGV, &_nyd_oncrash);
267 #endif
268 command_manager_start();
270 if (isatty(STDIN_FILENO)) /* TODO should be isatty(0) && isatty(2)?? */
271 options |= OPT_TTYIN | OPT_INTERACTIVE;
272 if (isatty(STDOUT_FILENO))
273 options |= OPT_TTYOUT;
274 if (IS_TTY_SESSION())
275 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
277 /* -- >8 -- 8< -- */
279 /* Define defaults for internal variables, based on POSIX 2008/Cor 1-2013 */
280 /* (Keep in sync:
281 * ./main.c:_startup(), ./nail.rc, ./nail.1:"Initial settings") */
282 /* noallnet */
283 /* noappend */
284 ok_bset(asksub, TRU1);
285 /* noaskbcc */
286 /* noaskcc */
287 /* noautoprint */
288 /* nobang */
289 /* nocmd */
290 /* nocrt */
291 /* nodebug */
292 /* nodot */
293 /* ok_vset(escape, ESCAPE *"~"*); TODO non-compliant */
294 /* noflipr */
295 /* nofolder */
296 ok_bset(header, TRU1);
297 /* nohold */
298 /* noignore */
299 /* noignoreeof */
300 /* nokeep */
301 /* nokeepsave */
302 /* nometoo */
303 /* noonehop -- Note: we ignore this one */
304 /* nooutfolder */
305 /* nopage */
306 ok_vset(prompt, "\\& "); /* POSIX "? " unless *bsdcompat*, then "& " */
307 /* noquiet */
308 /* norecord */
309 ok_bset(save, TRU1);
310 /* nosendwait */
311 /* noshowto */
312 /* nosign */
313 /* noSign */
314 /* ok_vset(toplines, "5"); XXX somewhat hmm */
316 /* TODO until we have an automatic mechanism for that, set some more
317 * TODO variables so that users see the internal fallback settings
318 * TODO (something like "defval=X,notempty=1") */
319 do {
320 char const *vp;
322 vp = env_vlook("SHELL", TRU1);
323 ok_vset(SHELL, (vp != NULL ? vp : XSHELL));
325 vp = env_vlook("LISTER", TRU1);
326 ok_vset(LISTER, (vp != NULL ? vp : XLISTER));
328 vp = env_vlook("PAGER", TRU1);
329 ok_vset(PAGER, (vp != NULL ? vp : XPAGER));
331 ok_vset(sendmail, SENDMAIL);
332 ok_vset(sendmail_progname, SENDMAIL_PROGNAME);
333 } while (0);
335 /* -- >8 -- 8< -- */
337 #ifdef HAVE_SETLOCALE
338 setlocale(LC_ALL, "");
339 mb_cur_max = MB_CUR_MAX;
340 # ifdef HAVE_NL_LANGINFO
341 if (ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
342 ok_vset(ttycharset, cp);
343 # endif
345 # ifdef HAVE_C90AMEND1
346 if (mb_cur_max > 1) {
347 wchar_t wc;
348 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
349 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
350 options |= OPT_UNICODE;
351 /* Reset possibly messed up state; luckily this also gives us an
352 * indication wether the encoding has locking shift state sequences */
353 /* TODO temporary - use option bits! */
354 enc_has_state = mbtowc(&wc, NULL, mb_cur_max);
356 # endif
357 #else
358 mb_cur_max = 1;
359 #endif
361 #ifdef HAVE_ICONV
362 iconvd = (iconv_t)-1;
363 #endif
364 NYD_LEAVE;
367 static size_t
368 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
370 /* Before spreserve(): use our string pool instead of LibC heap */
371 char const **newcpp;
372 NYD_ENTER;
374 newcpp = salloc(sizeof(char*) * newsize);
376 if (oldcnt > 0)
377 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
378 *cpp = newcpp;
379 NYD_LEAVE;
380 return newsize;
383 static void
384 _setup_vars(void)
386 /* Before spreserve(): use our string pool instead of LibC heap */
387 /* XXX further check paths? */
388 char const *cp;
389 uid_t uid;
390 struct passwd *pwuid, *pw;
391 NYD_ENTER;
393 tempdir = ((cp = env_vlook("TMPDIR", TRU1)) != NULL)
394 ? savestr(cp) : TMPDIR_FALLBACK;
396 cp = (myname == NULL) ? env_vlook("USER", TRU1) : myname;
397 uid = getuid();
398 if ((pwuid = getpwuid(uid)) == NULL)
399 panic(_("Cannot associate a name with uid %lu"), (ul_i)uid);
400 if (cp == NULL || *cp == '\0')
401 myname = pwuid->pw_name;
402 else if ((pw = getpwnam(cp)) == NULL) {
403 alert(_("\"%s\" is not a user of this system"), cp);
404 exit(67); /* XXX BSD EX_NOUSER */
405 } else {
406 myname = pw->pw_name;
407 if (pw->pw_uid != uid)
408 options |= OPT_u_FLAG;
410 myname = savestr(myname);
411 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
413 if ((cp = env_vlook("HOME", TRU1)) == NULL)
414 cp = "."; /* XXX User and Login objects; Login: pw->pw_dir */
415 homedir = savestr(cp);
416 NYD_LEAVE;
419 static void
420 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
422 struct termios tbuf;
423 #ifdef TIOCGWINSZ
424 struct winsize ws;
425 #elif defined TIOCGSIZE
426 struct ttysize ts;
427 #endif
428 NYD_ENTER;
430 scrnheight = realscreenheight = scrnwidth = 0;
432 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
433 * a little bit to be able to honour resizes during our lifetime and
434 * only honour it upon first run; abuse *is_sighdl* as an indicator */
435 if (!is_sighdl) {
436 char *cp;
437 long i;
439 if ((cp = env_vlook("LINES", FAL0)) != NULL &&
440 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
441 scrnheight = realscreenheight = (int)i;
442 if ((cp = env_vlook("COLUMNS", FAL0)) != NULL &&
443 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
444 scrnwidth = (int)i;
446 if (scrnwidth != 0 && scrnheight != 0)
447 goto jleave;
450 #ifdef TIOCGWINSZ
451 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
452 ws.ws_col = ws.ws_row = 0;
453 #elif defined TIOCGSIZE
454 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
455 ts.ts_lines = ts.ts_cols = 0;
456 #endif
458 if (scrnheight == 0) {
459 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
460 ? B9600 : cfgetospeed(&tbuf));
462 if (ospeed < B1200)
463 scrnheight = 9;
464 else if (ospeed == B1200)
465 scrnheight = 14;
466 #ifdef TIOCGWINSZ
467 else if (ws.ws_row != 0)
468 scrnheight = ws.ws_row;
469 #elif defined TIOCGSIZE
470 else if (ts.ts_lines != 0)
471 scrnheight = ts.ts_lines;
472 #endif
473 else
474 scrnheight = 24;
476 #if defined TIOCGWINSZ || defined TIOCGSIZE
477 if (0 ==
478 # ifdef TIOCGWINSZ
479 (realscreenheight = ws.ws_row)
480 # else
481 (realscreenheight = ts.ts_lines)
482 # endif
484 realscreenheight = 24;
485 #endif
488 if (scrnwidth == 0 && 0 ==
489 #ifdef TIOCGWINSZ
490 (scrnwidth = ws.ws_col)
491 #elif defined TIOCGSIZE
492 (scrnwidth = ts.ts_cols)
493 #endif
495 scrnwidth = 80;
497 jleave:
498 #ifdef SIGWINCH
499 if (is_sighdl && IS_TTY_SESSION())
500 tty_signal(SIGWINCH);
501 #endif
502 NYD_LEAVE;
505 static sigjmp_buf __hdrjmp; /* XXX */
507 static int
508 _rcv_mode(char const *folder, char const *Larg, struct X_arg *xhp)
510 char *cp;
511 int i;
512 sighandler_type prevint;
513 NYD_ENTER;
515 if (folder == NULL)
516 folder = "%";
517 else if (*folder == '@') {
518 /* This must be treated specially to make possible invocation like
519 * -A imap -f @mailbox */
520 if ((cp = ok_vlook(folder)) != NULL && which_protocol(cp) == PROTO_IMAP)
521 n_strlcpy(mailname, cp, PATH_MAX);
524 i = setfile(folder, FEDIT_NONE);
525 if (i < 0) {
526 exit_status = EXIT_ERR; /* error already reported */
527 goto jleave;
529 if (options & OPT_EXISTONLY) {
530 exit_status = i;
531 goto jleave;
533 if (options & (OPT_HEADERSONLY | OPT_HEADERLIST)) {
534 if ((exit_status = i) == EXIT_OK)
535 print_header_summary(Larg);
536 goto jleave;
538 check_folder_hook(FAL0);
540 if (i > 0 && !ok_blook(emptystart)) {
541 exit_status = EXIT_ERR;
542 goto jleave;
545 if (sigsetjmp(__hdrjmp, 1) == 0) {
546 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
547 safe_signal(SIGINT, _hdrstop);
548 if (!(options & OPT_N_FLAG)) {
549 if (!ok_blook(quiet))
550 printf(_("%s version %s. Type ? for help.\n"),
551 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
552 announce(1);
553 fflush(stdout);
555 safe_signal(SIGINT, prevint);
558 /* Enter the command loop */
559 if (xhp == NULL || _X_arg_eval(xhp)) {
560 if (options & OPT_INTERACTIVE)
561 tty_init();
562 commands();
563 if (options & OPT_INTERACTIVE)
564 tty_destroy();
567 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
568 safe_signal(SIGHUP, SIG_IGN);
569 safe_signal(SIGINT, SIG_IGN);
570 safe_signal(SIGQUIT, SIG_IGN);
572 save_mbox_for_possible_quitstuff();
573 quit();
574 jleave:
575 NYD_LEAVE;
576 return exit_status;
579 static void
580 _hdrstop(int signo)
582 NYD_X; /* Signal handler */
583 UNUSED(signo);
585 fflush(stdout);
586 fprintf(stderr, _("\nInterrupt\n"));
587 siglongjmp(__hdrjmp, 1);
590 static bool_t
591 _X_arg_eval(struct X_arg *xhp) /* TODO error handling not right */
593 struct eval_ctx ev;
594 struct X_arg *xp;
595 bool_t rv = TRU1;
596 NYD_ENTER;
598 while ((xp = xhp) != NULL) {
599 xhp = xp->xa_next;
601 memset(&ev, 0, sizeof ev);
602 ev.ev_line.s = xp->xa_cmd_buf;
603 ev.ev_line.l = xp->xa_cmd_len;
604 ev.ev_is_recursive = TRU1;
605 pstate &= ~PS_HOOK_MASK;
606 rv = (evaluate(&ev) == 0);
607 free(xp);
609 if (!rv) {
610 if (exit_status == EXIT_OK)
611 exit_status = EXIT_ERR;
612 break;
614 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
615 if (exit_status != EXIT_OK)
616 break;
617 if (pstate & PS_EVAL_ERROR) {
618 exit_status = EXIT_ERR;
619 break;
623 NYD_LEAVE;
624 return rv;
628 main(int argc, char *argv[])
630 static char const optstr[] = "A:a:Bb:c:DdEeFfHhiL:NnO:q:Rr:S:s:tu:VvX:~#.",
631 usagestr[] = N_(
632 " Synopsis:\n"
633 " %s -h | --help\n"
634 " %s [-BDdEFintv~] [-A account]\n"
635 "\t [-a attachment] [-b bcc-address] [-c cc-address]\n"
636 "\t [-q file] [-r from-address] [-S var[=value]...]\n"
637 "\t [-s subject] [-X cmd] [-.] to-address... [-- mta-option...]\n"
638 " %s [-BDdEeHiNnRv~#] [-A account]\n"
639 "\t [-L spec-list] [-r from-address] [-S var[=value]...]\n"
640 "\t [-X cmd] -f [file] [-- mta-option...]\n"
641 " %s [-BDdEeHiNnRv~#] [-A account]\n"
642 "\t [-L spec-list] [-r from-address] [-S var[=value]...]\n"
643 "\t [-u user] [-X cmd] [-- mta-option...]\n"
645 #define _USAGE_ARGS , progname, progname, progname, progname
647 struct X_arg *X_head = NULL, *X_curr = /* silence CC */ NULL;
648 struct a_arg *a_head = NULL, *a_curr = /* silence CC */ NULL;
649 struct name *to = NULL, *cc = NULL, *bcc = NULL;
650 struct attachment *attach = NULL;
651 char *cp = NULL, *subject = NULL, *qf = NULL, *Aarg = NULL, *Larg = NULL;
652 char const *okey, **oargs = NULL, *folder = NULL;
653 size_t oargs_size = 0, oargs_count = 0, smopts_size = 0;
654 int i;
655 NYD_ENTER;
658 * Start our lengthy setup, finalize by setting PS_STARTED
661 progname = argv[0];
662 _startup();
664 /* Command line parsing
665 * Variable settings need to be done twice, since the user surely wants the
666 * setting to take effect immediately, but also doesn't want it to be
667 * overwritten from within resource files */
668 while ((i = _getopt(argc, argv, optstr)) >= 0) {
669 switch (i) {
670 case 'A':
671 /* Execute an account command later on */
672 Aarg = _oarg;
673 break;
674 case 'a':
675 options |= OPT_SENDMODE;
676 { struct a_arg *nap = salloc(sizeof(struct a_arg));
677 if (a_head == NULL)
678 a_head = nap;
679 else
680 a_curr->aa_next = nap;
681 nap->aa_next = NULL;
682 nap->aa_file = _oarg;
683 a_curr = nap;
685 break;
686 case 'B':
687 /* Make 0/1 line buffered */
688 setvbuf(stdin, NULL, _IOLBF, 0);
689 setvbuf(stdout, NULL, _IOLBF, 0);
690 break;
691 case 'b':
692 /* Get Blind Carbon Copy Recipient list */
693 options |= OPT_SENDMODE;
694 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
695 break;
696 case 'c':
697 /* Get Carbon Copy Recipient list */
698 options |= OPT_SENDMODE;
699 cc = cat(cc, lextract(_oarg, GCC | GFULL));
700 break;
701 case 'D':
702 #ifdef HAVE_IMAP
703 ok_bset(disconnected, TRU1);
704 okey = "disconnected";
705 goto joarg;
706 #else
707 break;
708 #endif
709 case 'd':
710 ok_bset(debug, TRU1);
711 okey = "debug";
712 goto joarg;
713 case 'E':
714 ok_bset(skipemptybody, TRU1);
715 okey = "skipemptybody";
716 goto joarg;
717 case 'e':
718 options |= OPT_EXISTONLY;
719 break;
720 case 'F':
721 options |= OPT_F_FLAG | OPT_SENDMODE;
722 break;
723 case 'f':
724 /* User is specifying file to "edit" with Mail, as opposed to reading
725 * system mailbox. If no argument is given, we read his mbox file.
726 * Check for remaining arguments later */
727 folder = "&";
728 break;
729 case 'H':
730 options |= OPT_HEADERSONLY;
731 break;
732 case 'h':
733 fprintf(stderr, V_(usagestr) _USAGE_ARGS);
734 goto jleave;
735 case 'i':
736 /* Ignore interrupts */
737 ok_bset(ignore, TRU1);
738 okey = "ignore";
739 goto joarg;
740 case 'L':
741 Larg = _oarg;
742 options |= OPT_HEADERLIST;
743 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
744 size_t j = strlen(++Larg);
745 if (j > 0)
746 Larg[j - 1] = '\0';
748 break;
749 case 'N':
750 /* Avoid initial header printing */
751 ok_bset(header, FAL0);
752 okey = "noheader";
753 goto joarg;
754 case 'n':
755 /* Don't source "unspecified system start-up file" */
756 options |= OPT_NOSRC;
757 break;
758 case 'O':
759 /* Additional options to pass-through to MTA TODO v15-compat legacy */
760 if (smopts_count == (size_t)smopts_size)
761 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_count);
762 smopts[smopts_count++] = _oarg;
763 break;
764 case 'q':
765 /* Quote file TODO drop? -Q with real quote?? what ? */
766 options |= OPT_SENDMODE;
767 if (*_oarg != '-')
768 qf = _oarg;
769 break;
770 case 'R':
771 /* Open folders read-only */
772 options |= OPT_R_FLAG;
773 break;
774 case 'r':
775 /* Set From address. */
776 options |= OPT_r_FLAG;
777 if (_oarg[0] != '\0') {
778 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
780 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
781 fprintf(stderr, _("Invalid address argument with -r\n"));
782 goto jusage;
784 option_r_arg = fa;
785 /* TODO -r options is set in smopts, but may
786 * TODO be overwritten by setting from= in
787 * TODO an interactive session!
788 * TODO Maybe disable setting of from?
789 * TODO Warn user? Update manual!! */
790 okey = savecat("from=", fa->n_fullname);
791 goto joarg;
793 break;
794 case 'S':
795 /* Set variable (twice) */
796 { char *a[2];
797 okey = a[0] = _oarg;
798 a[1] = NULL;
799 c_set(a);
801 joarg:
802 if (oargs_count == oargs_size)
803 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_count);
804 oargs[oargs_count++] = okey;
805 break;
806 case 's':
807 /* Subject: */
808 subject = _oarg;
809 options |= OPT_SENDMODE;
810 break;
811 case 't':
812 /* Read defined set of headers from mail to be send */
813 options |= OPT_SENDMODE | OPT_t_FLAG;
814 break;
815 case 'u':
816 /* Set user name to pretend to be; don't set OPT_u_FLAG yet, this is
817 * done as necessary in _setup_vars() above */
818 myname = _oarg;
819 break;
820 case 'V':
821 puts(ok_vlook(version));
822 exit(0);
823 /* NOTREACHED */
824 case 'v':
825 /* Be verbose */
826 ok_bset(verbose, TRU1);
827 okey = "verbose";
828 goto joarg;
829 case 'X': {
830 size_t l = strlen(_oarg);
831 struct X_arg *nxp = smalloc(sizeof(*nxp) -
832 VFIELD_SIZEOF(struct X_arg, xa_cmd_buf) + l +1);
833 if (X_head == NULL)
834 X_head = nxp;
835 else
836 X_curr->xa_next = nxp;
837 X_curr = nxp;
838 nxp->xa_next = NULL;
839 nxp->xa_cmd_len = l;
840 memcpy(nxp->xa_cmd_buf, _oarg, l +1);
842 break;
843 case '~':
844 /* Enable tilde escapes even in non-interactive mode */
845 options |= OPT_TILDE_FLAG;
846 break;
847 case '#':
848 /* Work in batch mode, even if non-interactive */
849 if (oargs_count + 6 >= oargs_size)
850 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_count);
851 /* xxx Setting most of the -# options immediately is useless, so be
852 * selective in what is set immediately */
853 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
854 folder = "/dev/null";
855 ok_bset(dot, TRU1);
856 ok_bset(emptystart, TRU1);
857 ok_bset(header, FAL0);
858 ok_bset(quiet, TRU1);
859 ok_bset(sendwait, TRU1);
860 ok_vset(MBOX, folder);
861 oargs[oargs_count + 0] = "dot";
862 oargs[oargs_count + 1] = "emptystart";
863 oargs[oargs_count + 2] = "noheader";
864 oargs[oargs_count + 3] = "quiet";
865 oargs[oargs_count + 4] = "sendwait";
866 oargs[oargs_count + 5] = "MBOX=/dev/null";
867 oargs_count += 6;
868 break;
869 case '.':
870 options |= OPT_SENDMODE;
871 goto jgetopt_done;
872 case '?':
873 jusage:
874 fprintf(stderr, V_(usagestr) _USAGE_ARGS);
875 #undef _USAGE_ARGS
876 exit_status = EXIT_USE;
877 goto jleave;
880 jgetopt_done:
883 /* The normal arguments may be followed by MTA arguments after a "--";
884 * however, -f may take off an argument, too, and before that.
885 * Since MTA arguments after "--" require *expandargv*, delay parsing off
886 * those options until after the resource files are loaded... */
887 if ((cp = argv[i = _oind]) == NULL)
889 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
890 ++i;
891 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
892 else if (folder != NULL && folder[1] == '\0') {
893 folder = cp;
894 if ((cp = argv[++i]) != NULL) {
895 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
896 fprintf(stderr, _("More than one file given with -f\n"));
897 goto jusage;
899 ++i;
901 } else {
902 options |= OPT_SENDMODE;
903 for (;;) {
904 to = cat(to, lextract(cp, GTO | GFULL));
905 if ((cp = argv[++i]) == NULL)
906 break;
907 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
908 ++i;
909 break;
913 _oind = i;
915 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
916 * allocate the necessary space for them before we call spreserve()! */
917 while (argv[i] != NULL)
918 ++i;
919 if (smopts_count + i > smopts_size)
920 DBG(smopts_size =) _grow_cpp(&smopts, smopts_count + i + 1, smopts_count);
922 /* Check for inconsistent arguments */
923 if (options & OPT_SENDMODE) {
924 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
925 fprintf(stderr, _("Cannot give -f and people to send to.\n"));
926 goto jusage;
928 if (myname != NULL) {
929 fprintf(stderr, _(
930 "The -u option cannot be used in send mode\n"));
931 goto jusage;
933 if (!(options & OPT_t_FLAG) && to == NULL) {
934 fprintf(stderr, _(
935 "Send options without primary recipient specified.\n"));
936 goto jusage;
938 if (options & (OPT_HEADERSONLY | OPT_HEADERLIST)) {
939 fprintf(stderr, _(
940 "The -H and -L options cannot be used in send mode.\n"));
941 goto jusage;
943 if (options & OPT_R_FLAG) {
944 fprintf(stderr,
945 _("The -R option is meaningless in send mode.\n"));
946 goto jusage;
948 } else {
949 if (folder != NULL && myname != NULL) {
950 fprintf(stderr, _(
951 "The options -f and -u are mutually exclusive\n"));
952 goto jusage;
957 * Likely to go, perform more setup
960 _setup_vars();
962 if (options & OPT_INTERACTIVE) {
963 _setscreensize(0);
964 #ifdef SIGWINCH
965 # ifndef TTY_WANTS_SIGWINCH
966 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
967 # endif
968 safe_signal(SIGWINCH, _setscreensize);
969 #endif
970 } else
971 scrnheight = realscreenheight = 24, scrnwidth = 80;
973 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
974 spreserve();
976 if (!(options & OPT_NOSRC) && !env_blook("NAIL_NO_SYSTEM_RC", TRU1))
977 load(SYSCONFRC);
978 /* *expand() returns a savestr(), but load only uses the file name for
979 * fopen(), so it's safe to do this */
980 if ((cp = env_vlook("MAILRC", TRU1)) == NULL)
981 cp = UNCONST(MAILRC);
982 load(file_expand(cp));
983 if (env_vlook("NAIL_EXTRA_RC", TRU1) == NULL &&
984 (cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
985 load(file_expand(cp));
987 /* We had to wait until the resource files are loaded but it is time to get
988 * the termcap going, so that *term-ca-mode* won't hide our output for us */
989 #ifdef HAVE_TERMCAP
990 if ((options & (OPT_INTERACTIVE | OPT_HEADERSONLY | OPT_HEADERLIST))
991 == OPT_INTERACTIVE)
992 termcap_init(); /* TODO program state machine */
993 #endif
995 /* Now we can set the account */
996 if (Aarg != NULL) {
997 char const *a[2];
998 a[0] = Aarg;
999 a[1] = NULL;
1000 c_account(a);
1003 /* Ensure the -S and other command line options take precedence over
1004 * anything that may have been placed in resource files.
1005 * Our "ternary binary" option *verbose* needs special treament */
1006 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
1007 options &= ~OPT_VERB;
1008 for (i = 0; UICMP(z, i, <, oargs_count); ++i) {
1009 char const *a[2];
1010 a[0] = oargs[i];
1011 a[1] = NULL;
1012 c_set(a);
1015 /* Additional options to pass-through to MTA, and allowed to do so? */
1016 if ((cp = ok_vlook(expandargv)) != NULL) {
1017 bool_t isfail = !asccasecmp(cp, "fail"),
1018 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
1020 if ((cp = argv[i = _oind]) != NULL) {
1021 if (isfail ||
1022 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
1023 fprintf(stderr,
1024 _("*expandargv* doesn't allow additional MTA argument\n"));
1025 exit_status = EXIT_USE | EXIT_SEND_ERROR;
1026 goto jleave;
1028 do {
1029 assert(smopts_count + 1 <= smopts_size);
1030 smopts[smopts_count++] = cp;
1031 } while ((cp = argv[++i]) != NULL);
1036 * We're finally completely setup and ready to go
1039 pstate |= PS_STARTED;
1041 if (options & OPT_DEBUG)
1042 fprintf(stderr, _("user = %s, homedir = %s\n"), myname, homedir);
1044 if (!(options & OPT_SENDMODE)) {
1045 exit_status = _rcv_mode(folder, Larg, X_head);
1046 goto jleave;
1049 /* xxx exit_status = EXIT_OK; */
1050 if (X_head == NULL || _X_arg_eval(X_head)) {
1051 /* Now that full mailx(1)-style file expansion is possible handle the
1052 * attachments which we had delayed due to this.
1053 * This may use savestr(), but since we won't enter the command loop we
1054 * don't need to care about that */
1055 while (a_head != NULL) {
1056 attach = add_attachment(attach, a_head->aa_file, NULL);
1057 if (attach != NULL) {
1058 a_curr = a_head;
1059 a_head = a_head->aa_next;
1060 } else {
1061 perror(a_head->aa_file);
1062 exit_status = EXIT_ERR;
1063 goto jleave;
1067 if (options & OPT_INTERACTIVE)
1068 tty_init();
1069 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1070 if (options & OPT_INTERACTIVE)
1071 tty_destroy();
1074 jleave:
1075 #ifdef HAVE_TERMCAP
1076 if (options & OPT_INTERACTIVE)
1077 termcap_destroy();
1078 #endif
1079 #ifdef HAVE_DEBUG
1080 sreset(FAL0);
1081 smemcheck();
1082 #endif
1083 NYD_LEAVE;
1084 return exit_status;
1087 FL int
1088 c_rexit(void *v) /* TODO program state machine */
1090 UNUSED(v);
1091 NYD_ENTER;
1093 if (!(pstate & PS_SOURCING)) {
1094 #ifdef HAVE_TERMCAP
1095 if (options & OPT_INTERACTIVE)
1096 termcap_destroy();
1097 #endif
1098 exit(0);
1100 NYD_LEAVE;
1101 return 1;
1104 /* s-it-mode */