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