README: mention *crawl* branch
[s-mailx.git] / main.c
blob4464f04edbd35ff6972cf777c7ca90ab4e3b4bd8
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"
68 struct a_arg {
69 struct a_arg *aa_next;
70 char *aa_file;
73 /* Perform basic startup initialization */
74 static void _startup(void);
76 /* Grow a char** */
77 static int _grow_cpp(char const ***cpp, int size, int count);
79 /* Initialize *tempdir*, *myname*, *homedir* */
80 static void _setup_vars(void);
82 /* We're in an interactive session - compute what the screen size for printing
83 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
84 * We use the following algorithm for the height:
85 * If baud rate < 1200, use 9
86 * If baud rate = 1200, use 14
87 * If baud rate > 1200, use 24 or ws_row
88 * Width is either 80 or ws_col */
89 static void _setscreensize(int is_sighdl);
91 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
92 * the system mailbox, and open up the right stuff */
93 static int _rcv_mode(char const *folder);
95 /* Interrupt printing of the headers */
96 static void _hdrstop(int signo);
98 static void
99 _startup(void)
101 char *cp;
103 /* Absolutely the first thing we do is save our egid
104 * and set it to the rgid, so that we can safely run
105 * setgid. We use the sgid (saved set-gid) to allow ourselves
106 * to revert to the egid if we want (temporarily) to become
107 * privileged */
108 effectivegid = getegid();
109 realgid = getgid();
110 if (setgid(realgid) < 0) {
111 perror("setgid");
112 exit(1);
115 image = -1;
117 if ((cp = strrchr(progname, '/')) != NULL)
118 progname = ++cp;
120 /* Set up a reasonable environment.
121 * Figure out whether we are being run interactively,
122 * start the SIGCHLD catcher, and so forth */
123 safe_signal(SIGCHLD, sigchild);
125 if (isatty(0))
126 options |= OPT_TTYIN | OPT_INTERACTIVE;
127 if (isatty(1))
128 options |= OPT_TTYOUT;
129 if (IS_TTY_SESSION())
130 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
131 assign("header", "");
132 assign("save", "");
134 #ifdef HAVE_SETLOCALE
135 setlocale(LC_ALL, "");
136 mb_cur_max = MB_CUR_MAX;
137 # if defined HAVE_NL_LANGINFO && defined CODESET
138 if (value("ttycharset") == NULL && (cp = nl_langinfo(CODESET)) != NULL)
139 assign("ttycharset", cp);
140 # endif
142 # if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
143 if (mb_cur_max > 1) {
144 wchar_t wc;
145 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
146 mbtowc(&wc, "\342\202\254", 3) == 3 &&
147 wc == 0x20AC)
148 utf8 = 1;
149 /* Reset state - it may have been messed up; luckily this also
150 * gives us an indication wether the encoding has locking shift
151 * state sequences */
152 /* TODO temporary - use option bits! */
153 enc_has_state = mbtowc(&wc, NULL, mb_cur_max);
155 # endif
156 #else
157 mb_cur_max = 1;
158 #endif
160 #ifdef HAVE_CATGETS
161 # ifdef NL_CAT_LOCALE
162 catd = catopen(CATNAME, NL_CAT_LOCALE);
163 # else
164 catd = catopen(CATNAME, 0);
165 # endif
166 #endif
168 #ifdef HAVE_ICONV
169 iconvd = (iconv_t)-1;
170 #endif
173 static int
174 _grow_cpp(char const ***cpp, int size, int count)
176 /* Before spreserve(): use our string pool instead of LibC heap;
177 * Increment *size* by at least 5! */
178 char const **newcpp = salloc(sizeof(char*) * (size += 8));
180 if (count > 0)
181 memcpy(newcpp, *cpp, count * sizeof(char*));
182 *cpp = newcpp;
183 return size;
186 static void
187 _setup_vars(void)
189 /* Before spreserve(): use our string pool instead of LibC heap */
190 char const *cp;
192 tempdir = ((cp = getenv("TMPDIR")) != NULL) ? savestr(cp) : "/tmp";
194 myname = savestr(username());
196 if ((cp = getenv("HOME")) == NULL)
197 cp = ".";
198 homedir = savestr(cp);
201 static void
202 _setscreensize(int is_sighdl)
204 struct termios tbuf;
205 #ifdef TIOCGWINSZ
206 struct winsize ws;
207 #elif defined TIOCGSIZE
208 struct ttysize ts;
209 #endif
211 scrnheight = realscreenheight = scrnwidth = 0;
213 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
214 * a little bit to be able to honour resizes during our lifetime and
215 * only honour it upon first run; abuse *is_sighdl* as an indicator */
216 if (is_sighdl == 0) {
217 char *cp;
218 long i;
220 if ((cp = getenv("LINES")) != NULL &&
221 (i = strtol(cp, NULL, 10)) > 0)
222 scrnheight = realscreenheight = (int)i;
223 if ((cp = getenv("COLUMNS")) != NULL &&
224 (i = strtol(cp, NULL, 10)) > 0)
225 scrnwidth = (int)i;
227 if (scrnwidth != 0 && scrnheight != 0)
228 goto jleave;
231 #ifdef TIOCGWINSZ
232 if (ioctl(1, TIOCGWINSZ, &ws) < 0)
233 ws.ws_col = ws.ws_row = 0;
234 #elif defined TIOCGSIZE
235 if (ioctl(1, TIOCGSIZE, &ws) < 0)
236 ts.ts_lines = ts.ts_cols = 0;
237 #endif
239 if (scrnheight == 0) {
240 speed_t ospeed = (tcgetattr(1, &tbuf) < 0) ? B9600 :
241 cfgetospeed(&tbuf);
243 if (ospeed < B1200)
244 scrnheight = 9;
245 else if (ospeed == B1200)
246 scrnheight = 14;
247 #ifdef TIOCGWINSZ
248 else if (ws.ws_row != 0)
249 scrnheight = ws.ws_row;
250 #elif defined TIOCGSIZE
251 else if (ts.ts_lines != 0)
252 scrnheight = ts.ts_lines;
253 #endif
254 else
255 scrnheight = 24;
257 #if defined TIOCGWINSZ || defined TIOCGSIZE
258 if (0 ==
259 # ifdef TIOCGWINSZ
260 (realscreenheight = ws.ws_row)
261 # else
262 (realscreenheight = ts.ts_lines)
263 # endif
265 realscreenheight = 24;
266 #endif
269 if (scrnwidth == 0 && 0 ==
270 #ifdef TIOCGWINSZ
271 (scrnwidth = ws.ws_col)
272 #elif defined TIOCGSIZE
273 (scrnwidth = ts.ts_cols)
274 #endif
276 scrnwidth = 80;
278 jleave:
279 #ifdef SIGWINCH
280 if (is_sighdl && (options & OPT_INTERACTIVE))
281 tty_signal(SIGWINCH);
282 #endif
285 static sigjmp_buf __hdrjmp; /* XXX */
287 static int
288 _rcv_mode(char const *folder)
290 char *cp;
291 int i;
292 sighandler_type prevint;
294 if (folder == NULL)
295 folder = "%";
296 else if (*folder == '@') {
297 /* This must be treated specially to make invocation like
298 * -A imap -f @mailbox work */
299 if ((cp = value("folder")) != NULL &&
300 which_protocol(cp) == PROTO_IMAP)
301 (void)n_strlcpy(mailname, cp, MAXPATHLEN);
304 i = setfile(folder, 0);
305 if (i < 0)
306 exit(1); /* error already reported */
307 if (options & OPT_EXISTONLY)
308 exit(i);
310 if (options & OPT_HEADERSONLY) {
311 #ifdef USE_IMAP
312 if (mb.mb_type == MB_IMAP)
313 imap_getheaders(1, msgCount);
314 #endif
315 time_current_update(&time_current, FAL0);
316 for (i = 1; i <= msgCount; i++)
317 printhead(i, stdout, 0);
318 exit(exit_status);
321 callhook(mailname, 0);
322 if (i > 0 && value("emptystart") == NULL)
323 exit(1);
325 if (sigsetjmp(__hdrjmp, 1) == 0) {
326 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
327 safe_signal(SIGINT, _hdrstop);
328 if ((options & OPT_N_FLAG) == 0) {
329 if (! value("quiet"))
330 printf(tr(140,
331 "%s version %s. Type ? for help.\n"),
332 value("bsdcompat") ? "Mail" : uagent,
333 version);
334 announce(1);
335 fflush(stdout);
337 safe_signal(SIGINT, prevint);
340 /* Enter the command loop */
341 if (options & OPT_INTERACTIVE)
342 tty_init();
343 commands();
344 if (options & OPT_INTERACTIVE)
345 tty_destroy();
347 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
348 safe_signal(SIGHUP, SIG_IGN);
349 safe_signal(SIGINT, SIG_IGN);
350 safe_signal(SIGQUIT, SIG_IGN);
352 n_strlcpy(mboxname, expand("&"), sizeof(mboxname));
353 quit();
354 return exit_status;
357 static void
358 _hdrstop(int signo)
360 (void)signo;
362 fflush(stdout);
363 fprintf(stderr, tr(141, "\nInterrupt\n"));
364 siglongjmp(__hdrjmp, 1);
367 char const *const weekday_names[7 + 1] = {
368 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL
370 char const *const month_names[12 + 1] = {
371 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
372 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL
375 sighandler_type dflpipe = SIG_DFL;
377 int
378 main(int argc, char *argv[])
380 static char const optstr[] = "A:a:Bb:c:DdEeFfHiNnO:q:Rr:S:s:tu:Vv~#",
381 usagestr[] =
382 "Synopsis:\n"
383 " %s [-BDdEFintv~] [-A acc] [-a attachment] "
384 "[-b bcc-addr] [-c cc-addr]\n"
385 "\t [-O mtaopt [-O mtaopt-arg]] [-q file] [-r from-addr] "
386 "[-S var[=value]]\n"
387 "\t [-s subject] to-addr...\n"
388 " %s [-BDdEeHiNnRv~#] [-A acct] "
389 "[-S var[=value]] -f [file]\n"
390 " %s [-BDdEeiNnRv~#] [-A acc] [-S var[=value]] [-u user]\n";
392 struct a_arg *a_head = NULL, *a_curr = /* silence CC */ NULL;
393 struct name *to = NULL, *cc = NULL, *bcc = NULL;
394 struct attachment *attach = NULL;
395 char *cp = NULL, *subject = NULL, *qf = NULL, *Aflag = NULL;
396 char const *okey, **oargs = NULL, *folder = NULL;
397 int oargs_size = 0, oargs_count = 0, smopts_size = 0, i;
400 * Start our lengthy setup
403 starting =
404 unset_allow_undefined = TRU1;
406 progname = argv[0];
407 _startup();
409 /* Command line parsing */
410 while ((i = getopt(argc, argv, optstr)) >= 0) {
411 switch (i) {
412 case 'A':
413 /* Execute an account command later on */
414 Aflag = optarg;
415 break;
416 case 'a':
417 { struct a_arg *nap = ac_alloc(
418 sizeof(struct a_arg));
419 if (a_head == NULL)
420 a_head = nap;
421 else
422 a_curr->aa_next = nap;
423 nap->aa_next = NULL;
424 nap->aa_file = optarg;
425 a_curr = nap;
427 options |= OPT_SENDMODE;
428 break;
429 case 'B':
430 /* Make 0/1 line buffered */
431 setvbuf(stdin, NULL, _IOLBF, 0);
432 setvbuf(stdout, NULL, _IOLBF, 0);
433 break;
434 case 'b':
435 /* Get Blind Carbon Copy Recipient list */
436 bcc = cat(bcc, checkaddrs(lextract(optarg,GBCC|GFULL)));
437 options |= OPT_SENDMODE;
438 break;
439 case 'c':
440 /* Get Carbon Copy Recipient list */
441 cc = cat(cc, checkaddrs(lextract(optarg, GCC|GFULL)));
442 options |= OPT_SENDMODE;
443 break;
444 case 'D':
445 #ifdef USE_IMAP
446 okey = "disconnected";
447 goto joarg;
448 #else
449 break;
450 #endif
451 case 'd':
452 okey = "debug";
453 #ifdef WANT_ASSERTS
454 assign(okey, "");
455 #endif
456 goto joarg;
457 case 'E':
458 okey = "skipemptybody";
459 goto joarg;
460 case 'e':
461 options |= OPT_EXISTONLY;
462 break;
463 case 'F':
464 options |= OPT_F_FLAG | OPT_SENDMODE;
465 break;
466 case 'f':
467 /* User is specifying file to "edit" with Mail,
468 * as opposed to reading system mailbox.
469 * If no argument is given, we read his mbox file.
470 * Check for remaining arguments later */
471 folder = "&";
472 break;
473 case 'H':
474 options |= OPT_HEADERSONLY;
475 break;
476 case 'i':
477 /* Ignore interrupts */
478 okey = "ignore";
479 goto joarg;
480 case 'N':
481 /* Avoid initial header printing */
482 okey = "noheader";
483 goto joarg;
484 case 'n':
485 /* Don't source "unspecified system start-up file" */
486 options |= OPT_NOSRC;
487 break;
488 case 'O':
489 /* Additional options to pass-through to MTA */
490 if (smopts_count == (size_t)smopts_size)
491 smopts_size = _grow_cpp(&smopts, smopts_size,
492 (int)smopts_count);
493 smopts[smopts_count++] = skin(optarg);
494 break;
495 case 'q':
496 /* Quote file TODO drop? -Q with real quote?? what ? */
497 if (*optarg != '-')
498 qf = optarg;
499 options |= OPT_SENDMODE;
500 break;
501 case 'R':
502 /* Open folders read-only */
503 options |= OPT_R_FLAG;
504 break;
505 case 'r':
506 /* Set From address. */
507 options |= OPT_r_FLAG;
508 if ((option_r_arg = optarg)[0] != '\0') {
509 struct name *fa = nalloc(optarg, GFULL);
511 if (is_addr_invalid(fa, 1) ||
512 is_fileorpipe_addr(fa)) {
513 fprintf(stderr, tr(271,
514 "Invalid address argument "
515 "with -r\n"));
516 goto usage;
518 option_r_arg = fa->n_name;
519 /* TODO -r options is set in smopts, but may
520 * TODO be overwritten by setting from= in
521 * TODO an interactive session!
522 * TODO Maybe disable setting of from?
523 * TODO Warn user? Update manual!! */
524 okey = savecat("from=", fa->n_fullname);
525 goto joarg;
526 /* ..and fa goes even though it is ready :/ */
528 break;
529 case 'S':
530 /* Set variable. We need to do this twice, since the
531 * user surely wants the setting to take effect
532 * immediately, but also doesn't want it to be
533 * overwritten from within resource files */
534 { char *a[2];
535 okey = a[0] = optarg;
536 a[1] = NULL;
537 set(a);
539 joarg:
540 if (oargs_count == oargs_size)
541 oargs_size = _grow_cpp(&oargs, oargs_size,
542 oargs_count);
543 oargs[oargs_count++] = okey;
544 break;
545 case 's':
546 /* Subject: */
547 subject = optarg;
548 options |= OPT_SENDMODE;
549 break;
550 case 't':
551 /* Read defined set of headers from mail to be send */
552 options |= OPT_SENDMODE | OPT_t_FLAG;
553 break;
554 case 'u':
555 /* Set user name to pretend to be */
556 myname = option_u_arg = optarg;
557 break;
558 case 'V':
559 puts(version);
560 exit(0);
561 /* NOTREACHED */
562 case 'v':
563 /* Be verbose */
564 okey = "verbose";
565 #ifdef WANT_ASSERTS
566 assign(okey, "");
567 #endif
568 goto joarg;
569 case '~':
570 /* Enable tilde escapes even in non-interactive mode */
571 options |= OPT_TILDE_FLAG;
572 break;
573 case '#':
574 /* Work in batch mode, even if non-interactive */
575 if (oargs_count + 3 >= oargs_size)
576 oargs_size = _grow_cpp(&oargs, oargs_size,
577 oargs_count);
578 oargs[oargs_count++] = "dot";
579 oargs[oargs_count++] = "emptystart";
580 oargs[oargs_count++] = "noheader";
581 oargs[oargs_count++] = "sendwait";
582 options |= OPT_TILDE_FLAG | OPT_BATCH_FLAG;
583 break;
584 case '?':
585 usage: fprintf(stderr, tr(135, usagestr),
586 progname, progname, progname);
587 exit(2);
591 if (folder != NULL) {
592 if (optind < argc) {
593 if (optind + 1 < argc) {
594 fprintf(stderr, tr(205,
595 "More than one file given with -f\n"));
596 goto usage;
598 folder = argv[optind];
600 } else {
601 for (i = optind; argv[i]; i++)
602 to = cat(to, checkaddrs(lextract(argv[i], GTO|GFULL)));
603 if (to != NULL)
604 options |= OPT_SENDMODE;
607 /* Check for inconsistent arguments */
608 if (folder != NULL && to != NULL) {
609 fprintf(stderr, tr(137,
610 "Cannot give -f and people to send to.\n"));
611 goto usage;
613 if ((options & (OPT_SENDMODE|OPT_t_FLAG)) == OPT_SENDMODE &&
614 to == NULL) {
615 fprintf(stderr, tr(138,
616 "Send options without primary recipient specified.\n"));
617 goto usage;
619 if ((options & OPT_R_FLAG) && to != NULL) {
620 fprintf(stderr, "The -R option is meaningless in send mode.\n");
621 goto usage;
625 * Likely to go, perform more setup
628 _setup_vars();
630 if (options & OPT_INTERACTIVE) {
631 _setscreensize(0);
632 #ifdef SIGWINCH
633 # ifndef TTY_WANTS_SIGWINCH
634 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
635 # endif
636 safe_signal(SIGWINCH, _setscreensize);
637 #endif
638 } else
639 scrnheight = realscreenheight = 24, scrnwidth = 80;
641 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
642 spreserve();
644 if ((options & OPT_NOSRC) == 0)
645 load(SYSCONFRC);
646 /* *expand() returns a savestr(), but load only uses the file name
647 * for fopen(), so it's safe to do this */
648 if ((cp = getenv("MAILRC")) != NULL)
649 load(file_expand(cp));
650 else if ((cp = getenv("NAILRC")) != NULL)
651 load(file_expand(cp));
652 else
653 load(file_expand("~/.mailrc"));
654 if (getenv("NAIL_EXTRA_RC") == NULL &&
655 (cp = value("NAIL_EXTRA_RC")) != NULL)
656 load(file_expand(cp));
658 /* Now we can set the account */
659 if (Aflag != NULL) {
660 char *a[2];
661 a[0] = Aflag;
662 a[1] = NULL;
663 account(a);
666 /* Ensure the -S and other command line options take precedence over
667 * anything that may have been placed in resource files */
668 for (i = 0; i < oargs_count; ++i) {
669 char const *a[2];
670 a[0] = oargs[i];
671 a[1] = NULL;
672 set(a);
676 * We're finally completely setup and ready to go
679 starting =
680 unset_allow_undefined = FAL0;
682 if (options & OPT_DEBUG)
683 fprintf(stderr, tr(199, "user = %s, homedir = %s\n"),
684 myname, homedir);
686 if (! (options & OPT_SENDMODE))
687 return _rcv_mode(folder);
689 /* Now that full mailx(1)-style file expansion is possible handle the
690 * attachments which we had delayed due to this.
691 * This may use savestr(), but since we won't enter the command loop we
692 * don't need to care about that */
693 while (a_head != NULL) {
694 attach = add_attachment(attach, a_head->aa_file, NULL);
695 if (attach != NULL) {
696 a_curr = a_head;
697 a_head = a_head->aa_next;
698 ac_free(a_curr);
699 } else {
700 perror(a_head->aa_file);
701 exit(1);
705 /* xxx exit_status = EXIT_OK; */
706 if (options & OPT_INTERACTIVE)
707 tty_init();
708 mail(to, cc, bcc, subject, attach, qf, ((options & OPT_F_FLAG) != 0));
709 if (options & OPT_INTERACTIVE)
710 tty_destroy();
711 return exit_status;