Do some error checking in puthead()
[s-mailx.git] / main.c
blob902538943b9bea06f3ee5477351b7a1167764186
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_empty[1] = "";
69 VL ui16_t const class_char[1 + 0x7F] = {
70 #define a_BC C_BLANK | C_CNTRL
71 #define a_SC C_SPACE | C_CNTRL
72 #define a_WC C_WHITE | C_CNTRL
73 /* 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel */
74 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
75 /* 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si */
76 C_CNTRL, a_BC, a_WC, a_SC, a_SC, a_SC, C_CNTRL, C_CNTRL,
77 /* 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb */
78 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
79 /* 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us */
80 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
81 #undef a_WC
82 #undef a_SC
83 #undef a_BC
84 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
85 C_BLANK, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
86 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
87 C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
88 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
89 C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL,
90 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
91 C_DIGIT, C_DIGIT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
92 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
93 C_PUNCT, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
94 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
95 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
96 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
97 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
98 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
99 C_UPPER, C_UPPER, C_UPPER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
100 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
101 C_PUNCT, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
102 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
103 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
104 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
105 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
106 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
107 C_LOWER, C_LOWER, C_LOWER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_CNTRL
110 /* Our own little getopt(3) */
111 static char *_oarg;
112 static int _oind, /*_oerr,*/ _oopt;
114 /* Our own little getopt(3); note --help is special-treated as 'h' */
115 static int _getopt(int argc, char * const argv[], char const *optstring);
117 /* Perform basic startup initialization */
118 static void _startup(void);
120 /* Grow a char** */
121 static size_t _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt);
123 /* Setup some variables which we require to be valid / verified */
124 static void _setup_vars(void);
126 /* We're in an interactive session - compute what the screen size for printing
127 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
128 * We use the following algorithm for the height:
129 * If baud rate < 1200, use 9
130 * If baud rate = 1200, use 14
131 * If baud rate > 1200, use 24 or ws_row
132 * Width is either 80 or ws_col */
133 static void _setscreensize(int is_sighdl);
135 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
136 * the system mailbox, and open up the right stuff */
137 static int _rcv_mode(char const *folder, char const *Larg);
139 /* Interrupt printing of the headers */
140 static void _hdrstop(int signo);
142 static int
143 _getopt(int argc, char * const argv[], char const *optstring)
145 static char const *lastp;
147 int rv = -1/*, colon*/;
148 char const *curp;
149 NYD_ENTER;
151 _oarg = NULL;
153 /*if ((colon = (optstring[0] == ':')))
154 ++optstring;*/
156 if (lastp != NULL) {
157 curp = lastp;
158 lastp = NULL;
159 } else {
160 if (_oind >= argc || argv[_oind] == NULL || argv[_oind][0] != '-' ||
161 argv[_oind][1] == '\0')
162 goto jleave;
163 if (argv[_oind][1] == '-' && argv[_oind][2] == '\0') {
164 /* We need this in for MTA arg detection (easier) ++_oind;*/
165 goto jleave;
167 curp = &argv[_oind][1];
170 for(_oopt = curp[0]; optstring[0] != '\0';){
171 if(optstring[0] != _oopt){
172 optstring += 1 + (optstring[1] == ':');
173 continue;
176 if (optstring[1] == ':') {
177 if (curp[1] != '\0') {
178 _oarg = n_UNCONST(curp + 1);
179 ++_oind;
180 } else {
181 if ((_oind += 2) > argc) {
182 /*if (!colon *//*&& _oerr*//*)*/ {
183 n_err(_("%s: option requires an argument -- %c\n"),
184 argv[0], (char)_oopt);
186 rv = (/*colon ? ':' :*/ '?');
187 goto jleave;
189 _oarg = argv[_oind - 1];
191 } else {
192 if (curp[1] != '\0')
193 lastp = curp + 1;
194 else
195 ++_oind;
197 rv = _oopt;
198 goto jleave;
201 /* Special support for --help, which is quite common */
202 if (_oopt == '-' && !strcmp(curp, "-help") && curp - 1 == argv[_oind]) {
203 ++_oind;
204 rv = 'h';
205 goto jleave;
208 /* Definitive error */
209 /*if (!colon *//*&& opterr*//*)*/
210 n_err(_("%s: invalid option -- %c\n"), argv[0], _oopt);
211 if (curp[1] != '\0')
212 lastp = curp + 1;
213 else
214 ++_oind;
215 _oarg = NULL;
216 rv = '?';
217 jleave:
218 NYD_LEAVE;
219 return rv;
222 static void
223 _startup(void)
225 char *cp;
226 NYD_ENTER;
228 image = -1;
229 dflpipe = SIG_DFL;
230 _oind = /*_oerr =*/ 1;
232 if ((cp = strrchr(progname, '/')) != NULL)
233 progname = ++cp;
235 /* Set up a reasonable environment */
237 #ifdef HAVE_NYD
238 safe_signal(SIGABRT, &_nyd_oncrash);
239 # ifdef SIGBUS
240 safe_signal(SIGBUS, &_nyd_oncrash);
241 # endif
242 safe_signal(SIGFPE, &_nyd_oncrash);
243 safe_signal(SIGILL, &_nyd_oncrash);
244 safe_signal(SIGSEGV, &_nyd_oncrash);
245 #endif
246 command_manager_start();
248 if (isatty(STDIN_FILENO)) /* TODO should be isatty(0) && isatty(2)?? */
249 options |= OPT_TTYIN;
250 if (isatty(STDOUT_FILENO))
251 options |= OPT_TTYOUT;
252 if ((options & (OPT_TTYIN | OPT_TTYOUT)) == (OPT_TTYIN | OPT_TTYOUT)) {
253 options |= OPT_INTERACTIVE;
254 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
257 /* -- >8 -- 8< -- */
259 #ifndef HAVE_SETLOCALE
260 mb_cur_max = 1;
261 #else
262 setlocale(LC_ALL, n_empty);
263 mb_cur_max = MB_CUR_MAX;
264 # ifdef HAVE_NL_LANGINFO
265 if(ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
266 ok_vset(ttycharset, cp);
267 # endif
269 # ifdef HAVE_C90AMEND1
270 if(mb_cur_max > 1){
271 # ifdef HAVE_ALWAYS_UNICODE_LOCALE
272 options |= OPT_UNICODE;
273 # else
274 wchar_t wc;
275 if(mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
276 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
277 options |= OPT_UNICODE;
278 /* Reset possibly messed up state; luckily this also gives us an
279 * indication whether the encoding has locking shift state sequences */
280 if(mbtowc(&wc, NULL, mb_cur_max))
281 options |= OPT_ENC_MBSTATE;
282 # endif
284 # endif
285 #endif
287 #ifdef HAVE_ICONV
288 iconvd = (iconv_t)-1;
289 #endif
290 NYD_LEAVE;
293 static size_t
294 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
296 /* Just use auto-reclaimed storage, it will be preserved */
297 char const **newcpp;
298 NYD_ENTER;
300 newcpp = salloc(sizeof(char*) * newsize);
302 if (oldcnt > 0)
303 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
304 *cpp = newcpp;
305 NYD_LEAVE;
306 return newsize;
309 static void
310 _setup_vars(void){
311 /* XXX furtherly check paths? */
312 struct passwd *pwuid;
313 char const *cp;
314 NYD_ENTER;
316 group_id = getgid();
317 if((pwuid = getpwuid(user_id = getuid())) == NULL)
318 n_panic(_("Cannot associate a name with uid %lu"), (ul_i)user_id);
319 myname = savestr(pwuid->pw_name); /* XXX replace uses with vlook(LOGNAME)! */
321 /* C99 */{
322 char const *ep;
323 bool_t doenv;
325 if(!(doenv = (ep = ok_vlook(LOGNAME)) == NULL) &&
326 (doenv = strcmp(myname, ep)))
327 n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
328 ep, myname);
329 if(doenv){
330 pstate |= PS_ROOT;
331 ok_vset(LOGNAME, myname);
332 pstate &= ~PS_ROOT;
335 if((ep = ok_vlook(USER)) != NULL && strcmp(myname, ep)){
336 n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
337 ep, myname);
338 pstate |= PS_ROOT;
339 ok_vset(USER, myname);
340 pstate &= ~PS_ROOT;
344 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
346 /* */
347 if((cp = ok_vlook(HOME)) == NULL){
348 cp = pwuid->pw_dir;
349 pstate |= PS_ROOT;
350 ok_vset(HOME, cp);
351 pstate &= ~PS_ROOT;
354 (void)ok_vlook(TMPDIR);
355 NYD_LEAVE;
358 static void
359 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
361 struct termios tbuf;
362 #ifdef TIOCGWINSZ
363 struct winsize ws;
364 #elif defined TIOCGSIZE
365 struct ttysize ts;
366 #endif
367 NYD_ENTER;
369 scrnheight = realscreenheight = scrnwidth = 0;
371 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
372 * a little bit to be able to honour resizes during our lifetime and
373 * only honour it upon first run; abuse *is_sighdl* as an indicator */
374 if (!is_sighdl) {
375 char *cp;
377 /* We manage those variables for our child processes, so ensure they
378 * are up to date, always */
379 if (options & OPT_INTERACTIVE)
380 pstate |= PS_SIGWINCH_PEND;
382 if ((cp = ok_vlook(LINES)) != NULL)
383 scrnheight = realscreenheight = (int)strtoul(cp, NULL, 0); /* TODO */
384 if ((cp = ok_vlook(COLUMNS)) != NULL)
385 scrnwidth = (int)strtoul(cp, NULL, 0); /* TODO posui32= not posnum=! */
387 if (scrnwidth != 0 && scrnheight != 0)
388 goto jleave;
391 #ifdef TIOCGWINSZ
392 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
393 ws.ws_col = ws.ws_row = 0;
394 #elif defined TIOCGSIZE
395 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
396 ts.ts_lines = ts.ts_cols = 0;
397 #endif
399 if (scrnheight == 0) {
400 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
401 ? B9600 : cfgetospeed(&tbuf));
403 if (ospeed < B1200)
404 scrnheight = 9;
405 else if (ospeed == B1200)
406 scrnheight = 14;
407 #ifdef TIOCGWINSZ
408 else if (ws.ws_row != 0)
409 scrnheight = ws.ws_row;
410 #elif defined TIOCGSIZE
411 else if (ts.ts_lines != 0)
412 scrnheight = ts.ts_lines;
413 #endif
414 else
415 scrnheight = 24;
417 #if defined TIOCGWINSZ || defined TIOCGSIZE
418 if (0 ==
419 # ifdef TIOCGWINSZ
420 (realscreenheight = ws.ws_row)
421 # else
422 (realscreenheight = ts.ts_lines)
423 # endif
425 realscreenheight = 24;
426 #endif
429 if (scrnwidth == 0 && 0 ==
430 #ifdef TIOCGWINSZ
431 (scrnwidth = ws.ws_col)
432 #elif defined TIOCGSIZE
433 (scrnwidth = ts.ts_cols)
434 #endif
436 scrnwidth = 80;
438 jleave:
439 #ifdef SIGWINCH
440 if (is_sighdl) {
441 pstate |= PS_SIGWINCH_PEND; /* XXX Not atomic */
442 if (options & OPT_INTERACTIVE)
443 n_tty_signal(SIGWINCH);
445 #endif
446 NYD_LEAVE;
449 static sigjmp_buf __hdrjmp; /* XXX */
451 static int
452 _rcv_mode(char const *folder, char const *Larg)
454 int i;
455 sighandler_type prevint;
456 NYD_ENTER;
458 if (folder == NULL)
459 folder = "%";
461 if (options & OPT_QUICKRUN_MASK)
462 i = FEDIT_RDONLY;
463 else
464 i = FEDIT_NONE;
465 i = setfile(folder, i);
466 if (i < 0) {
467 exit_status = EXIT_ERR; /* error already reported */
468 goto jquit;
470 if (options & OPT_QUICKRUN_MASK) {
471 exit_status = i;
472 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
473 (options & OPT_HEADERLIST)))
474 print_header_summary(Larg);
475 goto jquit;
477 check_folder_hook(FAL0);
479 if (i > 0 && !ok_blook(emptystart)) {
480 exit_status = EXIT_ERR;
481 goto jleave;
484 if (sigsetjmp(__hdrjmp, 1) == 0) {
485 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
486 safe_signal(SIGINT, _hdrstop);
487 if (!(options & OPT_N_FLAG)) {
488 if (!ok_blook(quiet))
489 printf(_("%s version %s. Type `?' for help\n"),
490 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
491 announce(1);
492 fflush(stdout);
494 safe_signal(SIGINT, prevint);
497 /* Enter the command loop */
498 if (options & OPT_INTERACTIVE)
499 n_tty_init();
500 n_commands();
501 if (options & OPT_INTERACTIVE)
502 n_tty_destroy();
504 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
505 safe_signal(SIGHUP, SIG_IGN);
506 safe_signal(SIGINT, SIG_IGN);
507 safe_signal(SIGQUIT, SIG_IGN);
509 jquit:
510 save_mbox_for_possible_quitstuff();
511 quit();
512 jleave:
513 NYD_LEAVE;
514 return exit_status;
517 static void
518 _hdrstop(int signo)
520 NYD_X; /* Signal handler */
521 n_UNUSED(signo);
523 fflush(stdout);
524 n_err_sighdl(_("\nInterrupt\n"));
525 siglongjmp(__hdrjmp, 1);
529 main(int argc, char *argv[]){
530 /* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
531 static char const
532 optstr[] = "A:a:Bb:c:dEeFfHhiL:M:m:NnO:q:Rr:S:s:tu:VvX:::~#.",
533 usagestr[] = N_(
534 "Synopsis:\n"
535 " %s -h\n"
537 " %s [-BdEFintv~] [-: spec] [-A account]\n"
538 "\t [-a attachment] [-b bcc-addr] [-c cc-addr]\n"
539 "\t [-M type | -m file | -q file | -t]\n"
540 "\t [-r from-addr] [-S var[=value]..]\n"
541 "\t [-s subject] [-X cmd] [-.] to-addr.. [-- mta-option..]\n"
543 " %s [-BdEeHiNnRv~] [-: spec] [-A account]\n"
544 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
545 "\t [-u user] [-X cmd] [-- mta-option..]\n"
547 " %s [-BdEeHiNnRv~#] [-: spec] [-A account] -f\n"
548 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
549 "\t [-X cmd] [file] [-- mta-option..]\n"
551 #define _USAGE_ARGS , progname, progname, progname, progname
553 struct a_arg *a_head, *a_curr;
554 struct name *to, *cc, *bcc;
555 struct attachment *attach;
556 char *cp, *subject, *qf, *Aarg, *Larg;
557 char const *okey, **oargs, **Xargs, *folder, *emsg;
558 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
559 enum{
560 a_RF_NONE = 0,
561 a_RF_SET = 1<<0,
562 a_RF_SYSTEM = 1<<1,
563 a_RF_USER = 1<<2,
564 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
565 } resfiles;
566 int i;
567 NYD_ENTER;
569 a_head = NULL;
570 n_UNINIT(a_curr, NULL);
571 to = cc = bcc = NULL;
572 attach = NULL;
573 cp = subject = qf =
574 Aarg = Larg = NULL;
575 oargs = Xargs = NULL;
576 folder = emsg = NULL;
577 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
578 resfiles = a_RF_ALL;
581 * Start our lengthy setup, finalize by setting PS_STARTED
584 progname = argv[0];
585 _startup();
587 /* Command line parsing
588 * Variable settings need to be done twice, since the user surely wants the
589 * setting to take effect immediately, but also doesn't want it to be
590 * overwritten from within resource files */
591 while ((i = _getopt(argc, argv, optstr)) >= 0) {
592 switch (i) {
593 case 'A':
594 /* Execute an account command later on */
595 Aarg = _oarg;
596 break;
597 case 'a':
598 options |= OPT_SENDMODE;
599 { struct a_arg *nap = salloc(sizeof(struct a_arg));
600 if (a_head == NULL)
601 a_head = nap;
602 else
603 a_curr->aa_next = nap;
604 nap->aa_next = NULL;
605 nap->aa_file = _oarg;
606 a_curr = nap;
608 break;
609 case 'B':
610 /* Make 0/1 line buffered */
611 setvbuf(stdin, NULL, _IOLBF, 0);
612 setvbuf(stdout, NULL, _IOLBF, 0);
613 break;
614 case 'b':
615 /* Get Blind Carbon Copy Recipient list */
616 options |= OPT_SENDMODE;
617 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
618 break;
619 case 'c':
620 /* Get Carbon Copy Recipient list */
621 options |= OPT_SENDMODE;
622 cc = cat(cc, lextract(_oarg, GCC | GFULL));
623 break;
624 case 'd':
625 ok_bset(debug);
626 okey = "debug";
627 goto joarg;
628 case 'E':
629 ok_bset(skipemptybody);
630 okey = "skipemptybody";
631 goto joarg;
632 case 'e':
633 options |= OPT_EXISTONLY;
634 break;
635 case 'F':
636 options |= OPT_F_FLAG | OPT_SENDMODE;
637 break;
638 case 'f':
639 /* User is specifying file to "edit" with Mail, as opposed to reading
640 * system mailbox. If no argument is given, we read his mbox file.
641 * Check for remaining arguments later */
642 folder = "&";
643 break;
644 case 'H':
645 options |= OPT_HEADERSONLY;
646 break;
647 case 'h':
648 n_err(V_(usagestr) _USAGE_ARGS);
649 goto j_leave;
650 case 'i':
651 /* Ignore interrupts */
652 ok_bset(ignore);
653 okey = "ignore";
654 goto joarg;
655 case 'L':
656 Larg = _oarg;
657 options |= OPT_HEADERLIST;
658 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
659 size_t j = strlen(++Larg);
660 if (j > 0)
661 Larg[j - 1] = '\0';
663 break;
664 case 'M':
665 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf != (char*)-1))
666 goto jeMmq;
667 option_Mm_arg = _oarg;
668 qf = (char*)-1;
669 if(0){
670 /* FALLTHRU*/
671 case 'm':
672 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf == (char*)-1))
673 goto jeMmq;
674 qf = _oarg;
676 options |= OPT_SENDMODE | OPT_Mm_FLAG;
677 break;
678 case 'N':
679 /* Avoid initial header printing */
680 ok_bclear(header);
681 okey = "noheader";
682 goto joarg;
683 case 'n':
684 /* Don't source "unspecified system start-up file" */
685 if(resfiles & a_RF_SET){
686 emsg = N_("-n cannot be used in conjunction with -:");
687 goto jusage;
689 resfiles = a_RF_USER;
690 break;
691 case 'O':
692 /* Additional options to pass-through to MTA TODO v15-compat legacy */
693 if (smopts_cnt == smopts_size)
694 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_cnt);
695 smopts[smopts_cnt++] = _oarg;
696 break;
697 case 'q':
698 if (qf != NULL && (options & OPT_Mm_FLAG)) {
699 jeMmq:
700 emsg = N_("Only one of -M, -m or -q may be given");
701 goto jusage;
703 /* Quote file TODO drop? -Q with real quote?? what ? */
704 options |= OPT_SENDMODE;
705 /* Allow for now, we have to special check validity of -q- later on! */
706 qf = (_oarg[0] == '-' && _oarg[1] == '\0') ? (char*)-1 : _oarg;
707 break;
708 case 'R':
709 /* Open folders read-only */
710 options |= OPT_R_FLAG;
711 break;
712 case 'r':
713 /* Set From address. */
714 options |= OPT_r_FLAG;
715 if (_oarg[0] != '\0') {
716 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
718 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
719 emsg = N_("Invalid address argument with -r");
720 goto jusage;
722 option_r_arg = fa;
723 /* TODO -r options is set in smopts, but may
724 * TODO be overwritten by setting from= in
725 * TODO an interactive session!
726 * TODO Maybe disable setting of from?
727 * TODO Warn user? Update manual!! */
728 okey = savecat("from=", fa->n_fullname);
729 goto joarg;
731 break;
732 case 'S':
733 /* Set variable (TODO twice [only if successful]) */
734 { char *a[2];
735 bool_t b;
737 okey = a[0] = _oarg;
738 a[1] = NULL;
739 pstate |= PS_ROBOT;
740 b = (c_set(a) == 0);
741 pstate &= ~PS_ROBOT;
742 if(!b)
743 break;
745 joarg:
746 if (oargs_cnt == oargs_size)
747 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
748 oargs[oargs_cnt++] = okey;
749 break;
750 case 's':
751 /* Subject: */
752 subject = _oarg;
753 options |= OPT_SENDMODE;
754 break;
755 case 't':
756 /* Read defined set of headers from mail to be sent */
757 options |= OPT_SENDMODE | OPT_t_FLAG;
758 break;
759 case 'u':
760 /* Temporarily set myname so that we can recognize the -u condition */
761 myname = savecat("%", _oarg);
762 break;
763 case 'V':
764 printf(_("%s version %s\n"), uagent, ok_vlook(version));
765 exit_status = EXIT_OK;
766 goto j_leave;
767 case 'v':
768 /* Be verbose */
769 ok_bset(verbose);
770 okey = "verbose";
771 goto joarg;
772 case 'X':
773 /* Add to list of commands to exec before entering normal operation */
774 if (Xargs_cnt == Xargs_size)
775 Xargs_size = _grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
776 Xargs[Xargs_cnt++] = _oarg;
777 break;
778 case ':':
779 /* Control which resource files shall be loaded */
780 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
781 emsg = N_("-n cannot be used in conjunction with -:");
782 goto jusage;
784 resfiles = a_RF_SET;
785 while((i = *_oarg++) != '\0')
786 switch(i){
787 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
788 case 'U': case 'u': resfiles |= a_RF_USER; break;
789 case ':': case '/': resfiles &= ~a_RF_ALL; break;
790 default:
791 emsg = N_("Invalid argument of -:");
792 goto jusage;
794 break;
795 case '~':
796 /* Enable tilde escapes even in non-interactive mode */
797 options |= OPT_TILDE_FLAG;
798 break;
799 case '#':
800 /* Work in batch mode, even if non-interactive */
801 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
802 if (oargs_cnt + 8 >= oargs_size)
803 oargs_size = _grow_cpp(&oargs, oargs_size + 9, oargs_cnt);
804 folder = "/dev/null";
805 ok_vset(MAIL, folder);
806 ok_vset(MBOX, folder);
807 ok_bset(emptystart);
808 ok_bclear(header);
809 ok_vset(inbox, folder);
810 ok_bset(quiet);
811 ok_bset(sendwait);
812 ok_bset(typescript_mode);
813 oargs[oargs_cnt + 0] = "MAIL=/dev/null";
814 oargs[oargs_cnt + 1] = "MBOX=/dev/null";
815 oargs[oargs_cnt + 2] = "emptystart";
816 oargs[oargs_cnt + 3] = "noheader";
817 oargs[oargs_cnt + 4] = "inbox=/dev/null";
818 oargs[oargs_cnt + 5] = "quiet";
819 oargs[oargs_cnt + 6] = "sendwait";
820 oargs[oargs_cnt + 7] = "typescript-mode";
821 oargs_cnt += 8;
822 break;
823 case '.':
824 options |= OPT_SENDMODE;
825 goto jgetopt_done;
826 case '?':
827 jusage:
828 if (emsg != NULL)
829 n_err("%s\n", V_(emsg));
830 n_err(V_(usagestr) _USAGE_ARGS);
831 #undef _USAGE_ARGS
832 exit_status = EXIT_USE;
833 goto j_leave;
836 jgetopt_done:
839 /* The normal arguments may be followed by MTA arguments after a "--";
840 * however, -f may take off an argument, too, and before that.
841 * Since MTA arguments after "--" require *expandargv*, delay parsing off
842 * those options until after the resource files are loaded... */
843 if ((cp = argv[i = _oind]) == NULL)
845 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
846 ++i;
847 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
848 else if (folder != NULL && /*folder[0] == '&' &&*/ folder[1] == '\0') {
849 folder = cp;
850 if ((cp = argv[++i]) != NULL) {
851 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
852 emsg = N_("More than one file given with -f");
853 goto jusage;
855 ++i;
857 } else {
858 options |= OPT_SENDMODE;
859 for (;;) {
860 to = cat(to, lextract(cp, GTO | GFULL));
861 if ((cp = argv[++i]) == NULL)
862 break;
863 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
864 ++i;
865 break;
869 _oind = i;
871 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
872 * allocate the necessary space for them before we fixate that storage! */
873 while (argv[i] != NULL)
874 ++i;
875 if (smopts_cnt + i > smopts_size)
876 DBG(smopts_size =) _grow_cpp(&smopts, smopts_cnt + i + 1, smopts_cnt);
878 /* Check for inconsistent arguments, fix some temporaries */
879 if (options & OPT_SENDMODE) {
880 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
881 * XXX in order to function. Ideally that would not be needed */
882 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
883 emsg = N_("Cannot give -f and people to send to.");
884 goto jusage;
886 if (myname != NULL) {
887 emsg = N_("The -u option cannot be used in send mode");
888 goto jusage;
890 if (!(options & OPT_t_FLAG) && to == NULL) {
891 emsg = N_("Send options without primary recipient specified.");
892 goto jusage;
894 if ((options & OPT_t_FLAG) && qf != NULL) {
895 emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
896 goto jusage;
898 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
899 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
900 goto jusage;
902 if (options & OPT_R_FLAG) {
903 emsg = N_("The -R option is meaningless in send mode.");
904 goto jusage;
907 if (options & OPT_INTERACTIVE) {
908 if (qf == (char*)-1) {
909 if (!(options & OPT_Mm_FLAG))
910 emsg = N_("-q can't use standard input when interactive.\n");
911 goto jusage;
914 } else {
915 if (myname != NULL && folder != NULL) {
916 emsg = N_("The options -u and -f (and -#) are mutually exclusive");
917 goto jusage;
919 if ((options & (OPT_EXISTONLY | OPT_HEADERSONLY)) ==
920 (OPT_EXISTONLY | OPT_HEADERSONLY)) {
921 emsg = N_("The options -e and -H are mutual exclusive");
922 goto jusage;
924 if ((options & (OPT_HEADERSONLY | OPT_HEADERLIST)) == /* TODO OBSOLETE */
925 (OPT_HEADERSONLY | OPT_HEADERLIST))
926 OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
928 if(myname != NULL)
929 folder = myname;
933 * Likely to go, perform more setup
936 _setup_vars();
938 if (options & OPT_INTERACTIVE) {
939 _setscreensize(0);
940 #ifdef SIGWINCH
941 # ifndef TTY_WANTS_SIGWINCH
942 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
943 # endif
944 safe_signal(SIGWINCH, &_setscreensize);
945 #endif
946 } else
947 scrnheight = realscreenheight = 24, scrnwidth = 80;
949 /* Fixate the current snapshot of our global auto-reclaimed storage instance.
950 * Memory is auto-reclaimed from now on */
951 n_memory_autorec_fixate();
953 /* load() any resource files */
954 if(resfiles & a_RF_ALL){
955 /* *expand() returns a savestr(), but load only uses the file name for
956 * fopen(), so it's safe to do this */
957 if((resfiles & a_RF_SYSTEM) && !ok_blook(NAIL_NO_SYSTEM_RC))
958 n_load(VAL_SYSCONFDIR "/" VAL_SYSCONFRC);
959 if(resfiles & a_RF_USER)
960 n_load(file_expand(ok_vlook(MAILRC)));
961 if((cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
962 n_load(file_expand(cp));
965 /* Ensure the -S and other command line options take precedence over
966 * anything that may have been placed in resource files.
967 * Our "ternary binary" option *verbose* needs special treament */
968 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
969 options &= ~OPT_VERB;
970 /* ..and be silent when unsetting an undefined variable */
971 pstate |= PS_ROBOT;
972 for (i = 0; UICMP(z, i, <, oargs_cnt); ++i) {
973 char const *a[2];
975 a[0] = oargs[i];
976 a[1] = NULL;
977 c_set(a);
979 pstate &= ~PS_ROBOT;
981 /* Cause possible umask(2), now that any setting is established, and before
982 * we change accounts, evaluate commands etc. */
983 (void)ok_vlook(umask);
985 /* Additional options to pass-through to MTA, and allowed to do so? */
986 if ((cp = ok_vlook(expandargv)) != NULL) {
987 bool_t isfail = !asccasecmp(cp, "fail"),
988 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
990 if ((options & OPT_D_V) && !isfail && !isrestrict && *cp != '\0')
991 n_err(_("Unknown *expandargv* value: %s\n"), cp);
993 if ((cp = argv[i = _oind]) != NULL) {
994 if (isfail ||
995 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
996 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
997 "using *sendmail-arguments*\n"));
998 exit_status = EXIT_USE | EXIT_SEND_ERROR;
999 goto jleave;
1001 do {
1002 assert(smopts_cnt + 1 <= smopts_size);
1003 smopts[smopts_cnt++] = cp;
1004 } while ((cp = argv[++i]) != NULL);
1008 /* We had to wait until the resource files are loaded and any command line
1009 * setting has been restored, but get the termcap up and going before we
1010 * switch account or running commands */
1011 #ifdef n_HAVE_TCAP
1012 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1013 n_termcap_init();
1014 #endif
1016 /* Now we can set the account */
1017 if (Aarg != NULL) {
1018 char const *a[2];
1019 a[0] = Aarg;
1020 a[1] = NULL;
1021 c_account(a);
1024 /* "load()" commands given on command line */
1025 if(Xargs_cnt > 0)
1026 n_load_Xargs(Xargs, Xargs_cnt);
1028 /* Final tests */
1029 if(options & OPT_Mm_FLAG){
1030 if(qf == (char*)-1){
1031 if(!mime_type_check_mtname(option_Mm_arg)){
1032 n_err(_("Could not find `mimetype' for -M argument: %s\n"),
1033 option_Mm_arg);
1034 exit_status = EXIT_ERR;
1035 goto jleave;
1037 }else if((option_Mm_arg = mime_type_classify_filename(qf)) == NULL){
1038 n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
1039 n_shexp_quote_cp(qf, FAL0));
1040 exit_status = EXIT_ERR;
1041 goto jleave;
1042 }else if(!asccasecmp(option_Mm_arg, "text/plain")) /* TODO no: magic!! */
1043 option_Mm_arg = NULL;
1047 * We're finally completely setup and ready to go
1049 pstate |= PS_STARTED;
1051 if (!(options & OPT_SENDMODE)) {
1052 exit_status = _rcv_mode(folder, Larg);
1053 goto jleave;
1056 /* Now that full mailx(1)-style file expansion is possible handle the
1057 * attachments which we had delayed due to this.
1058 * This may use savestr(), but since we won't enter the command loop we
1059 * don't need to care about that */
1060 for (cp = NULL; a_head != NULL;) {
1061 struct attachment *nahp, *nap;
1063 if ((nahp = add_attachment(n_LEXINPUT_CTX_DEFAULT, attach,
1064 a_head->aa_file, &nap)) != NULL) {
1065 attach = nahp;
1066 /* Did we split a charset set name for fixation purposes? */
1067 if (cp != NULL) {
1068 nap->a_conv = AC_FIX_INCS;
1069 nap->a_input_charset = cp;
1070 cp = NULL;
1072 a_head = a_head->aa_next;
1073 continue;
1075 i = errno;
1077 /* It may not have worked because of an appended character set name, so
1078 * try to split name and charset and retry once */
1079 if (cp == NULL && (cp = strrchr(a_head->aa_file, '=')) != NULL) {
1080 char *ncp, *nfp = savestrbuf(a_head->aa_file,
1081 PTR2SIZE(cp - a_head->aa_file));
1083 for (ncp = ++cp; *ncp != '\0'; ++ncp)
1084 if (!alnumchar(*ncp) && !punctchar(*ncp))
1085 break;
1086 if (*ncp == '\0') {
1087 a_head->aa_file = nfp;
1088 continue;
1092 n_perr(a_head->aa_file, i);
1093 exit_status = EXIT_ERR;
1094 goto jleave;
1097 if (options & OPT_INTERACTIVE)
1098 n_tty_init();
1099 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1100 if (options & OPT_INTERACTIVE)
1101 n_tty_destroy();
1103 jleave:
1104 #ifdef n_HAVE_TCAP
1105 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1106 n_termcap_destroy();
1107 #endif
1108 j_leave:
1109 #ifdef HAVE_MEMORY_DEBUG
1110 n_memory_autorec_pop(NULL);
1111 #endif
1112 n_memory_reset();
1113 NYD_LEAVE;
1114 return exit_status;
1117 FL int
1118 c_exit(void *v){/* TODO program state machine */
1119 NYD_ENTER;
1120 n_UNUSED(v);
1122 if(pstate & PS_STARTED){
1123 if(!(pstate & PS_SOURCING)){
1124 #ifdef n_HAVE_TCAP
1125 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) ==
1126 OPT_INTERACTIVE)
1127 n_termcap_destroy();
1128 #endif
1129 exit(EXIT_OK);
1132 pstate |= PS_EXIT;
1133 NYD_LEAVE;
1134 return 0;
1137 /* Source the others in that case! */
1138 #ifdef HAVE_AMALGAMATION
1139 # include "config.h"
1140 #endif
1142 /* s-it-mode */