Add *message-id-disable*
[s-mailx.git] / main.c
bloba61b49801591a08548bcf6722d76c2b7b44daac7
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Startup -- interface with user.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2013 Steffen "Daode" Nurpmeso <sdaoden@users.sf.net>.
6 */
7 /*
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
41 * Most strcpy/sprintf functions have been changed to strncpy/snprintf to
42 * correct several buffer overruns (at least one ot them was exploitable).
43 * Sat Jun 20 04:58:09 CEST 1998 Alvaro Martinez Echevarria <alvaro@lander.es>
44 * ---
45 * Note: We set egid to realgid ... and only if we need the egid we will
46 * switch back temporary. Nevertheless, I do not like seg faults.
47 * Werner Fink, <werner@suse.de>
50 #include "config.h"
52 #include <sys/ioctl.h>
53 #include <sys/stat.h>
54 #include <fcntl.h>
55 #include <termios.h>
56 #include <unistd.h>
57 #ifdef HAVE_NL_LANGINFO
58 # include <langinfo.h>
59 #endif
60 #ifdef HAVE_SETLOCALE
61 # include <locale.h>
62 #endif
64 #define _MAIL_GLOBS_
65 #include "rcv.h"
66 #include "extern.h"
67 #include "version.h"
69 struct a_arg {
70 struct a_arg *aa_next;
71 char *aa_file;
74 /* Perform basic startup initialization */
75 static void _startup(void);
77 /* Grow a char** */
78 static int _grow_cpp(char const ***cpp, int size, int cnt);
80 /* Initialize *tempdir*, *myname*, *homedir* */
81 static void _setup_vars(void);
83 /* We're in an interactive session - compute what the screen size for printing
84 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
85 * We use the following algorithm for the height:
86 * If baud rate < 1200, use 9
87 * If baud rate = 1200, use 14
88 * If baud rate > 1200, use 24 or ws_row
89 * Width is either 80 or ws_col */
90 static void _setscreensize(int is_sighdl);
92 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
93 * the system mailbox, and open up the right stuff */
94 static int _rcv_mode(char const *folder);
96 /* Interrupt printing of the headers */
97 static void _hdrstop(int signo);
99 static void
100 _startup(void)
102 char *cp;
104 /* Absolutely the first thing we do is save our egid
105 * and set it to the rgid, so that we can safely run
106 * setgid. We use the sgid (saved set-gid) to allow ourselves
107 * to revert to the egid if we want (temporarily) to become
108 * privileged */
109 effectivegid = getegid();
110 realgid = getgid();
111 if (setgid(realgid) < 0) {
112 perror("setgid");
113 exit(1);
116 image = -1;
118 if ((cp = strrchr(progname, '/')) != NULL)
119 progname = ++cp;
121 /* Set up a reasonable environment.
122 * Figure out whether we are being run interactively,
123 * start the SIGCHLD catcher, and so forth */
124 safe_signal(SIGCHLD, sigchild);
126 if (isatty(0))
127 options |= OPT_TTYIN | OPT_INTERACTIVE;
128 if (isatty(1))
129 options |= OPT_TTYOUT;
130 if (IS_TTY_SESSION())
131 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
132 assign("header", "");
133 assign("save", "");
135 #ifdef HAVE_SETLOCALE
136 setlocale(LC_ALL, "");
137 mb_cur_max = MB_CUR_MAX;
138 # if defined HAVE_NL_LANGINFO && defined CODESET
139 if (value("ttycharset") == NULL && (cp = nl_langinfo(CODESET)) != NULL)
140 assign("ttycharset", cp);
141 # endif
143 # if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
144 if (mb_cur_max > 1) {
145 wchar_t wc;
146 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
147 mbtowc(&wc, "\342\202\254", 3) == 3 &&
148 wc == 0x20AC)
149 utf8 = 1;
150 /* Reset state - it may have been messed up; luckily this also
151 * gives us an indication wether the encoding has locking shift
152 * state sequences */
153 /* TODO temporary - use option bits! */
154 enc_has_state = mbtowc(&wc, NULL, mb_cur_max);
156 # endif
157 #else
158 mb_cur_max = 1;
159 #endif
161 #ifdef HAVE_CATGETS
162 # ifdef NL_CAT_LOCALE
163 catd = catopen(CATNAME, NL_CAT_LOCALE);
164 # else
165 catd = catopen(CATNAME, 0);
166 # endif
167 #endif
169 #ifdef HAVE_ICONV
170 iconvd = (iconv_t)-1;
171 #endif
174 static int
175 _grow_cpp(char const ***cpp, int size, int cnt)
177 /* Before spreserve(): use our string pool instead of LibC heap;
178 * Increment *size* by at least 5! */
179 char const **newcpp = salloc(sizeof(char*) * (size += 8));
181 if (cnt > 0)
182 memcpy(newcpp, *cpp, (size_t)cnt * sizeof(char*));
183 *cpp = newcpp;
184 return size;
187 static void
188 _setup_vars(void)
190 /* Before spreserve(): use our string pool instead of LibC heap */
191 char const *cp;
193 tempdir = ((cp = getenv("TMPDIR")) != NULL) ? savestr(cp) : "/tmp";
195 myname = savestr(username());
197 if ((cp = getenv("HOME")) == NULL)
198 cp = ".";
199 homedir = savestr(cp);
202 static void
203 _setscreensize(int is_sighdl)
205 struct termios tbuf;
206 #ifdef TIOCGWINSZ
207 struct winsize ws;
208 #elif defined TIOCGSIZE
209 struct ttysize ts;
210 #endif
212 scrnheight = realscreenheight = scrnwidth = 0;
214 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
215 * a little bit to be able to honour resizes during our lifetime and
216 * only honour it upon first run; abuse *is_sighdl* as an indicator */
217 if (is_sighdl == 0) {
218 char *cp;
219 long i;
221 if ((cp = getenv("LINES")) != NULL &&
222 (i = strtol(cp, NULL, 10)) > 0)
223 scrnheight = realscreenheight = (int)i;
224 if ((cp = getenv("COLUMNS")) != NULL &&
225 (i = strtol(cp, NULL, 10)) > 0)
226 scrnwidth = (int)i;
228 if (scrnwidth != 0 && scrnheight != 0)
229 goto jleave;
232 #ifdef TIOCGWINSZ
233 if (ioctl(1, TIOCGWINSZ, &ws) < 0)
234 ws.ws_col = ws.ws_row = 0;
235 #elif defined TIOCGSIZE
236 if (ioctl(1, TIOCGSIZE, &ws) < 0)
237 ts.ts_lines = ts.ts_cols = 0;
238 #endif
240 if (scrnheight == 0) {
241 speed_t ospeed = (tcgetattr(1, &tbuf) < 0) ? B9600 :
242 cfgetospeed(&tbuf);
244 if (ospeed < B1200)
245 scrnheight = 9;
246 else if (ospeed == B1200)
247 scrnheight = 14;
248 #ifdef TIOCGWINSZ
249 else if (ws.ws_row != 0)
250 scrnheight = ws.ws_row;
251 #elif defined TIOCGSIZE
252 else if (ts.ts_lines != 0)
253 scrnheight = ts.ts_lines;
254 #endif
255 else
256 scrnheight = 24;
258 #if defined TIOCGWINSZ || defined TIOCGSIZE
259 if (0 ==
260 # ifdef TIOCGWINSZ
261 (realscreenheight = ws.ws_row)
262 # else
263 (realscreenheight = ts.ts_lines)
264 # endif
266 realscreenheight = 24;
267 #endif
270 if (scrnwidth == 0 && 0 ==
271 #ifdef TIOCGWINSZ
272 (scrnwidth = ws.ws_col)
273 #elif defined TIOCGSIZE
274 (scrnwidth = ts.ts_cols)
275 #endif
277 scrnwidth = 80;
279 jleave:
280 #ifdef SIGWINCH
281 if (is_sighdl && (options & OPT_INTERACTIVE))
282 tty_signal(SIGWINCH);
283 #endif
286 static sigjmp_buf __hdrjmp; /* XXX */
288 static int
289 _rcv_mode(char const *folder)
291 char *cp;
292 int i;
293 sighandler_type prevint;
295 if (folder == NULL)
296 folder = "%";
297 else if (*folder == '@') {
298 /* This must be treated specially to make invocation like
299 * -A imap -f @mailbox work */
300 if ((cp = value("folder")) != NULL &&
301 which_protocol(cp) == PROTO_IMAP)
302 (void)n_strlcpy(mailname, cp, MAXPATHLEN);
305 i = setfile(folder, 0);
306 if (i < 0)
307 exit(1); /* error already reported */
308 if (options & OPT_EXISTONLY)
309 exit(i);
311 if (options & OPT_HEADERSONLY) {
312 #ifdef HAVE_IMAP
313 if (mb.mb_type == MB_IMAP)
314 imap_getheaders(1, msgCount);
315 #endif
316 time_current_update(&time_current, FAL0);
317 for (i = 1; i <= msgCount; i++)
318 printhead(i, stdout, 0);
319 exit(exit_status);
322 callhook(mailname, 0);
323 if (i > 0 && value("emptystart") == NULL)
324 exit(1);
326 if (sigsetjmp(__hdrjmp, 1) == 0) {
327 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
328 safe_signal(SIGINT, _hdrstop);
329 if ((options & OPT_N_FLAG) == 0) {
330 if (! value("quiet"))
331 printf(tr(140,
332 "%s version %s. Type ? for help.\n"),
333 value("bsdcompat") ? "Mail" : uagent,
334 version);
335 announce(1);
336 fflush(stdout);
338 safe_signal(SIGINT, prevint);
341 /* Enter the command loop */
342 if (options & OPT_INTERACTIVE)
343 tty_init();
344 commands();
345 if (options & OPT_INTERACTIVE)
346 tty_destroy();
348 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
349 safe_signal(SIGHUP, SIG_IGN);
350 safe_signal(SIGINT, SIG_IGN);
351 safe_signal(SIGQUIT, SIG_IGN);
353 n_strlcpy(mboxname, expand("&"), sizeof(mboxname));
354 quit();
355 return exit_status;
358 static void
359 _hdrstop(int signo)
361 (void)signo;
363 fflush(stdout);
364 fprintf(stderr, tr(141, "\nInterrupt\n"));
365 siglongjmp(__hdrjmp, 1);
368 char const *const weekday_names[7 + 1] = {
369 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
371 char const *const month_names[12 + 1] = {
372 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
373 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL
376 char const *const uagent = UAGENT;
377 char const *const version = VERSION;
379 sighandler_type dflpipe = SIG_DFL;
381 int
382 main(int argc, char *argv[])
384 static char const optstr[] = "A:a:Bb:c:DdEeFfHiNnO:q:Rr:S:s:tu:Vv~#",
385 usagestr[] =
386 "Synopsis:\n"
387 " %s [-BDdEFintv~] [-A acc] [-a attachment] "
388 "[-b bcc-addr] [-c cc-addr]\n"
389 "\t [-O mtaopt [-O mtaopt-arg]] [-q file] [-r from-addr] "
390 "[-S var[=value]]\n"
391 "\t [-s subject] to-addr...\n"
392 " %s [-BDdEeHiNnRv~#] [-A acct] "
393 "[-S var[=value]] -f [file]\n"
394 " %s [-BDdEeiNnRv~#] [-A acc] [-S var[=value]] [-u user]\n";
396 struct a_arg *a_head = NULL, *a_curr = /* silence CC */ NULL;
397 struct name *to = NULL, *cc = NULL, *bcc = NULL;
398 struct attachment *attach = NULL;
399 char *cp = NULL, *subject = NULL, *qf = NULL, *Aflag = NULL;
400 char const *okey, **oargs = NULL, *folder = NULL;
401 int oargs_size = 0, oargs_count = 0, smopts_size = 0, i;
404 * Start our lengthy setup
407 starting =
408 unset_allow_undefined = TRU1;
410 progname = argv[0];
411 _startup();
413 /* Command line parsing */
414 while ((i = getopt(argc, argv, optstr)) >= 0) {
415 switch (i) {
416 case 'A':
417 /* Execute an account command later on */
418 Aflag = optarg;
419 break;
420 case 'a':
421 { struct a_arg *nap = ac_alloc(
422 sizeof(struct a_arg));
423 if (a_head == NULL)
424 a_head = nap;
425 else
426 a_curr->aa_next = nap;
427 nap->aa_next = NULL;
428 nap->aa_file = optarg;
429 a_curr = nap;
431 options |= OPT_SENDMODE;
432 break;
433 case 'B':
434 /* Make 0/1 line buffered */
435 setvbuf(stdin, NULL, _IOLBF, 0);
436 setvbuf(stdout, NULL, _IOLBF, 0);
437 break;
438 case 'b':
439 /* Get Blind Carbon Copy Recipient list */
440 bcc = cat(bcc, checkaddrs(lextract(optarg,GBCC|GFULL)));
441 options |= OPT_SENDMODE;
442 break;
443 case 'c':
444 /* Get Carbon Copy Recipient list */
445 cc = cat(cc, checkaddrs(lextract(optarg, GCC|GFULL)));
446 options |= OPT_SENDMODE;
447 break;
448 case 'D':
449 #ifdef HAVE_IMAP
450 okey = "disconnected";
451 goto joarg;
452 #else
453 break;
454 #endif
455 case 'd':
456 okey = "debug";
457 #ifdef WANT_ASSERTS
458 assign(okey, "");
459 #endif
460 goto joarg;
461 case 'E':
462 okey = "skipemptybody";
463 goto joarg;
464 case 'e':
465 options |= OPT_EXISTONLY;
466 break;
467 case 'F':
468 options |= OPT_F_FLAG | OPT_SENDMODE;
469 break;
470 case 'f':
471 /* User is specifying file to "edit" with Mail,
472 * as opposed to reading system mailbox.
473 * If no argument is given, we read his mbox file.
474 * Check for remaining arguments later */
475 folder = "&";
476 break;
477 case 'H':
478 options |= OPT_HEADERSONLY;
479 break;
480 case 'i':
481 /* Ignore interrupts */
482 okey = "ignore";
483 goto joarg;
484 case 'N':
485 /* Avoid initial header printing */
486 okey = "noheader";
487 goto joarg;
488 case 'n':
489 /* Don't source "unspecified system start-up file" */
490 options |= OPT_NOSRC;
491 break;
492 case 'O':
493 /* Additional options to pass-through to MTA */
494 if (smopts_count == (size_t)smopts_size)
495 smopts_size = _grow_cpp(&smopts, smopts_size,
496 (int)smopts_count);
497 smopts[smopts_count++] = skin(optarg);
498 break;
499 case 'q':
500 /* Quote file TODO drop? -Q with real quote?? what ? */
501 if (*optarg != '-')
502 qf = optarg;
503 options |= OPT_SENDMODE;
504 break;
505 case 'R':
506 /* Open folders read-only */
507 options |= OPT_R_FLAG;
508 break;
509 case 'r':
510 /* Set From address. */
511 options |= OPT_r_FLAG;
512 if ((option_r_arg = optarg)[0] != '\0') {
513 struct name *fa = nalloc(optarg, GFULL);
515 if (is_addr_invalid(fa, 1) ||
516 is_fileorpipe_addr(fa)) {
517 fprintf(stderr, tr(271,
518 "Invalid address argument "
519 "with -r\n"));
520 goto usage;
522 option_r_arg = fa->n_name;
523 /* TODO -r options is set in smopts, but may
524 * TODO be overwritten by setting from= in
525 * TODO an interactive session!
526 * TODO Maybe disable setting of from?
527 * TODO Warn user? Update manual!! */
528 okey = savecat("from=", fa->n_fullname);
529 goto joarg;
530 /* ..and fa goes even though it is ready :/ */
532 break;
533 case 'S':
534 /* Set variable. We need to do this twice, since the
535 * user surely wants the setting to take effect
536 * immediately, but also doesn't want it to be
537 * overwritten from within resource files */
538 { char *a[2];
539 okey = a[0] = optarg;
540 a[1] = NULL;
541 set(a);
543 joarg:
544 if (oargs_count == oargs_size)
545 oargs_size = _grow_cpp(&oargs, oargs_size,
546 oargs_count);
547 oargs[oargs_count++] = okey;
548 break;
549 case 's':
550 /* Subject: */
551 subject = optarg;
552 options |= OPT_SENDMODE;
553 break;
554 case 't':
555 /* Read defined set of headers from mail to be send */
556 options |= OPT_SENDMODE | OPT_t_FLAG;
557 break;
558 case 'u':
559 /* Set user name to pretend to be */
560 myname = option_u_arg = optarg;
561 break;
562 case 'V':
563 puts(version);
564 exit(0);
565 /* NOTREACHED */
566 case 'v':
567 /* Be verbose */
568 okey = "verbose";
569 #ifdef WANT_ASSERTS
570 assign(okey, "");
571 #endif
572 goto joarg;
573 case '~':
574 /* Enable tilde escapes even in non-interactive mode */
575 options |= OPT_TILDE_FLAG;
576 break;
577 case '#':
578 /* Work in batch mode, even if non-interactive */
579 if (oargs_count + 3 >= oargs_size)
580 oargs_size = _grow_cpp(&oargs, oargs_size,
581 oargs_count);
582 oargs[oargs_count++] = "dot";
583 oargs[oargs_count++] = "emptystart";
584 oargs[oargs_count++] = "noheader";
585 oargs[oargs_count++] = "sendwait";
586 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
587 break;
588 case '?':
589 usage: fprintf(stderr, tr(135, usagestr),
590 progname, progname, progname);
591 exit(2);
595 if (folder != NULL) {
596 if (optind < argc) {
597 if (optind + 1 < argc) {
598 fprintf(stderr, tr(205,
599 "More than one file given with -f\n"));
600 goto usage;
602 folder = argv[optind];
604 } else {
605 for (i = optind; argv[i]; i++)
606 to = cat(to, checkaddrs(lextract(argv[i], GTO|GFULL)));
607 if (to != NULL)
608 options |= OPT_SENDMODE;
611 /* Check for inconsistent arguments */
612 if (folder != NULL && to != NULL) {
613 fprintf(stderr, tr(137,
614 "Cannot give -f and people to send to.\n"));
615 goto usage;
617 if ((options & (OPT_SENDMODE|OPT_t_FLAG)) == OPT_SENDMODE &&
618 to == NULL) {
619 fprintf(stderr, tr(138,
620 "Send options without primary recipient specified.\n"));
621 goto usage;
623 if ((options & OPT_R_FLAG) && to != NULL) {
624 fprintf(stderr, "The -R option is meaningless in send mode.\n");
625 goto usage;
629 * Likely to go, perform more setup
632 _setup_vars();
634 if (options & OPT_INTERACTIVE) {
635 _setscreensize(0);
636 #ifdef SIGWINCH
637 # ifndef TTY_WANTS_SIGWINCH
638 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
639 # endif
640 safe_signal(SIGWINCH, _setscreensize);
641 #endif
642 } else
643 scrnheight = realscreenheight = 24, scrnwidth = 80;
645 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
646 spreserve();
648 if ((options & OPT_NOSRC) == 0 && getenv("NAIL_NO_SYSTEM_RC") == NULL)
649 load(SYSCONFRC);
650 /* *expand() returns a savestr(), but load only uses the file name
651 * for fopen(), so it's safe to do this */
652 if ((cp = getenv("MAILRC")) != NULL)
653 load(file_expand(cp));
654 else if ((cp = getenv("NAILRC")) != NULL)
655 load(file_expand(cp));
656 else
657 load(file_expand("~/.mailrc"));
658 if (getenv("NAIL_EXTRA_RC") == NULL &&
659 (cp = value("NAIL_EXTRA_RC")) != NULL)
660 load(file_expand(cp));
662 /* Now we can set the account */
663 if (Aflag != NULL) {
664 char *a[2];
665 a[0] = Aflag;
666 a[1] = NULL;
667 account(a);
670 /* Ensure the -S and other command line options take precedence over
671 * anything that may have been placed in resource files */
672 for (i = 0; i < oargs_count; ++i) {
673 char const *a[2];
674 a[0] = oargs[i];
675 a[1] = NULL;
676 set(a);
680 * We're finally completely setup and ready to go
683 starting =
684 unset_allow_undefined = FAL0;
686 if (options & OPT_DEBUG)
687 fprintf(stderr, tr(199, "user = %s, homedir = %s\n"),
688 myname, homedir);
690 if (! (options & OPT_SENDMODE))
691 return _rcv_mode(folder);
693 /* Now that full mailx(1)-style file expansion is possible handle the
694 * attachments which we had delayed due to this.
695 * This may use savestr(), but since we won't enter the command loop we
696 * don't need to care about that */
697 while (a_head != NULL) {
698 attach = add_attachment(attach, a_head->aa_file, NULL);
699 if (attach != NULL) {
700 a_curr = a_head;
701 a_head = a_head->aa_next;
702 ac_free(a_curr);
703 } else {
704 perror(a_head->aa_file);
705 exit(1);
709 /* xxx exit_status = EXIT_OK; */
710 if (options & OPT_INTERACTIVE)
711 tty_init();
712 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
713 if (options & OPT_INTERACTIVE)
714 tty_destroy();
715 return exit_status;