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>.
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
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
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>
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 #ifndef HAVE_AMALGAMATION
55 #include <sys/ioctl.h>
60 #ifdef HAVE_NL_LANGINFO
61 # include <langinfo.h>
70 struct a_arg
*aa_next
;
74 /* (extern, but not with amalgamation, so define here) */
75 VL
char const weekday_names
[7 + 1][4] = {
76 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ""
78 VL
char const month_names
[12 + 1][4] = {
79 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
80 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""
82 VL
char const uagent
[] = UAGENT
;
83 VL
char const version
[] = VERSION
;
84 /*VL char const features[]; The "feature string" comes from config.h */
86 VL sighandler_type dflpipe
= SIG_DFL
;
88 /* getopt(3) fallback implementation */
92 /*# define _oerr opterr*/
96 static int _oind
, /*_oerr,*/ _oopt
;
99 /* getopt(3) fallback implementation */
101 # define _getopt getopt
103 static int _getopt(int argc
, char *const argv
[], const char *optstring
);
106 /* Perform basic startup initialization */
107 static void _startup(void);
110 static int _grow_cpp(char const ***cpp
, int size
, int cnt
);
112 /* Initialize *tempdir*, *myname*, *homedir* */
113 static void _setup_vars(void);
115 /* We're in an interactive session - compute what the screen size for printing
116 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
117 * We use the following algorithm for the height:
118 * If baud rate < 1200, use 9
119 * If baud rate = 1200, use 14
120 * If baud rate > 1200, use 24 or ws_row
121 * Width is either 80 or ws_col */
122 static void _setscreensize(int is_sighdl
);
124 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
125 * the system mailbox, and open up the right stuff */
126 static int _rcv_mode(char const *folder
);
128 /* Interrupt printing of the headers */
129 static void _hdrstop(int signo
);
133 _getopt(int argc
, char * const argv
[], char const *optstring
)
135 static char const *lastp
;
139 if ((colon
= (optstring
[0] == ':')))
145 if (_oind
>= argc
|| argv
[_oind
] == 0 || argv
[_oind
][0] != '-' ||
146 argv
[_oind
][1] == '\0')
148 if (argv
[_oind
][1] == '-' && argv
[_oind
][2] == '\0') {
152 curp
= &argv
[_oind
][1];
156 while (optstring
[0] != '\0') {
157 if (optstring
[0] == ':' || optstring
[0] != _oopt
) {
161 if (optstring
[1] == ':') {
162 if (curp
[1] != '\0') {
163 _oarg
= UNCONST(&curp
[1]);
166 if ((_oind
+= 2) > argc
) {
167 if (!colon
/*&& _oerr*/) {
169 tr(79, "%s: option requires an argument -- %c\n"),
170 argv
[0], (char)_oopt
);
172 rv
= (colon
? ':' : '?');
175 _oarg
= argv
[_oind
- 1];
188 if (!colon
/*&& opterr*/)
189 fprintf(stderr
, tr(78, "%s: illegal option -- %c\n"), argv
[0], _oopt
);
199 #endif /* !HAVE_GETOPT */
206 /* Absolutely the first thing we do is save our egid
207 * and set it to the rgid, so that we can safely run
208 * setgid. We use the sgid (saved set-gid) to allow ourselves
209 * to revert to the egid if we want (temporarily) to become
210 * privileged XXX (s-nail-)*dotlock(-program)* */
211 effectivegid
= getegid();
213 if (setgid(realgid
) < 0) {
221 _oind
= /*_oerr =*/ 1;
224 if ((cp
= strrchr(progname
, '/')) != NULL
)
227 /* Set up a reasonable environment.
228 * Figure out whether we are being run interactively,
229 * start the SIGCHLD catcher, and so forth */
230 safe_signal(SIGCHLD
, sigchild
);
232 if (isatty(STDIN_FILENO
)) /* TODO should be isatty(0) && isatty(2)?? */
233 options
|= OPT_TTYIN
| OPT_INTERACTIVE
;
234 if (isatty(STDOUT_FILENO
))
235 options
|= OPT_TTYOUT
;
236 if (IS_TTY_SESSION())
237 safe_signal(SIGPIPE
, dflpipe
= SIG_IGN
);
239 /* Define defaults for internal variables, based on POSIX 2008/Cor 1-2013 */
242 assign("asksub", "");
251 /* assign("escape", "~"); TODO non-compliant */
254 assign("header", "");
261 /* noonehop -- Note: we ignore this one */
264 assign("prompt", "\\& "); /* POSIX "? " unless *bsdcompat*, then "& " */
272 /* assign("toplines", "5"); XXX somewhat hmm */
274 #ifdef HAVE_SETLOCALE
275 setlocale(LC_ALL
, "");
276 mb_cur_max
= MB_CUR_MAX
;
277 # ifdef HAVE_NL_LANGINFO
278 if (voption("ttycharset") == NULL
&& (cp
= nl_langinfo(CODESET
)) != NULL
)
279 assign("ttycharset", cp
);
282 # ifdef HAVE_C90AMEND1
283 if (mb_cur_max
> 1) {
285 if (mbtowc(&wc
, "\303\266", 2) == 2 && wc
== 0xF6 &&
286 mbtowc(&wc
, "\342\202\254", 3) == 3 && wc
== 0x20AC)
288 /* Reset state - it may have been messed up; luckily this also
289 * gives us an indication wether the encoding has locking shift
291 /* TODO temporary - use option bits! */
292 enc_has_state
= mbtowc(&wc
, NULL
, mb_cur_max
);
300 # ifdef NL_CAT_LOCALE
301 catd
= catopen(CATNAME
, NL_CAT_LOCALE
);
303 catd
= catopen(CATNAME
, 0);
308 iconvd
= (iconv_t
)-1;
313 _grow_cpp(char const ***cpp
, int size
, int cnt
)
315 /* Before spreserve(): use our string pool instead of LibC heap;
316 * Increment *size* by at least 5! */
317 char const **newcpp
= salloc(sizeof(char*) * (size
+= 8));
320 memcpy(newcpp
, *cpp
, (size_t)cnt
* sizeof(char*));
328 /* Before spreserve(): use our string pool instead of LibC heap */
329 /* XXX further check paths? */
332 struct passwd
*pwuid
, *pw
;
334 tempdir
= ((cp
= getenv("TMPDIR")) != NULL
) ? savestr(cp
) : TMPDIR_FALLBACK
;
336 cp
= (myname
== NULL
) ? getenv("USER") : myname
;
338 if ((pwuid
= getpwuid(uid
)) == NULL
)
339 panic(tr(201, "Cannot associate a name with uid %lu"), (ul_it
)uid
);
341 myname
= pwuid
->pw_name
;
342 else if ((pw
= getpwnam(cp
)) == NULL
)
343 panic(tr(236, "`%s' is not a user of this system"), cp
);
345 myname
= pw
->pw_name
;
346 if (pw
->pw_uid
!= uid
)
347 options
|= OPT_u_FLAG
;
349 myname
= savestr(myname
);
350 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
352 if ((cp
= getenv("HOME")) == NULL
)
353 cp
= "."; /* XXX User and Login objects; Login: pw->pw_dir */
354 homedir
= savestr(cp
);
358 _setscreensize(int is_sighdl
)
363 #elif defined TIOCGSIZE
367 scrnheight
= realscreenheight
= scrnwidth
= 0;
369 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
370 * a little bit to be able to honour resizes during our lifetime and
371 * only honour it upon first run; abuse *is_sighdl* as an indicator */
376 if ((cp
= getenv("LINES")) != NULL
&& (i
= strtol(cp
, NULL
, 10)) > 0)
377 scrnheight
= realscreenheight
= (int)i
;
378 if ((cp
= getenv("COLUMNS")) != NULL
&& (i
= strtol(cp
, NULL
, 10)) > 0)
381 if (scrnwidth
!= 0 && scrnheight
!= 0)
386 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) < 0)
387 ws
.ws_col
= ws
.ws_row
= 0;
388 #elif defined TIOCGSIZE
389 if (ioctl(STDOUT_FILENO
, TIOCGSIZE
, &ws
) < 0)
390 ts
.ts_lines
= ts
.ts_cols
= 0;
393 if (scrnheight
== 0) {
394 speed_t ospeed
= ((tcgetattr(STDOUT_FILENO
, &tbuf
) < 0)
395 ? B9600
: cfgetospeed(&tbuf
));
399 else if (ospeed
== B1200
)
402 else if (ws
.ws_row
!= 0)
403 scrnheight
= ws
.ws_row
;
404 #elif defined TIOCGSIZE
405 else if (ts
.ts_lines
!= 0)
406 scrnheight
= ts
.ts_lines
;
411 #if defined TIOCGWINSZ || defined TIOCGSIZE
414 (realscreenheight
= ws
.ws_row
)
416 (realscreenheight
= ts
.ts_lines
)
419 realscreenheight
= 24;
423 if (scrnwidth
== 0 && 0 ==
425 (scrnwidth
= ws
.ws_col
)
426 #elif defined TIOCGSIZE
427 (scrnwidth
= ts
.ts_cols
)
434 if (is_sighdl
&& IS_TTY_SESSION())
435 tty_signal(SIGWINCH
);
439 static sigjmp_buf __hdrjmp
; /* XXX */
442 _rcv_mode(char const *folder
)
446 sighandler_type prevint
;
450 else if (*folder
== '@') {
451 /* This must be treated specially to make invocation like
452 * -A imap -f @mailbox work */
453 if ((cp
= value("folder")) != NULL
&& which_protocol(cp
) == PROTO_IMAP
)
454 (void)n_strlcpy(mailname
, cp
, MAXPATHLEN
);
457 i
= setfile(folder
, 0);
459 exit(1); /* error already reported */
460 if (options
& OPT_EXISTONLY
)
463 if (options
& OPT_HEADERSONLY
) {
465 if (mb
.mb_type
== MB_IMAP
)
466 imap_getheaders(1, msgCount
);
468 time_current_update(&time_current
, FAL0
);
469 for (i
= 1; i
<= msgCount
; ++i
)
470 printhead(i
, stdout
, 0);
474 callhook(mailname
, 0);
475 if (i
> 0 && !boption("emptystart"))
478 if (sigsetjmp(__hdrjmp
, 1) == 0) {
479 if ((prevint
= safe_signal(SIGINT
, SIG_IGN
)) != SIG_IGN
)
480 safe_signal(SIGINT
, _hdrstop
);
481 if (!(options
& OPT_N_FLAG
)) {
483 printf(tr(140, "%s version %s. Type ? for help.\n"),
484 (boption("bsdcompat") ? "Mail" : uagent
), version
);
488 safe_signal(SIGINT
, prevint
);
491 /* Enter the command loop */
492 if (options
& OPT_INTERACTIVE
)
495 if (options
& OPT_INTERACTIVE
)
498 if (mb
.mb_type
== MB_FILE
|| mb
.mb_type
== MB_MAILDIR
) {
499 safe_signal(SIGHUP
, SIG_IGN
);
500 safe_signal(SIGINT
, SIG_IGN
);
501 safe_signal(SIGQUIT
, SIG_IGN
);
503 save_mbox_for_possible_quitstuff();
514 fprintf(stderr
, tr(141, "\nInterrupt\n"));
515 siglongjmp(__hdrjmp
, 1);
519 main(int argc
, char *argv
[])
521 static char const optstr
[] = "A:a:Bb:c:DdEeFfHiNnO:q:Rr:S:s:tu:Vv~#",
524 " %s [-BDdEFintv~] [-A acc] [-a attachment] "
525 "[-b bcc-addr] [-c cc-addr]\n"
526 "\t [-O mtaopt [-O mtaopt-arg]] [-q file] [-r from-addr] "
528 "\t [-s subject] to-addr...\n"
529 " %s [-BDdEeHiNnRv~#] [-A acct] "
530 "[-S var[=value]] -f [file]\n"
531 " %s [-BDdEeiNnRv~#] [-A acc] [-S var[=value]] [-u user]\n";
533 struct a_arg
*a_head
= NULL
, *a_curr
= /* silence CC */ NULL
;
534 struct name
*to
= NULL
, *cc
= NULL
, *bcc
= NULL
;
535 struct attachment
*attach
= NULL
;
536 char *cp
= NULL
, *subject
= NULL
, *qf
= NULL
, *Aflag
= NULL
;
537 char const *okey
, **oargs
= NULL
, *folder
= NULL
;
538 int oargs_size
= 0, oargs_count
= 0, smopts_size
= 0, i
;
541 * Start our lengthy setup
545 unset_allow_undefined
= TRU1
;
550 /* Command line parsing */
551 while ((i
= _getopt(argc
, argv
, optstr
)) >= 0) {
554 /* Execute an account command later on */
558 { struct a_arg
*nap
= ac_alloc(sizeof(struct a_arg
));
562 a_curr
->aa_next
= nap
;
564 nap
->aa_file
= _oarg
;
567 options
|= OPT_SENDMODE
;
570 /* Make 0/1 line buffered */
571 setvbuf(stdin
, NULL
, _IOLBF
, 0);
572 setvbuf(stdout
, NULL
, _IOLBF
, 0);
575 /* Get Blind Carbon Copy Recipient list */
576 bcc
= cat(bcc
, checkaddrs(lextract(_oarg
, GBCC
| GFULL
)));
577 options
|= OPT_SENDMODE
;
580 /* Get Carbon Copy Recipient list */
581 cc
= cat(cc
, checkaddrs(lextract(_oarg
, GCC
| GFULL
)));
582 options
|= OPT_SENDMODE
;
586 okey
= "disconnected";
598 okey
= "skipemptybody";
601 options
|= OPT_EXISTONLY
;
604 options
|= OPT_F_FLAG
| OPT_SENDMODE
;
607 /* User is specifying file to "edit" with Mail, as opposed to reading
608 * system mailbox. If no argument is given, we read his mbox file.
609 * Check for remaining arguments later */
613 options
|= OPT_HEADERSONLY
;
616 /* Ignore interrupts */
620 /* Avoid initial header printing */
624 /* Don't source "unspecified system start-up file" */
625 options
|= OPT_NOSRC
;
628 /* Additional options to pass-through to MTA */
629 if (smopts_count
== (size_t)smopts_size
)
630 smopts_size
= _grow_cpp(&smopts
, smopts_size
, (int)smopts_count
);
631 smopts
[smopts_count
++] = skin(_oarg
);
634 /* Quote file TODO drop? -Q with real quote?? what ? */
637 options
|= OPT_SENDMODE
;
640 /* Open folders read-only */
641 options
|= OPT_R_FLAG
;
644 /* Set From address. */
645 options
|= OPT_r_FLAG
;
646 if ((option_r_arg
= _oarg
)[0] != '\0') {
647 struct name
*fa
= nalloc(_oarg
, GFULL
);
649 if (is_addr_invalid(fa
, 1) || is_fileorpipe_addr(fa
)) {
650 fprintf(stderr
, tr(271, "Invalid address argument with -r\n"));
653 option_r_arg
= fa
->n_name
;
654 /* TODO -r options is set in smopts, but may
655 * TODO be overwritten by setting from= in
656 * TODO an interactive session!
657 * TODO Maybe disable setting of from?
658 * TODO Warn user? Update manual!! */
659 okey
= savecat("from=", fa
->n_fullname
);
661 /* ..and fa goes even though it is ready :/ */
665 /* Set variable. We need to do this twice, since the
666 * user surely wants the setting to take effect
667 * immediately, but also doesn't want it to be
668 * overwritten from within resource files */
675 if (oargs_count
== oargs_size
)
676 oargs_size
= _grow_cpp(&oargs
, oargs_size
, oargs_count
);
677 oargs
[oargs_count
++] = okey
;
682 options
|= OPT_SENDMODE
;
685 /* Read defined set of headers from mail to be send */
686 options
|= OPT_SENDMODE
| OPT_t_FLAG
;
689 /* Set user name to pretend to be; don't set OPT_u_FLAG yet, this is
690 * done as necessary in _setup_vars() above */
705 /* Enable tilde escapes even in non-interactive mode */
706 options
|= OPT_TILDE_FLAG
;
709 /* Work in batch mode, even if non-interactive */
710 if (oargs_count
+ 5 >= oargs_size
)
711 oargs_size
= _grow_cpp(&oargs
, oargs_size
, oargs_count
);
712 oargs
[oargs_count
++] = "dot";
713 oargs
[oargs_count
++] = "emptystart";
714 oargs
[oargs_count
++] = "noheader";
715 oargs
[oargs_count
++] = "quiet";
716 oargs
[oargs_count
++] = "sendwait";
717 options
|= OPT_TILDE_FLAG
| OPT_BATCH_FLAG
;
721 fprintf(stderr
, tr(135, usagestr
), progname
, progname
, progname
);
726 if (folder
!= NULL
) {
728 if (_oind
+ 1 < argc
) {
729 fprintf(stderr
, tr(205, "More than one file given with -f\n"));
732 folder
= argv
[_oind
];
735 for (i
= _oind
; argv
[i
]; ++i
)
736 to
= cat(to
, checkaddrs(lextract(argv
[i
], GTO
| GFULL
)));
738 options
|= OPT_SENDMODE
;
741 /* Check for inconsistent arguments */
742 if (folder
!= NULL
&& to
!= NULL
) {
743 fprintf(stderr
, tr(137, "Cannot give -f and people to send to.\n"));
746 if ((options
& (OPT_SENDMODE
| OPT_t_FLAG
)) == OPT_SENDMODE
&& to
== NULL
) {
747 fprintf(stderr
, tr(138,
748 "Send options without primary recipient specified.\n"));
751 if ((options
& OPT_R_FLAG
) && to
!= NULL
) {
752 fprintf(stderr
, tr(235, "The -R option is meaningless in send mode.\n"));
757 * Likely to go, perform more setup
762 if (options
& OPT_INTERACTIVE
) {
765 # ifndef TTY_WANTS_SIGWINCH
766 if (safe_signal(SIGWINCH
, SIG_IGN
) != SIG_IGN
)
768 safe_signal(SIGWINCH
, _setscreensize
);
771 scrnheight
= realscreenheight
= 24, scrnwidth
= 80;
773 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
776 if (!(options
& OPT_NOSRC
) && getenv("NAIL_NO_SYSTEM_RC") == NULL
)
778 /* *expand() returns a savestr(), but load only uses the file name for
779 * fopen(), so it's safe to do this */
780 if ((cp
= getenv("MAILRC")) != NULL
)
781 load(file_expand(cp
));
782 else if ((cp
= getenv("NAILRC")) != NULL
)
783 load(file_expand(cp
));
785 load(file_expand(MAILRC
));
786 if (getenv("NAIL_EXTRA_RC") == NULL
&& (cp
= value("NAIL_EXTRA_RC")) != NULL
)
787 load(file_expand(cp
));
789 /* Now we can set the account */
797 /* Ensure the -S and other command line options take precedence over
798 * anything that may have been placed in resource files */
799 for (i
= 0; i
< oargs_count
; ++i
) {
807 * We're finally completely setup and ready to go
811 unset_allow_undefined
= FAL0
;
813 if (options
& OPT_DEBUG
)
814 fprintf(stderr
, tr(199, "user = %s, homedir = %s\n"), myname
, homedir
);
816 if (!(options
& OPT_SENDMODE
)) {
817 exit_status
= _rcv_mode(folder
);
821 /* Now that full mailx(1)-style file expansion is possible handle the
822 * attachments which we had delayed due to this.
823 * This may use savestr(), but since we won't enter the command loop we
824 * don't need to care about that */
825 while (a_head
!= NULL
) {
826 attach
= add_attachment(attach
, a_head
->aa_file
, NULL
);
827 if (attach
!= NULL
) {
829 a_head
= a_head
->aa_next
;
832 perror(a_head
->aa_file
);
837 /* xxx exit_status = EXIT_OK; */
838 if (options
& OPT_INTERACTIVE
)
840 mail(to
, cc
, bcc
, subject
, attach
, qf
, ((options
& OPT_F_FLAG
) != 0));
841 if (options
& OPT_INTERACTIVE
)
847 /* vim:set fenc=utf-8:s-it-mode */