More or less completely rewrite mime_enc.c..
[s-mailx.git] / main.c
blob6e00bbe8b6da6a590926caa7fa88e8fd0724e445
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Startup and initialization.
3 *@ This file is also used to materialize externals.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2016 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 #undef n_FILE
37 #define n_FILE main
38 #define n_MAIN_SOURCE
40 #include "nail.h"
42 #include <sys/ioctl.h>
44 #include <pwd.h>
46 #ifdef HAVE_NL_LANGINFO
47 # include <langinfo.h>
48 #endif
49 #ifdef HAVE_SETLOCALE
50 # include <locale.h>
51 #endif
53 struct a_arg {
54 struct a_arg *aa_next;
55 char *aa_file;
58 /* (extern, but not with amalgamation, so define here) */
59 VL char const weekday_names[7 + 1][4] = {
60 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ""
62 VL char const month_names[12 + 1][4] = {
63 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
64 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""
66 VL char const uagent[sizeof VAL_UAGENT] = VAL_UAGENT;
67 VL char const n_error[sizeof n_ERROR] = N_(n_ERROR);
68 VL ui16_t const class_char[1 + 0x7F] = {
69 #define a_BC C_BLANK | C_CNTRL
70 #define a_SC C_SPACE | C_CNTRL
71 #define a_WC C_WHITE | C_CNTRL
72 /* 000 nul 001 soh 002 stx 003 etx 004 eot 005 enq 006 ack 007 bel */
73 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
74 /* 010 bs 011 ht 012 nl 013 vt 014 np 015 cr 016 so 017 si */
75 C_CNTRL, a_BC, a_WC, a_SC, a_SC, a_SC, C_CNTRL, C_CNTRL,
76 /* 020 dle 021 dc1 022 dc2 023 dc3 024 dc4 025 nak 026 syn 027 etb */
77 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
78 /* 030 can 031 em 032 sub 033 esc 034 fs 035 gs 036 rs 037 us */
79 C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL, C_CNTRL,
80 #undef a_WC
81 #undef a_SC
82 #undef a_BC
83 /* 040 sp 041 ! 042 " 043 # 044 $ 045 % 046 & 047 ' */
84 C_BLANK, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
85 /* 050 ( 051 ) 052 * 053 + 054 , 055 - 056 . 057 / */
86 C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
87 /* 060 0 061 1 062 2 063 3 064 4 065 5 066 6 067 7 */
88 C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL, C_OCTAL,
89 /* 070 8 071 9 072 : 073 ; 074 < 075 = 076 > 077 ? */
90 C_DIGIT, C_DIGIT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
91 /* 100 @ 101 A 102 B 103 C 104 D 105 E 106 F 107 G */
92 C_PUNCT, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
93 /* 110 H 111 I 112 J 113 K 114 L 115 M 116 N 117 O */
94 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
95 /* 120 P 121 Q 122 R 123 S 124 T 125 U 126 V 127 W */
96 C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER, C_UPPER,
97 /* 130 X 131 Y 132 Z 133 [ 134 \ 135 ] 136 ^ 137 _ */
98 C_UPPER, C_UPPER, C_UPPER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT,
99 /* 140 ` 141 a 142 b 143 c 144 d 145 e 146 f 147 g */
100 C_PUNCT, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
101 /* 150 h 151 i 152 j 153 k 154 l 155 m 156 n 157 o */
102 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
103 /* 160 p 161 q 162 r 163 s 164 t 165 u 166 v 167 w */
104 C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER, C_LOWER,
105 /* 170 x 171 y 172 z 173 { 174 | 175 } 176 ~ 177 del */
106 C_LOWER, C_LOWER, C_LOWER, C_PUNCT, C_PUNCT, C_PUNCT, C_PUNCT, C_CNTRL
109 /* Our own little getopt(3) */
110 static char *_oarg;
111 static int _oind, /*_oerr,*/ _oopt;
113 /* Our own little getopt(3); note --help is special-treated as 'h' */
114 static int _getopt(int argc, char * const argv[], char const *optstring);
116 /* Perform basic startup initialization */
117 static void _startup(void);
119 /* Grow a char** */
120 static size_t _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt);
122 /* Setup some variables which we require to be valid / verified */
123 static void _setup_vars(void);
125 /* We're in an interactive session - compute what the screen size for printing
126 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
127 * We use the following algorithm for the height:
128 * If baud rate < 1200, use 9
129 * If baud rate = 1200, use 14
130 * If baud rate > 1200, use 24 or ws_row
131 * Width is either 80 or ws_col */
132 static void _setscreensize(int is_sighdl);
134 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
135 * the system mailbox, and open up the right stuff */
136 static int _rcv_mode(char const *folder, char const *Larg);
138 /* Interrupt printing of the headers */
139 static void _hdrstop(int signo);
141 static int
142 _getopt(int argc, char * const argv[], char const *optstring)
144 static char const *lastp;
146 int rv = -1/*, colon*/;
147 char const *curp;
148 NYD_ENTER;
150 _oarg = NULL;
152 /*if ((colon = (optstring[0] == ':')))
153 ++optstring;*/
155 if (lastp != NULL) {
156 curp = lastp;
157 lastp = NULL;
158 } else {
159 if (_oind >= argc || argv[_oind] == NULL || argv[_oind][0] != '-' ||
160 argv[_oind][1] == '\0')
161 goto jleave;
162 if (argv[_oind][1] == '-' && argv[_oind][2] == '\0') {
163 /* We need this in for MTA arg detection (easier) ++_oind;*/
164 goto jleave;
166 curp = &argv[_oind][1];
169 for(_oopt = curp[0]; optstring[0] != '\0';){
170 if(optstring[0] != _oopt){
171 optstring += 1 + (optstring[1] == ':');
172 continue;
175 if (optstring[1] == ':') {
176 if (curp[1] != '\0') {
177 _oarg = n_UNCONST(curp + 1);
178 ++_oind;
179 } else {
180 if ((_oind += 2) > argc) {
181 /*if (!colon *//*&& _oerr*//*)*/ {
182 n_err(_("%s: option requires an argument -- %c\n"),
183 argv[0], (char)_oopt);
185 rv = (/*colon ? ':' :*/ '?');
186 goto jleave;
188 _oarg = argv[_oind - 1];
190 } else {
191 if (curp[1] != '\0')
192 lastp = curp + 1;
193 else
194 ++_oind;
196 rv = _oopt;
197 goto jleave;
200 /* Special support for --help, which is quite common */
201 if (_oopt == '-' && !strcmp(curp, "-help") && curp - 1 == argv[_oind]) {
202 ++_oind;
203 rv = 'h';
204 goto jleave;
207 /* Definitive error */
208 /*if (!colon *//*&& opterr*//*)*/
209 n_err(_("%s: invalid option -- %c\n"), argv[0], _oopt);
210 if (curp[1] != '\0')
211 lastp = curp + 1;
212 else
213 ++_oind;
214 _oarg = NULL;
215 rv = '?';
216 jleave:
217 NYD_LEAVE;
218 return rv;
221 static void
222 _startup(void)
224 char *cp;
225 NYD_ENTER;
227 image = -1;
228 dflpipe = SIG_DFL;
229 _oind = /*_oerr =*/ 1;
231 if ((cp = strrchr(progname, '/')) != NULL)
232 progname = ++cp;
234 /* Set up a reasonable environment */
236 #ifdef HAVE_NYD
237 safe_signal(SIGABRT, &_nyd_oncrash);
238 # ifdef SIGBUS
239 safe_signal(SIGBUS, &_nyd_oncrash);
240 # endif
241 safe_signal(SIGFPE, &_nyd_oncrash);
242 safe_signal(SIGILL, &_nyd_oncrash);
243 safe_signal(SIGSEGV, &_nyd_oncrash);
244 #endif
245 command_manager_start();
247 if (isatty(STDIN_FILENO)) /* TODO should be isatty(0) && isatty(2)?? */
248 options |= OPT_TTYIN;
249 if (isatty(STDOUT_FILENO))
250 options |= OPT_TTYOUT;
251 if ((options & (OPT_TTYIN | OPT_TTYOUT)) == (OPT_TTYIN | OPT_TTYOUT)) {
252 options |= OPT_INTERACTIVE;
253 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
256 /* -- >8 -- 8< -- */
258 #ifndef HAVE_SETLOCALE
259 mb_cur_max = 1;
260 #else
261 setlocale(LC_ALL, "");
262 mb_cur_max = MB_CUR_MAX;
263 # ifdef HAVE_NL_LANGINFO
264 if(ok_vlook(ttycharset) == NULL && (cp = nl_langinfo(CODESET)) != NULL)
265 ok_vset(ttycharset, cp);
266 # endif
268 # ifdef HAVE_C90AMEND1
269 if(mb_cur_max > 1){
270 # ifdef HAVE_ALWAYS_UNICODE_LOCALE
271 options |= OPT_UNICODE;
272 # else
273 wchar_t wc;
274 if(mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
275 mbtowc(&wc, "\342\202\254", 3) == 3 && wc == 0x20AC)
276 options |= OPT_UNICODE;
277 /* Reset possibly messed up state; luckily this also gives us an
278 * indication whether the encoding has locking shift state sequences */
279 if(mbtowc(&wc, NULL, mb_cur_max))
280 options |= OPT_ENC_MBSTATE;
281 # endif
283 # endif
284 #endif
286 #ifdef HAVE_ICONV
287 iconvd = (iconv_t)-1;
288 #endif
289 NYD_LEAVE;
292 static size_t
293 _grow_cpp(char const ***cpp, size_t newsize, size_t oldcnt)
295 /* Just use auto-reclaimed storage, it will be preserved */
296 char const **newcpp;
297 NYD_ENTER;
299 newcpp = salloc(sizeof(char*) * newsize);
301 if (oldcnt > 0)
302 memcpy(newcpp, *cpp, oldcnt * sizeof(char*));
303 *cpp = newcpp;
304 NYD_LEAVE;
305 return newsize;
308 static void
309 _setup_vars(void){
310 /* XXX furtherly check paths? */
311 struct passwd *pwuid;
312 char const *cp;
313 NYD_ENTER;
315 group_id = getgid();
316 if((pwuid = getpwuid(user_id = getuid())) == NULL)
317 n_panic(_("Cannot associate a name with uid %lu"), (ul_i)user_id);
318 myname = savestr(pwuid->pw_name); /* XXX replace uses with vlook(LOGNAME)! */
320 /* C99 */{
321 char const *ep;
322 bool_t doenv;
324 if(!(doenv = (ep = ok_vlook(LOGNAME)) == NULL) &&
325 (doenv = strcmp(myname, ep)))
326 n_err(_("Warning: $LOGNAME (%s) not identical to user (%s)!\n"),
327 ep, myname);
328 if(doenv){
329 pstate |= PS_ROOT;
330 ok_vset(LOGNAME, myname);
331 pstate &= ~PS_ROOT;
334 if((ep = ok_vlook(USER)) != NULL && strcmp(myname, ep)){
335 n_err(_("Warning: $USER (%s) not identical to user (%s)!\n"),
336 ep, myname);
337 pstate |= PS_ROOT;
338 ok_vset(USER, myname);
339 pstate &= ~PS_ROOT;
343 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
345 /* */
346 if((cp = ok_vlook(HOME)) == NULL){
347 cp = pwuid->pw_dir;
348 pstate |= PS_ROOT;
349 ok_vset(HOME, cp);
350 pstate &= ~PS_ROOT;
353 (void)ok_vlook(TMPDIR);
354 NYD_LEAVE;
357 static void
358 _setscreensize(int is_sighdl) /* TODO global policy; int wraps; minvals! */
360 struct termios tbuf;
361 #ifdef TIOCGWINSZ
362 struct winsize ws;
363 #elif defined TIOCGSIZE
364 struct ttysize ts;
365 #endif
366 NYD_ENTER;
368 scrnheight = realscreenheight = scrnwidth = 0;
370 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
371 * a little bit to be able to honour resizes during our lifetime and
372 * only honour it upon first run; abuse *is_sighdl* as an indicator */
373 if (!is_sighdl) {
374 char *cp;
376 /* We manage those variables for our child processes, so ensure they
377 * are up to date, always */
378 if (options & OPT_INTERACTIVE)
379 pstate |= PS_SIGWINCH_PEND;
381 if ((cp = ok_vlook(LINES)) != NULL)
382 scrnheight = realscreenheight = (int)strtoul(cp, NULL, 0); /* TODO */
383 if ((cp = ok_vlook(COLUMNS)) != NULL)
384 scrnwidth = (int)strtoul(cp, NULL, 0); /* TODO posui32= not posnum=! */
386 if (scrnwidth != 0 && scrnheight != 0)
387 goto jleave;
390 #ifdef TIOCGWINSZ
391 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1)
392 ws.ws_col = ws.ws_row = 0;
393 #elif defined TIOCGSIZE
394 if (ioctl(STDOUT_FILENO, TIOCGSIZE, &ws) == -1)
395 ts.ts_lines = ts.ts_cols = 0;
396 #endif
398 if (scrnheight == 0) {
399 speed_t ospeed = ((tcgetattr(STDOUT_FILENO, &tbuf) == -1)
400 ? B9600 : cfgetospeed(&tbuf));
402 if (ospeed < B1200)
403 scrnheight = 9;
404 else if (ospeed == B1200)
405 scrnheight = 14;
406 #ifdef TIOCGWINSZ
407 else if (ws.ws_row != 0)
408 scrnheight = ws.ws_row;
409 #elif defined TIOCGSIZE
410 else if (ts.ts_lines != 0)
411 scrnheight = ts.ts_lines;
412 #endif
413 else
414 scrnheight = 24;
416 #if defined TIOCGWINSZ || defined TIOCGSIZE
417 if (0 ==
418 # ifdef TIOCGWINSZ
419 (realscreenheight = ws.ws_row)
420 # else
421 (realscreenheight = ts.ts_lines)
422 # endif
424 realscreenheight = 24;
425 #endif
428 if (scrnwidth == 0 && 0 ==
429 #ifdef TIOCGWINSZ
430 (scrnwidth = ws.ws_col)
431 #elif defined TIOCGSIZE
432 (scrnwidth = ts.ts_cols)
433 #endif
435 scrnwidth = 80;
437 jleave:
438 #ifdef SIGWINCH
439 if (is_sighdl) {
440 pstate |= PS_SIGWINCH_PEND; /* XXX Not atomic */
441 if (options & OPT_INTERACTIVE)
442 n_tty_signal(SIGWINCH);
444 #endif
445 NYD_LEAVE;
448 static sigjmp_buf __hdrjmp; /* XXX */
450 static int
451 _rcv_mode(char const *folder, char const *Larg)
453 int i;
454 sighandler_type prevint;
455 NYD_ENTER;
457 if (folder == NULL)
458 folder = "%";
460 if (options & OPT_QUICKRUN_MASK)
461 i = FEDIT_RDONLY;
462 else
463 i = FEDIT_NONE;
464 i = setfile(folder, i);
465 if (i < 0) {
466 exit_status = EXIT_ERR; /* error already reported */
467 goto jquit;
469 if (options & OPT_QUICKRUN_MASK) {
470 exit_status = i;
471 if (i == EXIT_OK && (!(options & OPT_EXISTONLY) ||
472 (options & OPT_HEADERLIST)))
473 print_header_summary(Larg);
474 goto jquit;
476 check_folder_hook(FAL0);
478 if (i > 0 && !ok_blook(emptystart)) {
479 exit_status = EXIT_ERR;
480 goto jleave;
483 if (sigsetjmp(__hdrjmp, 1) == 0) {
484 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
485 safe_signal(SIGINT, _hdrstop);
486 if (!(options & OPT_N_FLAG)) {
487 if (!ok_blook(quiet))
488 printf(_("%s version %s. Type `?' for help\n"),
489 (ok_blook(bsdcompat) ? "Mail" : uagent), ok_vlook(version));
490 announce(1);
491 fflush(stdout);
493 safe_signal(SIGINT, prevint);
496 /* Enter the command loop */
497 if (options & OPT_INTERACTIVE)
498 n_tty_init();
499 n_commands();
500 if (options & OPT_INTERACTIVE)
501 n_tty_destroy();
503 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
504 safe_signal(SIGHUP, SIG_IGN);
505 safe_signal(SIGINT, SIG_IGN);
506 safe_signal(SIGQUIT, SIG_IGN);
508 jquit:
509 save_mbox_for_possible_quitstuff();
510 quit();
511 jleave:
512 NYD_LEAVE;
513 return exit_status;
516 static void
517 _hdrstop(int signo)
519 NYD_X; /* Signal handler */
520 n_UNUSED(signo);
522 fflush(stdout);
523 n_err_sighdl(_("\nInterrupt\n"));
524 siglongjmp(__hdrjmp, 1);
528 main(int argc, char *argv[]){
529 /* Keep in SYNC: ./nail.1:"SYNOPSIS, main() */
530 static char const
531 optstr[] = "A:a:Bb:c:dEeFfHhiL:M:m:NnO:q:Rr:S:s:tu:VvX:::~#.",
532 usagestr[] = N_(
533 "Synopsis:\n"
534 " %s -h\n"
536 " %s [-BdEFintv~] [-: spec] [-A account]\n"
537 "\t [-a attachment] [-b bcc-addr] [-c cc-addr]\n"
538 "\t [-M type | -m file | -q file | -t]\n"
539 "\t [-r from-addr] [-S var[=value]..]\n"
540 "\t [-s subject] [-X cmd] [-.] to-addr.. [-- mta-option..]\n"
542 " %s [-BdEeHiNnRv~] [-: spec] [-A account]\n"
543 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
544 "\t [-u user] [-X cmd] [-- mta-option..]\n"
546 " %s [-BdEeHiNnRv~#] [-: spec] [-A account] -f\n"
547 "\t [-L spec-list] [-r from-addr] [-S var[=value]..]\n"
548 "\t [-X cmd] [file] [-- mta-option..]\n"
550 #define _USAGE_ARGS , progname, progname, progname, progname
552 struct a_arg *a_head, *a_curr;
553 struct name *to, *cc, *bcc;
554 struct attachment *attach;
555 char *cp, *subject, *qf, *Aarg, *Larg;
556 char const *okey, **oargs, **Xargs, *folder, *emsg;
557 size_t oargs_size, oargs_cnt, Xargs_size, Xargs_cnt, smopts_size;
558 enum{
559 a_RF_NONE = 0,
560 a_RF_SET = 1<<0,
561 a_RF_SYSTEM = 1<<1,
562 a_RF_USER = 1<<2,
563 a_RF_ALL = a_RF_SYSTEM | a_RF_USER
564 } resfiles;
565 int i;
566 NYD_ENTER;
568 a_head = NULL;
569 n_UNINIT(a_curr, NULL);
570 to = cc = bcc = NULL;
571 attach = NULL;
572 cp = subject = qf =
573 Aarg = Larg = NULL;
574 oargs = Xargs = NULL;
575 folder = emsg = NULL;
576 oargs_size = oargs_cnt = Xargs_size = Xargs_cnt = smopts_size = 0;
577 resfiles = a_RF_ALL;
580 * Start our lengthy setup, finalize by setting PS_STARTED
583 progname = argv[0];
584 _startup();
586 /* Command line parsing
587 * Variable settings need to be done twice, since the user surely wants the
588 * setting to take effect immediately, but also doesn't want it to be
589 * overwritten from within resource files */
590 while ((i = _getopt(argc, argv, optstr)) >= 0) {
591 switch (i) {
592 case 'A':
593 /* Execute an account command later on */
594 Aarg = _oarg;
595 break;
596 case 'a':
597 options |= OPT_SENDMODE;
598 { struct a_arg *nap = salloc(sizeof(struct a_arg));
599 if (a_head == NULL)
600 a_head = nap;
601 else
602 a_curr->aa_next = nap;
603 nap->aa_next = NULL;
604 nap->aa_file = _oarg;
605 a_curr = nap;
607 break;
608 case 'B':
609 /* Make 0/1 line buffered */
610 setvbuf(stdin, NULL, _IOLBF, 0);
611 setvbuf(stdout, NULL, _IOLBF, 0);
612 break;
613 case 'b':
614 /* Get Blind Carbon Copy Recipient list */
615 options |= OPT_SENDMODE;
616 bcc = cat(bcc, lextract(_oarg, GBCC | GFULL));
617 break;
618 case 'c':
619 /* Get Carbon Copy Recipient list */
620 options |= OPT_SENDMODE;
621 cc = cat(cc, lextract(_oarg, GCC | GFULL));
622 break;
623 case 'd':
624 ok_bset(debug);
625 okey = "debug";
626 goto joarg;
627 case 'E':
628 ok_bset(skipemptybody);
629 okey = "skipemptybody";
630 goto joarg;
631 case 'e':
632 options |= OPT_EXISTONLY;
633 break;
634 case 'F':
635 options |= OPT_F_FLAG | OPT_SENDMODE;
636 break;
637 case 'f':
638 /* User is specifying file to "edit" with Mail, as opposed to reading
639 * system mailbox. If no argument is given, we read his mbox file.
640 * Check for remaining arguments later */
641 folder = "&";
642 break;
643 case 'H':
644 options |= OPT_HEADERSONLY;
645 break;
646 case 'h':
647 n_err(V_(usagestr) _USAGE_ARGS);
648 goto j_leave;
649 case 'i':
650 /* Ignore interrupts */
651 ok_bset(ignore);
652 okey = "ignore";
653 goto joarg;
654 case 'L':
655 Larg = _oarg;
656 options |= OPT_HEADERLIST;
657 if (*Larg == '"' || *Larg == '\'') { /* TODO list.c:listspec_check() */
658 size_t j = strlen(++Larg);
659 if (j > 0)
660 Larg[j - 1] = '\0';
662 break;
663 case 'M':
664 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf != (char*)-1))
665 goto jeMmq;
666 option_Mm_arg = _oarg;
667 qf = (char*)-1;
668 if(0){
669 /* FALLTHRU*/
670 case 'm':
671 if(qf != NULL && (!(options & OPT_Mm_FLAG) || qf == (char*)-1))
672 goto jeMmq;
673 qf = _oarg;
675 options |= OPT_SENDMODE | OPT_Mm_FLAG;
676 break;
677 case 'N':
678 /* Avoid initial header printing */
679 ok_bclear(header);
680 okey = "noheader";
681 goto joarg;
682 case 'n':
683 /* Don't source "unspecified system start-up file" */
684 if(resfiles & a_RF_SET){
685 emsg = N_("-n cannot be used in conjunction with -:");
686 goto jusage;
688 resfiles = a_RF_USER;
689 break;
690 case 'O':
691 /* Additional options to pass-through to MTA TODO v15-compat legacy */
692 if (smopts_cnt == smopts_size)
693 smopts_size = _grow_cpp(&smopts, smopts_size + 8, smopts_cnt);
694 smopts[smopts_cnt++] = _oarg;
695 break;
696 case 'q':
697 if (qf != NULL && (options & OPT_Mm_FLAG)) {
698 jeMmq:
699 emsg = N_("Only one of -M, -m or -q may be given");
700 goto jusage;
702 /* Quote file TODO drop? -Q with real quote?? what ? */
703 options |= OPT_SENDMODE;
704 /* Allow for now, we have to special check validity of -q- later on! */
705 qf = (_oarg[0] == '-' && _oarg[1] == '\0') ? (char*)-1 : _oarg;
706 break;
707 case 'R':
708 /* Open folders read-only */
709 options |= OPT_R_FLAG;
710 break;
711 case 'r':
712 /* Set From address. */
713 options |= OPT_r_FLAG;
714 if (_oarg[0] != '\0') {
715 struct name *fa = nalloc(_oarg, GSKIN | GFULL | GFULLEXTRA);
717 if (is_addr_invalid(fa, EACM_STRICT | EACM_NOLOG)) {
718 emsg = N_("Invalid address argument with -r");
719 goto jusage;
721 option_r_arg = fa;
722 /* TODO -r options is set in smopts, but may
723 * TODO be overwritten by setting from= in
724 * TODO an interactive session!
725 * TODO Maybe disable setting of from?
726 * TODO Warn user? Update manual!! */
727 okey = savecat("from=", fa->n_fullname);
728 goto joarg;
730 break;
731 case 'S':
732 /* Set variable (TODO twice [only if successful]) */
733 { char *a[2];
734 bool_t b;
736 okey = a[0] = _oarg;
737 a[1] = NULL;
738 pstate |= PS_ROBOT;
739 b = (c_set(a) == 0);
740 pstate &= ~PS_ROBOT;
741 if(!b)
742 break;
744 joarg:
745 if (oargs_cnt == oargs_size)
746 oargs_size = _grow_cpp(&oargs, oargs_size + 8, oargs_cnt);
747 oargs[oargs_cnt++] = okey;
748 break;
749 case 's':
750 /* Subject: */
751 subject = _oarg;
752 options |= OPT_SENDMODE;
753 break;
754 case 't':
755 /* Read defined set of headers from mail to be sent */
756 options |= OPT_SENDMODE | OPT_t_FLAG;
757 break;
758 case 'u':
759 /* Temporarily set myname so that we can recognize the -u condition */
760 myname = savecat("%", _oarg);
761 break;
762 case 'V':
763 printf(_("%s version %s\n"), uagent, ok_vlook(version));
764 exit_status = EXIT_OK;
765 goto j_leave;
766 case 'v':
767 /* Be verbose */
768 ok_bset(verbose);
769 okey = "verbose";
770 goto joarg;
771 case 'X':
772 /* Add to list of commands to exec before entering normal operation */
773 if (Xargs_cnt == Xargs_size)
774 Xargs_size = _grow_cpp(&Xargs, Xargs_size + 8, Xargs_cnt);
775 Xargs[Xargs_cnt++] = _oarg;
776 break;
777 case ':':
778 /* Control which resource files shall be loaded */
779 if(!(resfiles & (a_RF_SET | a_RF_SYSTEM))){
780 emsg = N_("-n cannot be used in conjunction with -:");
781 goto jusage;
783 resfiles = a_RF_SET;
784 while((i = *_oarg++) != '\0')
785 switch(i){
786 case 'S': case 's': resfiles |= a_RF_SYSTEM; break;
787 case 'U': case 'u': resfiles |= a_RF_USER; break;
788 case ':': case '/': resfiles &= ~a_RF_ALL; break;
789 default:
790 emsg = N_("Invalid argument of -:");
791 goto jusage;
793 break;
794 case '~':
795 /* Enable tilde escapes even in non-interactive mode */
796 options |= OPT_TILDE_FLAG;
797 break;
798 case '#':
799 /* Work in batch mode, even if non-interactive */
800 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
801 if (oargs_cnt + 8 >= oargs_size)
802 oargs_size = _grow_cpp(&oargs, oargs_size + 9, oargs_cnt);
803 folder = "/dev/null";
804 ok_vset(MAIL, folder);
805 ok_vset(MBOX, folder);
806 ok_bset(emptystart);
807 ok_bclear(header);
808 ok_vset(inbox, folder);
809 ok_bset(quiet);
810 ok_bset(sendwait);
811 ok_bset(typescript_mode);
812 oargs[oargs_cnt + 0] = "MAIL=/dev/null";
813 oargs[oargs_cnt + 1] = "MBOX=/dev/null";
814 oargs[oargs_cnt + 2] = "emptystart";
815 oargs[oargs_cnt + 3] = "noheader";
816 oargs[oargs_cnt + 4] = "inbox=/dev/null";
817 oargs[oargs_cnt + 5] = "quiet";
818 oargs[oargs_cnt + 6] = "sendwait";
819 oargs[oargs_cnt + 7] = "typescript-mode";
820 oargs_cnt += 8;
821 break;
822 case '.':
823 options |= OPT_SENDMODE;
824 goto jgetopt_done;
825 case '?':
826 jusage:
827 if (emsg != NULL)
828 n_err("%s\n", V_(emsg));
829 n_err(V_(usagestr) _USAGE_ARGS);
830 #undef _USAGE_ARGS
831 exit_status = EXIT_USE;
832 goto j_leave;
835 jgetopt_done:
838 /* The normal arguments may be followed by MTA arguments after a "--";
839 * however, -f may take off an argument, too, and before that.
840 * Since MTA arguments after "--" require *expandargv*, delay parsing off
841 * those options until after the resource files are loaded... */
842 if ((cp = argv[i = _oind]) == NULL)
844 else if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0')
845 ++i;
846 /* OPT_BATCH_FLAG sets to /dev/null, but -f can still be used and sets & */
847 else if (folder != NULL && /*folder[0] == '&' &&*/ folder[1] == '\0') {
848 folder = cp;
849 if ((cp = argv[++i]) != NULL) {
850 if (cp[0] != '-' || cp[1] != '-' || cp[2] != '\0') {
851 emsg = N_("More than one file given with -f");
852 goto jusage;
854 ++i;
856 } else {
857 options |= OPT_SENDMODE;
858 for (;;) {
859 to = cat(to, lextract(cp, GTO | GFULL));
860 if ((cp = argv[++i]) == NULL)
861 break;
862 if (cp[0] == '-' && cp[1] == '-' && cp[2] == '\0') {
863 ++i;
864 break;
868 _oind = i;
870 /* ...BUT, since we use salloc() for the MTA smopts storage we need to
871 * allocate the necessary space for them before we fixate that storage! */
872 while (argv[i] != NULL)
873 ++i;
874 if (smopts_cnt + i > smopts_size)
875 DBG(smopts_size =) _grow_cpp(&smopts, smopts_cnt + i + 1, smopts_cnt);
877 /* Check for inconsistent arguments, fix some temporaries */
878 if (options & OPT_SENDMODE) {
879 /* XXX This is only because BATCH_FLAG sets *folder*=/dev/null
880 * XXX in order to function. Ideally that would not be needed */
881 if (folder != NULL && !(options & OPT_BATCH_FLAG)) {
882 emsg = N_("Cannot give -f and people to send to.");
883 goto jusage;
885 if (myname != NULL) {
886 emsg = N_("The -u option cannot be used in send mode");
887 goto jusage;
889 if (!(options & OPT_t_FLAG) && to == NULL) {
890 emsg = N_("Send options without primary recipient specified.");
891 goto jusage;
893 if ((options & OPT_t_FLAG) && qf != NULL) {
894 emsg = N_("The -M, -m, -q and -t options are mutual exclusive.");
895 goto jusage;
897 if (options & (OPT_EXISTONLY | OPT_HEADERSONLY | OPT_HEADERLIST)) {
898 emsg = N_("The -e, -H and -L options cannot be used in send mode.");
899 goto jusage;
901 if (options & OPT_R_FLAG) {
902 emsg = N_("The -R option is meaningless in send mode.");
903 goto jusage;
906 if (options & OPT_INTERACTIVE) {
907 if (qf == (char*)-1) {
908 if (!(options & OPT_Mm_FLAG))
909 emsg = N_("-q can't use standard input when interactive.\n");
910 goto jusage;
913 } else {
914 if (myname != NULL && folder != NULL) {
915 emsg = N_("The options -u and -f (and -#) are mutually exclusive");
916 goto jusage;
918 if ((options & (OPT_EXISTONLY | OPT_HEADERSONLY)) ==
919 (OPT_EXISTONLY | OPT_HEADERSONLY)) {
920 emsg = N_("The options -e and -H are mutual exclusive");
921 goto jusage;
923 if ((options & (OPT_HEADERSONLY | OPT_HEADERLIST)) == /* TODO OBSOLETE */
924 (OPT_HEADERSONLY | OPT_HEADERLIST))
925 OBSOLETE(_("please use \"-e -L xy\" instead of \"-H -L xy\""));
927 if(myname != NULL)
928 folder = myname;
932 * Likely to go, perform more setup
935 _setup_vars();
937 if (options & OPT_INTERACTIVE) {
938 _setscreensize(0);
939 #ifdef SIGWINCH
940 # ifndef TTY_WANTS_SIGWINCH
941 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
942 # endif
943 safe_signal(SIGWINCH, &_setscreensize);
944 #endif
945 } else
946 scrnheight = realscreenheight = 24, scrnwidth = 80;
948 /* Fixate the current snapshot of our global auto-reclaimed storage instance.
949 * Memory is auto-reclaimed from now on */
950 n_memory_autorec_fixate();
952 /* load() any resource files */
953 if(resfiles & a_RF_ALL){
954 /* *expand() returns a savestr(), but load only uses the file name for
955 * fopen(), so it's safe to do this */
956 if((resfiles & a_RF_SYSTEM) && !ok_blook(NAIL_NO_SYSTEM_RC))
957 n_load(VAL_SYSCONFDIR "/" VAL_SYSCONFRC);
958 if(resfiles & a_RF_USER)
959 n_load(file_expand(ok_vlook(MAILRC)));
960 if((cp = ok_vlook(NAIL_EXTRA_RC)) != NULL)
961 n_load(file_expand(cp));
964 /* Ensure the -S and other command line options take precedence over
965 * anything that may have been placed in resource files.
966 * Our "ternary binary" option *verbose* needs special treament */
967 if ((options & (OPT_VERB | OPT_VERBVERB)) == OPT_VERB)
968 options &= ~OPT_VERB;
969 /* ..and be silent when unsetting an undefined variable */
970 pstate |= PS_ROBOT;
971 for (i = 0; UICMP(z, i, <, oargs_cnt); ++i) {
972 char const *a[2];
974 a[0] = oargs[i];
975 a[1] = NULL;
976 c_set(a);
978 pstate &= ~PS_ROBOT;
980 /* Cause possible umask(2), now that any setting is established, and before
981 * we change accounts, evaluate commands etc. */
982 (void)ok_vlook(umask);
984 /* Additional options to pass-through to MTA, and allowed to do so? */
985 if ((cp = ok_vlook(expandargv)) != NULL) {
986 bool_t isfail = !asccasecmp(cp, "fail"),
987 isrestrict = (!isfail && !asccasecmp(cp, "restrict"));
989 if ((options & OPT_D_V) && !isfail && !isrestrict && *cp != '\0')
990 n_err(_("Unknown *expandargv* value: %s\n"), cp);
992 if ((cp = argv[i = _oind]) != NULL) {
993 if (isfail ||
994 (isrestrict && !(options & (OPT_INTERACTIVE |OPT_TILDE_FLAG)))) {
995 n_err(_("*expandargv* doesn't allow MTA arguments; consider "
996 "using *sendmail-arguments*\n"));
997 exit_status = EXIT_USE | EXIT_SEND_ERROR;
998 goto jleave;
1000 do {
1001 assert(smopts_cnt + 1 <= smopts_size);
1002 smopts[smopts_cnt++] = cp;
1003 } while ((cp = argv[++i]) != NULL);
1007 /* We had to wait until the resource files are loaded and any command line
1008 * setting has been restored, but get the termcap up and going before we
1009 * switch account or running commands */
1010 #ifdef n_HAVE_TCAP
1011 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1012 n_termcap_init();
1013 #endif
1015 /* Now we can set the account */
1016 if (Aarg != NULL) {
1017 char const *a[2];
1018 a[0] = Aarg;
1019 a[1] = NULL;
1020 c_account(a);
1023 /* "load()" commands given on command line */
1024 if(Xargs_cnt > 0)
1025 n_load_Xargs(Xargs, Xargs_cnt);
1027 /* Final tests */
1028 if(options & OPT_Mm_FLAG){
1029 if(qf == (char*)-1){
1030 if(!mime_type_check_mtname(option_Mm_arg)){
1031 n_err(_("Could not find `mimetype' for -M argument: %s\n"),
1032 option_Mm_arg);
1033 exit_status = EXIT_ERR;
1034 goto jleave;
1036 }else if((option_Mm_arg = mime_type_classify_filename(qf)) == NULL){
1037 n_err(_("Could not `mimetype'-classify -m argument: %s\n"),
1038 n_shexp_quote_cp(qf, FAL0));
1039 exit_status = EXIT_ERR;
1040 goto jleave;
1041 }else if(!asccasecmp(option_Mm_arg, "text/plain")) /* TODO no: magic!! */
1042 option_Mm_arg = NULL;
1046 * We're finally completely setup and ready to go
1048 pstate |= PS_STARTED;
1050 if (!(options & OPT_SENDMODE)) {
1051 exit_status = _rcv_mode(folder, Larg);
1052 goto jleave;
1055 /* Now that full mailx(1)-style file expansion is possible handle the
1056 * attachments which we had delayed due to this.
1057 * This may use savestr(), but since we won't enter the command loop we
1058 * don't need to care about that */
1059 for (cp = NULL; a_head != NULL;) {
1060 struct attachment *nahp, *nap;
1062 if ((nahp = add_attachment(n_LEXINPUT_CTX_BASE, attach, a_head->aa_file,
1063 &nap)) != NULL) {
1064 attach = nahp;
1065 /* Did we split a charset set name for fixation purposes? */
1066 if (cp != NULL) {
1067 nap->a_conv = AC_FIX_INCS;
1068 nap->a_input_charset = cp;
1069 cp = NULL;
1071 a_head = a_head->aa_next;
1072 continue;
1074 i = errno;
1076 /* It may not have worked because of an appended character set name, so
1077 * try to split name and charset and retry once */
1078 if (cp == NULL && (cp = strrchr(a_head->aa_file, '=')) != NULL) {
1079 char *ncp, *nfp = savestrbuf(a_head->aa_file,
1080 PTR2SIZE(cp - a_head->aa_file));
1082 for (ncp = ++cp; *ncp != '\0'; ++ncp)
1083 if (!alnumchar(*ncp) && !punctchar(*ncp))
1084 break;
1085 if (*ncp == '\0') {
1086 a_head->aa_file = nfp;
1087 continue;
1091 n_perr(a_head->aa_file, i);
1092 exit_status = EXIT_ERR;
1093 goto jleave;
1096 if (options & OPT_INTERACTIVE)
1097 n_tty_init();
1098 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
1099 if (options & OPT_INTERACTIVE)
1100 n_tty_destroy();
1102 jleave:
1103 #ifdef n_HAVE_TCAP
1104 if((options & (OPT_INTERACTIVE | OPT_QUICKRUN_MASK)) == OPT_INTERACTIVE)
1105 n_termcap_destroy();
1106 #endif
1107 j_leave:
1108 #ifdef HAVE_MEMORY_DEBUG
1109 n_memory_autorec_pop(NULL);
1110 #endif
1111 n_memory_reset();
1112 NYD_LEAVE;
1113 return exit_status;
1116 FL int
1117 c_exit(void *v){/* TODO program state machine */
1118 NYD_ENTER;
1119 n_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 */