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