Add -: command line option (Robert Elz)..
[s-mailx.git] / main.c
blob220b3f2df84a569966b1df84b7aa31e228309821
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;
251 if (isatty(STDOUT_FILENO))
252 options |= OPT_TTYOUT;
253 if ((options & (OPT_TTYIN | OPT_TTYOUT)) == (OPT_TTYIN | OPT_TTYOUT)) {
254 options |= OPT_INTERACTIVE;
255 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
258 /* -- >8 -- 8< -- */
260 /* Define defaults for internal variables, based on POSIX 2008/Cor 1-2013 */
261 /* (Keep in sync:
262 * ./main.c:_startup(), ./nail.rc, ./nail.1:"Initial settings") */
263 /* noallnet */
264 /* noappend */
265 ok_bset(asksub, TRU1);
266 /* noaskbcc */
267 /* noaskcc */
268 /* noautoprint */
269 /* nobang */
270 /* nocmd */
271 /* nocrt */
272 /* nodebug */
273 /* nodot */
274 /* ok_vset(escape, ESCAPE *"~"*); TODO non-compliant */
275 /* noflipr */
276 /* nofolder */
277 ok_bset(header, TRU1);
278 /* nohold */
279 /* noignore */
280 /* noignoreeof */
281 /* nokeep */
282 /* nokeepsave */
283 /* nometoo */
284 /* noonehop -- Note: we ignore this one */
285 /* nooutfolder */
286 /* nopage */
287 ok_vset(prompt, "\\& "); /* POSIX "? " unless *bsdcompat*, then "& " */
288 /* noquiet */
289 /* norecord */
290 ok_bset(save, TRU1);
291 /* nosendwait */
292 /* noshowto */
293 /* nosign */
294 /* noSign */
295 /* ok_vset(toplines, "5"); XXX somewhat hmm */
297 /* TODO until we have an automatic mechanism for that, set some more
298 * TODO variables so that users see the internal fallback settings
299 * TODO (something like "defval=X,notempty=1") */
300 do {
301 char const *vp;
303 vp = env_vlook("SHELL", TRU1);
304 ok_vset(SHELL, (vp != NULL ? vp : XSHELL));
306 vp = env_vlook("LISTER", TRU1);
307 ok_vset(LISTER, (vp != NULL ? vp : XLISTER));
309 vp = env_vlook("PAGER", TRU1);
310 ok_vset(PAGER, (vp != NULL ? vp : XPAGER));
312 ok_vset(sendmail, SENDMAIL);
313 ok_vset(sendmail_progname, SENDMAIL_PROGNAME);
314 } while (0);
316 /* -- >8 -- 8< -- */
318 #ifdef HAVE_SETLOCALE
319 setlocale(LC_ALL, "");
320 mb_cur_max = MB_CUR_MAX;
321 # ifdef HAVE_NL_LANGINFO
322 if (ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
323 ok_vset(ttycharset, cp);
324 # endif
326 # ifdef HAVE_C90AMEND1
327 if (mb_cur_max > 1) {
328 wchar_t wc;
329 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
330 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
331 options |= OPT_UNICODE;
332 /* Reset possibly messed up state; luckily this also gives us an
333 * indication wether the encoding has locking shift state sequences */
334 /* TODO temporary - use option bits! */
335 if (mbtowc(&wc, NULL, mb_cur_max))
336 options |= OPT_ENC_MBSTATE;
338 # endif
339 #else
340 mb_cur_max = 1;
341 #endif
343 #ifdef HAVE_ICONV
344 iconvd = (iconv_t)-1;
345 #endif
346 NYD_LEAVE;
349 static size_t
350 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
352 /* Before spreserve(): use our string pool instead of LibC heap */
353 char const **newcpp;
354 NYD_ENTER;
356 newcpp = salloc(sizeof(char*) * newsize);
358 if (oldcnt > 0)
359 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
360 *cpp = newcpp;
361 NYD_LEAVE;
362 return newsize;
365 static void
366 _setup_vars(void)
368 /* Before spreserve(): use our string pool instead of LibC heap */
369 /* XXX further check paths? */
370 char const *cp;
371 uid_t uid;
372 struct passwd *pwuid, *pw;
373 NYD_ENTER;
375 /* Verify and fixate user identification */
376 if (myname != NULL)
377 cp = myname;
378 else if ((cp = env_vlook("LOGNAME", TRU1)) == NULL)
379 cp = env_vlook("USER", TRU1);
381 group_id = getgid();
382 user_id = uid = getuid();
383 if ((pwuid = getpwuid(uid)) == NULL)
384 n_panic(_("Cannot associate a name with uid %u"), user_id);
386 if (cp == NULL || *cp == '\0')
387 myname = pwuid->pw_name;
388 else if ((pw = getpwnam(cp)) == NULL) {
389 n_alert(_("\"%s\" is not a user of this system"), cp);
390 exit(EXIT_NOUSER);
391 } else {
392 myname = pw->pw_name;
393 if (pw->pw_uid != uid)
394 options |= OPT_u_FLAG;
396 myname = savestr(myname);
397 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
399 /* */
400 if ((cp = env_vlook("HOME", TRU1)) == NULL)
401 cp = "."; /* XXX User and Login objects; Login: pw->pw_dir */
402 homedir = savestr(cp);
404 tempdir = ((cp = env_vlook("TMPDIR", TRU1)) != NULL)
405 ? savestr(cp) : TMPDIR_FALLBACK;
406 NYD_LEAVE;
409 static void
410 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
412 struct termios tbuf;
413 #ifdef TIOCGWINSZ
414 struct winsize ws;
415 #elif defined TIOCGSIZE
416 struct ttysize ts;
417 #endif
418 NYD_ENTER;
420 scrnheight = realscreenheight = scrnwidth = 0;
422 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
423 * a little bit to be able to honour resizes during our lifetime and
424 * only honour it upon first run; abuse *is_sighdl* as an indicator */
425 if (!is_sighdl) {
426 char *cp;
427 long i;
429 if ((cp = env_vlook("LINES", FAL0)) != NULL &&
430 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
431 scrnheight = realscreenheight = (int)i;
432 if ((cp = env_vlook("COLUMNS", FAL0)) != NULL &&
433 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
434 scrnwidth = (int)i;
436 if (scrnwidth != 0 && scrnheight != 0)
437 goto jleave;
440 #ifdef TIOCGWINSZ
441 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
442 ws.ws_col = ws.ws_row = 0;
443 #elif defined TIOCGSIZE
444 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
445 ts.ts_lines = ts.ts_cols = 0;
446 #endif
448 if (scrnheight == 0) {
449 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
450 ? B9600 : cfgetospeed(&tbuf));
452 if (ospeed < B1200)
453 scrnheight = 9;
454 else if (ospeed == B1200)
455 scrnheight = 14;
456 #ifdef TIOCGWINSZ
457 else if (ws.ws_row != 0)
458 scrnheight = ws.ws_row;
459 #elif defined TIOCGSIZE
460 else if (ts.ts_lines != 0)
461 scrnheight = ts.ts_lines;
462 #endif
463 else
464 scrnheight = 24;
466 #if defined TIOCGWINSZ || defined TIOCGSIZE
467 if (0 ==
468 # ifdef TIOCGWINSZ
469 (realscreenheight = ws.ws_row)
470 # else
471 (realscreenheight = ts.ts_lines)
472 # endif
474 realscreenheight = 24;
475 #endif
478 if (scrnwidth == 0 && 0 ==
479 #ifdef TIOCGWINSZ
480 (scrnwidth = ws.ws_col)
481 #elif defined TIOCGSIZE
482 (scrnwidth = ts.ts_cols)
483 #endif
485 scrnwidth = 80;
487 jleave:
488 #ifdef SIGWINCH
489 if (is_sighdl && (options & OPT_INTERACTIVE))
490 n_tty_signal(SIGWINCH);
491 #endif
492 NYD_LEAVE;
495 static sigjmp_buf __hdrjmp; /* XXX */
497 static int
498 _rcv_mode(char const *folder, char const *Larg, struct X_arg *xhp)
500 int i;
501 sighandler_type prevint;
502 NYD_ENTER;
504 if (folder == NULL)
505 folder = "%";
507 if (options & OPT_QUICKRUN_MASK)
508 i = FEDIT_RDONLY;
509 else
510 i = FEDIT_NONE;
511 i = setfile(folder, i);
512 if (i < 0) {
513 exit_status = EXIT_ERR; /* error already reported */
514 goto jquit;
516 if (options & OPT_QUICKRUN_MASK) {
517 exit_status = i;
518 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
519 (options & OPT_HEADERLIST)))
520 print_header_summary(Larg);
521 goto jquit;
523 check_folder_hook(FAL0);
525 if (i > 0 && !ok_blook(emptystart)) {
526 exit_status = EXIT_ERR;
527 goto jleave;
530 if (sigsetjmp(__hdrjmp, 1) == 0) {
531 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
532 safe_signal(SIGINT, _hdrstop);
533 if (!(options & OPT_N_FLAG)) {
534 if (!ok_blook(quiet))
535 printf(_("%s version %s. Type ? for help.\n"),
536 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
537 announce(1);
538 fflush(stdout);
540 safe_signal(SIGINT, prevint);
543 /* Enter the command loop */
544 if (xhp == NULL || _X_arg_eval(xhp)) {
545 if (options & OPT_INTERACTIVE)
546 n_tty_init();
547 commands();
548 if (options & OPT_INTERACTIVE)
549 n_tty_destroy();
552 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
553 safe_signal(SIGHUP, SIG_IGN);
554 safe_signal(SIGINT, SIG_IGN);
555 safe_signal(SIGQUIT, SIG_IGN);
557 jquit:
558 save_mbox_for_possible_quitstuff();
559 quit();
560 jleave:
561 NYD_LEAVE;
562 return exit_status;
565 static void
566 _hdrstop(int signo)
568 NYD_X; /* Signal handler */
569 UNUSED(signo);
571 fflush(stdout);
572 n_err_sighdl(_("\nInterrupt\n"));
573 siglongjmp(__hdrjmp, 1);
576 static bool_t
577 _X_arg_eval(struct X_arg *xhp) /* TODO error handling not right */
579 struct eval_ctx ev;
580 struct X_arg *xp;
581 bool_t rv = TRU1;
582 NYD_ENTER;
584 while ((xp = xhp) != NULL) {
585 xhp = xp->xa_next;
587 memset(&ev, 0, sizeof ev);
588 ev.ev_line.s = xp->xa_cmd_buf;
589 ev.ev_line.l = xp->xa_cmd_len;
590 ev.ev_is_recursive = TRU1;
591 pstate &= ~PS_HOOK_MASK;
592 rv = (evaluate(&ev) == 0);
593 free(xp);
595 if (!rv) {
596 if (exit_status == EXIT_OK)
597 exit_status = EXIT_ERR;
598 break;
600 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
601 if (exit_status != EXIT_OK)
602 break;
603 if (pstate & PS_EVAL_ERROR) {
604 exit_status = EXIT_ERR;
605 break;
609 NYD_LEAVE;
610 return rv;
614 main(int argc, char *argv[])
616 static char const optstr[] = "A:a:Bb:c:dEeFfHhiL:NnO:q:Rr:S:s:tu:VvX:::~#.",
617 usagestr[] = N_(
618 " Synopsis:\n"
619 " %s -h | --help\n"
620 " %s [-BdEFintv~] [-: spec] [-A account]\n"
621 "\t [-a attachment] [-b bcc-address] [-c cc-address]\n"
622 "\t [-q file] [-r from-address] [-S var[=value]...]\n"
623 "\t [-s subject] [-X cmd] [-.] to-address... [-- mta-option...]\n"
624 " %s [-BdEeHiNnRv~#] [-: spec] [-A account]\n"
625 "\t [-L spec-list] [-r from-address] [-S var[=value]...]\n"
626 "\t [-X cmd] -f [file] [-- mta-option...]\n"
627 " %s [-BdEeHiNnRv~#] [-: spec] [-A account]\n"
628 "\t [-L spec-list] [-r from-address] [-S var[=value]...]\n"
629 "\t [-u user] [-X cmd] [-- mta-option...]\n"
631 #define _USAGE_ARGS , progname, progname, progname, progname
633 struct X_arg *X_head = NULL, *X_curr = /* silence CC */ NULL;
634 struct a_arg *a_head = NULL, *a_curr = /* silence CC */ NULL;
635 struct name *to = NULL, *cc = NULL, *bcc = NULL;
636 struct attachment *attach = NULL;
637 char *cp = NULL, *subject = NULL, *qf = NULL, *Aarg = NULL, *Larg = NULL;
638 char const *okey, **oargs = NULL, *folder = NULL, *emsg = NULL;
639 size_t oargs_size = 0, oargs_count = 0, smopts_size = 0;
640 enum{
641 a_RF_NONE = 0,
642 a_RF_SET = 1<<0,
643 a_RF_SYSTEM = 1<<1,
644 a_RF_USER = 1<<2,
645 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
646 } resfiles;
647 int i;
648 NYD_ENTER;
650 resfiles = a_RF_ALL;
653 * Start our lengthy setup, finalize by setting PS_STARTED
656 progname = argv[0];
657 _startup();
659 /* Command line parsing
660 * Variable settings need to be done twice, since the user surely wants the
661 * setting to take effect immediately, but also doesn't want it to be
662 * overwritten from within resource files */
663 while ((i = _getopt(argc, argv, optstr)) >= 0) {
664 switch (i) {
665 case 'A':
666 /* Execute an account command later on */
667 Aarg = _oarg;
668 break;
669 case 'a':
670 options |= OPT_SENDMODE;
671 { struct a_arg *nap = salloc(sizeof(struct a_arg));
672 if (a_head == NULL)
673 a_head = nap;
674 else
675 a_curr->aa_next = nap;
676 nap->aa_next = NULL;
677 nap->aa_file = _oarg;
678 a_curr = nap;
680 break;
681 case 'B':
682 /* Make 0/1 line buffered */
683 setvbuf(stdin, NULL, _IOLBF, 0);
684 setvbuf(stdout, NULL, _IOLBF, 0);
685 break;
686 case 'b':
687 /* Get Blind Carbon Copy Recipient list */
688 options |= OPT_SENDMODE;
689 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
690 break;
691 case 'c':
692 /* Get Carbon Copy Recipient list */
693 options |= OPT_SENDMODE;
694 cc = cat(cc, lextract(_oarg, GCC | GFULL));
695 break;
696 case 'd':
697 ok_bset(debug, TRU1);
698 okey = "debug";
699 goto joarg;
700 case 'E':
701 ok_bset(skipemptybody, TRU1);
702 okey = "skipemptybody";
703 goto joarg;
704 case 'e':
705 options |= OPT_EXISTONLY;
706 break;
707 case 'F':
708 options |= OPT_F_FLAG | OPT_SENDMODE;
709 break;
710 case 'f':
711 /* User is specifying file to "edit" with Mail, as opposed to reading
712 * system mailbox. If no argument is given, we read his mbox file.
713 * Check for remaining arguments later */
714 folder = "&";
715 break;
716 case 'H':
717 options |= OPT_HEADERSONLY;
718 break;
719 case 'h':
720 n_err(V_(usagestr) _USAGE_ARGS);
721 goto jleave;
722 case 'i':
723 /* Ignore interrupts */
724 ok_bset(ignore, TRU1);
725 okey = "ignore";
726 goto joarg;
727 case 'L':
728 Larg = _oarg;
729 options |= OPT_HEADERLIST;
730 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
731 size_t j = strlen(++Larg);
732 if (j > 0)
733 Larg[j - 1] = '\0';
735 break;
736 case 'N':
737 /* Avoid initial header printing */
738 ok_bset(header, FAL0);
739 okey = "noheader";
740 goto joarg;
741 case 'n':
742 /* Don't source "unspecified system start-up file" */
743 if(resfiles & a_RF_SET){
744 emsg = N_("-n cannot be used in conjunction with -:");
745 goto jusage;
747 resfiles = a_RF_USER;
748 break;
749 case 'O':
750 /* Additional options to pass-through to MTA TODO v15-compat legacy */
751 if (smopts_count == (size_t)smopts_size)
752 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_count);
753 smopts[smopts_count++] = _oarg;
754 break;
755 case 'q':
756 /* Quote file TODO drop? -Q with real quote?? what ? */
757 options |= OPT_SENDMODE;
758 if (*_oarg != '-')
759 qf = _oarg;
760 break;
761 case 'R':
762 /* Open folders read-only */
763 options |= OPT_R_FLAG;
764 break;
765 case 'r':
766 /* Set From address. */
767 options |= OPT_r_FLAG;
768 if (_oarg[0] != '\0') {
769 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
771 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
772 emsg = N_("Invalid address argument with -r");
773 goto jusage;
775 option_r_arg = fa;
776 /* TODO -r options is set in smopts, but may
777 * TODO be overwritten by setting from= in
778 * TODO an interactive session!
779 * TODO Maybe disable setting of from?
780 * TODO Warn user? Update manual!! */
781 okey = savecat("from=", fa->n_fullname);
782 goto joarg;
784 break;
785 case 'S':
786 /* Set variable (twice) */
787 { char *a[2];
788 okey = a[0] = _oarg;
789 a[1] = NULL;
790 c_set(a);
792 joarg:
793 if (oargs_count == oargs_size)
794 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_count);
795 oargs[oargs_count++] = okey;
796 break;
797 case 's':
798 /* Subject: */
799 subject = _oarg;
800 options |= OPT_SENDMODE;
801 break;
802 case 't':
803 /* Read defined set of headers from mail to be send */
804 options |= OPT_SENDMODE | OPT_t_FLAG;
805 break;
806 case 'u':
807 /* Set user name to pretend to be; don't set OPT_u_FLAG yet, this is
808 * done as necessary in _setup_vars() above */
809 myname = _oarg;
810 break;
811 case 'V':
812 puts(ok_vlook(version));
813 exit(EXIT_OK);
814 /* NOTREACHED */
815 case 'v':
816 /* Be verbose */
817 ok_bset(verbose, TRU1);
818 okey = "verbose";
819 goto joarg;
820 case 'X': {
821 /* Add to list of commands to exec before entering normal operation */
822 size_t l = strlen(_oarg);
823 struct X_arg *nxp = smalloc(sizeof(*nxp) -
824 VFIELD_SIZEOF(struct X_arg, xa_cmd_buf) + l +1);
825 if (X_head == NULL)
826 X_head = nxp;
827 else
828 X_curr->xa_next = nxp;
829 X_curr = nxp;
830 nxp->xa_next = NULL;
831 nxp->xa_cmd_len = l;
832 memcpy(nxp->xa_cmd_buf, _oarg, l +1);
834 break;
835 case ':':
836 /* Control which resource files shall be loaded */
837 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
838 emsg = N_("-n cannot be used in conjunction with -:");
839 goto jusage;
841 resfiles = a_RF_SET;
842 while((i = *_oarg++) != '\0')
843 switch(i){
844 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
845 case 'U': case 'u': resfiles |= a_RF_USER; break;
846 case ':': case '/': resfiles &= ~a_RF_ALL; break;
847 default:
848 emsg = N_("Invalid argument of -:");
849 goto jusage;
851 break;
852 case '~':
853 /* Enable tilde escapes even in non-interactive mode */
854 options |= OPT_TILDE_FLAG;
855 break;
856 case '#':
857 /* Work in batch mode, even if non-interactive */
858 if (oargs_count + 5 >= oargs_size)
859 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_count);
860 /* xxx Setting most of the -# options immediately is useless, so be
861 * selective in what is set immediately */
862 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
863 folder = "/dev/null";
864 ok_bset(emptystart, TRU1);
865 ok_bset(header, FAL0);
866 ok_bset(quiet, TRU1);
867 ok_bset(sendwait, TRU1);
868 ok_vset(MBOX, folder);
869 oargs[oargs_count + 0] = "emptystart";
870 oargs[oargs_count + 1] = "noheader";
871 oargs[oargs_count + 2] = "quiet";
872 oargs[oargs_count + 3] = "sendwait";
873 oargs[oargs_count + 4] = "MBOX=/dev/null";
874 oargs_count += 5;
875 break;
876 case '.':
877 options |= OPT_SENDMODE;
878 goto jgetopt_done;
879 case '?':
880 jusage:
881 if (emsg != NULL)
882 n_err("%s\n", V_(emsg));
883 n_err(V_(usagestr) _USAGE_ARGS);
884 #undef _USAGE_ARGS
885 exit_status = EXIT_USE;
886 goto jleave;
889 jgetopt_done:
892 /* The normal arguments may be followed by MTA arguments after a "--";
893 * however, -f may take off an argument, too, and before that.
894 * Since MTA arguments after "--" require *expandargv*, delay parsing off
895 * those options until after the resource files are loaded... */
896 if ((cp = argv[i = _oind]) == NULL)
898 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
899 ++i;
900 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
901 else if (folder != NULL && folder[1] == '\0') {
902 folder = cp;
903 if ((cp = argv[++i]) != NULL) {
904 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
905 emsg = N_("More than one file given with -f");
906 goto jusage;
908 ++i;
910 } else {
911 options |= OPT_SENDMODE;
912 for (;;) {
913 to = cat(to, lextract(cp, GTO | GFULL));
914 if ((cp = argv[++i]) == NULL)
915 break;
916 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
917 ++i;
918 break;
922 _oind = i;
924 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
925 * allocate the necessary space for them before we call spreserve()! */
926 while (argv[i] != NULL)
927 ++i;
928 if (smopts_count + i > smopts_size)
929 DBG(smopts_size =) _grow_cpp(&smopts, smopts_count + i + 1, smopts_count);
931 /* Check for inconsistent arguments */
932 if (options & OPT_SENDMODE) {
933 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
934 emsg = N_("Cannot give -f and people to send to.");
935 goto jusage;
937 if (myname != NULL) {
938 emsg = N_("The -u option cannot be used in send mode");
939 goto jusage;
941 if (!(options & OPT_t_FLAG) && to == NULL) {
942 emsg = N_("Send options without primary recipient specified.");
943 goto jusage;
945 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
946 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
947 goto jusage;
949 if (options & OPT_R_FLAG) {
950 emsg = N_("The -R option is meaningless in send mode.");
951 goto jusage;
953 } else {
954 if (folder != NULL && myname != NULL) {
955 emsg = N_("The options -f and -u are mutually exclusive");
956 goto jusage;
958 if ((options & (OPT_EXISTONLY | OPT_HEADERSONLY)) ==
959 (OPT_EXISTONLY | OPT_HEADERSONLY)) {
960 emsg = N_("The options -e and -H are mutual exclusive");
961 goto jusage;
963 if ((options & (OPT_HEADERSONLY | OPT_HEADERLIST)) == /* TODO OBSOLETE */
964 (OPT_HEADERSONLY | OPT_HEADERLIST))
965 OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
969 * Likely to go, perform more setup
972 _setup_vars();
974 if (options & OPT_INTERACTIVE) {
975 _setscreensize(0);
976 #ifdef SIGWINCH
977 # ifndef TTY_WANTS_SIGWINCH
978 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
979 # endif
980 safe_signal(SIGWINCH, _setscreensize);
981 #endif
982 } else
983 scrnheight = realscreenheight = 24, scrnwidth = 80;
985 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
986 spreserve();
988 /* load() any resource files */
989 if(resfiles & a_RF_ALL){
990 /* *expand() returns a savestr(), but load only uses the file name for
991 * fopen(), so it's safe to do this */
992 if((resfiles & a_RF_SYSTEM) && !env_blook("NAIL_NO_SYSTEM_RC", TRU1))
993 load(SYSCONFDIR "/" SYSCONFRC);
994 if(resfiles & a_RF_USER){
995 if((cp = env_vlook("MAILRC", TRU1)) == NULL)
996 cp = UNCONST(MAILRC);
997 load(file_expand(cp));
999 if(env_vlook("NAIL_EXTRA_RC", TRU1) == NULL &&
1000 (cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
1001 load(file_expand(cp));
1004 /* We had to wait until the resource files are loaded but it is time to get
1005 * the termcap going, so that *term-ca-mode* won't hide our output for us */
1006 #ifdef HAVE_TERMCAP
1007 if ((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1008 termcap_init(); /* TODO program state machine */
1009 #endif
1011 /* Now we can set the account */
1012 if (Aarg != NULL) {
1013 char const *a[2];
1014 a[0] = Aarg;
1015 a[1] = NULL;
1016 c_account(a);
1019 /* Ensure the -S and other command line options take precedence over
1020 * anything that may have been placed in resource files.
1021 * Our "ternary binary" option *verbose* needs special treament */
1022 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
1023 options &= ~OPT_VERB;
1024 for (i = 0; UICMP(z, i, <, oargs_count); ++i) {
1025 char const *a[2];
1026 a[0] = oargs[i];
1027 a[1] = NULL;
1028 c_set(a);
1031 /* Additional options to pass-through to MTA, and allowed to do so? */
1032 if ((cp = ok_vlook(expandargv)) != NULL) {
1033 bool_t isfail = !asccasecmp(cp, "fail"),
1034 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
1036 if ((cp = argv[i = _oind]) != NULL) {
1037 if (isfail ||
1038 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
1039 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
1040 "using *sendmail-arguments*\n"));
1041 exit_status = EXIT_USE | EXIT_SEND_ERROR;
1042 goto jleave;
1044 do {
1045 assert(smopts_count + 1 <= smopts_size);
1046 smopts[smopts_count++] = cp;
1047 } while ((cp = argv[++i]) != NULL);
1052 * We're finally completely setup and ready to go
1055 pstate |= PS_STARTED;
1057 if (options & OPT_DEBUG)
1058 n_err(_("user = %s, homedir = %s\n"), myname, homedir);
1060 if (!(options & OPT_SENDMODE)) {
1061 exit_status = _rcv_mode(folder, Larg, X_head);
1062 goto jleave;
1065 /* xxx exit_status = EXIT_OK; */
1066 if (X_head != NULL && !_X_arg_eval(X_head))
1067 goto jleave;
1069 /* Now that full mailx(1)-style file expansion is possible handle the
1070 * attachments which we had delayed due to this.
1071 * This may use savestr(), but since we won't enter the command loop we
1072 * don't need to care about that */
1073 for (cp = NULL; a_head != NULL;) {
1074 struct attachment *nahp, *nap;
1076 if ((nahp = add_attachment(attach, a_head->aa_file, &nap)) != NULL) {
1077 attach = nahp;
1078 /* Did we split a charset set name for fixation purposes? */
1079 if (cp != NULL) {
1080 nap->a_conv = AC_FIX_INCS;
1081 nap->a_input_charset = cp;
1082 cp = NULL;
1084 a_head = a_head->aa_next;
1085 continue;
1087 i = errno;
1089 /* It may not have worked because of an appended character set name, so
1090 * try to split name and charset and retry once */
1091 if (cp == NULL && (cp = strrchr(a_head->aa_file, '=')) != NULL) {
1092 char *ncp, *nfp = savestrbuf(a_head->aa_file,
1093 PTR2SIZE(cp - a_head->aa_file));
1095 for (ncp = ++cp; *ncp != '\0'; ++ncp)
1096 if (!alnumchar(*ncp) && !punctchar(*ncp))
1097 break;
1098 if (*ncp == '\0') {
1099 a_head->aa_file = nfp;
1100 continue;
1104 n_perr(a_head->aa_file, i);
1105 exit_status = EXIT_ERR;
1106 goto jleave;
1109 if (options & OPT_INTERACTIVE)
1110 n_tty_init();
1111 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1112 if (options & OPT_INTERACTIVE)
1113 n_tty_destroy();
1115 jleave:
1116 #ifdef HAVE_TERMCAP
1117 if (options & OPT_INTERACTIVE)
1118 termcap_destroy();
1119 #endif
1120 #ifdef HAVE_DEBUG
1121 sreset(FAL0);
1122 smemcheck();
1123 #endif
1124 NYD_LEAVE;
1125 return exit_status;
1128 FL int
1129 c_rexit(void *v) /* TODO program state machine */
1131 UNUSED(v);
1132 NYD_ENTER;
1134 if (!(pstate & PS_SOURCING)) {
1135 #ifdef HAVE_TERMCAP
1136 if (options & OPT_INTERACTIVE)
1137 termcap_destroy();
1138 #endif
1139 exit(EXIT_OK);
1141 NYD_LEAVE;
1142 return 1;
1145 /* Source the others in that case! */
1146 #ifdef HAVE_AMALGAMATION
1147 # include "config.h"
1148 #endif
1150 /* s-it-mode */