Show the Content-Description:, as applicable
[s-mailx.git] / main.c
blob83a0bd5942533616de738f14e51b3e13541224dd
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 /* STDOUT is always line buffered from our point of view */
259 setvbuf(stdout, NULL, _IOLBF, 0);
261 /* -- >8 -- 8< -- */
263 #ifndef HAVE_SETLOCALE
264 mb_cur_max = 1;
265 #else
266 setlocale(LC_ALL, n_empty);
267 mb_cur_max = MB_CUR_MAX;
268 # ifdef HAVE_NL_LANGINFO
269 if(ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
270 ok_vset(ttycharset, cp);
271 # endif
273 # ifdef HAVE_C90AMEND1
274 if(mb_cur_max > 1){
275 # ifdef HAVE_ALWAYS_UNICODE_LOCALE
276 options |= OPT_UNICODE;
277 # else
278 wchar_t wc;
279 if(mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
280 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
281 options |= OPT_UNICODE;
282 /* Reset possibly messed up state; luckily this also gives us an
283 * indication whether the encoding has locking shift state sequences */
284 if(mbtowc(&wc, NULL, mb_cur_max))
285 options |= OPT_ENC_MBSTATE;
286 # endif
288 # endif
289 #endif
291 #ifdef HAVE_ICONV
292 iconvd = (iconv_t)-1;
293 #endif
294 NYD_LEAVE;
297 static size_t
298 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
300 /* Just use auto-reclaimed storage, it will be preserved */
301 char const **newcpp;
302 NYD_ENTER;
304 newcpp = salloc(sizeof(char*) * newsize);
306 if (oldcnt > 0)
307 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
308 *cpp = newcpp;
309 NYD_LEAVE;
310 return newsize;
313 static void
314 _setup_vars(void){
315 /* XXX furtherly check paths? */
316 struct passwd *pwuid;
317 char const *cp;
318 NYD_ENTER;
320 group_id = getgid();
321 if((pwuid = getpwuid(user_id = getuid())) == NULL)
322 n_panic(_("Cannot associate a name with uid %lu"), (ul_i)user_id);
323 myname = savestr(pwuid->pw_name); /* XXX replace uses with vlook(LOGNAME)! */
325 /* C99 */{
326 char const *ep;
327 bool_t doenv;
329 if(!(doenv = (ep = ok_vlook(LOGNAME)) == NULL) &&
330 (doenv = strcmp(myname, ep)))
331 n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
332 ep, myname);
333 if(doenv){
334 pstate |= PS_ROOT;
335 ok_vset(LOGNAME, myname);
336 pstate &= ~PS_ROOT;
339 if((ep = ok_vlook(USER)) != NULL && strcmp(myname, ep)){
340 n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
341 ep, myname);
342 pstate |= PS_ROOT;
343 ok_vset(USER, myname);
344 pstate &= ~PS_ROOT;
348 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
350 /* */
351 if((cp = ok_vlook(HOME)) == NULL){
352 cp = pwuid->pw_dir;
353 pstate |= PS_ROOT;
354 ok_vset(HOME, cp);
355 pstate &= ~PS_ROOT;
358 /* Ensure some variables get loaded */
359 (void)ok_blook(POSIXLY_CORRECT);
360 (void)ok_vlook(TMPDIR);
361 NYD_LEAVE;
364 static void
365 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
367 struct termios tbuf;
368 #ifdef TIOCGWINSZ
369 struct winsize ws;
370 #elif defined TIOCGSIZE
371 struct ttysize ts;
372 #endif
373 NYD_ENTER;
375 scrnheight = realscreenheight = scrnwidth = 0;
377 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
378 * a little bit to be able to honour resizes during our lifetime and
379 * only honour it upon first run; abuse *is_sighdl* as an indicator */
380 if (!is_sighdl) {
381 char *cp;
383 /* We manage those variables for our child processes, so ensure they
384 * are up to date, always */
385 if (options & OPT_INTERACTIVE)
386 pstate |= PS_SIGWINCH_PEND;
388 if ((cp = ok_vlook(LINES)) != NULL)
389 scrnheight = realscreenheight = (int)strtoul(cp, NULL, 0); /* TODO */
390 if ((cp = ok_vlook(COLUMNS)) != NULL)
391 scrnwidth = (int)strtoul(cp, NULL, 0); /* TODO posui32= not posnum=! */
393 if (scrnwidth != 0 && scrnheight != 0)
394 goto jleave;
397 #ifdef TIOCGWINSZ
398 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
399 ws.ws_col = ws.ws_row = 0;
400 #elif defined TIOCGSIZE
401 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
402 ts.ts_lines = ts.ts_cols = 0;
403 #endif
405 if (scrnheight == 0) {
406 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
407 ? B9600 : cfgetospeed(&tbuf));
409 if (ospeed < B1200)
410 scrnheight = 9;
411 else if (ospeed == B1200)
412 scrnheight = 14;
413 #ifdef TIOCGWINSZ
414 else if (ws.ws_row != 0)
415 scrnheight = ws.ws_row;
416 #elif defined TIOCGSIZE
417 else if (ts.ts_lines != 0)
418 scrnheight = ts.ts_lines;
419 #endif
420 else
421 scrnheight = 24;
423 #if defined TIOCGWINSZ || defined TIOCGSIZE
424 if (0 ==
425 # ifdef TIOCGWINSZ
426 (realscreenheight = ws.ws_row)
427 # else
428 (realscreenheight = ts.ts_lines)
429 # endif
431 realscreenheight = 24;
432 #endif
435 if (scrnwidth == 0 && 0 ==
436 #ifdef TIOCGWINSZ
437 (scrnwidth = ws.ws_col)
438 #elif defined TIOCGSIZE
439 (scrnwidth = ts.ts_cols)
440 #endif
442 scrnwidth = 80;
444 jleave:
445 #ifdef SIGWINCH
446 if (is_sighdl) {
447 pstate |= PS_SIGWINCH_PEND; /* XXX Not atomic */
448 if (options & OPT_INTERACTIVE)
449 n_tty_signal(SIGWINCH);
451 #endif
452 NYD_LEAVE;
455 static sigjmp_buf __hdrjmp; /* XXX */
457 static int
458 _rcv_mode(char const *folder, char const *Larg)
460 int i;
461 sighandler_type prevint;
462 NYD_ENTER;
464 if (folder == NULL)
465 folder = "%";
467 if (options & OPT_QUICKRUN_MASK)
468 i = FEDIT_RDONLY;
469 else
470 i = FEDIT_NONE;
471 i = setfile(folder, i);
472 if (i < 0) {
473 exit_status = EXIT_ERR; /* error already reported */
474 goto jquit;
476 if (options & OPT_QUICKRUN_MASK) {
477 exit_status = i;
478 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
479 (options & OPT_HEADERLIST)))
480 print_header_summary(Larg);
481 goto jquit;
483 check_folder_hook(FAL0);
485 if (i > 0 && !ok_blook(emptystart)) {
486 exit_status = EXIT_ERR;
487 goto jleave;
490 if (sigsetjmp(__hdrjmp, 1) == 0) {
491 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
492 safe_signal(SIGINT, _hdrstop);
493 if (!(options & OPT_N_FLAG)) {
494 if (!ok_blook(quiet))
495 printf(_("%s version %s. Type `?' for help\n"),
496 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
497 announce(1);
498 fflush(stdout);
500 safe_signal(SIGINT, prevint);
503 /* Enter the command loop */
504 if (options & OPT_INTERACTIVE)
505 n_tty_init();
506 n_commands();
507 if (options & OPT_INTERACTIVE)
508 n_tty_destroy();
510 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
511 safe_signal(SIGHUP, SIG_IGN);
512 safe_signal(SIGINT, SIG_IGN);
513 safe_signal(SIGQUIT, SIG_IGN);
515 jquit:
516 save_mbox_for_possible_quitstuff();
517 quit(FAL0);
518 jleave:
519 NYD_LEAVE;
520 return exit_status;
523 static void
524 _hdrstop(int signo)
526 NYD_X; /* Signal handler */
527 n_UNUSED(signo);
529 fflush(stdout);
530 n_err_sighdl(_("\nInterrupt\n"));
531 siglongjmp(__hdrjmp, 1);
535 main(int argc, char *argv[]){
536 /* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
537 static char const
538 optstr[] = "A:a:Bb:c:dEeFfHhiL:M:m:NnO:q:Rr:S:s:tu:VvX:::~#.",
539 usagestr[] = N_(
540 "Synopsis:\n"
541 " %s -h\n"
543 " %s [-BdEFintv~] [-: spec] [-A account]\n"
544 "\t [-a attachment] [-b bcc-addr] [-c cc-addr]\n"
545 "\t [-M type | -m file | -q file | -t]\n"
546 "\t [-r from-addr] [-S var[=value]..]\n"
547 "\t [-s subject] [-X cmd] [-.] to-addr.. [-- mta-option..]\n"
549 " %s [-BdEeHiNnRv~] [-: spec] [-A account]\n"
550 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
551 "\t [-u user] [-X cmd] [-- mta-option..]\n"
553 " %s [-BdEeHiNnRv~#] [-: spec] [-A account] -f\n"
554 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
555 "\t [-X cmd] [file] [-- mta-option..]\n"
557 #define _USAGE_ARGS , progname, progname, progname, progname
559 struct a_arg *a_head, *a_curr;
560 struct name *to, *cc, *bcc;
561 struct attachment *attach;
562 char *cp, *subject, *qf, *Aarg, *Larg;
563 char const *okey, **oargs, **Xargs, *folder, *emsg;
564 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
565 enum{
566 a_RF_NONE = 0,
567 a_RF_SET = 1<<0,
568 a_RF_SYSTEM = 1<<1,
569 a_RF_USER = 1<<2,
570 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
571 } resfiles;
572 int i;
573 NYD_ENTER;
575 a_head = NULL;
576 n_UNINIT(a_curr, NULL);
577 to = cc = bcc = NULL;
578 attach = NULL;
579 subject = qf =
580 Aarg = Larg = NULL;
581 oargs = Xargs = NULL;
582 folder = emsg = NULL;
583 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
584 resfiles = a_RF_ALL;
587 * Start our lengthy setup, finalize by setting PS_STARTED
590 progname = argv[0];
591 _startup();
593 /* Command line parsing
594 * Variable settings need to be done twice, since the user surely wants the
595 * setting to take effect immediately, but also doesn't want it to be
596 * overwritten from within resource files */
597 while ((i = _getopt(argc, argv, optstr)) >= 0) {
598 switch (i) {
599 case 'A':
600 /* Execute an account command later on */
601 Aarg = _oarg;
602 break;
603 case 'a':
604 options |= OPT_SENDMODE;
605 { struct a_arg *nap = salloc(sizeof(struct a_arg));
606 if (a_head == NULL)
607 a_head = nap;
608 else
609 a_curr->aa_next = nap;
610 nap->aa_next = NULL;
611 nap->aa_file = _oarg;
612 a_curr = nap;
614 break;
615 case 'B':
616 OBSOLETE(_("-B is obsolete, please use -# as necessary"));
617 break;
618 case 'b':
619 /* Get Blind Carbon Copy Recipient list */
620 options |= OPT_SENDMODE;
621 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
622 break;
623 case 'c':
624 /* Get Carbon Copy Recipient list */
625 options |= OPT_SENDMODE;
626 cc = cat(cc, lextract(_oarg, GCC | GFULL));
627 break;
628 case 'd':
629 ok_bset(debug);
630 okey = "debug";
631 goto joarg;
632 case 'E':
633 OBSOLETE(_("-E will be removed, please use \"-Sskipemptybody\""));
634 ok_bset(skipemptybody);
635 okey = "skipemptybody";
636 goto joarg;
637 case 'e':
638 options |= OPT_EXISTONLY;
639 break;
640 case 'F':
641 options |= OPT_F_FLAG | OPT_SENDMODE;
642 break;
643 case 'f':
644 /* User is specifying file to "edit" with Mail, as opposed to reading
645 * system mailbox. If no argument is given, we read his mbox file.
646 * Check for remaining arguments later */
647 folder = "&";
648 break;
649 case 'H':
650 options |= OPT_HEADERSONLY;
651 break;
652 case 'h':
653 n_err(V_(usagestr) _USAGE_ARGS);
654 goto j_leave;
655 case 'i':
656 /* Ignore interrupts */
657 ok_bset(ignore);
658 okey = "ignore";
659 goto joarg;
660 case 'L':
661 Larg = _oarg;
662 options |= OPT_HEADERLIST;
663 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
664 size_t j = strlen(++Larg);
665 if (j > 0)
666 Larg[j - 1] = '\0';
668 break;
669 case 'M':
670 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf != (char*)-1))
671 goto jeMmq;
672 option_Mm_arg = _oarg;
673 qf = (char*)-1;
674 if(0){
675 /* FALLTHRU*/
676 case 'm':
677 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf == (char*)-1))
678 goto jeMmq;
679 qf = _oarg;
681 options |= OPT_SENDMODE | OPT_Mm_FLAG;
682 break;
683 case 'N':
684 /* Avoid initial header printing */
685 ok_bclear(header);
686 okey = "noheader";
687 goto joarg;
688 case 'n':
689 /* Don't source "unspecified system start-up file" */
690 if(resfiles & a_RF_SET){
691 emsg = N_("-n cannot be used in conjunction with -:");
692 goto jusage;
694 resfiles = a_RF_USER;
695 break;
696 case 'O':
697 /* Additional options to pass-through to MTA TODO v15-compat legacy */
698 if (smopts_cnt == smopts_size)
699 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_cnt);
700 smopts[smopts_cnt++] = _oarg;
701 break;
702 case 'q':
703 if (qf != NULL && (options & OPT_Mm_FLAG)) {
704 jeMmq:
705 emsg = N_("Only one of -M, -m or -q may be given");
706 goto jusage;
708 /* Quote file TODO drop? -Q with real quote?? what ? */
709 options |= OPT_SENDMODE;
710 /* Allow for now, we have to special check validity of -q- later on! */
711 qf = (_oarg[0] == '-' && _oarg[1] == '\0') ? (char*)-1 : _oarg;
712 break;
713 case 'R':
714 /* Open folders read-only */
715 options |= OPT_R_FLAG;
716 break;
717 case 'r':
718 /* Set From address. */
719 options |= OPT_r_FLAG;
720 if (_oarg[0] != '\0') {
721 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
723 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
724 emsg = N_("Invalid address argument with -r");
725 goto jusage;
727 option_r_arg = fa;
728 /* TODO -r options is set in smopts, but may
729 * TODO be overwritten by setting from= in
730 * TODO an interactive session!
731 * TODO Maybe disable setting of from?
732 * TODO Warn user? Update manual!! */
733 okey = savecat("from=", fa->n_fullname);
734 goto joarg;
736 break;
737 case 'S':
738 /* Set variable (TODO twice [only if successful]) */
739 { char *a[2];
740 bool_t b;
742 okey = a[0] = _oarg;
743 a[1] = NULL;
744 pstate |= PS_ROBOT;
745 b = (c_set(a) == 0);
746 pstate &= ~PS_ROBOT;
747 if(!b)
748 break;
750 joarg:
751 if (oargs_cnt == oargs_size)
752 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
753 oargs[oargs_cnt++] = okey;
754 break;
755 case 's':
756 /* Subject:; take care for Debian #419840 and strip any \r and \n */
757 if(n_anyof_cp("\n\r", subject = _oarg)){
758 n_err(_("-s: normalizing away invalid ASCII NL / CR bytes\n"));
759 for(cp = subject = savestr(_oarg); *cp != '\0'; ++cp)
760 if(*cp == '\n' || *cp == '\r')
761 *cp = ' ';
763 options |= OPT_SENDMODE;
764 break;
765 case 't':
766 /* Read defined set of headers from mail to be sent */
767 options |= OPT_SENDMODE | OPT_t_FLAG;
768 break;
769 case 'u':
770 /* Temporarily set myname so that we can recognize the -u condition */
771 myname = savecat("%", _oarg);
772 break;
773 case 'V':
774 printf(_("%s version %s\n"), uagent, ok_vlook(version));
775 exit_status = EXIT_OK;
776 goto j_leave;
777 case 'v':
778 /* Be verbose */
779 ok_bset(verbose);
780 okey = "verbose";
781 goto joarg;
782 case 'X':
783 /* Add to list of commands to exec before entering normal operation */
784 if (Xargs_cnt == Xargs_size)
785 Xargs_size = _grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
786 Xargs[Xargs_cnt++] = _oarg;
787 break;
788 case ':':
789 /* Control which resource files shall be loaded */
790 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
791 emsg = N_("-n cannot be used in conjunction with -:");
792 goto jusage;
794 resfiles = a_RF_SET;
795 while((i = *_oarg++) != '\0')
796 switch(i){
797 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
798 case 'U': case 'u': resfiles |= a_RF_USER; break;
799 case ':': case '/': resfiles &= ~a_RF_ALL; break;
800 default:
801 emsg = N_("Invalid argument of -:");
802 goto jusage;
804 break;
805 case '~':
806 /* Enable command escapes even in non-interactive mode */
807 options |= OPT_TILDE_FLAG;
808 break;
809 case '#':
810 /* Work in batch mode, even if non-interactive */
811 if(!(options & OPT_INTERACTIVE))
812 setvbuf(stdin, NULL, _IOLBF, 0);
813 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
814 if (oargs_cnt + 8 >= oargs_size)
815 oargs_size = _grow_cpp(&oargs, oargs_size + 9, oargs_cnt);
816 folder = "/dev/null";
817 ok_vset(MAIL, folder);
818 ok_vset(MBOX, folder);
819 ok_bset(emptystart);
820 ok_bclear(header);
821 ok_vset(inbox, folder);
822 ok_bset(quiet);
823 ok_bset(sendwait);
824 ok_bset(typescript_mode);
825 oargs[oargs_cnt + 0] = "MAIL=/dev/null";
826 oargs[oargs_cnt + 1] = "MBOX=/dev/null";
827 oargs[oargs_cnt + 2] = "emptystart";
828 oargs[oargs_cnt + 3] = "noheader";
829 oargs[oargs_cnt + 4] = "inbox=/dev/null";
830 oargs[oargs_cnt + 5] = "quiet";
831 oargs[oargs_cnt + 6] = "sendwait";
832 oargs[oargs_cnt + 7] = "typescript-mode";
833 oargs_cnt += 8;
834 break;
835 case '.':
836 options |= OPT_SENDMODE;
837 goto jgetopt_done;
838 case '?':
839 jusage:
840 if (emsg != NULL)
841 n_err("%s\n", V_(emsg));
842 n_err(V_(usagestr) _USAGE_ARGS);
843 #undef _USAGE_ARGS
844 exit_status = EXIT_USE;
845 goto j_leave;
848 jgetopt_done:
851 /* The normal arguments may be followed by MTA arguments after a "--";
852 * however, -f may take off an argument, too, and before that.
853 * Since MTA arguments after "--" require *expandargv*, delay parsing off
854 * those options until after the resource files are loaded... */
855 if ((cp = argv[i = _oind]) == NULL)
857 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
858 ++i;
859 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
860 else if (folder != NULL && /*folder[0] == '&' &&*/ folder[1] == '\0') {
861 folder = cp;
862 if ((cp = argv[++i]) != NULL) {
863 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
864 emsg = N_("More than one file given with -f");
865 goto jusage;
867 ++i;
869 } else {
870 options |= OPT_SENDMODE;
871 for (;;) {
872 to = cat(to, lextract(cp, GTO | GFULL));
873 if ((cp = argv[++i]) == NULL)
874 break;
875 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
876 ++i;
877 break;
881 _oind = i;
883 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
884 * allocate the necessary space for them before we fixate that storage! */
885 while (argv[i] != NULL)
886 ++i;
887 if (smopts_cnt + i > smopts_size)
888 DBG(smopts_size =) _grow_cpp(&smopts, smopts_cnt + i + 1, smopts_cnt);
890 /* Check for inconsistent arguments, fix some temporaries */
891 if (options & OPT_SENDMODE) {
892 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
893 * XXX in order to function. Ideally that would not be needed */
894 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
895 emsg = N_("Cannot give -f and people to send to.");
896 goto jusage;
898 if (myname != NULL) {
899 emsg = N_("The -u option cannot be used in send mode");
900 goto jusage;
902 if (!(options & OPT_t_FLAG) && to == NULL) {
903 emsg = N_("Send options without primary recipient specified.");
904 goto jusage;
906 if ((options & OPT_t_FLAG) && qf != NULL) {
907 emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
908 goto jusage;
910 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
911 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
912 goto jusage;
914 if (options & OPT_R_FLAG) {
915 emsg = N_("The -R option is meaningless in send mode.");
916 goto jusage;
919 if (options & OPT_INTERACTIVE) {
920 if (qf == (char*)-1) {
921 if (!(options & OPT_Mm_FLAG))
922 emsg = N_("-q can't use standard input when interactive.\n");
923 goto jusage;
926 } else {
927 if (myname != NULL && folder != NULL) {
928 emsg = N_("The options -u and -f (and -#) are mutually exclusive");
929 goto jusage;
931 if ((options & (OPT_EXISTONLY | OPT_HEADERSONLY)) ==
932 (OPT_EXISTONLY | OPT_HEADERSONLY)) {
933 emsg = N_("The options -e and -H are mutual exclusive");
934 goto jusage;
936 if ((options & (OPT_HEADERSONLY | OPT_HEADERLIST)) == /* TODO OBSOLETE */
937 (OPT_HEADERSONLY | OPT_HEADERLIST))
938 OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
940 if(myname != NULL)
941 folder = myname;
945 * Likely to go, perform more setup
948 _setup_vars();
950 if (options & OPT_INTERACTIVE) {
951 _setscreensize(0);
952 #ifdef SIGWINCH
953 # ifndef TTY_WANTS_SIGWINCH
954 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
955 # endif
956 safe_signal(SIGWINCH, &_setscreensize);
957 #endif
958 } else
959 scrnheight = realscreenheight = 24, scrnwidth = 80;
961 /* Fixate the current snapshot of our global auto-reclaimed storage instance.
962 * Memory is auto-reclaimed from now on */
963 n_memory_autorec_fixate();
965 /* load() any resource files */
966 if(resfiles & a_RF_ALL){
967 /* *expand() returns a savestr(), but load only uses the file name for
968 * fopen(), so it's safe to do this */
969 if((resfiles & a_RF_SYSTEM) && !ok_blook(NAIL_NO_SYSTEM_RC))
970 n_load(VAL_SYSCONFDIR "/" VAL_SYSCONFRC);
971 if(resfiles & a_RF_USER)
972 n_load(fexpand(ok_vlook(MAILRC), FEXP_LOCAL | FEXP_NOPROTO));
973 if((cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
974 n_load(fexpand(cp, FEXP_LOCAL | FEXP_NOPROTO));
977 /* Ensure the -S and other command line options take precedence over
978 * anything that may have been placed in resource files.
979 * Our "ternary binary" option *verbose* needs special treament */
980 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
981 options &= ~OPT_VERB;
982 /* ..and be silent when unsetting an undefined variable */
983 pstate |= PS_ROBOT;
984 for (i = 0; UICMP(z, i, <, oargs_cnt); ++i) {
985 char const *a[2];
987 a[0] = oargs[i];
988 a[1] = NULL;
989 c_set(a);
991 pstate &= ~PS_ROBOT;
993 /* Cause possible umask(2), now that any setting is established, and before
994 * we change accounts, evaluate commands etc. */
995 (void)ok_vlook(umask);
997 /* Additional options to pass-through to MTA, and allowed to do so? */
998 if ((cp = ok_vlook(expandargv)) != NULL) {
999 bool_t isfail = !asccasecmp(cp, "fail"),
1000 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
1002 if ((options & OPT_D_V) && !isfail && !isrestrict && *cp != '\0')
1003 n_err(_("Unknown *expandargv* value: %s\n"), cp);
1005 if ((cp = argv[i = _oind]) != NULL) {
1006 if (isfail ||
1007 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
1008 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
1009 "using *sendmail-arguments*\n"));
1010 exit_status = EXIT_USE | EXIT_SEND_ERROR;
1011 goto jleave;
1013 do {
1014 assert(smopts_cnt + 1 <= smopts_size);
1015 smopts[smopts_cnt++] = cp;
1016 } while ((cp = argv[++i]) != NULL);
1020 /* We had to wait until the resource files are loaded and any command line
1021 * setting has been restored, but get the termcap up and going before we
1022 * switch account or running commands */
1023 #ifdef n_HAVE_TCAP
1024 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1025 n_termcap_init();
1026 #endif
1028 /* Now we can set the account */
1029 if (Aarg != NULL) {
1030 char const *a[2];
1031 a[0] = Aarg;
1032 a[1] = NULL;
1033 c_account(a);
1036 /* "load()" commands given on command line */
1037 if(Xargs_cnt > 0)
1038 n_load_Xargs(Xargs, Xargs_cnt);
1040 /* Final tests */
1041 if(options & OPT_Mm_FLAG){
1042 if(qf == (char*)-1){
1043 if(!mime_type_check_mtname(option_Mm_arg)){
1044 n_err(_("Could not find `mimetype' for -M argument: %s\n"),
1045 option_Mm_arg);
1046 exit_status = EXIT_ERR;
1047 goto jleave;
1049 }else if((option_Mm_arg = mime_type_classify_filename(qf)) == NULL){
1050 n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
1051 n_shexp_quote_cp(qf, FAL0));
1052 exit_status = EXIT_ERR;
1053 goto jleave;
1054 }else if(!asccasecmp(option_Mm_arg, "text/plain")) /* TODO no: magic!! */
1055 option_Mm_arg = NULL;
1059 * We're finally completely setup and ready to go
1061 pstate |= PS_STARTED;
1063 if (!(options & OPT_SENDMODE)) {
1064 exit_status = _rcv_mode(folder, Larg);
1065 goto jleave;
1068 /* Now that full mailx(1)-style file expansion is possible handle the
1069 * attachments which we had delayed due to this.
1070 * This may use savestr(), but since we won't enter the command loop we
1071 * don't need to care about that */
1072 for (cp = NULL; a_head != NULL;) {
1073 struct attachment *nahp, *nap;
1075 if ((nahp = add_attachment(n_LEXINPUT_CTX_DEFAULT, attach,
1076 a_head->aa_file, &nap)) != NULL) {
1077 attach = nahp;
1078 /* Did we split a charset set name for fixation purposes? */
1079 if (cp != NULL) {
1080 nap->a_conv = AC_FIX_INCS;
1081 nap->a_input_charset = cp;
1082 cp = NULL;
1084 a_head = a_head->aa_next;
1085 continue;
1087 i = errno;
1089 /* It may not have worked because of an appended character set name, so
1090 * try to split name and charset and retry once */
1091 if (cp == NULL && (cp = strrchr(a_head->aa_file, '=')) != NULL) {
1092 char *ncp, *nfp = savestrbuf(a_head->aa_file,
1093 PTR2SIZE(cp - a_head->aa_file));
1095 for (ncp = ++cp; *ncp != '\0'; ++ncp)
1096 if (!alnumchar(*ncp) && !punctchar(*ncp))
1097 break;
1098 if (*ncp == '\0') {
1099 a_head->aa_file = nfp;
1100 continue;
1104 n_perr(a_head->aa_file, i);
1105 exit_status = EXIT_ERR;
1106 goto jleave;
1109 if (options & OPT_INTERACTIVE)
1110 n_tty_init();
1111 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1112 if (options & OPT_INTERACTIVE)
1113 n_tty_destroy();
1115 jleave:
1116 #ifdef n_HAVE_TCAP
1117 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1118 n_termcap_destroy();
1119 #endif
1120 j_leave:
1121 #ifdef HAVE_MEMORY_DEBUG
1122 n_memory_autorec_pop(NULL);
1123 #endif
1124 n_memory_reset();
1125 NYD_LEAVE;
1126 return exit_status;
1129 FL int
1130 c_exit(void *v){/* TODO program state machine */
1131 NYD_ENTER;
1132 n_UNUSED(v);
1134 if(pstate & PS_STARTED){
1135 if(!(pstate & PS_SOURCING)){
1136 #ifdef n_HAVE_TCAP
1137 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) ==
1138 OPT_INTERACTIVE)
1139 n_termcap_destroy();
1140 #endif
1141 exit(EXIT_OK);
1144 pstate |= PS_EXIT;
1145 NYD_LEAVE;
1146 return 0;
1149 /* Source the others in that case! */
1150 #ifdef HAVE_AMALGAMATION
1151 # include "config.h"
1152 #endif
1154 /* s-it-mode */