Move string dope from strings.c to the new memory.c..
[s-mailx.git] / main.c
blob3ab0aaa1452c4733ce5bfc27af19c0dce7f7585d
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Startup and initialization.
3 *@ This file is also used to materialize externals.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 #undef n_FILE
37 #define n_FILE main
38 #define n_MAIN_SOURCE
40 #include "nail.h"
42 #include <sys/ioctl.h>
44 #include <pwd.h>
46 #ifdef HAVE_NL_LANGINFO
47 # include <langinfo.h>
48 #endif
49 #ifdef HAVE_SETLOCALE
50 # include <locale.h>
51 #endif
53 struct a_arg {
54 struct a_arg *aa_next;
55 char *aa_file;
58 struct X_arg {
59 struct X_arg *xa_next;
60 size_t xa_cmd_len;
61 char xa_cmd_buf[VFIELD_SIZE(sizeof(size_t))];
64 /* (extern, but not with amalgamation, so define here) */
65 VL char const weekday_names[7 + 1][4] = {
66 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ""
68 VL char const month_names[12 + 1][4] = {
69 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
70 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""
72 VL char const uagent[sizeof UAGENT] = UAGENT;
73 VL uc_i const class_char[1 + 0x7F] = {
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, C_BLANK, C_WHITE, C_SPACE, C_SPACE, C_SPACE, 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 /* 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 /* Initialize *tempdir*, *myname*, *homedir* */
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,
136 struct X_arg *xhp);
138 /* Interrupt printing of the headers */
139 static void _hdrstop(int signo);
141 /* -X arg given at least once, evaluate the list in order */
142 static bool_t _X_arg_eval(struct X_arg *xhp);
144 static int
145 _getopt(int argc, char * const argv[], char const *optstring)
147 static char const *lastp;
149 int rv = -1/*, colon*/;
150 char const *curp;
151 NYD_ENTER;
153 _oarg = NULL;
155 /*if ((colon = (optstring[0] == ':')))
156 ++optstring;*/
158 if (lastp != NULL) {
159 curp = lastp;
160 lastp = NULL;
161 } else {
162 if (_oind >= argc || argv[_oind] == NULL || argv[_oind][0] != '-' ||
163 argv[_oind][1] == '\0')
164 goto jleave;
165 if (argv[_oind][1] == '-' && argv[_oind][2] == '\0') {
166 /* We need this in for MTA arg detection (easier) ++_oind;*/
167 goto jleave;
169 curp = &argv[_oind][1];
172 for(_oopt = curp[0]; optstring[0] != '\0';){
173 if(optstring[0] != _oopt){
174 optstring += 1 + (optstring[1] == ':');
175 continue;
178 if (optstring[1] == ':') {
179 if (curp[1] != '\0') {
180 _oarg = UNCONST(curp + 1);
181 ++_oind;
182 } else {
183 if ((_oind += 2) > argc) {
184 /*if (!colon *//*&& _oerr*//*)*/ {
185 n_err(_("%s: option requires an argument -- %c\n"),
186 argv[0], (char)_oopt);
188 rv = (/*colon ? ':' :*/ '?');
189 goto jleave;
191 _oarg = argv[_oind - 1];
193 } else {
194 if (curp[1] != '\0')
195 lastp = curp + 1;
196 else
197 ++_oind;
199 rv = _oopt;
200 goto jleave;
203 /* Special support for --help, which is quite common */
204 if (_oopt == '-' && !strcmp(curp, "-help") && curp - 1 == argv[_oind]) {
205 ++_oind;
206 rv = 'h';
207 goto jleave;
210 /* Definitive error */
211 /*if (!colon *//*&& opterr*//*)*/
212 n_err(_("%s: invalid option -- %c\n"), argv[0], _oopt);
213 if (curp[1] != '\0')
214 lastp = curp + 1;
215 else
216 ++_oind;
217 _oarg = NULL;
218 rv = '?';
219 jleave:
220 NYD_LEAVE;
221 return rv;
224 static void
225 _startup(void)
227 char *cp;
228 NYD_ENTER;
230 image = -1;
231 dflpipe = SIG_DFL;
232 _oind = /*_oerr =*/ 1;
234 if ((cp = strrchr(progname, '/')) != NULL)
235 progname = ++cp;
237 /* Set up a reasonable environment */
239 #ifdef HAVE_NYD
240 safe_signal(SIGABRT, &_nyd_oncrash);
241 # ifdef SIGBUS
242 safe_signal(SIGBUS, &_nyd_oncrash);
243 # endif
244 safe_signal(SIGFPE, &_nyd_oncrash);
245 safe_signal(SIGILL, &_nyd_oncrash);
246 safe_signal(SIGSEGV, &_nyd_oncrash);
247 #endif
248 command_manager_start();
250 if (isatty(STDIN_FILENO)) /* TODO should be isatty(0) && isatty(2)?? */
251 options |= OPT_TTYIN;
252 if (isatty(STDOUT_FILENO))
253 options |= OPT_TTYOUT;
254 if ((options & (OPT_TTYIN | OPT_TTYOUT)) == (OPT_TTYIN | OPT_TTYOUT)) {
255 options |= OPT_INTERACTIVE;
256 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
259 /* -- >8 -- 8< -- */
261 /* Define defaults for internal variables, based on POSIX 2008/Cor 1-2013 */
262 /* (Keep in sync:
263 * ./main.c:_startup(), ./nail.rc, ./nail.1:"Initial settings") */
264 /* noallnet */
265 /* noappend */
266 ok_bset(asksub, TRU1);
267 /* noaskbcc */
268 /* noaskcc */
269 /* noautoprint */
270 /* nobang */
271 /* nocmd */
272 /* nocrt */
273 /* nodebug */
274 /* nodot */
275 /* ok_vset(escape, ESCAPE *"~"*); TODO non-compliant */
276 /* noflipr */
277 /* nofolder */
278 ok_bset(header, TRU1);
279 /* nohold */
280 /* noignore */
281 /* noignoreeof */
282 /* nokeep */
283 /* nokeepsave */
284 /* nometoo */
285 /* noonehop -- Note: we ignore this one */
286 /* nooutfolder */
287 /* nopage */
288 ok_vset(prompt, "\\& "); /* POSIX "? " unless *bsdcompat*, then "& " */
289 /* noquiet */
290 /* norecord */
291 ok_bset(save, TRU1);
292 /* nosendwait */
293 /* noshowto */
294 /* nosign */
295 /* noSign */
296 /* ok_vset(toplines, "5"); XXX somewhat hmm */
298 /* TODO until we have an automatic mechanism for that, set some more
299 * TODO variables so that users see the internal fallback settings
300 * TODO (something like "defval=X,notempty=1") */
301 do {
302 char const *vp;
304 vp = env_vlook("SHELL", TRU1);
305 ok_vset(SHELL, (vp != NULL ? vp : XSHELL));
307 vp = env_vlook("LISTER", TRU1);
308 ok_vset(LISTER, (vp != NULL ? vp : XLISTER));
310 vp = env_vlook("PAGER", TRU1);
311 ok_vset(PAGER, (vp != NULL ? vp : XPAGER));
313 ok_vset(sendmail, SENDMAIL);
314 ok_vset(sendmail_progname, SENDMAIL_PROGNAME);
315 } while (0);
317 /* -- >8 -- 8< -- */
319 #ifdef HAVE_SETLOCALE
320 setlocale(LC_ALL, "");
321 mb_cur_max = MB_CUR_MAX;
322 # ifdef HAVE_NL_LANGINFO
323 if (ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
324 ok_vset(ttycharset, cp);
325 # endif
327 # ifdef HAVE_C90AMEND1
328 if (mb_cur_max > 1) {
329 wchar_t wc;
330 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
331 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
332 options |= OPT_UNICODE;
333 /* Reset possibly messed up state; luckily this also gives us an
334 * indication wether the encoding has locking shift state sequences */
335 /* TODO temporary - use option bits! */
336 if (mbtowc(&wc, NULL, mb_cur_max))
337 options |= OPT_ENC_MBSTATE;
339 # endif
340 #else
341 mb_cur_max = 1;
342 #endif
344 #ifdef HAVE_ICONV
345 iconvd = (iconv_t)-1;
346 #endif
347 NYD_LEAVE;
350 static size_t
351 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
353 /* Before spreserve(): use our string pool instead of LibC heap */
354 char const **newcpp;
355 NYD_ENTER;
357 newcpp = salloc(sizeof(char*) * newsize);
359 if (oldcnt > 0)
360 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
361 *cpp = newcpp;
362 NYD_LEAVE;
363 return newsize;
366 static void
367 _setup_vars(void)
369 /* Before spreserve(): use our string pool instead of LibC heap */
370 /* XXX further check paths? */
371 char const *cp;
372 uid_t uid;
373 struct passwd *pwuid, *pw;
374 NYD_ENTER;
376 /* Verify and fixate user identification */
377 if (myname != NULL)
378 cp = myname;
379 else if ((cp = env_vlook("LOGNAME", TRU1)) == NULL)
380 cp = env_vlook("USER", TRU1);
382 group_id = getgid();
383 user_id = uid = getuid();
384 if ((pwuid = getpwuid(uid)) == NULL)
385 n_panic(_("Cannot associate a name with uid %u"), user_id);
387 if (cp == NULL || *cp == '\0')
388 myname = pwuid->pw_name;
389 else if ((pw = getpwnam(cp)) == NULL) {
390 n_alert(_("\"%s\" is not a user of this system"), cp);
391 exit(EXIT_NOUSER);
392 } else {
393 myname = pw->pw_name;
394 if (pw->pw_uid != uid)
395 options |= OPT_u_FLAG;
397 myname = savestr(myname);
398 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
400 /* */
401 if ((cp = env_vlook("HOME", TRU1)) == NULL)
402 cp = "."; /* XXX User and Login objects; Login: pw->pw_dir */
403 homedir = savestr(cp);
405 tempdir = ((cp = env_vlook("TMPDIR", TRU1)) != NULL)
406 ? savestr(cp) : TMPDIR_FALLBACK;
407 NYD_LEAVE;
410 static void
411 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
413 struct termios tbuf;
414 #ifdef TIOCGWINSZ
415 struct winsize ws;
416 #elif defined TIOCGSIZE
417 struct ttysize ts;
418 #endif
419 NYD_ENTER;
421 scrnheight = realscreenheight = scrnwidth = 0;
423 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
424 * a little bit to be able to honour resizes during our lifetime and
425 * only honour it upon first run; abuse *is_sighdl* as an indicator */
426 if (!is_sighdl) {
427 char *cp;
428 long i;
430 if ((cp = env_vlook("LINES", FAL0)) != NULL &&
431 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
432 scrnheight = realscreenheight = (int)i;
433 if ((cp = env_vlook("COLUMNS", FAL0)) != NULL &&
434 (i = strtol(cp, NULL, 10)) > 0 && i < INT_MAX)
435 scrnwidth = (int)i;
437 if (scrnwidth != 0 && scrnheight != 0)
438 goto jleave;
441 #ifdef TIOCGWINSZ
442 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
443 ws.ws_col = ws.ws_row = 0;
444 #elif defined TIOCGSIZE
445 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
446 ts.ts_lines = ts.ts_cols = 0;
447 #endif
449 if (scrnheight == 0) {
450 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
451 ? B9600 : cfgetospeed(&tbuf));
453 if (ospeed < B1200)
454 scrnheight = 9;
455 else if (ospeed == B1200)
456 scrnheight = 14;
457 #ifdef TIOCGWINSZ
458 else if (ws.ws_row != 0)
459 scrnheight = ws.ws_row;
460 #elif defined TIOCGSIZE
461 else if (ts.ts_lines != 0)
462 scrnheight = ts.ts_lines;
463 #endif
464 else
465 scrnheight = 24;
467 #if defined TIOCGWINSZ || defined TIOCGSIZE
468 if (0 ==
469 # ifdef TIOCGWINSZ
470 (realscreenheight = ws.ws_row)
471 # else
472 (realscreenheight = ts.ts_lines)
473 # endif
475 realscreenheight = 24;
476 #endif
479 if (scrnwidth == 0 && 0 ==
480 #ifdef TIOCGWINSZ
481 (scrnwidth = ws.ws_col)
482 #elif defined TIOCGSIZE
483 (scrnwidth = ts.ts_cols)
484 #endif
486 scrnwidth = 80;
488 jleave:
489 #ifdef SIGWINCH
490 if (is_sighdl && (options & OPT_INTERACTIVE))
491 n_tty_signal(SIGWINCH);
492 #endif
493 NYD_LEAVE;
496 static sigjmp_buf __hdrjmp; /* XXX */
498 static int
499 _rcv_mode(char const *folder, char const *Larg, struct X_arg *xhp)
501 int i;
502 sighandler_type prevint;
503 NYD_ENTER;
505 if (folder == NULL)
506 folder = "%";
508 if (options & OPT_QUICKRUN_MASK)
509 i = FEDIT_RDONLY;
510 else
511 i = FEDIT_NONE;
512 i = setfile(folder, i);
513 if (i < 0) {
514 exit_status = EXIT_ERR; /* error already reported */
515 goto jquit;
517 if (options & OPT_QUICKRUN_MASK) {
518 exit_status = i;
519 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
520 (options & OPT_HEADERLIST)))
521 print_header_summary(Larg);
522 goto jquit;
524 check_folder_hook(FAL0);
526 if (i > 0 && !ok_blook(emptystart)) {
527 exit_status = EXIT_ERR;
528 goto jleave;
531 if (sigsetjmp(__hdrjmp, 1) == 0) {
532 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
533 safe_signal(SIGINT, _hdrstop);
534 if (!(options & OPT_N_FLAG)) {
535 if (!ok_blook(quiet))
536 printf(_("%s version %s. Type ? for help.\n"),
537 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
538 announce(1);
539 fflush(stdout);
541 safe_signal(SIGINT, prevint);
544 /* Enter the command loop */
545 if (xhp == NULL || _X_arg_eval(xhp)) {
546 if (options & OPT_INTERACTIVE)
547 n_tty_init();
548 commands();
549 if (options & OPT_INTERACTIVE)
550 n_tty_destroy();
553 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
554 safe_signal(SIGHUP, SIG_IGN);
555 safe_signal(SIGINT, SIG_IGN);
556 safe_signal(SIGQUIT, SIG_IGN);
558 jquit:
559 save_mbox_for_possible_quitstuff();
560 quit();
561 jleave:
562 NYD_LEAVE;
563 return exit_status;
566 static void
567 _hdrstop(int signo)
569 NYD_X; /* Signal handler */
570 UNUSED(signo);
572 fflush(stdout);
573 n_err_sighdl(_("\nInterrupt\n"));
574 siglongjmp(__hdrjmp, 1);
577 static bool_t
578 _X_arg_eval(struct X_arg *xhp) /* TODO error handling not right */
580 struct eval_ctx ev;
581 struct X_arg *xp;
582 bool_t rv = TRU1;
583 NYD_ENTER;
585 while ((xp = xhp) != NULL) {
586 xhp = xp->xa_next;
588 memset(&ev, 0, sizeof ev);
589 ev.ev_line.s = xp->xa_cmd_buf;
590 ev.ev_line.l = xp->xa_cmd_len;
591 ev.ev_is_recursive = TRU1;
592 pstate &= ~PS_HOOK_MASK;
593 rv = (evaluate(&ev) == 0);
594 free(xp);
596 if (!rv) {
597 if (exit_status == EXIT_OK)
598 exit_status = EXIT_ERR;
599 break;
601 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
602 if (exit_status != EXIT_OK)
603 break;
604 if (pstate & PS_EVAL_ERROR) {
605 exit_status = EXIT_ERR;
606 break;
610 NYD_LEAVE;
611 return rv;
615 main(int argc, char *argv[])
617 static char const optstr[] = "A:a:Bb:c:dEeFfHhiL:NnO:q:Rr:S:s:tu:VvX:::~#.",
618 usagestr[] = N_(
619 " Synopsis:\n"
620 " %s -h | --help\n"
621 " %s [-BdEFintv~] [-: spec] [-A account]\n"
622 "\t [-a attachment] [-b bcc-address] [-c cc-address]\n"
623 "\t [-q file] [-r from-address] [-S var[=value]...]\n"
624 "\t [-s subject] [-X cmd] [-.] to-address... [-- mta-option...]\n"
625 " %s [-BdEeHiNnRv~#] [-: spec] [-A account]\n"
626 "\t [-L spec-list] [-r from-address] [-S var[=value]...]\n"
627 "\t [-X cmd] -f [file] [-- mta-option...]\n"
628 " %s [-BdEeHiNnRv~#] [-: spec] [-A account]\n"
629 "\t [-L spec-list] [-r from-address] [-S var[=value]...]\n"
630 "\t [-u user] [-X cmd] [-- mta-option...]\n"
632 #define _USAGE_ARGS , progname, progname, progname, progname
634 struct X_arg *X_head = NULL, *X_curr = /* silence CC */ NULL;
635 struct a_arg *a_head = NULL, *a_curr = /* silence CC */ NULL;
636 struct name *to = NULL, *cc = NULL, *bcc = NULL;
637 struct attachment *attach = NULL;
638 char *cp = NULL, *subject = NULL, *qf = NULL, *Aarg = NULL, *Larg = NULL;
639 char const *okey, **oargs = NULL, *folder = NULL, *emsg = NULL;
640 size_t oargs_size = 0, oargs_count = 0, smopts_size = 0;
641 enum{
642 a_RF_NONE = 0,
643 a_RF_SET = 1<<0,
644 a_RF_SYSTEM = 1<<1,
645 a_RF_USER = 1<<2,
646 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
647 } resfiles;
648 int i;
649 NYD_ENTER;
651 resfiles = a_RF_ALL;
654 * Start our lengthy setup, finalize by setting PS_STARTED
657 progname = argv[0];
658 _startup();
660 /* Command line parsing
661 * Variable settings need to be done twice, since the user surely wants the
662 * setting to take effect immediately, but also doesn't want it to be
663 * overwritten from within resource files */
664 while ((i = _getopt(argc, argv, optstr)) >= 0) {
665 switch (i) {
666 case 'A':
667 /* Execute an account command later on */
668 Aarg = _oarg;
669 break;
670 case 'a':
671 options |= OPT_SENDMODE;
672 { struct a_arg *nap = salloc(sizeof(struct a_arg));
673 if (a_head == NULL)
674 a_head = nap;
675 else
676 a_curr->aa_next = nap;
677 nap->aa_next = NULL;
678 nap->aa_file = _oarg;
679 a_curr = nap;
681 break;
682 case 'B':
683 /* Make 0/1 line buffered */
684 setvbuf(stdin, NULL, _IOLBF, 0);
685 setvbuf(stdout, NULL, _IOLBF, 0);
686 break;
687 case 'b':
688 /* Get Blind Carbon Copy Recipient list */
689 options |= OPT_SENDMODE;
690 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
691 break;
692 case 'c':
693 /* Get Carbon Copy Recipient list */
694 options |= OPT_SENDMODE;
695 cc = cat(cc, lextract(_oarg, GCC | GFULL));
696 break;
697 case 'd':
698 ok_bset(debug, TRU1);
699 okey = "debug";
700 goto joarg;
701 case 'E':
702 ok_bset(skipemptybody, TRU1);
703 okey = "skipemptybody";
704 goto joarg;
705 case 'e':
706 options |= OPT_EXISTONLY;
707 break;
708 case 'F':
709 options |= OPT_F_FLAG | OPT_SENDMODE;
710 break;
711 case 'f':
712 /* User is specifying file to "edit" with Mail, as opposed to reading
713 * system mailbox. If no argument is given, we read his mbox file.
714 * Check for remaining arguments later */
715 folder = "&";
716 break;
717 case 'H':
718 options |= OPT_HEADERSONLY;
719 break;
720 case 'h':
721 n_err(V_(usagestr) _USAGE_ARGS);
722 goto j_leave;
723 case 'i':
724 /* Ignore interrupts */
725 ok_bset(ignore, TRU1);
726 okey = "ignore";
727 goto joarg;
728 case 'L':
729 Larg = _oarg;
730 options |= OPT_HEADERLIST;
731 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
732 size_t j = strlen(++Larg);
733 if (j > 0)
734 Larg[j - 1] = '\0';
736 break;
737 case 'N':
738 /* Avoid initial header printing */
739 ok_bset(header, FAL0);
740 okey = "noheader";
741 goto joarg;
742 case 'n':
743 /* Don't source "unspecified system start-up file" */
744 if(resfiles & a_RF_SET){
745 emsg = N_("-n cannot be used in conjunction with -:");
746 goto jusage;
748 resfiles = a_RF_USER;
749 break;
750 case 'O':
751 /* Additional options to pass-through to MTA TODO v15-compat legacy */
752 if (smopts_count == (size_t)smopts_size)
753 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_count);
754 smopts[smopts_count++] = _oarg;
755 break;
756 case 'q':
757 /* Quote file TODO drop? -Q with real quote?? what ? */
758 options |= OPT_SENDMODE;
759 /* Allow for now, we have to special check validity of -q- later on! */
760 qf = (_oarg[0] == '-' && _oarg[1] == '\0') ? (char*)-1 : _oarg;
761 break;
762 case 'R':
763 /* Open folders read-only */
764 options |= OPT_R_FLAG;
765 break;
766 case 'r':
767 /* Set From address. */
768 options |= OPT_r_FLAG;
769 if (_oarg[0] != '\0') {
770 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
772 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
773 emsg = N_("Invalid address argument with -r");
774 goto jusage;
776 option_r_arg = fa;
777 /* TODO -r options is set in smopts, but may
778 * TODO be overwritten by setting from= in
779 * TODO an interactive session!
780 * TODO Maybe disable setting of from?
781 * TODO Warn user? Update manual!! */
782 okey = savecat("from=", fa->n_fullname);
783 goto joarg;
785 break;
786 case 'S':
787 /* Set variable (twice) */
788 { char *a[2];
789 okey = a[0] = _oarg;
790 a[1] = NULL;
791 c_set(a);
793 joarg:
794 if (oargs_count == oargs_size)
795 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_count);
796 oargs[oargs_count++] = okey;
797 break;
798 case 's':
799 /* Subject: */
800 subject = _oarg;
801 options |= OPT_SENDMODE;
802 break;
803 case 't':
804 /* Read defined set of headers from mail to be sent */
805 options |= OPT_SENDMODE | OPT_t_FLAG;
806 break;
807 case 'u':
808 /* Set user name to pretend to be; don't set OPT_u_FLAG yet, this is
809 * done as necessary in _setup_vars() above */
810 myname = _oarg;
811 break;
812 case 'V':
813 puts(ok_vlook(version));
814 exit(EXIT_OK);
815 /* NOTREACHED */
816 case 'v':
817 /* Be verbose */
818 ok_bset(verbose, TRU1);
819 okey = "verbose";
820 goto joarg;
821 case 'X': {
822 /* Add to list of commands to exec before entering normal operation */
823 size_t l = strlen(_oarg);
824 struct X_arg *nxp = smalloc(sizeof(*nxp) -
825 VFIELD_SIZEOF(struct X_arg, xa_cmd_buf) + l +1);
826 if (X_head == NULL)
827 X_head = nxp;
828 else
829 X_curr->xa_next = nxp;
830 X_curr = nxp;
831 nxp->xa_next = NULL;
832 nxp->xa_cmd_len = l;
833 memcpy(nxp->xa_cmd_buf, _oarg, l +1);
835 break;
836 case ':':
837 /* Control which resource files shall be loaded */
838 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
839 emsg = N_("-n cannot be used in conjunction with -:");
840 goto jusage;
842 resfiles = a_RF_SET;
843 while((i = *_oarg++) != '\0')
844 switch(i){
845 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
846 case 'U': case 'u': resfiles |= a_RF_USER; break;
847 case ':': case '/': resfiles &= ~a_RF_ALL; break;
848 default:
849 emsg = N_("Invalid argument of -:");
850 goto jusage;
852 break;
853 case '~':
854 /* Enable tilde escapes even in non-interactive mode */
855 options |= OPT_TILDE_FLAG;
856 break;
857 case '#':
858 /* Work in batch mode, even if non-interactive */
859 if (oargs_count + 5 >= oargs_size)
860 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_count);
861 /* xxx Setting most of the -# options immediately is useless, so be
862 * selective in what is set immediately */
863 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
864 folder = "/dev/null";
865 ok_bset(emptystart, TRU1);
866 ok_bset(header, FAL0);
867 ok_bset(quiet, TRU1);
868 ok_bset(sendwait, TRU1);
869 ok_vset(MBOX, folder);
870 oargs[oargs_count + 0] = "emptystart";
871 oargs[oargs_count + 1] = "noheader";
872 oargs[oargs_count + 2] = "quiet";
873 oargs[oargs_count + 3] = "sendwait";
874 oargs[oargs_count + 4] = "MBOX=/dev/null";
875 oargs_count += 5;
876 break;
877 case '.':
878 options |= OPT_SENDMODE;
879 goto jgetopt_done;
880 case '?':
881 jusage:
882 if (emsg != NULL)
883 n_err("%s\n", V_(emsg));
884 n_err(V_(usagestr) _USAGE_ARGS);
885 #undef _USAGE_ARGS
886 exit_status = EXIT_USE;
887 goto j_leave;
890 jgetopt_done:
893 /* The normal arguments may be followed by MTA arguments after a "--";
894 * however, -f may take off an argument, too, and before that.
895 * Since MTA arguments after "--" require *expandargv*, delay parsing off
896 * those options until after the resource files are loaded... */
897 if ((cp = argv[i = _oind]) == NULL)
899 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
900 ++i;
901 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
902 else if (folder != NULL && folder[1] == '\0') {
903 folder = cp;
904 if ((cp = argv[++i]) != NULL) {
905 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
906 emsg = N_("More than one file given with -f");
907 goto jusage;
909 ++i;
911 } else {
912 options |= OPT_SENDMODE;
913 for (;;) {
914 to = cat(to, lextract(cp, GTO | GFULL));
915 if ((cp = argv[++i]) == NULL)
916 break;
917 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
918 ++i;
919 break;
923 _oind = i;
925 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
926 * allocate the necessary space for them before we call spreserve()! */
927 while (argv[i] != NULL)
928 ++i;
929 if (smopts_count + i > smopts_size)
930 DBG(smopts_size =) _grow_cpp(&smopts, smopts_count + i + 1, smopts_count);
932 /* Check for inconsistent arguments */
933 if (options & OPT_SENDMODE) {
934 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
935 emsg = N_("Cannot give -f and people to send to.");
936 goto jusage;
938 if (myname != NULL) {
939 emsg = N_("The -u option cannot be used in send mode");
940 goto jusage;
942 if (!(options & OPT_t_FLAG) && to == NULL) {
943 emsg = N_("Send options without primary recipient specified.");
944 goto jusage;
946 if ((options & OPT_t_FLAG) && qf != NULL) {
947 emsg = N_("-t and -q are mutual exclusive.");
948 goto jusage;
950 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
951 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
952 goto jusage;
954 if (options & OPT_R_FLAG) {
955 emsg = N_("The -R option is meaningless in send mode.");
956 goto jusage;
958 } else {
959 if (folder != NULL && myname != NULL) {
960 emsg = N_("The options -f and -u are mutually exclusive");
961 goto jusage;
963 if ((options & (OPT_EXISTONLY | OPT_HEADERSONLY)) ==
964 (OPT_EXISTONLY | OPT_HEADERSONLY)) {
965 emsg = N_("The options -e and -H are mutual exclusive");
966 goto jusage;
968 if ((options & (OPT_HEADERSONLY | OPT_HEADERLIST)) == /* TODO OBSOLETE */
969 (OPT_HEADERSONLY | OPT_HEADERLIST))
970 OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
974 * Likely to go, perform more setup
977 _setup_vars();
979 if (options & OPT_INTERACTIVE) {
980 /* Now we can finally check wether -q- was given */
981 if (qf == (char*)-1) {
982 emsg = N_("In interactive mode -q cannot use standard input \"-\"\n");
983 goto jusage;
986 _setscreensize(0);
987 #ifdef SIGWINCH
988 # ifndef TTY_WANTS_SIGWINCH
989 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
990 # endif
991 safe_signal(SIGWINCH, _setscreensize);
992 #endif
993 } else
994 scrnheight = realscreenheight = 24, scrnwidth = 80;
996 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
997 spreserve();
999 /* load() any resource files */
1000 if(resfiles & a_RF_ALL){
1001 /* *expand() returns a savestr(), but load only uses the file name for
1002 * fopen(), so it's safe to do this */
1003 if((resfiles & a_RF_SYSTEM) && !env_blook("NAIL_NO_SYSTEM_RC", TRU1))
1004 load(SYSCONFDIR "/" SYSCONFRC);
1005 if(resfiles & a_RF_USER){
1006 if((cp = env_vlook("MAILRC", TRU1)) == NULL)
1007 cp = UNCONST(MAILRC);
1008 load(file_expand(cp));
1010 if(env_vlook("NAIL_EXTRA_RC", TRU1) == NULL &&
1011 (cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
1012 load(file_expand(cp));
1015 /* We had to wait until the resource files are loaded, but now it is time
1016 * to get the termcap up and going */
1017 #ifdef n_HAVE_TCAP
1018 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1019 n_termcap_init();
1020 #endif
1022 /* Now we can set the account */
1023 if (Aarg != NULL) {
1024 char const *a[2];
1025 a[0] = Aarg;
1026 a[1] = NULL;
1027 c_account(a);
1030 /* Ensure the -S and other command line options take precedence over
1031 * anything that may have been placed in resource files.
1032 * Our "ternary binary" option *verbose* needs special treament */
1033 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
1034 options &= ~OPT_VERB;
1035 for (i = 0; UICMP(z, i, <, oargs_count); ++i) {
1036 char const *a[2];
1037 a[0] = oargs[i];
1038 a[1] = NULL;
1039 c_set(a);
1042 /* Additional options to pass-through to MTA, and allowed to do so? */
1043 if ((cp = ok_vlook(expandargv)) != NULL) {
1044 bool_t isfail = !asccasecmp(cp, "fail"),
1045 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
1047 if ((options & OPT_D_V) && !isfail && !isrestrict && *cp != '\0')
1048 n_err(_("Unknown *expandargv* value: \"%s\"\n"), cp);
1050 if ((cp = argv[i = _oind]) != NULL) {
1051 if (isfail ||
1052 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
1053 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
1054 "using *sendmail-arguments*\n"));
1055 exit_status = EXIT_USE | EXIT_SEND_ERROR;
1056 goto jleave;
1058 do {
1059 assert(smopts_count + 1 <= smopts_size);
1060 smopts[smopts_count++] = cp;
1061 } while ((cp = argv[++i]) != NULL);
1066 * We're finally completely setup and ready to go
1069 pstate |= PS_STARTED;
1071 if (options & OPT_DEBUG)
1072 n_err(_("user = %s, homedir = %s\n"), myname, homedir);
1074 if (!(options & OPT_SENDMODE)) {
1075 exit_status = _rcv_mode(folder, Larg, X_head);
1076 goto jleave;
1079 /* xxx exit_status = EXIT_OK; */
1080 if (X_head != NULL && !_X_arg_eval(X_head))
1081 goto jleave;
1083 /* Now that full mailx(1)-style file expansion is possible handle the
1084 * attachments which we had delayed due to this.
1085 * This may use savestr(), but since we won't enter the command loop we
1086 * don't need to care about that */
1087 for (cp = NULL; a_head != NULL;) {
1088 struct attachment *nahp, *nap;
1090 if ((nahp = add_attachment(attach, a_head->aa_file, &nap)) != NULL) {
1091 attach = nahp;
1092 /* Did we split a charset set name for fixation purposes? */
1093 if (cp != NULL) {
1094 nap->a_conv = AC_FIX_INCS;
1095 nap->a_input_charset = cp;
1096 cp = NULL;
1098 a_head = a_head->aa_next;
1099 continue;
1101 i = errno;
1103 /* It may not have worked because of an appended character set name, so
1104 * try to split name and charset and retry once */
1105 if (cp == NULL && (cp = strrchr(a_head->aa_file, '=')) != NULL) {
1106 char *ncp, *nfp = savestrbuf(a_head->aa_file,
1107 PTR2SIZE(cp - a_head->aa_file));
1109 for (ncp = ++cp; *ncp != '\0'; ++ncp)
1110 if (!alnumchar(*ncp) && !punctchar(*ncp))
1111 break;
1112 if (*ncp == '\0') {
1113 a_head->aa_file = nfp;
1114 continue;
1118 n_perr(a_head->aa_file, i);
1119 exit_status = EXIT_ERR;
1120 goto jleave;
1123 if (options & OPT_INTERACTIVE)
1124 n_tty_init();
1125 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1126 if (options & OPT_INTERACTIVE)
1127 n_tty_destroy();
1129 jleave:
1130 #ifdef n_HAVE_TCAP
1131 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1132 n_termcap_destroy();
1133 #endif
1134 #ifdef HAVE_DEBUG
1135 sreset(FAL0);
1136 #endif
1137 j_leave:
1138 #ifdef HAVE_DEBUG
1139 n_memcheck();
1140 #endif
1141 NYD_LEAVE;
1142 return exit_status;
1145 FL int
1146 c_rexit(void *v) /* TODO program state machine */
1148 UNUSED(v);
1149 NYD_ENTER;
1151 if (!(pstate & PS_SOURCING)) {
1152 #ifdef n_HAVE_TCAP
1153 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1154 n_termcap_destroy();
1155 #endif
1156 exit(EXIT_OK);
1158 NYD_LEAVE;
1159 return 1;
1162 /* Source the others in that case! */
1163 #ifdef HAVE_AMALGAMATION
1164 # include "config.h"
1165 #endif
1167 /* s-it-mode */