Going a little step in direction namespace cleanup
[s-mailx.git] / main.c
blob1bbef1e22023abc5aa87b16cb072c36378497dba
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 ui16_t const n_class_char[1 + 0x7F] = {
71 #define a_BC C_BLANK | C_CNTRL
72 #define a_SC C_SPACE | C_CNTRL
73 #define a_WC C_WHITE | C_CNTRL
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, a_BC, a_WC, a_SC, a_SC, a_SC, 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 #undef a_WC
83 #undef a_SC
84 #undef a_BC
85 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
86 C_BLANK, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
87 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
88 C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
89 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
90 C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL,
91 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
92 C_DIGIT, C_DIGIT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
93 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
94 C_PUNCT, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
95 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
96 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
97 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
98 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
99 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
100 C_UPPER, C_UPPER, C_UPPER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
101 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
102 C_PUNCT, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
103 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
104 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
105 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
106 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
107 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
108 C_LOWER, C_LOWER, C_LOWER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_CNTRL
111 /* Our own little getopt(3) */
112 static char const *a_main_oarg;
113 static int a_main_oind, /*_oerr,*/ a_main_oopt;
115 /* Our own little getopt(3); note --help is special-treated as 'h' */
116 static int a_main_getopt(int argc, char * const argv[], char const *optstring);
118 /* Perform basic startup initialization */
119 static void a_main_startup(void);
121 /* Grow a char** */
122 static size_t a_main_grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt);
124 /* Setup some variables which we require to be valid / verified */
125 static void a_main_setup_vars(void);
127 /* We're in an interactive session - compute what the screen size for printing
128 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
129 * We use the following algorithm for the height:
130 * If baud rate < 1200, use 9
131 * If baud rate = 1200, use 14
132 * If baud rate > 1200, use 24 or ws_row
133 * Width is either 80 or ws_col */
134 static void a_main_setscreensize(int is_sighdl);
136 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
137 * the system mailbox, and open up the right stuff */
138 static int a_main_rcv_mode(char const *folder, char const *Larg);
140 /* Interrupt printing of the headers */
141 static void a_main_hdrstop(int signo);
143 static int
144 a_main_getopt(int argc, char * const argv[], char const *optstring){
145 static char const *lastp;
147 char const *curp;
148 int rv/*, colon*/;
149 NYD_ENTER;
151 a_main_oarg = NULL;
152 rv = -1;
154 /*if((colon = (optstring[0] == ':')))
155 ++optstring;*/
157 if(lastp != NULL){
158 curp = lastp;
159 lastp = NULL;
160 }else{
161 if(a_main_oind >= argc || argv[a_main_oind] == NULL ||
162 argv[a_main_oind][0] != '-' || argv[a_main_oind][1] == '\0')
163 goto jleave;
164 if(argv[a_main_oind][1] == '-' && argv[a_main_oind][2] == '\0'){
165 /* We need this in for MTA arg detection (easier) ++a_main_oind;*/
166 goto jleave;
168 curp = &argv[a_main_oind][1];
171 for(a_main_oopt = curp[0]; optstring[0] != '\0';){
172 if(optstring[0] != a_main_oopt){
173 optstring += 1 + (optstring[1] == ':');
174 continue;
177 if(optstring[1] == ':'){
178 if(curp[1] != '\0'){
179 a_main_oarg = n_UNCONST(curp + 1);
180 ++a_main_oind;
181 }else{
182 if((a_main_oind += 2) > argc){
183 /*if(!colon *//*&& _oerr*//*)*/{
184 n_err(_("%s: option requires an argument -- %c\n"),
185 argv[0], (char)a_main_oopt);
187 rv = (/*colon ? ':' :*/ '?');
188 goto jleave;
190 a_main_oarg = argv[a_main_oind - 1];
192 }else{
193 if(curp[1] != '\0')
194 lastp = curp + 1;
195 else
196 ++a_main_oind;
198 rv = a_main_oopt;
199 goto jleave;
202 /* Special support for --help, which is quite common */
203 if(a_main_oopt == '-' && !strcmp(curp, "-help") &&
204 &curp[-1] == argv[a_main_oind]){
205 ++a_main_oind;
206 rv = 'h';
207 goto jleave;
210 /* Definitive error */
211 /*if(!colon *//*&& opterr*//*)*/
212 n_err(_("%s: invalid option -- %c\n"), argv[0], a_main_oopt);
213 if(curp[1] != '\0')
214 lastp = curp + 1;
215 else
216 ++a_main_oind;
217 a_main_oarg = NULL;
218 rv = '?';
219 jleave:
220 NYD_LEAVE;
221 return rv;
224 static void
225 a_main_startup(void){
226 char *cp;
227 NYD_ENTER;
229 image = -1;
230 dflpipe = SIG_DFL;
231 a_main_oind = /*_oerr =*/ 1;
233 if((cp = strrchr(n_progname, '/')) != NULL)
234 n_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 /* TODO This is wrong: interactive is STDIN/STDERR for a POSIX sh(1).
250 * TODO For now we get this wrong, all over the place, as this software
251 * TODO has always been developed with stdout as an output channel.
252 * TODO Start doing it right for at least explicit terminal-related things,
253 * TODO but v15 should use ONLY this, also for terminal input! */
254 if(isatty(STDIN_FILENO)){
255 n_psonce |= n_PSO_TTYIN;
256 #if defined HAVE_MLE || defined HAVE_TERMCAP
257 n_tty_fp = fdopen(fileno(stdin), "w");
258 setvbuf(n_tty_fp, NULL, _IOLBF, 0);
259 #endif
261 if(isatty(STDOUT_FILENO))
262 n_psonce |= n_PSO_TTYOUT;
263 if((n_psonce & (n_PSO_TTYIN | n_PSO_TTYOUT)) ==
264 (n_PSO_TTYIN | n_PSO_TTYOUT)){
265 n_psonce |= n_PSO_INTERACTIVE;
266 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
269 /* STDOUT is always line buffered from our point of view */
270 setvbuf(stdout, NULL, _IOLBF, 0);
271 if(n_tty_fp == NULL)
272 n_tty_fp = stdout;
274 /* -- >8 -- 8< -- */
276 #ifndef HAVE_SETLOCALE
277 n_mb_cur_max = 1;
278 #else
279 setlocale(LC_ALL, n_empty);
280 n_mb_cur_max = MB_CUR_MAX;
281 # ifdef HAVE_NL_LANGINFO
282 if((cp = nl_langinfo(CODESET)) != NULL)
283 ok_vset(ttycharset, cp);
284 # endif
286 # ifdef HAVE_C90AMEND1
287 if(n_mb_cur_max > 1){
288 # ifdef HAVE_ALWAYS_UNICODE_LOCALE
289 n_psonce |= n_PSO_UNICODE;
290 # else
291 wchar_t wc;
292 if(mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
293 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
294 n_psonce |= n_PSO_UNICODE;
295 /* Reset possibly messed up state; luckily this also gives us an
296 * indication whether the encoding has locking shift state sequences */
297 if(mbtowc(&wc, NULL, n_mb_cur_max))
298 n_psonce |= n_PSO_ENC_MBSTATE;
299 # endif
301 # endif
302 #endif
304 #ifdef HAVE_ICONV
305 iconvd = (iconv_t)-1;
306 #endif
307 NYD_LEAVE;
310 static size_t
311 a_main_grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt){
312 /* Just use auto-reclaimed storage, it will be preserved */
313 char const **newcpp;
314 NYD_ENTER;
316 newcpp = salloc(sizeof(char*) * newsize);
318 if(oldcnt > 0)
319 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
320 *cpp = newcpp;
321 NYD_LEAVE;
322 return newsize;
325 static void
326 a_main_setup_vars(void){
327 struct passwd *pwuid;
328 char const *cp;
329 NYD_ENTER;
331 n_group_id = getgid();
332 if((pwuid = getpwuid(n_user_id = getuid())) == NULL)
333 n_panic(_("Cannot associate a name with uid %lu"), (ul_i)n_user_id);
335 /* C99 */{
336 char const *ep;
337 bool_t doenv;
339 if(!(doenv = (ep = ok_vlook(LOGNAME)) == NULL) &&
340 (doenv = strcmp(pwuid->pw_name, ep)))
341 n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
342 ep, pwuid->pw_name);
343 if(doenv){
344 n_pstate |= n_PS_ROOT;
345 ok_vset(LOGNAME, pwuid->pw_name);
346 n_pstate &= ~n_PS_ROOT;
349 if((ep = ok_vlook(USER)) != NULL && strcmp(pwuid->pw_name, ep)){
350 n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
351 ep, pwuid->pw_name);
352 n_pstate |= n_PS_ROOT;
353 ok_vset(USER, pwuid->pw_name);
354 n_pstate &= ~n_PS_ROOT;
358 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
360 /* */
361 if((cp = ok_vlook(HOME)) == NULL ||
362 !is_dir(cp) || access(cp, R_OK | W_OK | X_OK)){
363 cp = pwuid->pw_dir;
364 n_pstate |= n_PS_ROOT;
365 ok_vset(HOME, cp);
366 n_pstate &= ~n_PS_ROOT;
369 cp = ok_vlook(TMPDIR);
370 assert(cp != NULL);
371 if(!is_dir(cp) || access(cp, R_OK | W_OK | X_OK))
372 ok_vclear(TMPDIR);
374 /* Ensure some variables get loaded */
375 (void)ok_blook(POSIXLY_CORRECT);
376 NYD_LEAVE;
379 static void
380 a_main_setscreensize(int is_sighdl){/* TODO globl policy; int wraps; minvals! */
381 struct termios tbuf;
382 #ifdef TIOCGWINSZ
383 struct winsize ws;
384 #elif defined TIOCGSIZE
385 struct ttysize ts;
386 #endif
387 NYD_ENTER;
389 n_scrnheight = n_realscreenheight = n_scrnwidth = 0;
391 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
392 * a little bit to be able to honour resizes during our lifetime and
393 * only honour it upon first run; abuse *is_sighdl* as an indicator */
394 if(!is_sighdl){
395 char const *cp;
397 /* We manage those variables for our child processes, so ensure they
398 * are up to date, always */
399 if(n_psonce & n_PSO_INTERACTIVE)
400 n_pstate |= n_PS_SIGWINCH_PEND;
402 if((cp = ok_vlook(LINES)) != NULL)
403 n_scrnheight = n_realscreenheight = (int)strtoul(cp, NULL, 0); /*TODO*/
404 if((cp = ok_vlook(COLUMNS)) != NULL)
405 n_scrnwidth = (int)strtoul(cp, NULL, 0); /* TODO posui32= not posnum */
407 if(n_scrnwidth != 0 && n_scrnheight != 0)
408 goto jleave;
411 #ifdef TIOCGWINSZ
412 if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
413 ws.ws_col = ws.ws_row = 0;
414 #elif defined TIOCGSIZE
415 if(ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
416 ts.ts_lines = ts.ts_cols = 0;
417 #endif
419 if(n_scrnheight == 0){
420 speed_t ospeed;
422 ospeed = ((tcgetattr(fileno(n_tty_fp), &tbuf) == -1)
423 ? B9600 : cfgetospeed(&tbuf));
425 if(ospeed < B1200)
426 n_scrnheight = 9;
427 else if(ospeed == B1200)
428 n_scrnheight = 14;
429 #ifdef TIOCGWINSZ
430 else if(ws.ws_row != 0)
431 n_scrnheight = ws.ws_row;
432 #elif defined TIOCGSIZE
433 else if(ts.ts_lines != 0)
434 n_scrnheight = ts.ts_lines;
435 #endif
436 else
437 n_scrnheight = 24;
439 #if defined TIOCGWINSZ || defined TIOCGSIZE
440 if(0 ==
441 # ifdef TIOCGWINSZ
442 (n_realscreenheight = ws.ws_row)
443 # else
444 (n_realscreenheight = ts.ts_lines)
445 # endif
447 n_realscreenheight = 24;
448 #endif
451 if(n_scrnwidth == 0 && 0 ==
452 #ifdef TIOCGWINSZ
453 (n_scrnwidth = ws.ws_col)
454 #elif defined TIOCGSIZE
455 (n_scrnwidth = ts.ts_cols)
456 #endif
458 n_scrnwidth = 80;
460 jleave:
461 #ifdef SIGWINCH
462 if(is_sighdl){
463 n_pstate |= n_PS_SIGWINCH_PEND; /* XXX Not atomic */
464 if(n_psonce & n_PSO_INTERACTIVE)
465 n_tty_signal(SIGWINCH);
467 #endif
468 NYD_LEAVE;
471 static sigjmp_buf a_main__hdrjmp; /* XXX */
473 static int
474 a_main_rcv_mode(char const *folder, char const *Larg){
475 int i;
476 sighandler_type prevint;
477 NYD_ENTER;
479 if(folder == NULL)
480 folder = "%";
482 i = (n_poption & n_PO_QUICKRUN_MASK) ? FEDIT_RDONLY : FEDIT_NONE;
483 i = setfile(folder, i);
484 if(i < 0){
485 n_exit_status = n_EXIT_ERR; /* error already reported */
486 goto jquit;
488 if(n_poption & n_PO_QUICKRUN_MASK){
489 n_exit_status = i;
490 if(i == n_EXIT_OK && (!(n_poption & n_PO_EXISTONLY) ||
491 (n_poption & n_PO_HEADERLIST)))
492 print_header_summary(Larg);
493 goto jquit;
495 check_folder_hook(FAL0);
497 if(i > 0 && !ok_blook(emptystart)){
498 n_exit_status = n_EXIT_ERR;
499 goto jleave;
502 if(sigsetjmp(a_main__hdrjmp, 1) == 0){
503 if((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
504 safe_signal(SIGINT, &a_main_hdrstop);
505 if(!(n_poption & n_PO_N_FLAG)){
506 if(!ok_blook(quiet))
507 printf(_("%s version %s. Type `?' for help\n"),
508 (ok_blook(bsdcompat) ? "Mail" : n_uagent), ok_vlook(version));
509 announce(1);
510 fflush(stdout);
512 safe_signal(SIGINT, prevint);
515 /* Enter the command loop */
516 if(n_psonce & n_PSO_INTERACTIVE)
517 n_tty_init();
518 n_commands();
519 if(n_psonce & n_PSO_INTERACTIVE)
520 n_tty_destroy();
522 if(mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR){
523 safe_signal(SIGHUP, SIG_IGN);
524 safe_signal(SIGINT, SIG_IGN);
525 safe_signal(SIGQUIT, SIG_IGN);
527 jquit:
528 save_mbox_for_possible_quitstuff();
529 quit(FAL0);
530 jleave:
531 NYD_LEAVE;
532 return n_exit_status;
535 static void
536 a_main_hdrstop(int signo){
537 NYD_X; /* Signal handler */
538 n_UNUSED(signo);
540 fflush(stdout);
541 n_err_sighdl(_("\nInterrupt\n"));
542 siglongjmp(a_main__hdrjmp, 1);
546 main(int argc, char *argv[]){
547 /* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
548 static char const
549 optstr[] = "A:a:Bb:c:dEeFfHhiL:M:m:NnO:q:Rr:S:s:tu:VvX:::~#.",
550 usagestr[] = N_(
551 "Synopsis:\n"
552 " %s -h\n"
554 " %s [-BdEFintv~] [-: spec] [-A account]\n"
555 "\t [-a attachment] [-b bcc-addr] [-c cc-addr]\n"
556 "\t [-M type | -m file | -q file | -t]\n"
557 "\t [-r from-addr] [-S var[=value]..]\n"
558 "\t [-s subject] [-X cmd] [-.] to-addr.. [-- mta-option..]\n"
560 " %s [-BdEeHiNnRv~] [-: spec] [-A account]\n"
561 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
562 "\t [-u user] [-X cmd] [-- mta-option..]\n"
564 " %s [-BdEeHiNnRv~#] [-: spec] [-A account] -f\n"
565 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
566 "\t [-X cmd] [file] [-- mta-option..]\n"
568 #define _USAGE_ARGS , n_progname, n_progname, n_progname, n_progname
570 int i;
571 char *cp;
572 enum{
573 a_RF_NONE = 0,
574 a_RF_SET = 1<<0,
575 a_RF_SYSTEM = 1<<1,
576 a_RF_USER = 1<<2,
577 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
578 } resfiles;
579 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
580 char const *Aarg, *emsg, *folder, *Larg, *okey, **oargs, *qf,
581 *subject, *uarg, **Xargs;
582 struct attachment *attach;
583 struct name *to, *cc, *bcc;
584 struct a_arg *a_head, *a_curr;
585 NYD_ENTER;
587 a_head = NULL;
588 n_UNINIT(a_curr, NULL);
589 to = cc = bcc = NULL;
590 attach = NULL;
591 Aarg = emsg = folder = Larg = okey = qf = subject = uarg = NULL;
592 oargs = Xargs = NULL;
593 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
594 resfiles = a_RF_ALL;
597 * Start our lengthy setup, finalize by setting n_PSO_STARTED
600 n_progname = argv[0];
601 a_main_startup();
603 /* Command line parsing
604 * Variable settings need to be done twice, since the user surely wants the
605 * setting to take effect immediately, but also doesn't want it to be
606 * overwritten from within resource files */
607 while((i = a_main_getopt(argc, argv, optstr)) >= 0){
608 switch(i){
609 case 'A':
610 /* Execute an account command later on */
611 Aarg = a_main_oarg;
612 break;
613 case 'a':{
614 struct a_arg *nap;
616 n_psonce |= n_PSO_SENDMODE;
617 nap = salloc(sizeof(struct a_arg));
618 if(a_head == NULL)
619 a_head = nap;
620 else
621 a_curr->aa_next = nap;
622 nap->aa_next = NULL;
623 nap->aa_file = a_main_oarg;
624 a_curr = nap;
625 } break;
626 case 'B':
627 n_OBSOLETE(_("-B is obsolete, please use -# as necessary"));
628 break;
629 case 'b':
630 /* Get Blind Carbon Copy Recipient list */
631 n_psonce |= n_PSO_SENDMODE;
632 bcc = cat(bcc, lextract(a_main_oarg, GBCC | GFULL));
633 break;
634 case 'c':
635 /* Get Carbon Copy Recipient list */
636 n_psonce |= n_PSO_SENDMODE;
637 cc = cat(cc, lextract(a_main_oarg, GCC | GFULL));
638 break;
639 case 'd':
640 ok_bset(debug);
641 okey = "debug";
642 goto joarg;
643 case 'E':
644 n_OBSOLETE(_("-E will be removed, please use \"-Sskipemptybody\""));
645 ok_bset(skipemptybody);
646 okey = "skipemptybody";
647 goto joarg;
648 case 'e':
649 n_poption |= n_PO_EXISTONLY;
650 break;
651 case 'F':
652 n_poption |= n_PO_F_FLAG;
653 n_psonce |= n_PSO_SENDMODE;
654 break;
655 case 'f':
656 /* User is specifying file to "edit" with Mail, as opposed to reading
657 * system mailbox. If no argument is given, we read his mbox file.
658 * Check for remaining arguments later */
659 folder = "&";
660 break;
661 case 'H':
662 n_poption |= n_PO_HEADERSONLY;
663 break;
664 case 'h':
665 n_err(V_(usagestr) _USAGE_ARGS);
666 goto j_leave;
667 case 'i':
668 /* Ignore interrupts */
669 ok_bset(ignore);
670 okey = "ignore";
671 goto joarg;
672 case 'L':
673 Larg = a_main_oarg;
674 n_poption |= n_PO_HEADERLIST;
675 if(*Larg == '"' || *Larg == '\''){ /* TODO list.c:listspec_check() */
676 size_t j;
678 j = strlen(++Larg);
679 if(j > 0){
680 cp = savestrbuf(Larg, --j);
681 Larg = cp;
684 break;
685 case 'M':
686 if(qf != NULL && (!(n_poption & n_PO_Mm_FLAG) || qf != (char*)-1))
687 goto jeMmq;
688 n_poption_arg_Mm = a_main_oarg;
689 qf = (char*)-1;
690 if(0){
691 /* FALLTHRU*/
692 case 'm':
693 if(qf != NULL && (!(n_poption & n_PO_Mm_FLAG) || qf == (char*)-1))
694 goto jeMmq;
695 qf = a_main_oarg;
697 n_poption |= n_PO_Mm_FLAG;
698 n_psonce |= n_PSO_SENDMODE;
699 break;
700 case 'N':
701 /* Avoid initial header printing */
702 ok_bclear(header);
703 okey = "noheader";
704 goto joarg;
705 case 'n':
706 /* Don't source "unspecified system start-up file" */
707 if(resfiles & a_RF_SET){
708 emsg = N_("-n cannot be used in conjunction with -:");
709 goto jusage;
711 resfiles = a_RF_USER;
712 break;
713 case 'O':
714 /* Additional options to pass-through to MTA TODO v15-compat legacy */
715 if(n_smopts_cnt == smopts_size)
716 smopts_size = a_main_grow_cpp(&n_smopts, smopts_size + 8,
717 n_smopts_cnt);
718 n_smopts[n_smopts_cnt++] = a_main_oarg;
719 break;
720 case 'q':
721 if(qf != NULL && (n_poption & n_PO_Mm_FLAG)){
722 jeMmq:
723 emsg = N_("Only one of -M, -m or -q may be given");
724 goto jusage;
726 /* Quote file TODO drop? -Q with real quote?? what ? */
727 n_psonce |= n_PSO_SENDMODE;
728 /* Allow for now, we have to special check validity of -q- later on! */
729 qf = (a_main_oarg[0] == '-' && a_main_oarg[1] == '\0')
730 ? (char*)-1 : a_main_oarg;
731 break;
732 case 'R':
733 /* Open folders read-only */
734 n_poption |= n_PO_R_FLAG;
735 break;
736 case 'r':
737 /* Set From address. */
738 n_poption |= n_PO_r_FLAG;
739 if(a_main_oarg[0] != '\0'){
740 struct name *fa;
742 fa = nalloc(a_main_oarg, GSKIN | GFULL | GFULLEXTRA);
743 if(is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)){
744 emsg = N_("Invalid address argument with -r");
745 goto jusage;
747 n_poption_arg_r = fa;
748 /* TODO -r options is set in n_smopts, but may
749 * TODO be overwritten by setting from= in
750 * TODO an interactive session!
751 * TODO Maybe disable setting of from?
752 * TODO Warn user? Update manual!! */
753 okey = savecat("from=", fa->n_fullname);
754 goto joarg;
756 break;
757 case 'S':
758 /* Set variable (TODO twice [only if successful]) */
759 { char const *a[2];
760 bool_t b;
762 okey = a[0] = a_main_oarg;
763 a[1] = NULL;
764 n_pstate |= n_PS_ROBOT;
765 b = (c_set(a) == 0);
766 n_pstate &= ~n_PS_ROBOT;
767 if(!b)
768 break;
770 joarg:
771 if(oargs_cnt == oargs_size)
772 oargs_size = a_main_grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
773 oargs[oargs_cnt++] = okey;
774 break;
775 case 's':
776 /* Subject:; take care for Debian #419840 and strip any \r and \n */
777 if(n_anyof_cp("\n\r", subject = a_main_oarg)){
778 n_err(_("-s: normalizing away invalid ASCII NL / CR bytes\n"));
779 for(subject = cp = savestr(a_main_oarg); *cp != '\0'; ++cp)
780 if(*cp == '\n' || *cp == '\r')
781 *cp = ' ';
783 n_psonce |= n_PSO_SENDMODE;
784 break;
785 case 't':
786 /* Read defined set of headers from mail to be sent */
787 n_poption |= n_PO_t_FLAG;
788 n_psonce |= n_PSO_SENDMODE;
789 break;
790 case 'u':
791 uarg = savecat("%", a_main_oarg);
792 break;
793 case 'V':
794 printf(_("%s version %s\n"), n_uagent, ok_vlook(version));
795 n_exit_status = n_EXIT_OK;
796 goto j_leave;
797 case 'v':
798 /* Be verbose */
799 ok_bset(verbose);
800 okey = "verbose";
801 goto joarg;
802 case 'X':
803 /* Add to list of commands to exec before entering normal operation */
804 if(Xargs_cnt == Xargs_size)
805 Xargs_size = a_main_grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
806 Xargs[Xargs_cnt++] = a_main_oarg;
807 break;
808 case ':':
809 /* Control which resource files shall be loaded */
810 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
811 emsg = N_("-n cannot be used in conjunction with -:");
812 goto jusage;
814 resfiles = a_RF_SET;
815 while((i = *a_main_oarg++) != '\0')
816 switch(i){
817 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
818 case 'U': case 'u': resfiles |= a_RF_USER; break;
819 case ':': case '/': resfiles &= ~a_RF_ALL; break;
820 default:
821 emsg = N_("Invalid argument of -:");
822 goto jusage;
824 break;
825 case '~':
826 /* Enable command escapes even in non-interactive mode */
827 n_poption |= n_PO_TILDE_FLAG;
828 break;
829 case '#':
830 /* Work in batch mode, even if non-interactive */
831 if(!(n_psonce & n_PSO_INTERACTIVE))
832 setvbuf(stdin, NULL, _IOLBF, 0);
833 n_poption |= n_PO_TILDE_FLAG | n_PO_BATCH_FLAG;
834 if (oargs_cnt + 8 >= oargs_size)
835 oargs_size = a_main_grow_cpp(&oargs, oargs_size + 9, oargs_cnt);
836 folder = "/dev/null";
837 ok_vset(MAIL, folder);
838 ok_vset(MBOX, folder);
839 ok_bset(emptystart);
840 ok_bclear(header);
841 ok_vset(inbox, folder);
842 ok_bset(quiet);
843 ok_bset(sendwait);
844 ok_bset(typescript_mode);
845 oargs[oargs_cnt + 0] = "MAIL=/dev/null";
846 oargs[oargs_cnt + 1] = "MBOX=/dev/null";
847 oargs[oargs_cnt + 2] = "emptystart";
848 oargs[oargs_cnt + 3] = "noheader";
849 oargs[oargs_cnt + 4] = "inbox=/dev/null";
850 oargs[oargs_cnt + 5] = "quiet";
851 oargs[oargs_cnt + 6] = "sendwait";
852 oargs[oargs_cnt + 7] = "typescript-mode";
853 oargs_cnt += 8;
854 break;
855 case '.':
856 n_psonce |= n_PSO_SENDMODE;
857 goto jgetopt_done;
858 case '?':
859 jusage:
860 if(emsg != NULL)
861 n_err("%s\n", V_(emsg));
862 n_err(V_(usagestr) _USAGE_ARGS);
863 #undef _USAGE_ARGS
864 n_exit_status = n_EXIT_USE;
865 goto j_leave;
868 jgetopt_done:
871 /* The normal arguments may be followed by MTA arguments after a "--";
872 * however, -f may take off an argument, too, and before that.
873 * Since MTA arguments after "--" require *expandargv*, delay parsing off
874 * those options until after the resource files are loaded... */
875 if((cp = argv[i = a_main_oind]) == NULL)
877 else if(cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
878 ++i;
879 /* n_PO_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
880 else if(folder != NULL && /*folder[0] == '&' &&*/ folder[1] == '\0'){
881 folder = cp;
882 if((cp = argv[++i]) != NULL){
883 if(cp[0] != '-' || cp[1] != '-' || cp[2] != '\0'){
884 emsg = N_("More than one file given with -f");
885 goto jusage;
887 ++i;
889 }else{
890 n_psonce |= n_PSO_SENDMODE;
891 for(;;){
892 to = cat(to, lextract(cp, GTO | GFULL));
893 if((cp = argv[++i]) == NULL)
894 break;
895 if(cp[0] == '-' && cp[1] == '-' && cp[2] == '\0'){
896 ++i;
897 break;
901 a_main_oind = i;
903 /* ...BUT, since we use salloc() for the MTA n_smopts storage we need to
904 * allocate the necessary space for them before we fixate that storage! */
905 while(argv[i] != NULL)
906 ++i;
907 if(n_smopts_cnt + i > smopts_size)
908 DBG(smopts_size =)
909 a_main_grow_cpp(&n_smopts, n_smopts_cnt + i + 1, n_smopts_cnt);
911 /* Check for inconsistent arguments, fix some temporaries */
912 if(n_psonce & n_PSO_SENDMODE){
913 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
914 * XXX in order to function. Ideally that would not be needed */
915 if(folder != NULL && !(n_poption & n_PO_BATCH_FLAG)){
916 emsg = N_("Cannot give -f and people to send to.");
917 goto jusage;
919 if(uarg != NULL){
920 emsg = N_("The -u option cannot be used in send mode");
921 goto jusage;
923 if(!(n_poption & n_PO_t_FLAG) && to == NULL){
924 emsg = N_("Send options without primary recipient specified.");
925 goto jusage;
927 if((n_poption & n_PO_t_FLAG) && qf != NULL){
928 emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
929 goto jusage;
931 if(n_poption & (n_PO_EXISTONLY | n_PO_HEADERSONLY | n_PO_HEADERLIST)){
932 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
933 goto jusage;
935 if(n_poption & n_PO_R_FLAG){
936 emsg = N_("The -R option is meaningless in send mode.");
937 goto jusage;
940 if(n_psonce & n_PSO_INTERACTIVE){
941 if(qf == (char*)-1){
942 if(!(n_poption & n_PO_Mm_FLAG))
943 emsg = N_("-q can't use standard input when interactive.\n");
944 goto jusage;
947 }else{
948 if(uarg != NULL && folder != NULL){
949 emsg = N_("The options -u and -f (and -#) are mutually exclusive");
950 goto jusage;
952 if((n_poption & (n_PO_EXISTONLY | n_PO_HEADERSONLY)) ==
953 (n_PO_EXISTONLY | n_PO_HEADERSONLY)){
954 emsg = N_("The options -e and -H are mutual exclusive");
955 goto jusage;
957 if((n_poption & (n_PO_HEADERSONLY | n_PO_HEADERLIST) /* TODO OBSOLETE */
958 ) == (n_PO_HEADERSONLY | n_PO_HEADERLIST))
959 n_OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
961 if(uarg != NULL)
962 folder = uarg;
966 * Likely to go, perform more setup
969 a_main_setup_vars();
971 if(n_psonce & n_PSO_INTERACTIVE){
972 a_main_setscreensize(0);
973 #ifdef SIGWINCH
974 # ifndef TTY_WANTS_SIGWINCH
975 if(safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
976 # endif
977 safe_signal(SIGWINCH, &a_main_setscreensize);
978 #endif
979 }else
980 n_scrnheight = n_realscreenheight = 24, n_scrnwidth = 80;
982 /* Fixate the current snapshot of our global auto-reclaimed storage instance.
983 * Memory is auto-reclaimed from now on */
984 n_memory_autorec_fixate();
986 /* load() any resource files */
987 if(resfiles & a_RF_ALL){
988 /* *expand() returns a savestr(), but load only uses the file name for
989 * fopen(), so it's safe to do this */
990 if(resfiles & a_RF_SYSTEM){
991 bool_t nload;
993 if((nload = ok_blook(NAIL_NO_SYSTEM_RC)))
994 n_OBSOLETE(_("Please use $MAILX_NO_SYSTEM_RC instead of "
995 "$NAIL_NO_SYSTEM_RC"));
996 if(!nload && !ok_blook(MAILX_NO_SYSTEM_RC))
997 n_load(VAL_SYSCONFDIR "/" VAL_SYSCONFRC);
1000 if(resfiles & a_RF_USER)
1001 n_load(fexpand(ok_vlook(MAILRC), FEXP_LOCAL | FEXP_NOPROTO));
1003 if((cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
1004 n_OBSOLETE(_("Please use *mailx-extra-rc*, not *NAIL_EXTRA_RC*"));
1005 if(cp != NULL || (cp = ok_vlook(mailx_extra_rc)) != NULL)
1006 n_load(fexpand(cp, FEXP_LOCAL | FEXP_NOPROTO));
1009 /* Ensure the -S and other command line options take precedence over
1010 * anything that may have been placed in resource files.
1011 * Our "ternary binary" option *verbose* needs special treament */
1012 if((n_poption & (n_PO_VERB | n_PO_VERBVERB)) == n_PO_VERB)
1013 n_poption &= ~n_PO_VERB;
1014 /* ..and be silent when unsetting an undefined variable */
1015 n_pstate |= n_PS_ROBOT;
1016 for(i = 0; UICMP(z, i, <, oargs_cnt); ++i){
1017 char const *a[2];
1019 a[0] = oargs[i];
1020 a[1] = NULL;
1021 c_set(a);
1023 n_pstate &= ~n_PS_ROBOT;
1025 /* Cause possible umask(2), now that any setting is established, and before
1026 * we change accounts, evaluate commands etc. */
1027 (void)ok_vlook(umask);
1029 /* Additional options to pass-through to MTA, and allowed to do so? */
1030 if((cp = ok_vlook(expandargv)) != NULL){
1031 bool_t isfail, isrestrict;
1033 isfail = !asccasecmp(cp, "fail");
1034 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
1036 if((n_poption & n_PO_D_V) && !isfail && !isrestrict && *cp != '\0')
1037 n_err(_("Unknown *expandargv* value: %s\n"), cp);
1039 if((cp = argv[i = a_main_oind]) != NULL){
1040 if(isfail || (isrestrict && (!(n_poption & n_PO_TILDE_FLAG) ||
1041 !(n_psonce & n_PSO_INTERACTIVE)))){
1042 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
1043 "using *sendmail-arguments*\n"));
1044 n_exit_status = n_EXIT_USE | n_EXIT_SEND_ERROR;
1045 goto jleave;
1048 assert(n_smopts_cnt + 1 <= smopts_size);
1049 n_smopts[n_smopts_cnt++] = cp;
1050 }while((cp = argv[++i]) != NULL);
1054 /* We had to wait until the resource files are loaded and any command line
1055 * setting has been restored, but get the termcap up and going before we
1056 * switch account or running commands */
1057 #ifdef n_HAVE_TCAP
1058 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
1059 n_termcap_init();
1060 #endif
1062 /* Now we can set the account */
1063 if(Aarg != NULL){
1064 char const *a[2];
1066 a[0] = Aarg;
1067 a[1] = NULL;
1068 c_account(a);
1071 /* "load()" commands given on command line */
1072 if(Xargs_cnt > 0)
1073 n_load_Xargs(Xargs, Xargs_cnt);
1075 /* Final tests */
1076 if(n_poption & n_PO_Mm_FLAG){
1077 if(qf == (char*)-1){
1078 if(!mime_type_check_mtname(n_poption_arg_Mm)){
1079 n_err(_("Could not find `mimetype' for -M argument: %s\n"),
1080 n_poption_arg_Mm);
1081 n_exit_status = n_EXIT_ERR;
1082 goto jleave;
1084 }else if((n_poption_arg_Mm = mime_type_classify_filename(qf)) == NULL){
1085 n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
1086 n_shexp_quote_cp(qf, FAL0));
1087 n_exit_status = n_EXIT_ERR;
1088 goto jleave;
1089 }else if(!asccasecmp(n_poption_arg_Mm, "text/plain")) /* TODO no: magic */
1090 n_poption_arg_Mm = NULL;
1094 * We're finally completely setup and ready to go
1096 n_psonce |= n_PSO_STARTED;
1098 if(!(n_psonce & n_PSO_SENDMODE)){
1099 n_exit_status = a_main_rcv_mode(folder, Larg);
1100 goto jleave;
1103 /* Now that full mailx(1)-style file expansion is possible handle the
1104 * attachments which we had delayed due to this.
1105 * This may use savestr(), but since we won't enter the command loop we
1106 * don't need to care about that */
1107 for(; a_head != NULL; a_head = a_head->aa_next){
1108 enum n_attach_error aerr;
1110 attach = n_attachment_append(attach, a_head->aa_file, &aerr, NULL);
1111 if(aerr != n_ATTACH_ERR_NONE){
1112 n_exit_status = n_EXIT_ERR;
1113 goto jleave;
1117 if(n_psonce & n_PSO_INTERACTIVE)
1118 n_tty_init();
1119 mail(to, cc, bcc, subject, attach, qf, ((n_poption & n_PO_F_FLAG) != 0));
1120 if(n_psonce & n_PSO_INTERACTIVE)
1121 n_tty_destroy();
1123 jleave:
1124 /* Be aware of identical code for `exit' command! */
1125 #ifdef n_HAVE_TCAP
1126 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
1127 n_termcap_destroy();
1128 #endif
1130 j_leave:
1131 #ifdef HAVE_MEMORY_DEBUG
1132 n_memory_autorec_pop(NULL);
1133 #endif
1134 #if (defined HAVE_DEBUG || defined HAVE_DEVEL)
1135 n_memory_reset();
1136 #endif
1137 NYD_LEAVE;
1138 return n_exit_status;
1141 /* Source the others in that case! */
1142 #ifdef HAVE_AMALGAMATION
1143 # include "config.h"
1144 #endif
1146 /* s-it-mode */