quit()+descendants: add hold_sigs_on argument, let'em handle it
[s-mailx.git] / main.c
blob3462677baf01e0d2525dfc65965b8091eba0ec7c
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 - 2016 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 *aa_file;
58 /* (extern, but not with amalgamation, so define here) */
59 VL char const weekday_names[7 + 1][4] = {
60 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ""
62 VL char const month_names[12 + 1][4] = {
63 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
64 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""
66 VL char const 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 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 *_oarg;
113 static int _oind, /*_oerr,*/ _oopt;
115 /* Our own little getopt(3); note --help is special-treated as 'h' */
116 static int _getopt(int argc, char * const argv[], char const *optstring);
118 /* Perform basic startup initialization */
119 static void _startup(void);
121 /* Grow a char** */
122 static size_t _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 _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 _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 _rcv_mode(char const *folder, char const *Larg);
140 /* Interrupt printing of the headers */
141 static void _hdrstop(int signo);
143 static int
144 _getopt(int argc, char * const argv[], char const *optstring)
146 static char const *lastp;
148 int rv = -1/*, colon*/;
149 char const *curp;
150 NYD_ENTER;
152 _oarg = NULL;
154 /*if ((colon = (optstring[0] == ':')))
155 ++optstring;*/
157 if (lastp != NULL) {
158 curp = lastp;
159 lastp = NULL;
160 } else {
161 if (_oind >= argc || argv[_oind] == NULL || argv[_oind][0] != '-' ||
162 argv[_oind][1] == '\0')
163 goto jleave;
164 if (argv[_oind][1] == '-' && argv[_oind][2] == '\0') {
165 /* We need this in for MTA arg detection (easier) ++_oind;*/
166 goto jleave;
168 curp = &argv[_oind][1];
171 for(_oopt = curp[0]; optstring[0] != '\0';){
172 if(optstring[0] != _oopt){
173 optstring += 1 + (optstring[1] == ':');
174 continue;
177 if (optstring[1] == ':') {
178 if (curp[1] != '\0') {
179 _oarg = n_UNCONST(curp + 1);
180 ++_oind;
181 } else {
182 if ((_oind += 2) > argc) {
183 /*if (!colon *//*&& _oerr*//*)*/ {
184 n_err(_("%s: option requires an argument -- %c\n"),
185 argv[0], (char)_oopt);
187 rv = (/*colon ? ':' :*/ '?');
188 goto jleave;
190 _oarg = argv[_oind - 1];
192 } else {
193 if (curp[1] != '\0')
194 lastp = curp + 1;
195 else
196 ++_oind;
198 rv = _oopt;
199 goto jleave;
202 /* Special support for --help, which is quite common */
203 if (_oopt == '-' && !strcmp(curp, "-help") && curp - 1 == argv[_oind]) {
204 ++_oind;
205 rv = 'h';
206 goto jleave;
209 /* Definitive error */
210 /*if (!colon *//*&& opterr*//*)*/
211 n_err(_("%s: invalid option -- %c\n"), argv[0], _oopt);
212 if (curp[1] != '\0')
213 lastp = curp + 1;
214 else
215 ++_oind;
216 _oarg = NULL;
217 rv = '?';
218 jleave:
219 NYD_LEAVE;
220 return rv;
223 static void
224 _startup(void)
226 char *cp;
227 NYD_ENTER;
229 image = -1;
230 dflpipe = SIG_DFL;
231 _oind = /*_oerr =*/ 1;
233 if ((cp = strrchr(progname, '/')) != NULL)
234 progname = ++cp;
236 /* Set up a reasonable environment */
238 #ifdef HAVE_NYD
239 safe_signal(SIGABRT, &_nyd_oncrash);
240 # ifdef SIGBUS
241 safe_signal(SIGBUS, &_nyd_oncrash);
242 # endif
243 safe_signal(SIGFPE, &_nyd_oncrash);
244 safe_signal(SIGILL, &_nyd_oncrash);
245 safe_signal(SIGSEGV, &_nyd_oncrash);
246 #endif
247 command_manager_start();
249 if (isatty(STDIN_FILENO)) /* TODO should be isatty(0) && isatty(2)?? */
250 options |= OPT_TTYIN;
251 if (isatty(STDOUT_FILENO))
252 options |= OPT_TTYOUT;
253 if ((options & (OPT_TTYIN | OPT_TTYOUT)) == (OPT_TTYIN | OPT_TTYOUT)) {
254 options |= OPT_INTERACTIVE;
255 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
258 /* -- >8 -- 8< -- */
260 #ifndef HAVE_SETLOCALE
261 mb_cur_max = 1;
262 #else
263 setlocale(LC_ALL, n_empty);
264 mb_cur_max = MB_CUR_MAX;
265 # ifdef HAVE_NL_LANGINFO
266 if(ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
267 ok_vset(ttycharset, cp);
268 # endif
270 # ifdef HAVE_C90AMEND1
271 if(mb_cur_max > 1){
272 # ifdef HAVE_ALWAYS_UNICODE_LOCALE
273 options |= OPT_UNICODE;
274 # else
275 wchar_t wc;
276 if(mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
277 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
278 options |= OPT_UNICODE;
279 /* Reset possibly messed up state; luckily this also gives us an
280 * indication whether the encoding has locking shift state sequences */
281 if(mbtowc(&wc, NULL, mb_cur_max))
282 options |= OPT_ENC_MBSTATE;
283 # endif
285 # endif
286 #endif
288 #ifdef HAVE_ICONV
289 iconvd = (iconv_t)-1;
290 #endif
291 NYD_LEAVE;
294 static size_t
295 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
297 /* Just use auto-reclaimed storage, it will be preserved */
298 char const **newcpp;
299 NYD_ENTER;
301 newcpp = salloc(sizeof(char*) * newsize);
303 if (oldcnt > 0)
304 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
305 *cpp = newcpp;
306 NYD_LEAVE;
307 return newsize;
310 static void
311 _setup_vars(void){
312 /* XXX furtherly check paths? */
313 struct passwd *pwuid;
314 char const *cp;
315 NYD_ENTER;
317 group_id = getgid();
318 if((pwuid = getpwuid(user_id = getuid())) == NULL)
319 n_panic(_("Cannot associate a name with uid %lu"), (ul_i)user_id);
320 myname = savestr(pwuid->pw_name); /* XXX replace uses with vlook(LOGNAME)! */
322 /* C99 */{
323 char const *ep;
324 bool_t doenv;
326 if(!(doenv = (ep = ok_vlook(LOGNAME)) == NULL) &&
327 (doenv = strcmp(myname, ep)))
328 n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
329 ep, myname);
330 if(doenv){
331 pstate |= PS_ROOT;
332 ok_vset(LOGNAME, myname);
333 pstate &= ~PS_ROOT;
336 if((ep = ok_vlook(USER)) != NULL && strcmp(myname, ep)){
337 n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
338 ep, myname);
339 pstate |= PS_ROOT;
340 ok_vset(USER, myname);
341 pstate &= ~PS_ROOT;
345 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
347 /* */
348 if((cp = ok_vlook(HOME)) == NULL){
349 cp = pwuid->pw_dir;
350 pstate |= PS_ROOT;
351 ok_vset(HOME, cp);
352 pstate &= ~PS_ROOT;
355 (void)ok_vlook(TMPDIR);
356 NYD_LEAVE;
359 static void
360 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
362 struct termios tbuf;
363 #ifdef TIOCGWINSZ
364 struct winsize ws;
365 #elif defined TIOCGSIZE
366 struct ttysize ts;
367 #endif
368 NYD_ENTER;
370 scrnheight = realscreenheight = scrnwidth = 0;
372 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
373 * a little bit to be able to honour resizes during our lifetime and
374 * only honour it upon first run; abuse *is_sighdl* as an indicator */
375 if (!is_sighdl) {
376 char *cp;
378 /* We manage those variables for our child processes, so ensure they
379 * are up to date, always */
380 if (options & OPT_INTERACTIVE)
381 pstate |= PS_SIGWINCH_PEND;
383 if ((cp = ok_vlook(LINES)) != NULL)
384 scrnheight = realscreenheight = (int)strtoul(cp, NULL, 0); /* TODO */
385 if ((cp = ok_vlook(COLUMNS)) != NULL)
386 scrnwidth = (int)strtoul(cp, NULL, 0); /* TODO posui32= not posnum=! */
388 if (scrnwidth != 0 && scrnheight != 0)
389 goto jleave;
392 #ifdef TIOCGWINSZ
393 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
394 ws.ws_col = ws.ws_row = 0;
395 #elif defined TIOCGSIZE
396 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
397 ts.ts_lines = ts.ts_cols = 0;
398 #endif
400 if (scrnheight == 0) {
401 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
402 ? B9600 : cfgetospeed(&tbuf));
404 if (ospeed < B1200)
405 scrnheight = 9;
406 else if (ospeed == B1200)
407 scrnheight = 14;
408 #ifdef TIOCGWINSZ
409 else if (ws.ws_row != 0)
410 scrnheight = ws.ws_row;
411 #elif defined TIOCGSIZE
412 else if (ts.ts_lines != 0)
413 scrnheight = ts.ts_lines;
414 #endif
415 else
416 scrnheight = 24;
418 #if defined TIOCGWINSZ || defined TIOCGSIZE
419 if (0 ==
420 # ifdef TIOCGWINSZ
421 (realscreenheight = ws.ws_row)
422 # else
423 (realscreenheight = ts.ts_lines)
424 # endif
426 realscreenheight = 24;
427 #endif
430 if (scrnwidth == 0 && 0 ==
431 #ifdef TIOCGWINSZ
432 (scrnwidth = ws.ws_col)
433 #elif defined TIOCGSIZE
434 (scrnwidth = ts.ts_cols)
435 #endif
437 scrnwidth = 80;
439 jleave:
440 #ifdef SIGWINCH
441 if (is_sighdl) {
442 pstate |= PS_SIGWINCH_PEND; /* XXX Not atomic */
443 if (options & OPT_INTERACTIVE)
444 n_tty_signal(SIGWINCH);
446 #endif
447 NYD_LEAVE;
450 static sigjmp_buf __hdrjmp; /* XXX */
452 static int
453 _rcv_mode(char const *folder, char const *Larg)
455 int i;
456 sighandler_type prevint;
457 NYD_ENTER;
459 if (folder == NULL)
460 folder = "%";
462 if (options & OPT_QUICKRUN_MASK)
463 i = FEDIT_RDONLY;
464 else
465 i = FEDIT_NONE;
466 i = setfile(folder, i);
467 if (i < 0) {
468 exit_status = EXIT_ERR; /* error already reported */
469 goto jquit;
471 if (options & OPT_QUICKRUN_MASK) {
472 exit_status = i;
473 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
474 (options & OPT_HEADERLIST)))
475 print_header_summary(Larg);
476 goto jquit;
478 check_folder_hook(FAL0);
480 if (i > 0 && !ok_blook(emptystart)) {
481 exit_status = EXIT_ERR;
482 goto jleave;
485 if (sigsetjmp(__hdrjmp, 1) == 0) {
486 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
487 safe_signal(SIGINT, _hdrstop);
488 if (!(options & OPT_N_FLAG)) {
489 if (!ok_blook(quiet))
490 printf(_("%s version %s. Type `?' for help\n"),
491 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
492 announce(1);
493 fflush(stdout);
495 safe_signal(SIGINT, prevint);
498 /* Enter the command loop */
499 if (options & OPT_INTERACTIVE)
500 n_tty_init();
501 n_commands();
502 if (options & OPT_INTERACTIVE)
503 n_tty_destroy();
505 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
506 safe_signal(SIGHUP, SIG_IGN);
507 safe_signal(SIGINT, SIG_IGN);
508 safe_signal(SIGQUIT, SIG_IGN);
510 jquit:
511 save_mbox_for_possible_quitstuff();
512 quit(FAL0);
513 jleave:
514 NYD_LEAVE;
515 return exit_status;
518 static void
519 _hdrstop(int signo)
521 NYD_X; /* Signal handler */
522 n_UNUSED(signo);
524 fflush(stdout);
525 n_err_sighdl(_("\nInterrupt\n"));
526 siglongjmp(__hdrjmp, 1);
530 main(int argc, char *argv[]){
531 /* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
532 static char const
533 optstr[] = "A:a:Bb:c:dEeFfHhiL:M:m:NnO:q:Rr:S:s:tu:VvX:::~#.",
534 usagestr[] = N_(
535 "Synopsis:\n"
536 " %s -h\n"
538 " %s [-BdEFintv~] [-: spec] [-A account]\n"
539 "\t [-a attachment] [-b bcc-addr] [-c cc-addr]\n"
540 "\t [-M type | -m file | -q file | -t]\n"
541 "\t [-r from-addr] [-S var[=value]..]\n"
542 "\t [-s subject] [-X cmd] [-.] to-addr.. [-- mta-option..]\n"
544 " %s [-BdEeHiNnRv~] [-: spec] [-A account]\n"
545 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
546 "\t [-u user] [-X cmd] [-- mta-option..]\n"
548 " %s [-BdEeHiNnRv~#] [-: spec] [-A account] -f\n"
549 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
550 "\t [-X cmd] [file] [-- mta-option..]\n"
552 #define _USAGE_ARGS , progname, progname, progname, progname
554 struct a_arg *a_head, *a_curr;
555 struct name *to, *cc, *bcc;
556 struct attachment *attach;
557 char *cp, *subject, *qf, *Aarg, *Larg;
558 char const *okey, **oargs, **Xargs, *folder, *emsg;
559 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
560 enum{
561 a_RF_NONE = 0,
562 a_RF_SET = 1<<0,
563 a_RF_SYSTEM = 1<<1,
564 a_RF_USER = 1<<2,
565 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
566 } resfiles;
567 int i;
568 NYD_ENTER;
570 a_head = NULL;
571 n_UNINIT(a_curr, NULL);
572 to = cc = bcc = NULL;
573 attach = NULL;
574 cp = subject = qf =
575 Aarg = Larg = NULL;
576 oargs = Xargs = NULL;
577 folder = emsg = NULL;
578 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
579 resfiles = a_RF_ALL;
582 * Start our lengthy setup, finalize by setting PS_STARTED
585 progname = argv[0];
586 _startup();
588 /* Command line parsing
589 * Variable settings need to be done twice, since the user surely wants the
590 * setting to take effect immediately, but also doesn't want it to be
591 * overwritten from within resource files */
592 while ((i = _getopt(argc, argv, optstr)) >= 0) {
593 switch (i) {
594 case 'A':
595 /* Execute an account command later on */
596 Aarg = _oarg;
597 break;
598 case 'a':
599 options |= OPT_SENDMODE;
600 { struct a_arg *nap = salloc(sizeof(struct a_arg));
601 if (a_head == NULL)
602 a_head = nap;
603 else
604 a_curr->aa_next = nap;
605 nap->aa_next = NULL;
606 nap->aa_file = _oarg;
607 a_curr = nap;
609 break;
610 case 'B':
611 /* Make 0/1 line buffered */
612 setvbuf(stdin, NULL, _IOLBF, 0);
613 setvbuf(stdout, NULL, _IOLBF, 0);
614 break;
615 case 'b':
616 /* Get Blind Carbon Copy Recipient list */
617 options |= OPT_SENDMODE;
618 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
619 break;
620 case 'c':
621 /* Get Carbon Copy Recipient list */
622 options |= OPT_SENDMODE;
623 cc = cat(cc, lextract(_oarg, GCC | GFULL));
624 break;
625 case 'd':
626 ok_bset(debug);
627 okey = "debug";
628 goto joarg;
629 case 'E':
630 ok_bset(skipemptybody);
631 okey = "skipemptybody";
632 goto joarg;
633 case 'e':
634 options |= OPT_EXISTONLY;
635 break;
636 case 'F':
637 options |= OPT_F_FLAG | OPT_SENDMODE;
638 break;
639 case 'f':
640 /* User is specifying file to "edit" with Mail, as opposed to reading
641 * system mailbox. If no argument is given, we read his mbox file.
642 * Check for remaining arguments later */
643 folder = "&";
644 break;
645 case 'H':
646 options |= OPT_HEADERSONLY;
647 break;
648 case 'h':
649 n_err(V_(usagestr) _USAGE_ARGS);
650 goto j_leave;
651 case 'i':
652 /* Ignore interrupts */
653 ok_bset(ignore);
654 okey = "ignore";
655 goto joarg;
656 case 'L':
657 Larg = _oarg;
658 options |= OPT_HEADERLIST;
659 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
660 size_t j = strlen(++Larg);
661 if (j > 0)
662 Larg[j - 1] = '\0';
664 break;
665 case 'M':
666 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf != (char*)-1))
667 goto jeMmq;
668 option_Mm_arg = _oarg;
669 qf = (char*)-1;
670 if(0){
671 /* FALLTHRU*/
672 case 'm':
673 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf == (char*)-1))
674 goto jeMmq;
675 qf = _oarg;
677 options |= OPT_SENDMODE | OPT_Mm_FLAG;
678 break;
679 case 'N':
680 /* Avoid initial header printing */
681 ok_bclear(header);
682 okey = "noheader";
683 goto joarg;
684 case 'n':
685 /* Don't source "unspecified system start-up file" */
686 if(resfiles & a_RF_SET){
687 emsg = N_("-n cannot be used in conjunction with -:");
688 goto jusage;
690 resfiles = a_RF_USER;
691 break;
692 case 'O':
693 /* Additional options to pass-through to MTA TODO v15-compat legacy */
694 if (smopts_cnt == smopts_size)
695 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_cnt);
696 smopts[smopts_cnt++] = _oarg;
697 break;
698 case 'q':
699 if (qf != NULL && (options & OPT_Mm_FLAG)) {
700 jeMmq:
701 emsg = N_("Only one of -M, -m or -q may be given");
702 goto jusage;
704 /* Quote file TODO drop? -Q with real quote?? what ? */
705 options |= OPT_SENDMODE;
706 /* Allow for now, we have to special check validity of -q- later on! */
707 qf = (_oarg[0] == '-' && _oarg[1] == '\0') ? (char*)-1 : _oarg;
708 break;
709 case 'R':
710 /* Open folders read-only */
711 options |= OPT_R_FLAG;
712 break;
713 case 'r':
714 /* Set From address. */
715 options |= OPT_r_FLAG;
716 if (_oarg[0] != '\0') {
717 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
719 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
720 emsg = N_("Invalid address argument with -r");
721 goto jusage;
723 option_r_arg = fa;
724 /* TODO -r options is set in smopts, but may
725 * TODO be overwritten by setting from= in
726 * TODO an interactive session!
727 * TODO Maybe disable setting of from?
728 * TODO Warn user? Update manual!! */
729 okey = savecat("from=", fa->n_fullname);
730 goto joarg;
732 break;
733 case 'S':
734 /* Set variable (TODO twice [only if successful]) */
735 { char *a[2];
736 bool_t b;
738 okey = a[0] = _oarg;
739 a[1] = NULL;
740 pstate |= PS_ROBOT;
741 b = (c_set(a) == 0);
742 pstate &= ~PS_ROBOT;
743 if(!b)
744 break;
746 joarg:
747 if (oargs_cnt == oargs_size)
748 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
749 oargs[oargs_cnt++] = okey;
750 break;
751 case 's':
752 /* Subject: */
753 subject = _oarg;
754 options |= OPT_SENDMODE;
755 break;
756 case 't':
757 /* Read defined set of headers from mail to be sent */
758 options |= OPT_SENDMODE | OPT_t_FLAG;
759 break;
760 case 'u':
761 /* Temporarily set myname so that we can recognize the -u condition */
762 myname = savecat("%", _oarg);
763 break;
764 case 'V':
765 printf(_("%s version %s\n"), uagent, ok_vlook(version));
766 exit_status = EXIT_OK;
767 goto j_leave;
768 case 'v':
769 /* Be verbose */
770 ok_bset(verbose);
771 okey = "verbose";
772 goto joarg;
773 case 'X':
774 /* Add to list of commands to exec before entering normal operation */
775 if (Xargs_cnt == Xargs_size)
776 Xargs_size = _grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
777 Xargs[Xargs_cnt++] = _oarg;
778 break;
779 case ':':
780 /* Control which resource files shall be loaded */
781 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
782 emsg = N_("-n cannot be used in conjunction with -:");
783 goto jusage;
785 resfiles = a_RF_SET;
786 while((i = *_oarg++) != '\0')
787 switch(i){
788 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
789 case 'U': case 'u': resfiles |= a_RF_USER; break;
790 case ':': case '/': resfiles &= ~a_RF_ALL; break;
791 default:
792 emsg = N_("Invalid argument of -:");
793 goto jusage;
795 break;
796 case '~':
797 /* Enable tilde escapes even in non-interactive mode */
798 options |= OPT_TILDE_FLAG;
799 break;
800 case '#':
801 /* Work in batch mode, even if non-interactive */
802 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
803 if (oargs_cnt + 8 >= oargs_size)
804 oargs_size = _grow_cpp(&oargs, oargs_size + 9, oargs_cnt);
805 folder = "/dev/null";
806 ok_vset(MAIL, folder);
807 ok_vset(MBOX, folder);
808 ok_bset(emptystart);
809 ok_bclear(header);
810 ok_vset(inbox, folder);
811 ok_bset(quiet);
812 ok_bset(sendwait);
813 ok_bset(typescript_mode);
814 oargs[oargs_cnt + 0] = "MAIL=/dev/null";
815 oargs[oargs_cnt + 1] = "MBOX=/dev/null";
816 oargs[oargs_cnt + 2] = "emptystart";
817 oargs[oargs_cnt + 3] = "noheader";
818 oargs[oargs_cnt + 4] = "inbox=/dev/null";
819 oargs[oargs_cnt + 5] = "quiet";
820 oargs[oargs_cnt + 6] = "sendwait";
821 oargs[oargs_cnt + 7] = "typescript-mode";
822 oargs_cnt += 8;
823 break;
824 case '.':
825 options |= OPT_SENDMODE;
826 goto jgetopt_done;
827 case '?':
828 jusage:
829 if (emsg != NULL)
830 n_err("%s\n", V_(emsg));
831 n_err(V_(usagestr) _USAGE_ARGS);
832 #undef _USAGE_ARGS
833 exit_status = EXIT_USE;
834 goto j_leave;
837 jgetopt_done:
840 /* The normal arguments may be followed by MTA arguments after a "--";
841 * however, -f may take off an argument, too, and before that.
842 * Since MTA arguments after "--" require *expandargv*, delay parsing off
843 * those options until after the resource files are loaded... */
844 if ((cp = argv[i = _oind]) == NULL)
846 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
847 ++i;
848 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
849 else if (folder != NULL && /*folder[0] == '&' &&*/ folder[1] == '\0') {
850 folder = cp;
851 if ((cp = argv[++i]) != NULL) {
852 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
853 emsg = N_("More than one file given with -f");
854 goto jusage;
856 ++i;
858 } else {
859 options |= OPT_SENDMODE;
860 for (;;) {
861 to = cat(to, lextract(cp, GTO | GFULL));
862 if ((cp = argv[++i]) == NULL)
863 break;
864 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
865 ++i;
866 break;
870 _oind = i;
872 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
873 * allocate the necessary space for them before we fixate that storage! */
874 while (argv[i] != NULL)
875 ++i;
876 if (smopts_cnt + i > smopts_size)
877 DBG(smopts_size =) _grow_cpp(&smopts, smopts_cnt + i + 1, smopts_cnt);
879 /* Check for inconsistent arguments, fix some temporaries */
880 if (options & OPT_SENDMODE) {
881 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
882 * XXX in order to function. Ideally that would not be needed */
883 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
884 emsg = N_("Cannot give -f and people to send to.");
885 goto jusage;
887 if (myname != NULL) {
888 emsg = N_("The -u option cannot be used in send mode");
889 goto jusage;
891 if (!(options & OPT_t_FLAG) && to == NULL) {
892 emsg = N_("Send options without primary recipient specified.");
893 goto jusage;
895 if ((options & OPT_t_FLAG) && qf != NULL) {
896 emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
897 goto jusage;
899 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
900 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
901 goto jusage;
903 if (options & OPT_R_FLAG) {
904 emsg = N_("The -R option is meaningless in send mode.");
905 goto jusage;
908 if (options & OPT_INTERACTIVE) {
909 if (qf == (char*)-1) {
910 if (!(options & OPT_Mm_FLAG))
911 emsg = N_("-q can't use standard input when interactive.\n");
912 goto jusage;
915 } else {
916 if (myname != NULL && folder != NULL) {
917 emsg = N_("The options -u and -f (and -#) are mutually exclusive");
918 goto jusage;
920 if ((options & (OPT_EXISTONLY | OPT_HEADERSONLY)) ==
921 (OPT_EXISTONLY | OPT_HEADERSONLY)) {
922 emsg = N_("The options -e and -H are mutual exclusive");
923 goto jusage;
925 if ((options & (OPT_HEADERSONLY | OPT_HEADERLIST)) == /* TODO OBSOLETE */
926 (OPT_HEADERSONLY | OPT_HEADERLIST))
927 OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
929 if(myname != NULL)
930 folder = myname;
934 * Likely to go, perform more setup
937 _setup_vars();
939 if (options & OPT_INTERACTIVE) {
940 _setscreensize(0);
941 #ifdef SIGWINCH
942 # ifndef TTY_WANTS_SIGWINCH
943 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
944 # endif
945 safe_signal(SIGWINCH, &_setscreensize);
946 #endif
947 } else
948 scrnheight = realscreenheight = 24, scrnwidth = 80;
950 /* Fixate the current snapshot of our global auto-reclaimed storage instance.
951 * Memory is auto-reclaimed from now on */
952 n_memory_autorec_fixate();
954 /* load() any resource files */
955 if(resfiles & a_RF_ALL){
956 /* *expand() returns a savestr(), but load only uses the file name for
957 * fopen(), so it's safe to do this */
958 if((resfiles & a_RF_SYSTEM) && !ok_blook(NAIL_NO_SYSTEM_RC))
959 n_load(VAL_SYSCONFDIR "/" VAL_SYSCONFRC);
960 if(resfiles & a_RF_USER)
961 n_load(file_expand(ok_vlook(MAILRC)));
962 if((cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
963 n_load(file_expand(cp));
966 /* Ensure the -S and other command line options take precedence over
967 * anything that may have been placed in resource files.
968 * Our "ternary binary" option *verbose* needs special treament */
969 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
970 options &= ~OPT_VERB;
971 /* ..and be silent when unsetting an undefined variable */
972 pstate |= PS_ROBOT;
973 for (i = 0; UICMP(z, i, <, oargs_cnt); ++i) {
974 char const *a[2];
976 a[0] = oargs[i];
977 a[1] = NULL;
978 c_set(a);
980 pstate &= ~PS_ROBOT;
982 /* Cause possible umask(2), now that any setting is established, and before
983 * we change accounts, evaluate commands etc. */
984 (void)ok_vlook(umask);
986 /* Additional options to pass-through to MTA, and allowed to do so? */
987 if ((cp = ok_vlook(expandargv)) != NULL) {
988 bool_t isfail = !asccasecmp(cp, "fail"),
989 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
991 if ((options & OPT_D_V) && !isfail && !isrestrict && *cp != '\0')
992 n_err(_("Unknown *expandargv* value: %s\n"), cp);
994 if ((cp = argv[i = _oind]) != NULL) {
995 if (isfail ||
996 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
997 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
998 "using *sendmail-arguments*\n"));
999 exit_status = EXIT_USE | EXIT_SEND_ERROR;
1000 goto jleave;
1002 do {
1003 assert(smopts_cnt + 1 <= smopts_size);
1004 smopts[smopts_cnt++] = cp;
1005 } while ((cp = argv[++i]) != NULL);
1009 /* We had to wait until the resource files are loaded and any command line
1010 * setting has been restored, but get the termcap up and going before we
1011 * switch account or running commands */
1012 #ifdef n_HAVE_TCAP
1013 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1014 n_termcap_init();
1015 #endif
1017 /* Now we can set the account */
1018 if (Aarg != NULL) {
1019 char const *a[2];
1020 a[0] = Aarg;
1021 a[1] = NULL;
1022 c_account(a);
1025 /* "load()" commands given on command line */
1026 if(Xargs_cnt > 0)
1027 n_load_Xargs(Xargs, Xargs_cnt);
1029 /* Final tests */
1030 if(options & OPT_Mm_FLAG){
1031 if(qf == (char*)-1){
1032 if(!mime_type_check_mtname(option_Mm_arg)){
1033 n_err(_("Could not find `mimetype' for -M argument: %s\n"),
1034 option_Mm_arg);
1035 exit_status = EXIT_ERR;
1036 goto jleave;
1038 }else if((option_Mm_arg = mime_type_classify_filename(qf)) == NULL){
1039 n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
1040 n_shexp_quote_cp(qf, FAL0));
1041 exit_status = EXIT_ERR;
1042 goto jleave;
1043 }else if(!asccasecmp(option_Mm_arg, "text/plain")) /* TODO no: magic!! */
1044 option_Mm_arg = NULL;
1048 * We're finally completely setup and ready to go
1050 pstate |= PS_STARTED;
1052 if (!(options & OPT_SENDMODE)) {
1053 exit_status = _rcv_mode(folder, Larg);
1054 goto jleave;
1057 /* Now that full mailx(1)-style file expansion is possible handle the
1058 * attachments which we had delayed due to this.
1059 * This may use savestr(), but since we won't enter the command loop we
1060 * don't need to care about that */
1061 for (cp = NULL; a_head != NULL;) {
1062 struct attachment *nahp, *nap;
1064 if ((nahp = add_attachment(n_LEXINPUT_CTX_DEFAULT, attach,
1065 a_head->aa_file, &nap)) != NULL) {
1066 attach = nahp;
1067 /* Did we split a charset set name for fixation purposes? */
1068 if (cp != NULL) {
1069 nap->a_conv = AC_FIX_INCS;
1070 nap->a_input_charset = cp;
1071 cp = NULL;
1073 a_head = a_head->aa_next;
1074 continue;
1076 i = errno;
1078 /* It may not have worked because of an appended character set name, so
1079 * try to split name and charset and retry once */
1080 if (cp == NULL && (cp = strrchr(a_head->aa_file, '=')) != NULL) {
1081 char *ncp, *nfp = savestrbuf(a_head->aa_file,
1082 PTR2SIZE(cp - a_head->aa_file));
1084 for (ncp = ++cp; *ncp != '\0'; ++ncp)
1085 if (!alnumchar(*ncp) && !punctchar(*ncp))
1086 break;
1087 if (*ncp == '\0') {
1088 a_head->aa_file = nfp;
1089 continue;
1093 n_perr(a_head->aa_file, i);
1094 exit_status = EXIT_ERR;
1095 goto jleave;
1098 if (options & OPT_INTERACTIVE)
1099 n_tty_init();
1100 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1101 if (options & OPT_INTERACTIVE)
1102 n_tty_destroy();
1104 jleave:
1105 #ifdef n_HAVE_TCAP
1106 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1107 n_termcap_destroy();
1108 #endif
1109 j_leave:
1110 #ifdef HAVE_MEMORY_DEBUG
1111 n_memory_autorec_pop(NULL);
1112 #endif
1113 n_memory_reset();
1114 NYD_LEAVE;
1115 return exit_status;
1118 FL int
1119 c_exit(void *v){/* TODO program state machine */
1120 NYD_ENTER;
1121 n_UNUSED(v);
1123 if(pstate & PS_STARTED){
1124 if(!(pstate & PS_SOURCING)){
1125 #ifdef n_HAVE_TCAP
1126 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) ==
1127 OPT_INTERACTIVE)
1128 n_termcap_destroy();
1129 #endif
1130 exit(EXIT_OK);
1133 pstate |= PS_EXIT;
1134 NYD_LEAVE;
1135 return 0;
1138 /* Source the others in that case! */
1139 #ifdef HAVE_AMALGAMATION
1140 # include "config.h"
1141 #endif
1143 /* s-it-mode */