Add PS_SIGWINCH_PEND (mutt#3837 by flachkapp)..
[s-mailx.git] / main.c
blobc3d7da3d99ca34eefa2a892a5c8f5ba7a5db0c95
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Startup and initialization.
3 *@ This file is also used to materialize externals.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 #undef n_FILE
37 #define n_FILE main
38 #define n_MAIN_SOURCE
40 #include "nail.h"
42 #include <sys/ioctl.h>
44 #include <pwd.h>
46 #ifdef HAVE_NL_LANGINFO
47 # include <langinfo.h>
48 #endif
49 #ifdef HAVE_SETLOCALE
50 # include <locale.h>
51 #endif
53 struct a_arg {
54 struct a_arg *aa_next;
55 char *aa_file;
58 /* (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 UAGENT] = UAGENT;
67 VL uc_i const class_char[1 + 0x7F] = {
68 /* 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel */
69 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
70 /* 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si */
71 C_CNTRL, C_BLANK, C_WHITE, C_SPACE, C_SPACE, C_SPACE, C_CNTRL, C_CNTRL,
72 /* 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb */
73 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
74 /* 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us */
75 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
76 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
77 C_BLANK, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
78 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
79 C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
80 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
81 C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL,
82 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
83 C_DIGIT, C_DIGIT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
84 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
85 C_PUNCT, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
86 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
87 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
88 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
89 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
90 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
91 C_UPPER, C_UPPER, C_UPPER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
92 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
93 C_PUNCT, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
94 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
95 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
96 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
97 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
98 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
99 C_LOWER, C_LOWER, C_LOWER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_CNTRL
102 /* Our own little getopt(3) */
103 static char *_oarg;
104 static int _oind, /*_oerr,*/ _oopt;
106 /* Our own little getopt(3); note --help is special-treated as 'h' */
107 static int _getopt(int argc, char * const argv[], char const *optstring);
109 /* Perform basic startup initialization */
110 static void _startup(void);
112 /* Grow a char** */
113 static size_t _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt);
115 /* Initialize *tempdir*, *myname*, *homedir* */
116 static void _setup_vars(void);
118 /* We're in an interactive session - compute what the screen size for printing
119 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
120 * We use the following algorithm for the height:
121 * If baud rate < 1200, use 9
122 * If baud rate = 1200, use 14
123 * If baud rate > 1200, use 24 or ws_row
124 * Width is either 80 or ws_col */
125 static void _setscreensize(int is_sighdl);
127 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
128 * the system mailbox, and open up the right stuff */
129 static int _rcv_mode(char const *folder, char const *Larg);
131 /* Interrupt printing of the headers */
132 static void _hdrstop(int signo);
134 static int
135 _getopt(int argc, char * const argv[], char const *optstring)
137 static char const *lastp;
139 int rv = -1/*, colon*/;
140 char const *curp;
141 NYD_ENTER;
143 _oarg = NULL;
145 /*if ((colon = (optstring[0] == ':')))
146 ++optstring;*/
148 if (lastp != NULL) {
149 curp = lastp;
150 lastp = NULL;
151 } else {
152 if (_oind >= argc || argv[_oind] == NULL || argv[_oind][0] != '-' ||
153 argv[_oind][1] == '\0')
154 goto jleave;
155 if (argv[_oind][1] == '-' && argv[_oind][2] == '\0') {
156 /* We need this in for MTA arg detection (easier) ++_oind;*/
157 goto jleave;
159 curp = &argv[_oind][1];
162 for(_oopt = curp[0]; optstring[0] != '\0';){
163 if(optstring[0] != _oopt){
164 optstring += 1 + (optstring[1] == ':');
165 continue;
168 if (optstring[1] == ':') {
169 if (curp[1] != '\0') {
170 _oarg = UNCONST(curp + 1);
171 ++_oind;
172 } else {
173 if ((_oind += 2) > argc) {
174 /*if (!colon *//*&& _oerr*//*)*/ {
175 n_err(_("%s: option requires an argument -- %c\n"),
176 argv[0], (char)_oopt);
178 rv = (/*colon ? ':' :*/ '?');
179 goto jleave;
181 _oarg = argv[_oind - 1];
183 } else {
184 if (curp[1] != '\0')
185 lastp = curp + 1;
186 else
187 ++_oind;
189 rv = _oopt;
190 goto jleave;
193 /* Special support for --help, which is quite common */
194 if (_oopt == '-' && !strcmp(curp, "-help") && curp - 1 == argv[_oind]) {
195 ++_oind;
196 rv = 'h';
197 goto jleave;
200 /* Definitive error */
201 /*if (!colon *//*&& opterr*//*)*/
202 n_err(_("%s: invalid option -- %c\n"), argv[0], _oopt);
203 if (curp[1] != '\0')
204 lastp = curp + 1;
205 else
206 ++_oind;
207 _oarg = NULL;
208 rv = '?';
209 jleave:
210 NYD_LEAVE;
211 return rv;
214 static void
215 _startup(void)
217 char *cp;
218 NYD_ENTER;
220 image = -1;
221 dflpipe = SIG_DFL;
222 _oind = /*_oerr =*/ 1;
224 if ((cp = strrchr(progname, '/')) != NULL)
225 progname = ++cp;
227 /* Set up a reasonable environment */
229 #ifdef HAVE_NYD
230 safe_signal(SIGABRT, &_nyd_oncrash);
231 # ifdef SIGBUS
232 safe_signal(SIGBUS, &_nyd_oncrash);
233 # endif
234 safe_signal(SIGFPE, &_nyd_oncrash);
235 safe_signal(SIGILL, &_nyd_oncrash);
236 safe_signal(SIGSEGV, &_nyd_oncrash);
237 #endif
238 command_manager_start();
240 if (isatty(STDIN_FILENO)) /* TODO should be isatty(0) && isatty(2)?? */
241 options |= OPT_TTYIN;
242 if (isatty(STDOUT_FILENO))
243 options |= OPT_TTYOUT;
244 if ((options & (OPT_TTYIN | OPT_TTYOUT)) == (OPT_TTYIN | OPT_TTYOUT)) {
245 options |= OPT_INTERACTIVE;
246 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
249 /* -- >8 -- 8< -- */
251 /* Define defaults for internal variables, based on POSIX 2008/Cor 1-2013 */
252 /* (Keep in sync:
253 * ./main.c:_startup(), ./nail.rc, ./nail.1:"Initial settings") */
254 /* noallnet */
255 /* noappend */
256 ok_bset(asksub, TRU1);
257 /* noaskbcc */
258 /* noaskcc */
259 /* noautoprint */
260 /* nobang */
261 /* nocmd */
262 /* nocrt */
263 /* nodebug */
264 /* nodot */
265 /* ok_vset(escape, ESCAPE *"~"*); TODO non-compliant */
266 /* noflipr */
267 /* nofolder */
268 ok_bset(header, TRU1);
269 /* nohold */
270 /* noignore */
271 /* noignoreeof */
272 /* nokeep */
273 /* nokeepsave */
274 /* nometoo */
275 /* noonehop -- Note: we ignore this one */
276 /* nooutfolder */
277 /* nopage */
278 ok_vset(prompt, "\\& "); /* POSIX "? " unless *bsdcompat*, then "& " */
279 /* noquiet */
280 /* norecord */
281 ok_bset(save, TRU1);
282 /* nosendwait */
283 /* noshowto */
284 /* nosign */
285 /* noSign */
286 /* ok_vset(toplines, "5"); XXX somewhat hmm */
288 /* TODO until we have an automatic mechanism for that, set some more
289 * TODO variables so that users see the internal fallback settings
290 * TODO (something like "defval=X,notempty=1") */
291 do {
292 char const *vp;
294 vp = env_vlook("SHELL", TRU1);
295 ok_vset(SHELL, (vp != NULL ? vp : XSHELL));
297 vp = env_vlook("LISTER", TRU1);
298 ok_vset(LISTER, (vp != NULL ? vp : XLISTER));
300 vp = env_vlook("PAGER", TRU1);
301 ok_vset(PAGER, (vp != NULL ? vp : XPAGER));
303 ok_vset(sendmail, SENDMAIL);
304 ok_vset(sendmail_progname, SENDMAIL_PROGNAME);
305 } while (0);
307 /* -- >8 -- 8< -- */
309 #ifdef HAVE_SETLOCALE
310 setlocale(LC_ALL, "");
311 mb_cur_max = MB_CUR_MAX;
312 # ifdef HAVE_NL_LANGINFO
313 if (ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
314 ok_vset(ttycharset, cp);
315 # endif
317 # ifdef HAVE_C90AMEND1
318 if (mb_cur_max > 1) {
319 wchar_t wc;
320 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
321 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
322 options |= OPT_UNICODE;
323 /* Reset possibly messed up state; luckily this also gives us an
324 * indication wether the encoding has locking shift state sequences */
325 /* TODO temporary - use option bits! */
326 if (mbtowc(&wc, NULL, mb_cur_max))
327 options |= OPT_ENC_MBSTATE;
329 # endif
330 #else
331 mb_cur_max = 1;
332 #endif
334 #ifdef HAVE_ICONV
335 iconvd = (iconv_t)-1;
336 #endif
337 NYD_LEAVE;
340 static size_t
341 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
343 /* Before spreserve(): use our string pool instead of LibC heap */
344 char const **newcpp;
345 NYD_ENTER;
347 newcpp = salloc(sizeof(char*) * newsize);
349 if (oldcnt > 0)
350 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
351 *cpp = newcpp;
352 NYD_LEAVE;
353 return newsize;
356 static void
357 _setup_vars(void)
359 /* Before spreserve(): use our string pool instead of LibC heap */
360 /* XXX further check paths? */
361 char const *cp;
362 uid_t uid;
363 struct passwd *pwuid, *pw;
364 NYD_ENTER;
366 /* Verify and fixate user identification */
367 if (myname != NULL)
368 cp = myname;
369 else if ((cp = env_vlook("LOGNAME", TRU1)) == NULL)
370 cp = env_vlook("USER", TRU1);
372 group_id = getgid();
373 user_id = uid = getuid();
374 if ((pwuid = getpwuid(uid)) == NULL)
375 n_panic(_("Cannot associate a name with uid %u"), user_id);
377 if (cp == NULL || *cp == '\0')
378 myname = pwuid->pw_name;
379 else if ((pw = getpwnam(cp)) == NULL) {
380 n_alert(_("\"%s\" is not a user of this system"), cp);
381 exit(EXIT_NOUSER);
382 } else {
383 myname = pw->pw_name;
384 if (pw->pw_uid != uid)
385 options |= OPT_u_FLAG;
387 myname = savestr(myname);
388 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
390 /* */
391 if ((cp = env_vlook("HOME", TRU1)) == NULL)
392 cp = "."; /* XXX User and Login objects; Login: pw->pw_dir */
393 homedir = savestr(cp);
395 tempdir = ((cp = env_vlook("TMPDIR", TRU1)) != NULL)
396 ? savestr(cp) : TMPDIR_FALLBACK;
397 NYD_LEAVE;
400 static void
401 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
403 struct termios tbuf;
404 #ifdef TIOCGWINSZ
405 struct winsize ws;
406 #elif defined TIOCGSIZE
407 struct ttysize ts;
408 #endif
409 NYD_ENTER;
411 scrnheight = realscreenheight = scrnwidth = 0;
413 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
414 * a little bit to be able to honour resizes during our lifetime and
415 * only honour it upon first run; abuse *is_sighdl* as an indicator */
416 if (!is_sighdl) {
417 char *cp;
418 long i;
420 /* We manage those variables for our child processes, so ensure they
421 * are up to date, always */
422 if (options & OPT_INTERACTIVE)
423 pstate |= PS_SIGWINCH_PEND;
425 if ((cp = env_vlook("LINES", FAL0)) != NULL &&
426 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
427 scrnheight = realscreenheight = (int)i;
428 if ((cp = env_vlook("COLUMNS", FAL0)) != NULL &&
429 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
430 scrnwidth = (int)i;
432 if (scrnwidth != 0 && scrnheight != 0)
433 goto jleave;
436 #ifdef TIOCGWINSZ
437 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
438 ws.ws_col = ws.ws_row = 0;
439 #elif defined TIOCGSIZE
440 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
441 ts.ts_lines = ts.ts_cols = 0;
442 #endif
444 if (scrnheight == 0) {
445 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
446 ? B9600 : cfgetospeed(&tbuf));
448 if (ospeed < B1200)
449 scrnheight = 9;
450 else if (ospeed == B1200)
451 scrnheight = 14;
452 #ifdef TIOCGWINSZ
453 else if (ws.ws_row != 0)
454 scrnheight = ws.ws_row;
455 #elif defined TIOCGSIZE
456 else if (ts.ts_lines != 0)
457 scrnheight = ts.ts_lines;
458 #endif
459 else
460 scrnheight = 24;
462 #if defined TIOCGWINSZ || defined TIOCGSIZE
463 if (0 ==
464 # ifdef TIOCGWINSZ
465 (realscreenheight = ws.ws_row)
466 # else
467 (realscreenheight = ts.ts_lines)
468 # endif
470 realscreenheight = 24;
471 #endif
474 if (scrnwidth == 0 && 0 ==
475 #ifdef TIOCGWINSZ
476 (scrnwidth = ws.ws_col)
477 #elif defined TIOCGSIZE
478 (scrnwidth = ts.ts_cols)
479 #endif
481 scrnwidth = 80;
483 jleave:
484 #ifdef SIGWINCH
485 if (is_sighdl) {
486 pstate |= PS_SIGWINCH_PEND; /* XXX Not atomic */
487 if (options & OPT_INTERACTIVE)
488 n_tty_signal(SIGWINCH);
490 #endif
491 NYD_LEAVE;
494 static sigjmp_buf __hdrjmp; /* XXX */
496 static int
497 _rcv_mode(char const *folder, char const *Larg)
499 int i;
500 sighandler_type prevint;
501 NYD_ENTER;
503 if (folder == NULL)
504 folder = "%";
506 if (options & OPT_QUICKRUN_MASK)
507 i = FEDIT_RDONLY;
508 else
509 i = FEDIT_NONE;
510 i = setfile(folder, i);
511 if (i < 0) {
512 exit_status = EXIT_ERR; /* error already reported */
513 goto jquit;
515 if (options & OPT_QUICKRUN_MASK) {
516 exit_status = i;
517 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
518 (options & OPT_HEADERLIST)))
519 print_header_summary(Larg);
520 goto jquit;
522 check_folder_hook(FAL0);
524 if (i > 0 && !ok_blook(emptystart)) {
525 exit_status = EXIT_ERR;
526 goto jleave;
529 if (sigsetjmp(__hdrjmp, 1) == 0) {
530 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
531 safe_signal(SIGINT, _hdrstop);
532 if (!(options & OPT_N_FLAG)) {
533 if (!ok_blook(quiet))
534 printf(_("%s version %s. Type ? for help.\n"),
535 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
536 announce(1);
537 fflush(stdout);
539 safe_signal(SIGINT, prevint);
542 /* Enter the command loop */
543 if (options & OPT_INTERACTIVE)
544 n_tty_init();
545 n_commands();
546 if (options & OPT_INTERACTIVE)
547 n_tty_destroy();
549 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
550 safe_signal(SIGHUP, SIG_IGN);
551 safe_signal(SIGINT, SIG_IGN);
552 safe_signal(SIGQUIT, SIG_IGN);
554 jquit:
555 save_mbox_for_possible_quitstuff();
556 quit();
557 jleave:
558 NYD_LEAVE;
559 return exit_status;
562 static void
563 _hdrstop(int signo)
565 NYD_X; /* Signal handler */
566 UNUSED(signo);
568 fflush(stdout);
569 n_err_sighdl(_("\nInterrupt\n"));
570 siglongjmp(__hdrjmp, 1);
574 main(int argc, char *argv[]){
575 static char const optstr[] = "A:a:Bb:c:dEeFfHhiL:NnO:q:Rr:S:s:tu:VvX:::~#.",
576 usagestr[] = N_(
577 "Synopsis:\n"
578 " %s -h | --help\n"
579 " %s [-BdEFintv~] [-: spec] [-A account]\n"
580 "\t [-a attachment] [-b bcc-address] [-c cc-address]\n"
581 "\t [-q file] [-r from-address] [-S var[=value]..]\n"
582 "\t [-s subject] [-X cmd] [-.] to-address.. [-- mta-option..]\n"
583 " %s [-BdEeHiNnRv~#] [-: spec] [-A account]\n"
584 "\t [-L spec-list] [-r from-address] [-S var[=value]..]\n"
585 "\t [-X cmd] -f [file] [-- mta-option..]\n"
586 " %s [-BdEeHiNnRv~#] [-: spec] [-A account]\n"
587 "\t [-L spec-list] [-r from-address] [-S var[=value]..]\n"
588 "\t [-u user] [-X cmd] [-- mta-option..]\n"
590 #define _USAGE_ARGS , progname, progname, progname, progname
592 struct a_arg *a_head, *a_curr;
593 struct name *to, *cc, *bcc;
594 struct attachment *attach;
595 char *cp, *subject, *qf, *Aarg, *Larg;
596 char const *okey, **oargs, **Xargs, *folder, *emsg;
597 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
598 enum{
599 a_RF_NONE = 0,
600 a_RF_SET = 1<<0,
601 a_RF_SYSTEM = 1<<1,
602 a_RF_USER = 1<<2,
603 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
604 } resfiles;
605 int i;
606 NYD_ENTER;
608 a_head = NULL;
609 UNINIT(a_curr, NULL);
610 to = cc = bcc = NULL;
611 attach = NULL;
612 cp = subject = qf =
613 Aarg = Larg = NULL;
614 oargs = Xargs = NULL;
615 folder = emsg = NULL;
616 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
617 resfiles = a_RF_ALL;
620 * Start our lengthy setup, finalize by setting PS_STARTED
623 progname = argv[0];
624 _startup();
626 /* Command line parsing
627 * Variable settings need to be done twice, since the user surely wants the
628 * setting to take effect immediately, but also doesn't want it to be
629 * overwritten from within resource files */
630 while ((i = _getopt(argc, argv, optstr)) >= 0) {
631 switch (i) {
632 case 'A':
633 /* Execute an account command later on */
634 Aarg = _oarg;
635 break;
636 case 'a':
637 options |= OPT_SENDMODE;
638 { struct a_arg *nap = salloc(sizeof(struct a_arg));
639 if (a_head == NULL)
640 a_head = nap;
641 else
642 a_curr->aa_next = nap;
643 nap->aa_next = NULL;
644 nap->aa_file = _oarg;
645 a_curr = nap;
647 break;
648 case 'B':
649 /* Make 0/1 line buffered */
650 setvbuf(stdin, NULL, _IOLBF, 0);
651 setvbuf(stdout, NULL, _IOLBF, 0);
652 break;
653 case 'b':
654 /* Get Blind Carbon Copy Recipient list */
655 options |= OPT_SENDMODE;
656 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
657 break;
658 case 'c':
659 /* Get Carbon Copy Recipient list */
660 options |= OPT_SENDMODE;
661 cc = cat(cc, lextract(_oarg, GCC | GFULL));
662 break;
663 case 'd':
664 ok_bset(debug, TRU1);
665 okey = "debug";
666 goto joarg;
667 case 'E':
668 ok_bset(skipemptybody, TRU1);
669 okey = "skipemptybody";
670 goto joarg;
671 case 'e':
672 options |= OPT_EXISTONLY;
673 break;
674 case 'F':
675 options |= OPT_F_FLAG | OPT_SENDMODE;
676 break;
677 case 'f':
678 /* User is specifying file to "edit" with Mail, as opposed to reading
679 * system mailbox. If no argument is given, we read his mbox file.
680 * Check for remaining arguments later */
681 folder = "&";
682 break;
683 case 'H':
684 options |= OPT_HEADERSONLY;
685 break;
686 case 'h':
687 n_err(V_(usagestr) _USAGE_ARGS);
688 goto j_leave;
689 case 'i':
690 /* Ignore interrupts */
691 ok_bset(ignore, TRU1);
692 okey = "ignore";
693 goto joarg;
694 case 'L':
695 Larg = _oarg;
696 options |= OPT_HEADERLIST;
697 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
698 size_t j = strlen(++Larg);
699 if (j > 0)
700 Larg[j - 1] = '\0';
702 break;
703 case 'N':
704 /* Avoid initial header printing */
705 ok_bset(header, FAL0);
706 okey = "noheader";
707 goto joarg;
708 case 'n':
709 /* Don't source "unspecified system start-up file" */
710 if(resfiles & a_RF_SET){
711 emsg = N_("-n cannot be used in conjunction with -:");
712 goto jusage;
714 resfiles = a_RF_USER;
715 break;
716 case 'O':
717 /* Additional options to pass-through to MTA TODO v15-compat legacy */
718 if (smopts_cnt == smopts_size)
719 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_cnt);
720 smopts[smopts_cnt++] = _oarg;
721 break;
722 case 'q':
723 /* Quote file TODO drop? -Q with real quote?? what ? */
724 options |= OPT_SENDMODE;
725 /* Allow for now, we have to special check validity of -q- later on! */
726 qf = (_oarg[0] == '-' && _oarg[1] == '\0') ? (char*)-1 : _oarg;
727 break;
728 case 'R':
729 /* Open folders read-only */
730 options |= OPT_R_FLAG;
731 break;
732 case 'r':
733 /* Set From address. */
734 options |= OPT_r_FLAG;
735 if (_oarg[0] != '\0') {
736 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
738 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
739 emsg = N_("Invalid address argument with -r");
740 goto jusage;
742 option_r_arg = fa;
743 /* TODO -r options is set in smopts, but may
744 * TODO be overwritten by setting from= in
745 * TODO an interactive session!
746 * TODO Maybe disable setting of from?
747 * TODO Warn user? Update manual!! */
748 okey = savecat("from=", fa->n_fullname);
749 goto joarg;
751 break;
752 case 'S':
753 /* Set variable (twice) */
754 { char *a[2];
755 okey = a[0] = _oarg;
756 a[1] = NULL;
757 c_set(a);
759 joarg:
760 if (oargs_cnt == oargs_size)
761 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
762 oargs[oargs_cnt++] = okey;
763 break;
764 case 's':
765 /* Subject: */
766 subject = _oarg;
767 options |= OPT_SENDMODE;
768 break;
769 case 't':
770 /* Read defined set of headers from mail to be sent */
771 options |= OPT_SENDMODE | OPT_t_FLAG;
772 break;
773 case 'u':
774 /* Set user name to pretend to be; don't set OPT_u_FLAG yet, this is
775 * done as necessary in _setup_vars() above */
776 myname = _oarg;
777 break;
778 case 'V':
779 puts(ok_vlook(version));
780 exit(EXIT_OK);
781 /* NOTREACHED */
782 case 'v':
783 /* Be verbose */
784 ok_bset(verbose, TRU1);
785 okey = "verbose";
786 goto joarg;
787 case 'X':
788 /* Add to list of commands to exec before entering normal operation */
789 if (Xargs_cnt == Xargs_size)
790 Xargs_size = _grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
791 Xargs[Xargs_cnt++] = _oarg;
792 break;
793 case ':':
794 /* Control which resource files shall be loaded */
795 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
796 emsg = N_("-n cannot be used in conjunction with -:");
797 goto jusage;
799 resfiles = a_RF_SET;
800 while((i = *_oarg++) != '\0')
801 switch(i){
802 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
803 case 'U': case 'u': resfiles |= a_RF_USER; break;
804 case ':': case '/': resfiles &= ~a_RF_ALL; break;
805 default:
806 emsg = N_("Invalid argument of -:");
807 goto jusage;
809 break;
810 case '~':
811 /* Enable tilde escapes even in non-interactive mode */
812 options |= OPT_TILDE_FLAG;
813 break;
814 case '#':
815 /* Work in batch mode, even if non-interactive */
816 if (oargs_cnt + 5 >= oargs_size)
817 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
818 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
819 folder = "/dev/null";
820 ok_bset(emptystart, TRU1);
821 ok_bset(header, FAL0);
822 ok_bset(quiet, TRU1);
823 ok_bset(sendwait, TRU1);
824 ok_vset(MBOX, folder);
825 oargs[oargs_cnt + 0] = "emptystart";
826 oargs[oargs_cnt + 1] = "noheader";
827 oargs[oargs_cnt + 2] = "quiet";
828 oargs[oargs_cnt + 3] = "sendwait";
829 oargs[oargs_cnt + 4] = "MBOX=/dev/null";
830 oargs_cnt += 5;
831 break;
832 case '.':
833 options |= OPT_SENDMODE;
834 goto jgetopt_done;
835 case '?':
836 jusage:
837 if (emsg != NULL)
838 n_err("%s\n", V_(emsg));
839 n_err(V_(usagestr) _USAGE_ARGS);
840 #undef _USAGE_ARGS
841 exit_status = EXIT_USE;
842 goto j_leave;
845 jgetopt_done:
848 /* The normal arguments may be followed by MTA arguments after a "--";
849 * however, -f may take off an argument, too, and before that.
850 * Since MTA arguments after "--" require *expandargv*, delay parsing off
851 * those options until after the resource files are loaded... */
852 if ((cp = argv[i = _oind]) == NULL)
854 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
855 ++i;
856 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
857 else if (folder != NULL && folder[1] == '\0') {
858 folder = cp;
859 if ((cp = argv[++i]) != NULL) {
860 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
861 emsg = N_("More than one file given with -f");
862 goto jusage;
864 ++i;
866 } else {
867 options |= OPT_SENDMODE;
868 for (;;) {
869 to = cat(to, lextract(cp, GTO | GFULL));
870 if ((cp = argv[++i]) == NULL)
871 break;
872 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
873 ++i;
874 break;
878 _oind = i;
880 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
881 * allocate the necessary space for them before we call spreserve()! */
882 while (argv[i] != NULL)
883 ++i;
884 if (smopts_cnt + i > smopts_size)
885 DBG(smopts_size =) _grow_cpp(&smopts, smopts_cnt + i + 1, smopts_cnt);
887 /* Check for inconsistent arguments */
888 if (options & OPT_SENDMODE) {
889 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
890 * XXX in order to function. Ideally that would not be needed */
891 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
892 emsg = N_("Cannot give -f and people to send to.");
893 goto jusage;
895 if (myname != NULL) {
896 emsg = N_("The -u option cannot be used in send mode");
897 goto jusage;
899 if (!(options & OPT_t_FLAG) && to == NULL) {
900 emsg = N_("Send options without primary recipient specified.");
901 goto jusage;
903 if ((options & OPT_t_FLAG) && qf != NULL) {
904 emsg = N_("-t and -q are mutual exclusive.");
905 goto jusage;
907 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
908 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
909 goto jusage;
911 if (options & OPT_R_FLAG) {
912 emsg = N_("The -R option is meaningless in send mode.");
913 goto jusage;
915 } else {
916 if (folder != NULL && myname != NULL) {
917 emsg = N_("The options -f and -u 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\""));
931 * Likely to go, perform more setup
934 _setup_vars();
936 if (options & OPT_INTERACTIVE) {
937 /* Now we can finally check wether -q- was given */
938 if (qf == (char*)-1) {
939 emsg = N_("In interactive mode -q cannot use standard input \"-\"\n");
940 goto jusage;
943 _setscreensize(0);
944 #ifdef SIGWINCH
945 # ifndef TTY_WANTS_SIGWINCH
946 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
947 # endif
948 safe_signal(SIGWINCH, _setscreensize);
949 #endif
950 } else
951 scrnheight = realscreenheight = 24, scrnwidth = 80;
953 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
954 spreserve();
956 /* load() any resource files */
957 if(resfiles & a_RF_ALL){
958 /* *expand() returns a savestr(), but load only uses the file name for
959 * fopen(), so it's safe to do this */
960 if((resfiles & a_RF_SYSTEM) && !env_blook("NAIL_NO_SYSTEM_RC", TRU1))
961 n_load(SYSCONFDIR "/" SYSCONFRC);
962 if(resfiles & a_RF_USER){
963 if((cp = env_vlook("MAILRC", TRU1)) == NULL)
964 cp = UNCONST(MAILRC);
965 n_load(file_expand(cp));
967 if(env_vlook("NAIL_EXTRA_RC", TRU1) == NULL &&
968 (cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
969 n_load(file_expand(cp));
972 /* Ensure the -S and other command line options take precedence over
973 * anything that may have been placed in resource files.
974 * Our "ternary binary" option *verbose* needs special treament */
975 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
976 options &= ~OPT_VERB;
977 /* ..and be silent when unsetting an undefined variable */
978 pstate |= PS_ROBOT;
979 for (i = 0; UICMP(z, i, <, oargs_cnt); ++i) {
980 char const *a[2];
981 a[0] = oargs[i];
982 a[1] = NULL;
983 c_set(a);
985 pstate &= ~PS_ROBOT;
987 /* Additional options to pass-through to MTA, and allowed to do so? */
988 if ((cp = ok_vlook(expandargv)) != NULL) {
989 bool_t isfail = !asccasecmp(cp, "fail"),
990 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
992 if ((options & OPT_D_V) && !isfail && !isrestrict && *cp != '\0')
993 n_err(_("Unknown *expandargv* value: \"%s\"\n"), cp);
995 if ((cp = argv[i = _oind]) != NULL) {
996 if (isfail ||
997 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
998 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
999 "using *sendmail-arguments*\n"));
1000 exit_status = EXIT_USE | EXIT_SEND_ERROR;
1001 goto jleave;
1003 do {
1004 assert(smopts_cnt + 1 <= smopts_size);
1005 smopts[smopts_cnt++] = cp;
1006 } while ((cp = argv[++i]) != NULL);
1010 /* We had to wait until the resource files are loaded and any command line
1011 * setting has been restored, but get the termcap up and going before we
1012 * switch account or running commands */
1013 #ifdef n_HAVE_TCAP
1014 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1015 n_termcap_init();
1016 #endif
1018 /* Now we can set the account */
1019 if (Aarg != NULL) {
1020 char const *a[2];
1021 a[0] = Aarg;
1022 a[1] = NULL;
1023 c_account(a);
1026 /* "load()" commands given on command line */
1027 if (Xargs_cnt > 0){
1028 Xargs[Xargs_cnt] = NULL;
1029 n_load_Xargs(Xargs);
1033 * We're finally completely setup and ready to go
1035 pstate |= PS_STARTED;
1037 if (options & OPT_DEBUG)
1038 n_err(_("user = %s, homedir = %s\n"), myname, homedir);
1040 if (!(options & OPT_SENDMODE)) {
1041 exit_status = _rcv_mode(folder, Larg);
1042 goto jleave;
1045 /* Now that full mailx(1)-style file expansion is possible handle the
1046 * attachments which we had delayed due to this.
1047 * This may use savestr(), but since we won't enter the command loop we
1048 * don't need to care about that */
1049 for (cp = NULL; a_head != NULL;) {
1050 struct attachment *nahp, *nap;
1052 if ((nahp = add_attachment(attach, a_head->aa_file, &nap)) != NULL) {
1053 attach = nahp;
1054 /* Did we split a charset set name for fixation purposes? */
1055 if (cp != NULL) {
1056 nap->a_conv = AC_FIX_INCS;
1057 nap->a_input_charset = cp;
1058 cp = NULL;
1060 a_head = a_head->aa_next;
1061 continue;
1063 i = errno;
1065 /* It may not have worked because of an appended character set name, so
1066 * try to split name and charset and retry once */
1067 if (cp == NULL && (cp = strrchr(a_head->aa_file, '=')) != NULL) {
1068 char *ncp, *nfp = savestrbuf(a_head->aa_file,
1069 PTR2SIZE(cp - a_head->aa_file));
1071 for (ncp = ++cp; *ncp != '\0'; ++ncp)
1072 if (!alnumchar(*ncp) && !punctchar(*ncp))
1073 break;
1074 if (*ncp == '\0') {
1075 a_head->aa_file = nfp;
1076 continue;
1080 n_perr(a_head->aa_file, i);
1081 exit_status = EXIT_ERR;
1082 goto jleave;
1085 if (options & OPT_INTERACTIVE)
1086 n_tty_init();
1087 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1088 if (options & OPT_INTERACTIVE)
1089 n_tty_destroy();
1091 jleave:
1092 #ifdef n_HAVE_TCAP
1093 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1094 n_termcap_destroy();
1095 #endif
1096 #ifdef HAVE_MEMORY_DEBUG
1097 sreset(FAL0);
1098 #endif
1099 j_leave:
1100 #ifdef HAVE_MEMORY_DEBUG
1101 n_memcheck();
1102 #endif
1103 NYD_LEAVE;
1104 return exit_status;
1107 FL int
1108 c_exit(void *v){/* TODO program state machine */
1109 NYD_ENTER;
1110 UNUSED(v);
1112 if(pstate & PS_STARTED){
1113 if(!(pstate & PS_SOURCING)){
1114 #ifdef n_HAVE_TCAP
1115 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) ==
1116 OPT_INTERACTIVE)
1117 n_termcap_destroy();
1118 #endif
1119 exit(EXIT_OK);
1122 pstate |= PS_EXIT;
1123 NYD_LEAVE;
1124 return 0;
1127 /* Source the others in that case! */
1128 #ifdef HAVE_AMALGAMATION
1129 # include "config.h"
1130 #endif
1132 /* s-it-mode */