Implement `xcall' stack-avoidance optimization
[s-mailx.git] / main.c
blob2f0cebc696e567a5bab6be2fae37bc51d28eb28a
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 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
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 const *aa_file;
58 /* (extern, but not with amalgamation, so define here) */
59 VL char const n_weekday_names[7 + 1][4] = {
60 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ""
62 VL char const n_month_names[12 + 1][4] = {
63 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
64 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""
66 VL char const n_uagent[sizeof VAL_UAGENT] = VAL_UAGENT;
67 VL char const n_error[sizeof n_ERROR] = N_(n_ERROR);
68 VL char const n_unirepl[sizeof n_UNIREPL] = n_UNIREPL;
69 VL char const n_empty[1] = "";
70 VL char const n_0[2] = "0";
71 VL char const n_1[2] = "1";
72 VL char const n_m1[3] = "-1";
73 VL ui16_t const n_class_char[1 + 0x7F] = {
74 #define a_BC C_BLANK | C_CNTRL
75 #define a_SC C_SPACE | C_CNTRL
76 #define a_WC C_WHITE | C_CNTRL
77 /* 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel */
78 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
79 /* 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si */
80 C_CNTRL, a_BC, a_WC, a_SC, a_SC, a_SC, C_CNTRL, C_CNTRL,
81 /* 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb */
82 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
83 /* 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us */
84 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
85 #undef a_WC
86 #undef a_SC
87 #undef a_BC
88 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
89 C_BLANK, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
90 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
91 C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
92 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
93 C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL,
94 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
95 C_DIGIT, C_DIGIT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
96 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
97 C_PUNCT, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
98 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
99 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
100 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
101 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
102 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
103 C_UPPER, C_UPPER, C_UPPER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
104 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
105 C_PUNCT, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
106 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
107 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
108 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
109 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
110 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
111 C_LOWER, C_LOWER, C_LOWER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_CNTRL
114 /* Our own little getopt(3) */
115 static char const *a_main_oarg;
116 static int a_main_oind, /*_oerr,*/ a_main_oopt;
118 /* Our own little getopt(3); note --help is special-treated as 'h' */
119 static int a_main_getopt(int argc, char * const argv[], char const *optstring);
121 /* Perform basic startup initialization */
122 static void a_main_startup(void);
124 /* Grow a char** */
125 static size_t a_main_grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt);
127 /* Setup some variables which we require to be valid / verified */
128 static void a_main_setup_vars(void);
130 /* We're in an interactive session - compute what the screen size for printing
131 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
132 * We use the following algorithm for the height:
133 * If baud rate < 1200, use 9
134 * If baud rate = 1200, use 14
135 * If baud rate > 1200, use 24 or ws_row
136 * Width is either 80 or ws_col */
137 static void a_main_setscreensize(int is_sighdl);
139 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
140 * the system mailbox, and open up the right stuff */
141 static int a_main_rcv_mode(char const *folder, char const *Larg);
143 /* Interrupt printing of the headers */
144 static void a_main_hdrstop(int signo);
146 static int
147 a_main_getopt(int argc, char * const argv[], char const *optstring){
148 static char const *lastp;
150 char const *curp;
151 int rv/*, colon*/;
152 NYD_ENTER;
154 a_main_oarg = NULL;
155 rv = -1;
157 /*if((colon = (optstring[0] == ':')))
158 ++optstring;*/
160 if(lastp != NULL){
161 curp = lastp;
162 lastp = NULL;
163 }else{
164 if(a_main_oind >= argc || argv[a_main_oind] == NULL ||
165 argv[a_main_oind][0] != '-' || argv[a_main_oind][1] == '\0')
166 goto jleave;
167 if(argv[a_main_oind][1] == '-' && argv[a_main_oind][2] == '\0'){
168 /* We need this in for MTA arg detection (easier) ++a_main_oind;*/
169 goto jleave;
171 curp = &argv[a_main_oind][1];
174 for(a_main_oopt = curp[0]; optstring[0] != '\0';){
175 if(optstring[0] != a_main_oopt){
176 optstring += 1 + (optstring[1] == ':');
177 continue;
180 if(optstring[1] == ':'){
181 if(curp[1] != '\0'){
182 a_main_oarg = n_UNCONST(curp + 1);
183 ++a_main_oind;
184 }else{
185 if((a_main_oind += 2) > argc){
186 /*if(!colon *//*&& _oerr*//*)*/{
187 n_err(_("%s: option requires an argument -- %c\n"),
188 argv[0], (char)a_main_oopt);
190 rv = (/*colon ? ':' :*/ '?');
191 goto jleave;
193 a_main_oarg = argv[a_main_oind - 1];
195 }else{
196 if(curp[1] != '\0')
197 lastp = curp + 1;
198 else
199 ++a_main_oind;
201 rv = a_main_oopt;
202 goto jleave;
205 /* Special support for --help, which is quite common */
206 if(a_main_oopt == '-' && !strcmp(curp, "-help") &&
207 &curp[-1] == argv[a_main_oind]){
208 ++a_main_oind;
209 rv = 'h';
210 goto jleave;
213 /* Definitive error */
214 /*if(!colon *//*&& opterr*//*)*/
215 n_err(_("%s: invalid option -- %c\n"), argv[0], a_main_oopt);
216 if(curp[1] != '\0')
217 lastp = curp + 1;
218 else
219 ++a_main_oind;
220 a_main_oarg = NULL;
221 rv = '?';
222 jleave:
223 NYD_LEAVE;
224 return rv;
227 static void
228 a_main_startup(void){
229 char *cp;
230 NYD_ENTER;
232 n_stdin = stdin;
233 n_stdout = stdout;
234 n_stderr = stderr;
235 dflpipe = SIG_DFL;
236 a_main_oind = /*_oerr =*/ 1;
238 if((cp = strrchr(n_progname, '/')) != NULL)
239 n_progname = ++cp;
241 /* Set up a reasonable environment */
243 #ifdef HAVE_NYD
244 safe_signal(SIGABRT, &_nyd_oncrash);
245 # ifdef SIGBUS
246 safe_signal(SIGBUS, &_nyd_oncrash);
247 # endif
248 safe_signal(SIGFPE, &_nyd_oncrash);
249 safe_signal(SIGILL, &_nyd_oncrash);
250 safe_signal(SIGSEGV, &_nyd_oncrash);
251 #endif
252 command_manager_start();
254 /* TODO This is wrong: interactive is STDIN/STDERR for a POSIX sh(1).
255 * TODO For now we get this wrong, all over the place, as this software
256 * TODO has always been developed with stdout as an output channel.
257 * TODO Start doing it right for at least explicit terminal-related things,
258 * TODO but v15 should use ONLY this, also for terminal input! */
259 if(isatty(STDIN_FILENO)){
260 n_psonce |= n_PSO_TTYIN;
261 #if defined HAVE_MLE || defined HAVE_TERMCAP
262 n_tty_fp = fdopen(fileno(n_stdin), "w");
263 setvbuf(n_tty_fp, NULL, _IOLBF, 0);
264 #endif
266 if(isatty(STDOUT_FILENO))
267 n_psonce |= n_PSO_TTYOUT;
268 if((n_psonce & (n_PSO_TTYIN | n_PSO_TTYOUT)) ==
269 (n_PSO_TTYIN | n_PSO_TTYOUT)){
270 n_psonce |= n_PSO_INTERACTIVE;
271 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
274 /* STDOUT is always line buffered from our point of view */
275 setvbuf(n_stdout, NULL, _IOLBF, 0);
276 if(n_tty_fp == NULL)
277 n_tty_fp = n_stdout;
279 /* -- >8 -- 8< -- */
281 #ifndef HAVE_SETLOCALE
282 n_mb_cur_max = 1;
283 #else
284 setlocale(LC_ALL, n_empty);
285 n_mb_cur_max = MB_CUR_MAX;
286 # ifdef HAVE_NL_LANGINFO
287 if((cp = nl_langinfo(CODESET)) != NULL)
288 ok_vset(ttycharset, cp);
289 # endif
291 # ifdef HAVE_C90AMEND1
292 if(n_mb_cur_max > 1){
293 # ifdef HAVE_ALWAYS_UNICODE_LOCALE
294 n_psonce |= n_PSO_UNICODE;
295 # else
296 wchar_t wc;
297 if(mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
298 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
299 n_psonce |= n_PSO_UNICODE;
300 /* Reset possibly messed up state; luckily this also gives us an
301 * indication whether the encoding has locking shift state sequences */
302 if(mbtowc(&wc, NULL, n_mb_cur_max))
303 n_psonce |= n_PSO_ENC_MBSTATE;
304 # endif
306 # endif
307 #endif
309 #ifdef HAVE_ICONV
310 iconvd = (iconv_t)-1;
311 #endif
312 NYD_LEAVE;
315 static size_t
316 a_main_grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt){
317 /* Just use auto-reclaimed storage, it will be preserved */
318 char const **newcpp;
319 NYD_ENTER;
321 newcpp = salloc(sizeof(char*) * newsize);
323 if(oldcnt > 0)
324 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
325 *cpp = newcpp;
326 NYD_LEAVE;
327 return newsize;
330 static void
331 a_main_setup_vars(void){
332 struct passwd *pwuid;
333 char const *cp;
334 NYD_ENTER;
336 n_group_id = getgid();
337 if((pwuid = getpwuid(n_user_id = getuid())) == NULL)
338 n_panic(_("Cannot associate a name with uid %lu"), (ul_i)n_user_id);
340 /* C99 */{
341 char const *ep;
342 bool_t doenv;
344 if(!(doenv = (ep = ok_vlook(LOGNAME)) == NULL) &&
345 (doenv = strcmp(pwuid->pw_name, ep)))
346 n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
347 ep, pwuid->pw_name);
348 if(doenv){
349 n_pstate |= n_PS_ROOT;
350 ok_vset(LOGNAME, pwuid->pw_name);
351 n_pstate &= ~n_PS_ROOT;
354 if((ep = ok_vlook(USER)) != NULL && strcmp(pwuid->pw_name, ep)){
355 n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
356 ep, pwuid->pw_name);
357 n_pstate |= n_PS_ROOT;
358 ok_vset(USER, pwuid->pw_name);
359 n_pstate &= ~n_PS_ROOT;
363 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
365 /* Ensure some variables get loaded and/or verified */
367 /* This is not automatized just as $TMPDIR is for the initial setting, since
368 * we have the pwuid at hand and can simply use it! See accmacvar.c! */
369 if((cp = ok_vlook(HOME)) == NULL){
370 cp = pwuid->pw_dir;
371 n_pstate |= n_PS_ROOT;
372 ok_vset(HOME, cp);
373 n_pstate &= ~n_PS_ROOT;
376 (void)ok_vlook(TMPDIR);
377 (void)ok_blook(POSIXLY_CORRECT);
378 NYD_LEAVE;
381 static void
382 a_main_setscreensize(int is_sighdl){/* TODO globl policy; int wraps; minvals! */
383 struct termios tbuf;
384 #ifdef TIOCGWINSZ
385 struct winsize ws;
386 #elif defined TIOCGSIZE
387 struct ttysize ts;
388 #endif
389 NYD_ENTER;
391 n_scrnheight = n_realscreenheight = n_scrnwidth = 0;
393 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
394 * a little bit to be able to honour resizes during our lifetime and
395 * only honour it upon first run; abuse *is_sighdl* as an indicator */
396 if(!is_sighdl){
397 char const *cp;
399 /* We manage those variables for our child processes, so ensure they
400 * are up to date, always */
401 assert(n_psonce & n_PSO_INTERACTIVE);
402 n_pstate |= n_PS_SIGWINCH_PEND;
404 if((cp = ok_vlook(LINES)) != NULL){
405 n_idec_ui32_cp(&n_scrnheight, cp, 0, NULL);
406 n_realscreenheight = n_scrnheight;
408 if((cp = ok_vlook(COLUMNS)) != NULL)
409 n_idec_ui32_cp(&n_scrnwidth, cp, 0, NULL);
411 if(n_scrnwidth != 0 && n_scrnheight != 0)
412 goto jleave;
415 #ifdef TIOCGWINSZ
416 if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
417 ws.ws_col = ws.ws_row = 0;
418 #elif defined TIOCGSIZE
419 if(ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
420 ts.ts_lines = ts.ts_cols = 0;
421 #endif
423 if(n_scrnheight == 0){
424 speed_t ospeed;
426 ospeed = ((tcgetattr(fileno(n_tty_fp), &tbuf) == -1)
427 ? B9600 : cfgetospeed(&tbuf));
429 if(ospeed < B1200)
430 n_scrnheight = 9;
431 else if(ospeed == B1200)
432 n_scrnheight = 14;
433 #ifdef TIOCGWINSZ
434 else if(ws.ws_row != 0)
435 n_scrnheight = ws.ws_row;
436 #elif defined TIOCGSIZE
437 else if(ts.ts_lines != 0)
438 n_scrnheight = ts.ts_lines;
439 #endif
440 else
441 n_scrnheight = 24;
443 #if defined TIOCGWINSZ || defined TIOCGSIZE
444 if(0 ==
445 # ifdef TIOCGWINSZ
446 (n_realscreenheight = ws.ws_row)
447 # else
448 (n_realscreenheight = ts.ts_lines)
449 # endif
451 n_realscreenheight = 24;
452 #endif
455 if(n_scrnwidth == 0 && 0 ==
456 #ifdef TIOCGWINSZ
457 (n_scrnwidth = ws.ws_col)
458 #elif defined TIOCGSIZE
459 (n_scrnwidth = ts.ts_cols)
460 #endif
462 n_scrnwidth = 80;
464 jleave:
465 #ifdef SIGWINCH
466 if(is_sighdl){
467 assert(n_psonce & n_PSO_INTERACTIVE);
468 n_pstate |= n_PS_SIGWINCH_PEND; /* XXX Not atomic */
469 n_tty_signal(SIGWINCH);
471 #endif
472 NYD_LEAVE;
475 static sigjmp_buf a_main__hdrjmp; /* XXX */
477 static int
478 a_main_rcv_mode(char const *folder, char const *Larg){
479 int i;
480 sighandler_type prevint;
481 NYD_ENTER;
483 if(folder == NULL)
484 folder = "%";
486 i = (n_poption & n_PO_QUICKRUN_MASK) ? FEDIT_RDONLY : FEDIT_NONE;
487 i = setfile(folder, i);
488 if(i < 0){
489 n_exit_status = n_EXIT_ERR; /* error already reported */
490 goto jquit;
492 if(n_poption & n_PO_QUICKRUN_MASK){
493 n_exit_status = i;
494 if(i == n_EXIT_OK && (!(n_poption & n_PO_EXISTONLY) ||
495 (n_poption & n_PO_HEADERLIST)))
496 print_header_summary(Larg);
497 goto jquit;
499 temporary_folder_hook_check(FAL0);
501 if(i > 0 && !ok_blook(emptystart)){
502 n_exit_status = n_EXIT_ERR;
503 goto jleave;
506 if(sigsetjmp(a_main__hdrjmp, 1) == 0){
507 if((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
508 safe_signal(SIGINT, &a_main_hdrstop);
509 if(ok_blook(header)){
510 if(!ok_blook(quiet))
511 fprintf(n_stdout, _("%s version %s. Type `?' for help\n"),
512 (ok_blook(bsdcompat) ? "Mail" : n_uagent), ok_vlook(version));
513 announce(1);
514 fflush(n_stdout);
516 safe_signal(SIGINT, prevint);
519 /* Enter the command loop */
520 if(n_psonce & n_PSO_INTERACTIVE)
521 n_tty_init();
522 n_commands();
523 if(n_psonce & n_PSO_INTERACTIVE)
524 n_tty_destroy();
526 if(mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR){
527 safe_signal(SIGHUP, SIG_IGN);
528 safe_signal(SIGINT, SIG_IGN);
529 safe_signal(SIGQUIT, SIG_IGN);
531 jquit:
532 save_mbox_for_possible_quitstuff();
533 quit(FAL0);
534 jleave:
535 NYD_LEAVE;
536 return n_exit_status;
539 static void
540 a_main_hdrstop(int signo){
541 NYD_X; /* Signal handler */
542 n_UNUSED(signo);
544 fflush(n_stdout);
545 n_err_sighdl(_("\nInterrupt\n"));
546 siglongjmp(a_main__hdrjmp, 1);
550 main(int argc, char *argv[]){
551 /* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
552 static char const
553 optstr[] = "A:a:Bb:c:dEeFfHhiL:M:m:NnO:q:Rr:S:s:tu:VvX:::~#.",
554 usagestr[] = N_(
555 "Synopsis:\n"
556 " %s -h\n"
558 " %s [-BdEFintv~] [-: spec] [-A account]\n"
559 "\t [-a attachment] [-b bcc-addr] [-c cc-addr]\n"
560 "\t [-M type | -m file | -q file | -t]\n"
561 "\t [-r from-addr] [-S var[=value]..]\n"
562 "\t [-s subject] [-X cmd] [-.] to-addr.. [-- mta-option..]\n"
564 " %s [-BdEeHiNnRv~] [-: spec] [-A account]\n"
565 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
566 "\t [-u user] [-X cmd] [-- mta-option..]\n"
568 " %s [-BdEeHiNnRv~#] [-: spec] [-A account] -f\n"
569 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
570 "\t [-X cmd] [file] [-- mta-option..]\n"
572 #define _USAGE_ARGS , n_progname, n_progname, n_progname, n_progname
574 int i;
575 char *cp;
576 enum{
577 a_RF_NONE = 0,
578 a_RF_SET = 1<<0,
579 a_RF_SYSTEM = 1<<1,
580 a_RF_USER = 1<<2,
581 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
582 } resfiles;
583 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
584 char const *Aarg, *emsg, *folder, *Larg, *okey, **oargs, *qf,
585 *subject, *uarg, **Xargs;
586 struct attachment *attach;
587 struct name *to, *cc, *bcc;
588 struct a_arg *a_head, *a_curr;
589 NYD_ENTER;
591 a_head = NULL;
592 n_UNINIT(a_curr, NULL);
593 to = cc = bcc = NULL;
594 attach = NULL;
595 Aarg = emsg = folder = Larg = okey = qf = subject = uarg = NULL;
596 oargs = Xargs = NULL;
597 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
598 resfiles = a_RF_ALL;
601 * Start our lengthy setup, finalize by setting n_PSO_STARTED
604 n_progname = argv[0];
605 a_main_startup();
607 /* Command line parsing
608 * Variable settings need to be done twice, since the user surely wants the
609 * setting to take effect immediately, but also doesn't want it to be
610 * overwritten from within resource files */
611 while((i = a_main_getopt(argc, argv, optstr)) >= 0){
612 switch(i){
613 case 'A':
614 /* Execute an account command later on */
615 Aarg = a_main_oarg;
616 break;
617 case 'a':{
618 struct a_arg *nap;
620 n_psonce |= n_PSO_SENDMODE;
621 nap = salloc(sizeof(struct a_arg));
622 if(a_head == NULL)
623 a_head = nap;
624 else
625 a_curr->aa_next = nap;
626 nap->aa_next = NULL;
627 nap->aa_file = a_main_oarg;
628 a_curr = nap;
629 } break;
630 case 'B':
631 n_OBSOLETE(_("-B is obsolete, please use -# as necessary"));
632 break;
633 case 'b':
634 /* Get Blind Carbon Copy Recipient list */
635 n_psonce |= n_PSO_SENDMODE;
636 bcc = cat(bcc, lextract(a_main_oarg, GBCC | GFULL));
637 break;
638 case 'c':
639 /* Get Carbon Copy Recipient list */
640 n_psonce |= n_PSO_SENDMODE;
641 cc = cat(cc, lextract(a_main_oarg, GCC | GFULL));
642 break;
643 case 'd':
644 ok_bset(debug);
645 okey = "debug";
646 goto joarg;
647 case 'E':
648 n_OBSOLETE(_("-E will be removed, please use \"-Sskipemptybody\""));
649 ok_bset(skipemptybody);
650 okey = "skipemptybody";
651 goto joarg;
652 case 'e':
653 n_poption |= n_PO_EXISTONLY;
654 break;
655 case 'F':
656 n_poption |= n_PO_F_FLAG;
657 n_psonce |= n_PSO_SENDMODE;
658 break;
659 case 'f':
660 /* User is specifying file to "edit" with Mail, as opposed to reading
661 * system mailbox. If no argument is given, we read his mbox file.
662 * Check for remaining arguments later */
663 folder = "&";
664 break;
665 case 'H':
666 n_poption |= n_PO_HEADERSONLY;
667 break;
668 case 'h':
669 n_err(V_(usagestr) _USAGE_ARGS);
670 goto j_leave;
671 case 'i':
672 /* Ignore interrupts */
673 ok_bset(ignore);
674 okey = "ignore";
675 goto joarg;
676 case 'L':
677 Larg = a_main_oarg;
678 n_poption |= n_PO_HEADERLIST;
679 if(*Larg == '"' || *Larg == '\''){ /* TODO list.c:listspec_check() */
680 size_t j;
682 j = strlen(++Larg);
683 if(j > 0){
684 cp = savestrbuf(Larg, --j);
685 Larg = cp;
688 break;
689 case 'M':
690 if(qf != NULL && (!(n_poption & n_PO_Mm_FLAG) || qf != (char*)-1))
691 goto jeMmq;
692 n_poption_arg_Mm = a_main_oarg;
693 qf = (char*)-1;
694 if(0){
695 /* FALLTHRU*/
696 case 'm':
697 if(qf != NULL && (!(n_poption & n_PO_Mm_FLAG) || qf == (char*)-1))
698 goto jeMmq;
699 qf = a_main_oarg;
701 n_poption |= n_PO_Mm_FLAG;
702 n_psonce |= n_PSO_SENDMODE;
703 break;
704 case 'N':
705 /* Avoid initial header printing */
706 ok_bclear(header);
707 okey = "noheader";
708 goto joarg;
709 case 'n':
710 /* Don't source "unspecified system start-up file" */
711 if(resfiles & a_RF_SET){
712 emsg = N_("-n cannot be used in conjunction with -:");
713 goto jusage;
715 resfiles = a_RF_USER;
716 break;
717 case 'O':
718 /* Additional options to pass-through to MTA TODO v15-compat legacy */
719 if(n_smopts_cnt == smopts_size)
720 smopts_size = a_main_grow_cpp(&n_smopts, smopts_size + 8,
721 n_smopts_cnt);
722 n_smopts[n_smopts_cnt++] = a_main_oarg;
723 break;
724 case 'q':
725 if(qf != NULL && (n_poption & n_PO_Mm_FLAG)){
726 jeMmq:
727 emsg = N_("Only one of -M, -m or -q may be given");
728 goto jusage;
730 /* Quote file TODO drop? -Q with real quote?? what ? */
731 n_psonce |= n_PSO_SENDMODE;
732 /* Allow for now, we have to special check validity of -q- later on! */
733 qf = (a_main_oarg[0] == '-' && a_main_oarg[1] == '\0')
734 ? (char*)-1 : a_main_oarg;
735 break;
736 case 'R':
737 /* Open folders read-only */
738 n_poption |= n_PO_R_FLAG;
739 break;
740 case 'r':
741 /* Set From address. */
742 n_poption |= n_PO_r_FLAG;
743 if(a_main_oarg[0] != '\0'){
744 struct name *fa;
746 fa = nalloc(a_main_oarg, GSKIN | GFULL | GFULLEXTRA);
747 if(is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)){
748 emsg = N_("Invalid address argument with -r");
749 goto jusage;
751 n_poption_arg_r = fa;
752 /* TODO -r options is set in n_smopts, but may
753 * TODO be overwritten by setting from= in
754 * TODO an interactive session!
755 * TODO Maybe disable setting of from?
756 * TODO Warn user? Update manual!! */
757 okey = savecat("from=", fa->n_fullname);
758 goto joarg;
760 break;
761 case 'S':
762 /* Set variable (TODO twice [only if successful]) */
763 { char const *a[2];
764 bool_t b;
766 okey = a[0] = a_main_oarg;
767 a[1] = NULL;
768 n_pstate |= n_PS_ROBOT;
769 b = (c_set(a) == 0);
770 n_pstate &= ~n_PS_ROBOT;
771 if(!b)
772 break;
774 joarg:
775 if(oargs_cnt == oargs_size)
776 oargs_size = a_main_grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
777 oargs[oargs_cnt++] = okey;
778 break;
779 case 's':
780 /* Subject:; take care for Debian #419840 and strip any \r and \n */
781 if(n_anyof_cp("\n\r", subject = a_main_oarg)){
782 n_err(_("-s: normalizing away invalid ASCII NL / CR bytes\n"));
783 for(subject = cp = savestr(a_main_oarg); *cp != '\0'; ++cp)
784 if(*cp == '\n' || *cp == '\r')
785 *cp = ' ';
787 n_psonce |= n_PSO_SENDMODE;
788 break;
789 case 't':
790 /* Read defined set of headers from mail to be sent */
791 n_poption |= n_PO_t_FLAG;
792 n_psonce |= n_PSO_SENDMODE;
793 break;
794 case 'u':
795 uarg = savecat("%", a_main_oarg);
796 break;
797 case 'V':
798 fprintf(n_stdout, _("%s version %s\n"), n_uagent, ok_vlook(version));
799 n_exit_status = n_EXIT_OK;
800 goto j_leave;
801 case 'v':
802 /* Be verbose */
803 ok_bset(verbose);
804 okey = "verbose";
805 goto joarg;
806 case 'X':
807 /* Add to list of commands to exec before entering normal operation */
808 if(Xargs_cnt == Xargs_size)
809 Xargs_size = a_main_grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
810 Xargs[Xargs_cnt++] = a_main_oarg;
811 break;
812 case ':':
813 /* Control which resource files shall be loaded */
814 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
815 emsg = N_("-n cannot be used in conjunction with -:");
816 goto jusage;
818 resfiles = a_RF_SET;
819 while((i = *a_main_oarg++) != '\0')
820 switch(i){
821 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
822 case 'U': case 'u': resfiles |= a_RF_USER; break;
823 case ':': case '/': resfiles &= ~a_RF_ALL; break;
824 default:
825 emsg = N_("Invalid argument of -:");
826 goto jusage;
828 break;
829 case '~':
830 /* Enable command escapes even in non-interactive mode */
831 n_poption |= n_PO_TILDE_FLAG;
832 break;
833 case '#':
834 /* Work in batch mode, even if non-interactive */
835 if(!(n_psonce & n_PSO_INTERACTIVE))
836 setvbuf(n_stdin, NULL, _IOLBF, 0);
837 n_poption |= n_PO_TILDE_FLAG | n_PO_BATCH_FLAG;
838 if (oargs_cnt + 8 >= oargs_size)
839 oargs_size = a_main_grow_cpp(&oargs, oargs_size + 9, oargs_cnt);
840 folder = "/dev/null";
841 ok_vset(MAIL, folder);
842 ok_vset(MBOX, folder);
843 ok_bset(emptystart);
844 ok_bclear(header);
845 ok_vset(inbox, folder);
846 ok_bset(quiet);
847 ok_bset(sendwait);
848 ok_bset(typescript_mode);
849 oargs[oargs_cnt + 0] = "MAIL=/dev/null";
850 oargs[oargs_cnt + 1] = "MBOX=/dev/null";
851 oargs[oargs_cnt + 2] = "emptystart";
852 oargs[oargs_cnt + 3] = "noheader";
853 oargs[oargs_cnt + 4] = "inbox=/dev/null";
854 oargs[oargs_cnt + 5] = "quiet";
855 oargs[oargs_cnt + 6] = "sendwait";
856 oargs[oargs_cnt + 7] = "typescript-mode";
857 oargs_cnt += 8;
858 break;
859 case '.':
860 n_psonce |= n_PSO_SENDMODE;
861 goto jgetopt_done;
862 case '?':
863 jusage:
864 if(emsg != NULL)
865 n_err("%s\n", V_(emsg));
866 n_err(V_(usagestr) _USAGE_ARGS);
867 #undef _USAGE_ARGS
868 n_exit_status = n_EXIT_USE;
869 goto j_leave;
872 jgetopt_done:
875 /* The normal arguments may be followed by MTA arguments after a "--";
876 * however, -f may take off an argument, too, and before that.
877 * Since MTA arguments after "--" require *expandargv*, delay parsing off
878 * those options until after the resource files are loaded... */
879 if((cp = argv[i = a_main_oind]) == NULL)
881 else if(cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
882 ++i;
883 /* n_PO_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
884 else if(folder != NULL && /*folder[0] == '&' &&*/ folder[1] == '\0'){
885 folder = cp;
886 if((cp = argv[++i]) != NULL){
887 if(cp[0] != '-' || cp[1] != '-' || cp[2] != '\0'){
888 emsg = N_("More than one file given with -f");
889 goto jusage;
891 ++i;
893 }else{
894 n_psonce |= n_PSO_SENDMODE;
895 for(;;){
896 to = cat(to, lextract(cp, GTO | GFULL));
897 if((cp = argv[++i]) == NULL)
898 break;
899 if(cp[0] == '-' && cp[1] == '-' && cp[2] == '\0'){
900 ++i;
901 break;
905 a_main_oind = i;
907 /* ...BUT, since we use salloc() for the MTA n_smopts storage we need to
908 * allocate the necessary space for them before we fixate that storage! */
909 while(argv[i] != NULL)
910 ++i;
911 if(n_smopts_cnt + i > smopts_size)
912 DBG(smopts_size =)
913 a_main_grow_cpp(&n_smopts, n_smopts_cnt + i + 1, n_smopts_cnt);
915 /* Check for inconsistent arguments, fix some temporaries */
916 if(n_psonce & n_PSO_SENDMODE){
917 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
918 * XXX in order to function. Ideally that would not be needed */
919 if(folder != NULL && !(n_poption & n_PO_BATCH_FLAG)){
920 emsg = N_("Cannot give -f and people to send to.");
921 goto jusage;
923 if(uarg != NULL){
924 emsg = N_("The -u option cannot be used in send mode");
925 goto jusage;
927 if(!(n_poption & n_PO_t_FLAG) && to == NULL){
928 emsg = N_("Send options without primary recipient specified.");
929 goto jusage;
931 if((n_poption & n_PO_t_FLAG) && qf != NULL){
932 emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
933 goto jusage;
935 if(n_poption & (n_PO_EXISTONLY | n_PO_HEADERSONLY | n_PO_HEADERLIST)){
936 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
937 goto jusage;
939 if(n_poption & n_PO_R_FLAG){
940 emsg = N_("The -R option is meaningless in send mode.");
941 goto jusage;
944 if(n_psonce & n_PSO_INTERACTIVE){
945 if(qf == (char*)-1){
946 if(!(n_poption & n_PO_Mm_FLAG))
947 emsg = N_("-q can't use standard input when interactive.\n");
948 goto jusage;
951 }else{
952 if(uarg != NULL && folder != NULL){
953 emsg = N_("The options -u and -f (and -#) are mutually exclusive");
954 goto jusage;
956 if((n_poption & (n_PO_EXISTONLY | n_PO_HEADERSONLY)) ==
957 (n_PO_EXISTONLY | n_PO_HEADERSONLY)){
958 emsg = N_("The options -e and -H are mutual exclusive");
959 goto jusage;
961 if((n_poption & (n_PO_HEADERSONLY | n_PO_HEADERLIST) /* TODO OBSOLETE */
962 ) == (n_PO_HEADERSONLY | n_PO_HEADERLIST))
963 n_OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
965 if(uarg != NULL)
966 folder = uarg;
970 * Likely to go, perform more setup
973 a_main_setup_vars();
975 if(n_psonce & n_PSO_INTERACTIVE){
976 a_main_setscreensize(0);
977 #ifdef SIGWINCH
978 # ifndef TTY_WANTS_SIGWINCH
979 if(safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
980 # endif
981 safe_signal(SIGWINCH, &a_main_setscreensize);
982 #endif
983 }else
984 n_scrnheight = n_realscreenheight = 24, n_scrnwidth = 80;
986 /* Fixate the current snapshot of our global auto-reclaimed storage instance.
987 * Memory is auto-reclaimed from now on */
988 n_memory_autorec_fixate();
990 /* load() any resource files */
991 if(resfiles & a_RF_ALL){
992 /* *expand() returns a savestr(), but load only uses the file name for
993 * fopen(), so it's safe to do this */
994 if(resfiles & a_RF_SYSTEM){
995 bool_t nload;
997 if((nload = ok_blook(NAIL_NO_SYSTEM_RC)))
998 n_OBSOLETE(_("Please use $MAILX_NO_SYSTEM_RC instead of "
999 "$NAIL_NO_SYSTEM_RC"));
1000 if(!nload && !ok_blook(MAILX_NO_SYSTEM_RC))
1001 n_load(VAL_SYSCONFDIR "/" VAL_SYSCONFRC);
1004 if(resfiles & a_RF_USER)
1005 n_load(fexpand(ok_vlook(MAILRC), FEXP_LOCAL | FEXP_NOPROTO));
1007 if((cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
1008 n_OBSOLETE(_("Please use *mailx-extra-rc*, not *NAIL_EXTRA_RC*"));
1009 if(cp != NULL || (cp = ok_vlook(mailx_extra_rc)) != NULL)
1010 n_load(fexpand(cp, FEXP_LOCAL | FEXP_NOPROTO));
1013 /* Ensure the -S and other command line options take precedence over
1014 * anything that may have been placed in resource files.
1015 * Our "ternary binary" option *verbose* needs special treament */
1016 if((n_poption & (n_PO_VERB | n_PO_VERBVERB)) == n_PO_VERB)
1017 n_poption &= ~n_PO_VERB;
1018 /* ..and be silent when unsetting an undefined variable */
1019 n_pstate |= n_PS_ROBOT;
1020 for(i = 0; UICMP(z, i, <, oargs_cnt); ++i){
1021 char const *a[2];
1023 a[0] = oargs[i];
1024 a[1] = NULL;
1025 c_set(a);
1027 n_pstate &= ~n_PS_ROBOT;
1029 /* Cause possible umask(2), now that any setting is established, and before
1030 * we change accounts, evaluate commands etc. */
1031 (void)ok_vlook(umask);
1033 /* Additional options to pass-through to MTA, and allowed to do so? */
1034 if((cp = ok_vlook(expandargv)) != NULL){
1035 bool_t isfail, isrestrict;
1037 isfail = !asccasecmp(cp, "fail");
1038 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
1040 if((n_poption & n_PO_D_V) && !isfail && !isrestrict && *cp != '\0')
1041 n_err(_("Unknown *expandargv* value: %s\n"), cp);
1043 if((cp = argv[i = a_main_oind]) != NULL){
1044 if(isfail || (isrestrict && (!(n_poption & n_PO_TILDE_FLAG) ||
1045 !(n_psonce & n_PSO_INTERACTIVE)))){
1046 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
1047 "using *sendmail-arguments*\n"));
1048 n_exit_status = n_EXIT_USE | n_EXIT_SEND_ERROR;
1049 goto jleave;
1052 assert(n_smopts_cnt + 1 <= smopts_size);
1053 n_smopts[n_smopts_cnt++] = cp;
1054 }while((cp = argv[++i]) != NULL);
1058 /* We had to wait until the resource files are loaded and any command line
1059 * setting has been restored, but get the termcap up and going before we
1060 * switch account or running commands */
1061 #ifdef n_HAVE_TCAP
1062 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
1063 n_termcap_init();
1064 #endif
1066 /* Now we can set the account */
1067 if(Aarg != NULL){
1068 char const *a[2];
1070 a[0] = Aarg;
1071 a[1] = NULL;
1072 c_account(a);
1075 /* "load()" commands given on command line */
1076 if(Xargs_cnt > 0)
1077 n_load_Xargs(Xargs, Xargs_cnt);
1079 /* Final tests */
1080 if(n_poption & n_PO_Mm_FLAG){
1081 if(qf == (char*)-1){
1082 if(!mime_type_check_mtname(n_poption_arg_Mm)){
1083 n_err(_("Could not find `mimetype' for -M argument: %s\n"),
1084 n_poption_arg_Mm);
1085 n_exit_status = n_EXIT_ERR;
1086 goto jleave;
1088 }else if((n_poption_arg_Mm = mime_type_classify_filename(qf)) == NULL){
1089 n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
1090 n_shexp_quote_cp(qf, FAL0));
1091 n_exit_status = n_EXIT_ERR;
1092 goto jleave;
1093 }else if(!asccasecmp(n_poption_arg_Mm, "text/plain")) /* TODO no: magic */
1094 n_poption_arg_Mm = NULL;
1098 * We're finally completely setup and ready to go
1100 n_psonce |= n_PSO_STARTED;
1102 if(!(n_psonce & n_PSO_SENDMODE)){
1103 n_exit_status = a_main_rcv_mode(folder, Larg);
1104 goto jleave;
1107 /* Now that full mailx(1)-style file expansion is possible handle the
1108 * attachments which we had delayed due to this.
1109 * This may use savestr(), but since we won't enter the command loop we
1110 * don't need to care about that */
1111 for(; a_head != NULL; a_head = a_head->aa_next){
1112 enum n_attach_error aerr;
1114 attach = n_attachment_append(attach, a_head->aa_file, &aerr, NULL);
1115 if(aerr != n_ATTACH_ERR_NONE){
1116 n_exit_status = n_EXIT_ERR;
1117 goto jleave;
1121 if(n_psonce & n_PSO_INTERACTIVE)
1122 n_tty_init();
1123 mail(to, cc, bcc, subject, attach, qf, ((n_poption & n_PO_F_FLAG) != 0));
1124 if(n_psonce & n_PSO_INTERACTIVE)
1125 n_tty_destroy();
1127 jleave:
1128 /* Be aware of identical code for `exit' command! */
1129 #ifdef n_HAVE_TCAP
1130 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
1131 n_termcap_destroy();
1132 #endif
1134 j_leave:
1135 #ifdef HAVE_MEMORY_DEBUG
1136 n_memory_autorec_pop(NULL);
1137 #endif
1138 #if (defined HAVE_DEBUG || defined HAVE_DEVEL)
1139 n_memory_reset();
1140 #endif
1141 NYD_LEAVE;
1142 return n_exit_status;
1145 /* Source the others in that case! */
1146 #ifdef HAVE_AMALGAMATION
1147 # include "config.h"
1148 #endif
1150 /* s-it-mode */