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