n_memory_autorec_pop(): also call n_memory_check()
[s-mailx.git] / main.c
bloba9844ca0ad22861fca094fdffe9418793a46c015
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 - 2017 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 const *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 /* TODO This is wrong: interactive is STDIN/STDERR for a POSIX sh(1).
250 * TODO For now we get this wrong, all over the place, as this software
251 * TODO has always been developed with stdout as an output channel.
252 * TODO Start doing it right for at least explicit terminal-related things,
253 * TODO but v15 should use ONLY this, also for terminal input! */
254 if(isatty(STDIN_FILENO)){
255 options |= OPT_TTYIN;
256 #if defined HAVE_MLE || defined HAVE_TERMCAP
257 n_tty_fp = fdopen(fileno(stdin), "w");
258 setvbuf(n_tty_fp, NULL, _IOLBF, 0);
259 #endif
261 if(isatty(STDOUT_FILENO))
262 options |= OPT_TTYOUT;
263 if ((options & (OPT_TTYIN | OPT_TTYOUT)) == (OPT_TTYIN | OPT_TTYOUT)) {
264 options |= OPT_INTERACTIVE;
265 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
268 /* STDOUT is always line buffered from our point of view */
269 setvbuf(stdout, NULL, _IOLBF, 0);
270 if(n_tty_fp == NULL)
271 n_tty_fp = stdout;
273 /* -- >8 -- 8< -- */
275 #ifndef HAVE_SETLOCALE
276 mb_cur_max = 1;
277 #else
278 setlocale(LC_ALL, n_empty);
279 mb_cur_max = MB_CUR_MAX;
280 # ifdef HAVE_NL_LANGINFO
281 if((cp = nl_langinfo(CODESET)) != NULL)
282 ok_vset(ttycharset, cp);
283 # endif
285 # ifdef HAVE_C90AMEND1
286 if(mb_cur_max > 1){
287 # ifdef HAVE_ALWAYS_UNICODE_LOCALE
288 options |= OPT_UNICODE;
289 # else
290 wchar_t wc;
291 if(mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
292 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
293 options |= OPT_UNICODE;
294 /* Reset possibly messed up state; luckily this also gives us an
295 * indication whether the encoding has locking shift state sequences */
296 if(mbtowc(&wc, NULL, mb_cur_max))
297 options |= OPT_ENC_MBSTATE;
298 # endif
300 # endif
301 #endif
303 #ifdef HAVE_ICONV
304 iconvd = (iconv_t)-1;
305 #endif
306 NYD_LEAVE;
309 static size_t
310 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
312 /* Just use auto-reclaimed storage, it will be preserved */
313 char const **newcpp;
314 NYD_ENTER;
316 newcpp = salloc(sizeof(char*) * newsize);
318 if (oldcnt > 0)
319 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
320 *cpp = newcpp;
321 NYD_LEAVE;
322 return newsize;
325 static void
326 _setup_vars(void){
327 /* XXX furtherly check paths? */
328 struct passwd *pwuid;
329 char const *cp;
330 NYD_ENTER;
332 group_id = getgid();
333 if((pwuid = getpwuid(user_id = getuid())) == NULL)
334 n_panic(_("Cannot associate a name with uid %lu"), (ul_i)user_id);
336 /* C99 */{
337 char const *ep;
338 bool_t doenv;
340 if(!(doenv = (ep = ok_vlook(LOGNAME)) == NULL) &&
341 (doenv = strcmp(pwuid->pw_name, ep)))
342 n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
343 ep, pwuid->pw_name);
344 if(doenv){
345 pstate |= PS_ROOT;
346 ok_vset(LOGNAME, pwuid->pw_name);
347 pstate &= ~PS_ROOT;
350 if((ep = ok_vlook(USER)) != NULL && strcmp(pwuid->pw_name, ep)){
351 n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
352 ep, pwuid->pw_name);
353 pstate |= PS_ROOT;
354 ok_vset(USER, pwuid->pw_name);
355 pstate &= ~PS_ROOT;
359 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
361 /* */
362 if((cp = ok_vlook(HOME)) == NULL){
363 cp = pwuid->pw_dir;
364 pstate |= PS_ROOT;
365 ok_vset(HOME, cp);
366 pstate &= ~PS_ROOT;
369 /* Ensure some variables get loaded */
370 (void)ok_blook(POSIXLY_CORRECT);
371 (void)ok_vlook(TMPDIR);
372 NYD_LEAVE;
375 static void
376 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
378 struct termios tbuf;
379 #ifdef TIOCGWINSZ
380 struct winsize ws;
381 #elif defined TIOCGSIZE
382 struct ttysize ts;
383 #endif
384 NYD_ENTER;
386 scrnheight = realscreenheight = scrnwidth = 0;
388 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
389 * a little bit to be able to honour resizes during our lifetime and
390 * only honour it upon first run; abuse *is_sighdl* as an indicator */
391 if (!is_sighdl) {
392 char *cp;
394 /* We manage those variables for our child processes, so ensure they
395 * are up to date, always */
396 if (options & OPT_INTERACTIVE)
397 pstate |= PS_SIGWINCH_PEND;
399 if ((cp = ok_vlook(LINES)) != NULL)
400 scrnheight = realscreenheight = (int)strtoul(cp, NULL, 0); /* TODO */
401 if ((cp = ok_vlook(COLUMNS)) != NULL)
402 scrnwidth = (int)strtoul(cp, NULL, 0); /* TODO posui32= not posnum=! */
404 if (scrnwidth != 0 && scrnheight != 0)
405 goto jleave;
408 #ifdef TIOCGWINSZ
409 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
410 ws.ws_col = ws.ws_row = 0;
411 #elif defined TIOCGSIZE
412 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
413 ts.ts_lines = ts.ts_cols = 0;
414 #endif
416 if (scrnheight == 0) {
417 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
418 ? B9600 : cfgetospeed(&tbuf));
420 if (ospeed < B1200)
421 scrnheight = 9;
422 else if (ospeed == B1200)
423 scrnheight = 14;
424 #ifdef TIOCGWINSZ
425 else if (ws.ws_row != 0)
426 scrnheight = ws.ws_row;
427 #elif defined TIOCGSIZE
428 else if (ts.ts_lines != 0)
429 scrnheight = ts.ts_lines;
430 #endif
431 else
432 scrnheight = 24;
434 #if defined TIOCGWINSZ || defined TIOCGSIZE
435 if (0 ==
436 # ifdef TIOCGWINSZ
437 (realscreenheight = ws.ws_row)
438 # else
439 (realscreenheight = ts.ts_lines)
440 # endif
442 realscreenheight = 24;
443 #endif
446 if (scrnwidth == 0 && 0 ==
447 #ifdef TIOCGWINSZ
448 (scrnwidth = ws.ws_col)
449 #elif defined TIOCGSIZE
450 (scrnwidth = ts.ts_cols)
451 #endif
453 scrnwidth = 80;
455 jleave:
456 #ifdef SIGWINCH
457 if (is_sighdl) {
458 pstate |= PS_SIGWINCH_PEND; /* XXX Not atomic */
459 if (options & OPT_INTERACTIVE)
460 n_tty_signal(SIGWINCH);
462 #endif
463 NYD_LEAVE;
466 static sigjmp_buf __hdrjmp; /* XXX */
468 static int
469 _rcv_mode(char const *folder, char const *Larg)
471 int i;
472 sighandler_type prevint;
473 NYD_ENTER;
475 if (folder == NULL)
476 folder = "%";
478 if (options & OPT_QUICKRUN_MASK)
479 i = FEDIT_RDONLY;
480 else
481 i = FEDIT_NONE;
482 i = setfile(folder, i);
483 if (i < 0) {
484 exit_status = EXIT_ERR; /* error already reported */
485 goto jquit;
487 if (options & OPT_QUICKRUN_MASK) {
488 exit_status = i;
489 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
490 (options & OPT_HEADERLIST)))
491 print_header_summary(Larg);
492 goto jquit;
494 check_folder_hook(FAL0);
496 if (i > 0 && !ok_blook(emptystart)) {
497 exit_status = EXIT_ERR;
498 goto jleave;
501 if (sigsetjmp(__hdrjmp, 1) == 0) {
502 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
503 safe_signal(SIGINT, _hdrstop);
504 if (!(options & OPT_N_FLAG)) {
505 if (!ok_blook(quiet))
506 printf(_("%s version %s. Type `?' for help\n"),
507 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
508 announce(1);
509 fflush(stdout);
511 safe_signal(SIGINT, prevint);
514 /* Enter the command loop */
515 if (options & OPT_INTERACTIVE)
516 n_tty_init();
517 n_commands();
518 if (options & OPT_INTERACTIVE)
519 n_tty_destroy();
521 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
522 safe_signal(SIGHUP, SIG_IGN);
523 safe_signal(SIGINT, SIG_IGN);
524 safe_signal(SIGQUIT, SIG_IGN);
526 jquit:
527 save_mbox_for_possible_quitstuff();
528 quit(FAL0);
529 jleave:
530 NYD_LEAVE;
531 return exit_status;
534 static void
535 _hdrstop(int signo)
537 NYD_X; /* Signal handler */
538 n_UNUSED(signo);
540 fflush(stdout);
541 n_err_sighdl(_("\nInterrupt\n"));
542 siglongjmp(__hdrjmp, 1);
546 main(int argc, char *argv[]){
547 /* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
548 static char const
549 optstr[] = "A:a:Bb:c:dEeFfHhiL:M:m:NnO:q:Rr:S:s:tu:VvX:::~#.",
550 usagestr[] = N_(
551 "Synopsis:\n"
552 " %s -h\n"
554 " %s [-BdEFintv~] [-: spec] [-A account]\n"
555 "\t [-a attachment] [-b bcc-addr] [-c cc-addr]\n"
556 "\t [-M type | -m file | -q file | -t]\n"
557 "\t [-r from-addr] [-S var[=value]..]\n"
558 "\t [-s subject] [-X cmd] [-.] to-addr.. [-- mta-option..]\n"
560 " %s [-BdEeHiNnRv~] [-: spec] [-A account]\n"
561 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
562 "\t [-u user] [-X cmd] [-- mta-option..]\n"
564 " %s [-BdEeHiNnRv~#] [-: spec] [-A account] -f\n"
565 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
566 "\t [-X cmd] [file] [-- mta-option..]\n"
568 #define _USAGE_ARGS , progname, progname, progname, progname
570 struct a_arg *a_head, *a_curr;
571 struct name *to, *cc, *bcc;
572 struct attachment *attach;
573 char *cp, *subject, *qf, *Aarg, *Larg, *uarg;
574 char const *okey, **oargs, **Xargs, *folder, *emsg;
575 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
576 enum{
577 a_RF_NONE = 0,
578 a_RF_SET = 1<<0,
579 a_RF_SYSTEM = 1<<1,
580 a_RF_USER = 1<<2,
581 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
582 } resfiles;
583 int i;
584 NYD_ENTER;
586 a_head = NULL;
587 n_UNINIT(a_curr, NULL);
588 to = cc = bcc = NULL;
589 attach = NULL;
590 subject = qf =
591 Aarg = Larg = uarg = NULL;
592 oargs = Xargs = NULL;
593 folder = emsg = NULL;
594 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
595 resfiles = a_RF_ALL;
598 * Start our lengthy setup, finalize by setting PS_STARTED
601 progname = argv[0];
602 _startup();
604 /* Command line parsing
605 * Variable settings need to be done twice, since the user surely wants the
606 * setting to take effect immediately, but also doesn't want it to be
607 * overwritten from within resource files */
608 while ((i = _getopt(argc, argv, optstr)) >= 0) {
609 switch (i) {
610 case 'A':
611 /* Execute an account command later on */
612 Aarg = _oarg;
613 break;
614 case 'a':
615 options |= OPT_SENDMODE;
616 { struct a_arg *nap = salloc(sizeof(struct a_arg));
617 if(a_head == NULL)
618 a_head = nap;
619 else
620 a_curr->aa_next = nap;
621 nap->aa_next = NULL;
622 nap->aa_file = _oarg;
623 a_curr = nap;
625 break;
626 case 'B':
627 OBSOLETE(_("-B is obsolete, please use -# as necessary"));
628 break;
629 case 'b':
630 /* Get Blind Carbon Copy Recipient list */
631 options |= OPT_SENDMODE;
632 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
633 break;
634 case 'c':
635 /* Get Carbon Copy Recipient list */
636 options |= OPT_SENDMODE;
637 cc = cat(cc, lextract(_oarg, GCC | GFULL));
638 break;
639 case 'd':
640 ok_bset(debug);
641 okey = "debug";
642 goto joarg;
643 case 'E':
644 OBSOLETE(_("-E will be removed, please use \"-Sskipemptybody\""));
645 ok_bset(skipemptybody);
646 okey = "skipemptybody";
647 goto joarg;
648 case 'e':
649 options |= OPT_EXISTONLY;
650 break;
651 case 'F':
652 options |= OPT_F_FLAG | OPT_SENDMODE;
653 break;
654 case 'f':
655 /* User is specifying file to "edit" with Mail, as opposed to reading
656 * system mailbox. If no argument is given, we read his mbox file.
657 * Check for remaining arguments later */
658 folder = "&";
659 break;
660 case 'H':
661 options |= OPT_HEADERSONLY;
662 break;
663 case 'h':
664 n_err(V_(usagestr) _USAGE_ARGS);
665 goto j_leave;
666 case 'i':
667 /* Ignore interrupts */
668 ok_bset(ignore);
669 okey = "ignore";
670 goto joarg;
671 case 'L':
672 Larg = _oarg;
673 options |= OPT_HEADERLIST;
674 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
675 size_t j = strlen(++Larg);
676 if (j > 0)
677 Larg[j - 1] = '\0';
679 break;
680 case 'M':
681 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf != (char*)-1))
682 goto jeMmq;
683 option_Mm_arg = _oarg;
684 qf = (char*)-1;
685 if(0){
686 /* FALLTHRU*/
687 case 'm':
688 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf == (char*)-1))
689 goto jeMmq;
690 qf = _oarg;
692 options |= OPT_SENDMODE | OPT_Mm_FLAG;
693 break;
694 case 'N':
695 /* Avoid initial header printing */
696 ok_bclear(header);
697 okey = "noheader";
698 goto joarg;
699 case 'n':
700 /* Don't source "unspecified system start-up file" */
701 if(resfiles & a_RF_SET){
702 emsg = N_("-n cannot be used in conjunction with -:");
703 goto jusage;
705 resfiles = a_RF_USER;
706 break;
707 case 'O':
708 /* Additional options to pass-through to MTA TODO v15-compat legacy */
709 if (smopts_cnt == smopts_size)
710 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_cnt);
711 smopts[smopts_cnt++] = _oarg;
712 break;
713 case 'q':
714 if (qf != NULL && (options & OPT_Mm_FLAG)) {
715 jeMmq:
716 emsg = N_("Only one of -M, -m or -q may be given");
717 goto jusage;
719 /* Quote file TODO drop? -Q with real quote?? what ? */
720 options |= OPT_SENDMODE;
721 /* Allow for now, we have to special check validity of -q- later on! */
722 qf = (_oarg[0] == '-' && _oarg[1] == '\0') ? (char*)-1 : _oarg;
723 break;
724 case 'R':
725 /* Open folders read-only */
726 options |= OPT_R_FLAG;
727 break;
728 case 'r':
729 /* Set From address. */
730 options |= OPT_r_FLAG;
731 if (_oarg[0] != '\0') {
732 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
734 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
735 emsg = N_("Invalid address argument with -r");
736 goto jusage;
738 option_r_arg = fa;
739 /* TODO -r options is set in smopts, but may
740 * TODO be overwritten by setting from= in
741 * TODO an interactive session!
742 * TODO Maybe disable setting of from?
743 * TODO Warn user? Update manual!! */
744 okey = savecat("from=", fa->n_fullname);
745 goto joarg;
747 break;
748 case 'S':
749 /* Set variable (TODO twice [only if successful]) */
750 { char *a[2];
751 bool_t b;
753 okey = a[0] = _oarg;
754 a[1] = NULL;
755 pstate |= PS_ROBOT;
756 b = (c_set(a) == 0);
757 pstate &= ~PS_ROBOT;
758 if(!b)
759 break;
761 joarg:
762 if (oargs_cnt == oargs_size)
763 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
764 oargs[oargs_cnt++] = okey;
765 break;
766 case 's':
767 /* Subject:; take care for Debian #419840 and strip any \r and \n */
768 if(n_anyof_cp("\n\r", subject = _oarg)){
769 n_err(_("-s: normalizing away invalid ASCII NL / CR bytes\n"));
770 for(cp = subject = savestr(_oarg); *cp != '\0'; ++cp)
771 if(*cp == '\n' || *cp == '\r')
772 *cp = ' ';
774 options |= OPT_SENDMODE;
775 break;
776 case 't':
777 /* Read defined set of headers from mail to be sent */
778 options |= OPT_SENDMODE | OPT_t_FLAG;
779 break;
780 case 'u':
781 uarg = savecat("%", _oarg);
782 break;
783 case 'V':
784 printf(_("%s version %s\n"), uagent, ok_vlook(version));
785 exit_status = EXIT_OK;
786 goto j_leave;
787 case 'v':
788 /* Be verbose */
789 ok_bset(verbose);
790 okey = "verbose";
791 goto joarg;
792 case 'X':
793 /* Add to list of commands to exec before entering normal operation */
794 if (Xargs_cnt == Xargs_size)
795 Xargs_size = _grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
796 Xargs[Xargs_cnt++] = _oarg;
797 break;
798 case ':':
799 /* Control which resource files shall be loaded */
800 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
801 emsg = N_("-n cannot be used in conjunction with -:");
802 goto jusage;
804 resfiles = a_RF_SET;
805 while((i = *_oarg++) != '\0')
806 switch(i){
807 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
808 case 'U': case 'u': resfiles |= a_RF_USER; break;
809 case ':': case '/': resfiles &= ~a_RF_ALL; break;
810 default:
811 emsg = N_("Invalid argument of -:");
812 goto jusage;
814 break;
815 case '~':
816 /* Enable command escapes even in non-interactive mode */
817 options |= OPT_TILDE_FLAG;
818 break;
819 case '#':
820 /* Work in batch mode, even if non-interactive */
821 if(!(options & OPT_INTERACTIVE))
822 setvbuf(stdin, NULL, _IOLBF, 0);
823 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
824 if (oargs_cnt + 8 >= oargs_size)
825 oargs_size = _grow_cpp(&oargs, oargs_size + 9, oargs_cnt);
826 folder = "/dev/null";
827 ok_vset(MAIL, folder);
828 ok_vset(MBOX, folder);
829 ok_bset(emptystart);
830 ok_bclear(header);
831 ok_vset(inbox, folder);
832 ok_bset(quiet);
833 ok_bset(sendwait);
834 ok_bset(typescript_mode);
835 oargs[oargs_cnt + 0] = "MAIL=/dev/null";
836 oargs[oargs_cnt + 1] = "MBOX=/dev/null";
837 oargs[oargs_cnt + 2] = "emptystart";
838 oargs[oargs_cnt + 3] = "noheader";
839 oargs[oargs_cnt + 4] = "inbox=/dev/null";
840 oargs[oargs_cnt + 5] = "quiet";
841 oargs[oargs_cnt + 6] = "sendwait";
842 oargs[oargs_cnt + 7] = "typescript-mode";
843 oargs_cnt += 8;
844 break;
845 case '.':
846 options |= OPT_SENDMODE;
847 goto jgetopt_done;
848 case '?':
849 jusage:
850 if (emsg != NULL)
851 n_err("%s\n", V_(emsg));
852 n_err(V_(usagestr) _USAGE_ARGS);
853 #undef _USAGE_ARGS
854 exit_status = EXIT_USE;
855 goto j_leave;
858 jgetopt_done:
861 /* The normal arguments may be followed by MTA arguments after a "--";
862 * however, -f may take off an argument, too, and before that.
863 * Since MTA arguments after "--" require *expandargv*, delay parsing off
864 * those options until after the resource files are loaded... */
865 if ((cp = argv[i = _oind]) == NULL)
867 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
868 ++i;
869 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
870 else if (folder != NULL && /*folder[0] == '&' &&*/ folder[1] == '\0') {
871 folder = cp;
872 if ((cp = argv[++i]) != NULL) {
873 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
874 emsg = N_("More than one file given with -f");
875 goto jusage;
877 ++i;
879 } else {
880 options |= OPT_SENDMODE;
881 for (;;) {
882 to = cat(to, lextract(cp, GTO | GFULL));
883 if ((cp = argv[++i]) == NULL)
884 break;
885 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
886 ++i;
887 break;
891 _oind = i;
893 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
894 * allocate the necessary space for them before we fixate that storage! */
895 while (argv[i] != NULL)
896 ++i;
897 if (smopts_cnt + i > smopts_size)
898 DBG(smopts_size =) _grow_cpp(&smopts, smopts_cnt + i + 1, smopts_cnt);
900 /* Check for inconsistent arguments, fix some temporaries */
901 if (options & OPT_SENDMODE) {
902 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
903 * XXX in order to function. Ideally that would not be needed */
904 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
905 emsg = N_("Cannot give -f and people to send to.");
906 goto jusage;
908 if (uarg != NULL) {
909 emsg = N_("The -u option cannot be used in send mode");
910 goto jusage;
912 if (!(options & OPT_t_FLAG) && to == NULL) {
913 emsg = N_("Send options without primary recipient specified.");
914 goto jusage;
916 if ((options & OPT_t_FLAG) && qf != NULL) {
917 emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
918 goto jusage;
920 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
921 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
922 goto jusage;
924 if (options & OPT_R_FLAG) {
925 emsg = N_("The -R option is meaningless in send mode.");
926 goto jusage;
929 if (options & OPT_INTERACTIVE) {
930 if (qf == (char*)-1) {
931 if (!(options & OPT_Mm_FLAG))
932 emsg = N_("-q can't use standard input when interactive.\n");
933 goto jusage;
936 } else {
937 if (uarg != NULL && folder != NULL) {
938 emsg = N_("The options -u and -f (and -#) are mutually exclusive");
939 goto jusage;
941 if ((options & (OPT_EXISTONLY | OPT_HEADERSONLY)) ==
942 (OPT_EXISTONLY | OPT_HEADERSONLY)) {
943 emsg = N_("The options -e and -H are mutual exclusive");
944 goto jusage;
946 if ((options & (OPT_HEADERSONLY | OPT_HEADERLIST)) == /* TODO OBSOLETE */
947 (OPT_HEADERSONLY | OPT_HEADERLIST))
948 OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
950 if(uarg != NULL)
951 folder = uarg;
955 * Likely to go, perform more setup
958 _setup_vars();
960 if (options & OPT_INTERACTIVE) {
961 _setscreensize(0);
962 #ifdef SIGWINCH
963 # ifndef TTY_WANTS_SIGWINCH
964 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
965 # endif
966 safe_signal(SIGWINCH, &_setscreensize);
967 #endif
968 } else
969 scrnheight = realscreenheight = 24, scrnwidth = 80;
971 /* Fixate the current snapshot of our global auto-reclaimed storage instance.
972 * Memory is auto-reclaimed from now on */
973 n_memory_autorec_fixate();
975 /* load() any resource files */
976 if(resfiles & a_RF_ALL){
977 /* *expand() returns a savestr(), but load only uses the file name for
978 * fopen(), so it's safe to do this */
979 if((resfiles & a_RF_SYSTEM) && !ok_blook(NAIL_NO_SYSTEM_RC))
980 n_load(VAL_SYSCONFDIR "/" VAL_SYSCONFRC);
981 if(resfiles & a_RF_USER)
982 n_load(fexpand(ok_vlook(MAILRC), FEXP_LOCAL | FEXP_NOPROTO));
983 if((cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
984 n_load(fexpand(cp, FEXP_LOCAL | FEXP_NOPROTO));
987 /* Ensure the -S and other command line options take precedence over
988 * anything that may have been placed in resource files.
989 * Our "ternary binary" option *verbose* needs special treament */
990 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
991 options &= ~OPT_VERB;
992 /* ..and be silent when unsetting an undefined variable */
993 pstate |= PS_ROBOT;
994 for (i = 0; UICMP(z, i, <, oargs_cnt); ++i) {
995 char const *a[2];
997 a[0] = oargs[i];
998 a[1] = NULL;
999 c_set(a);
1001 pstate &= ~PS_ROBOT;
1003 /* Cause possible umask(2), now that any setting is established, and before
1004 * we change accounts, evaluate commands etc. */
1005 (void)ok_vlook(umask);
1007 /* Additional options to pass-through to MTA, and allowed to do so? */
1008 if ((cp = ok_vlook(expandargv)) != NULL) {
1009 bool_t isfail = !asccasecmp(cp, "fail"),
1010 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
1012 if ((options & OPT_D_V) && !isfail && !isrestrict && *cp != '\0')
1013 n_err(_("Unknown *expandargv* value: %s\n"), cp);
1015 if ((cp = argv[i = _oind]) != NULL) {
1016 if (isfail ||
1017 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
1018 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
1019 "using *sendmail-arguments*\n"));
1020 exit_status = EXIT_USE | EXIT_SEND_ERROR;
1021 goto jleave;
1023 do {
1024 assert(smopts_cnt + 1 <= smopts_size);
1025 smopts[smopts_cnt++] = cp;
1026 } while ((cp = argv[++i]) != NULL);
1030 /* We had to wait until the resource files are loaded and any command line
1031 * setting has been restored, but get the termcap up and going before we
1032 * switch account or running commands */
1033 #ifdef n_HAVE_TCAP
1034 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1035 n_termcap_init();
1036 #endif
1038 /* Now we can set the account */
1039 if (Aarg != NULL) {
1040 char const *a[2];
1041 a[0] = Aarg;
1042 a[1] = NULL;
1043 c_account(a);
1046 /* "load()" commands given on command line */
1047 if(Xargs_cnt > 0)
1048 n_load_Xargs(Xargs, Xargs_cnt);
1050 /* Final tests */
1051 if(options & OPT_Mm_FLAG){
1052 if(qf == (char*)-1){
1053 if(!mime_type_check_mtname(option_Mm_arg)){
1054 n_err(_("Could not find `mimetype' for -M argument: %s\n"),
1055 option_Mm_arg);
1056 exit_status = EXIT_ERR;
1057 goto jleave;
1059 }else if((option_Mm_arg = mime_type_classify_filename(qf)) == NULL){
1060 n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
1061 n_shexp_quote_cp(qf, FAL0));
1062 exit_status = EXIT_ERR;
1063 goto jleave;
1064 }else if(!asccasecmp(option_Mm_arg, "text/plain")) /* TODO no: magic!! */
1065 option_Mm_arg = NULL;
1069 * We're finally completely setup and ready to go
1071 pstate |= PS_STARTED;
1073 if (!(options & OPT_SENDMODE)) {
1074 exit_status = _rcv_mode(folder, Larg);
1075 goto jleave;
1078 /* Now that full mailx(1)-style file expansion is possible handle the
1079 * attachments which we had delayed due to this.
1080 * This may use savestr(), but since we won't enter the command loop we
1081 * don't need to care about that */
1082 for(; a_head != NULL; a_head = a_head->aa_next){
1083 enum n_attach_error aerr;
1085 attach = n_attachment_append(attach, a_head->aa_file, &aerr, NULL);
1086 if(aerr != n_ATTACH_ERR_NONE){
1087 exit_status = EXIT_ERR;
1088 goto jleave;
1092 if (options & OPT_INTERACTIVE)
1093 n_tty_init();
1094 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1095 if (options & OPT_INTERACTIVE)
1096 n_tty_destroy();
1098 jleave:
1099 /* Be aware of identical code for `exit' command! */
1100 #ifdef n_HAVE_TCAP
1101 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1102 n_termcap_destroy();
1103 #endif
1105 j_leave:
1106 #ifdef HAVE_MEMORY_DEBUG
1107 n_memory_autorec_pop(NULL);
1108 #endif
1109 #if (defined HAVE_DEBUG || defined HAVE_DEVEL)
1110 n_memory_reset();
1111 #endif
1112 NYD_LEAVE;
1113 return exit_status;
1116 /* Source the others in that case! */
1117 #ifdef HAVE_AMALGAMATION
1118 # include "config.h"
1119 #endif
1121 /* s-it-mode */