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 sighandler_type dflpipe
= SIG_DFL
;
86 /* getopt(3) fallback implementation */
90 /*# define _oerr opterr*/
94 static int _oind
, /*_oerr,*/ _oopt
;
97 /* getopt(3) fallback implementation */
99 # define _getopt getopt
101 static int _getopt(int argc
, char *const argv
[], const char *optstring
);
104 /* Perform basic startup initialization */
105 static void _startup(void);
108 static int _grow_cpp(char const ***cpp
, int size
, int cnt
);
110 /* Initialize *tempdir*, *myname*, *homedir* */
111 static void _setup_vars(void);
113 /* We're in an interactive session - compute what the screen size for printing
114 * headers etc. should be; notify tty upon resize if *is_sighdl* is not 0.
115 * We use the following algorithm for the height:
116 * If baud rate < 1200, use 9
117 * If baud rate = 1200, use 14
118 * If baud rate > 1200, use 24 or ws_row
119 * Width is either 80 or ws_col */
120 static void _setscreensize(int is_sighdl
);
122 /* Ok, we are reading mail. Decide whether we are editing a mailbox or reading
123 * the system mailbox, and open up the right stuff */
124 static int _rcv_mode(char const *folder
);
126 /* Interrupt printing of the headers */
127 static void _hdrstop(int signo
);
131 _getopt(int argc
, char * const argv
[], char const *optstring
)
133 static char const *lastp
;
137 if ((colon
= (optstring
[0] == ':')))
143 if (_oind
>= argc
|| argv
[_oind
] == 0 || argv
[_oind
][0] != '-' ||
144 argv
[_oind
][1] == '\0')
146 if (argv
[_oind
][1] == '-' && argv
[_oind
][2] == '\0') {
150 curp
= &argv
[_oind
][1];
154 while (optstring
[0] != '\0') {
155 if (optstring
[0] == ':' || optstring
[0] != _oopt
) {
159 if (optstring
[1] == ':') {
160 if (curp
[1] != '\0') {
161 _oarg
= UNCONST(&curp
[1]);
164 if ((_oind
+= 2) > argc
) {
165 if (!colon
/*&& _oerr*/) {
167 tr(79, "%s: option requires an argument -- %c\n"),
168 argv
[0], (char)_oopt
);
170 rv
= (colon
? ':' : '?');
173 _oarg
= argv
[_oind
- 1];
186 if (!colon
/*&& opterr*/)
187 fprintf(stderr
, tr(78, "%s: illegal option -- %c\n"), argv
[0], _oopt
);
197 #endif /* !HAVE_GETOPT */
204 /* Absolutely the first thing we do is save our egid
205 * and set it to the rgid, so that we can safely run
206 * setgid. We use the sgid (saved set-gid) to allow ourselves
207 * to revert to the egid if we want (temporarily) to become
208 * privileged XXX (s-nail-)*dotlock(-program)* */
209 effectivegid
= getegid();
211 if (setgid(realgid
) < 0) {
219 _oind
= /*_oerr =*/ 1;
222 if ((cp
= strrchr(progname
, '/')) != NULL
)
225 /* Set up a reasonable environment.
226 * Figure out whether we are being run interactively,
227 * start the SIGCHLD catcher, and so forth */
228 safe_signal(SIGCHLD
, sigchild
);
230 if (isatty(STDIN_FILENO
)) /* TODO should be isatty(0) && isatty(2)?? */
231 options
|= OPT_TTYIN
| OPT_INTERACTIVE
;
232 if (isatty(STDOUT_FILENO
))
233 options
|= OPT_TTYOUT
;
234 if (IS_TTY_SESSION())
235 safe_signal(SIGPIPE
, dflpipe
= SIG_IGN
);
236 assign("header", "");
239 #ifdef HAVE_SETLOCALE
240 setlocale(LC_ALL
, "");
241 mb_cur_max
= MB_CUR_MAX
;
242 # if defined HAVE_NL_LANGINFO && defined CODESET
243 if (voption("ttycharset") == NULL
&& (cp
= nl_langinfo(CODESET
)) != NULL
)
244 assign("ttycharset", cp
);
247 # if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
248 if (mb_cur_max
> 1) {
250 if (mbtowc(&wc
, "\303\266", 2) == 2 && wc
== 0xF6 &&
251 mbtowc(&wc
, "\342\202\254", 3) == 3 && wc
== 0x20AC)
253 /* Reset state - it may have been messed up; luckily this also
254 * gives us an indication wether the encoding has locking shift
256 /* TODO temporary - use option bits! */
257 enc_has_state
= mbtowc(&wc
, NULL
, mb_cur_max
);
265 # ifdef NL_CAT_LOCALE
266 catd
= catopen(CATNAME
, NL_CAT_LOCALE
);
268 catd
= catopen(CATNAME
, 0);
273 iconvd
= (iconv_t
)-1;
278 _grow_cpp(char const ***cpp
, int size
, int cnt
)
280 /* Before spreserve(): use our string pool instead of LibC heap;
281 * Increment *size* by at least 5! */
282 char const **newcpp
= salloc(sizeof(char*) * (size
+= 8));
285 memcpy(newcpp
, *cpp
, (size_t)cnt
* sizeof(char*));
293 /* Before spreserve(): use our string pool instead of LibC heap */
294 /* XXX further check paths? */
297 struct passwd
*pwuid
, *pw
;
299 tempdir
= ((cp
= getenv("TMPDIR")) != NULL
) ? savestr(cp
) : TMPDIR_FALLBACK
;
301 cp
= (myname
== NULL
) ? getenv("USER") : myname
;
303 if ((pwuid
= getpwuid(uid
)) == NULL
)
304 panic(tr(201, "Cannot associate a name with uid %lu"), (ul_it
)uid
);
306 myname
= pwuid
->pw_name
;
307 else if ((pw
= getpwnam(cp
)) == NULL
)
308 panic(tr(236, "`%s' is not a user of this system"), cp
);
310 myname
= pw
->pw_name
;
311 if (pw
->pw_uid
!= uid
)
312 options
|= OPT_u_FLAG
;
314 myname
= savestr(myname
);
315 /* XXX myfullname = pw->pw_gecos[OPTIONAL!] -> GUT THAT; TODO pw_shell */
317 if ((cp
= getenv("HOME")) == NULL
)
318 cp
= "."; /* XXX User and Login objects; Login: pw->pw_dir */
319 homedir
= savestr(cp
);
323 _setscreensize(int is_sighdl
)
328 #elif defined TIOCGSIZE
332 scrnheight
= realscreenheight
= scrnwidth
= 0;
334 /* (Also) POSIX: LINES and COLUMNS always override. Adjust this
335 * a little bit to be able to honour resizes during our lifetime and
336 * only honour it upon first run; abuse *is_sighdl* as an indicator */
341 if ((cp
= getenv("LINES")) != NULL
&& (i
= strtol(cp
, NULL
, 10)) > 0)
342 scrnheight
= realscreenheight
= (int)i
;
343 if ((cp
= getenv("COLUMNS")) != NULL
&& (i
= strtol(cp
, NULL
, 10)) > 0)
346 if (scrnwidth
!= 0 && scrnheight
!= 0)
351 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) < 0)
352 ws
.ws_col
= ws
.ws_row
= 0;
353 #elif defined TIOCGSIZE
354 if (ioctl(STDOUT_FILENO
, TIOCGSIZE
, &ws
) < 0)
355 ts
.ts_lines
= ts
.ts_cols
= 0;
358 if (scrnheight
== 0) {
359 speed_t ospeed
= ((tcgetattr(STDOUT_FILENO
, &tbuf
) < 0)
360 ? B9600
: cfgetospeed(&tbuf
));
364 else if (ospeed
== B1200
)
367 else if (ws
.ws_row
!= 0)
368 scrnheight
= ws
.ws_row
;
369 #elif defined TIOCGSIZE
370 else if (ts
.ts_lines
!= 0)
371 scrnheight
= ts
.ts_lines
;
376 #if defined TIOCGWINSZ || defined TIOCGSIZE
379 (realscreenheight
= ws
.ws_row
)
381 (realscreenheight
= ts
.ts_lines
)
384 realscreenheight
= 24;
388 if (scrnwidth
== 0 && 0 ==
390 (scrnwidth
= ws
.ws_col
)
391 #elif defined TIOCGSIZE
392 (scrnwidth
= ts
.ts_cols
)
399 if (is_sighdl
&& IS_TTY_SESSION())
400 tty_signal(SIGWINCH
);
404 static sigjmp_buf __hdrjmp
; /* XXX */
407 _rcv_mode(char const *folder
)
411 sighandler_type prevint
;
415 else if (*folder
== '@') {
416 /* This must be treated specially to make invocation like
417 * -A imap -f @mailbox work */
418 if ((cp
= value("folder")) != NULL
&& which_protocol(cp
) == PROTO_IMAP
)
419 (void)n_strlcpy(mailname
, cp
, MAXPATHLEN
);
422 i
= setfile(folder
, 0);
424 exit(1); /* error already reported */
425 if (options
& OPT_EXISTONLY
)
428 if (options
& OPT_HEADERSONLY
) {
430 if (mb
.mb_type
== MB_IMAP
)
431 imap_getheaders(1, msgCount
);
433 time_current_update(&time_current
, FAL0
);
434 for (i
= 1; i
<= msgCount
; ++i
)
435 printhead(i
, stdout
, 0);
439 callhook(mailname
, 0);
440 if (i
> 0 && !boption("emptystart"))
443 if (sigsetjmp(__hdrjmp
, 1) == 0) {
444 if ((prevint
= safe_signal(SIGINT
, SIG_IGN
)) != SIG_IGN
)
445 safe_signal(SIGINT
, _hdrstop
);
446 if (!(options
& OPT_N_FLAG
)) {
448 printf(tr(140, "%s version %s. Type ? for help.\n"),
449 (boption("bsdcompat") ? "Mail" : uagent
), version
);
453 safe_signal(SIGINT
, prevint
);
456 /* Enter the command loop */
457 if (options
& OPT_INTERACTIVE
)
460 if (options
& OPT_INTERACTIVE
)
463 if (mb
.mb_type
== MB_FILE
|| mb
.mb_type
== MB_MAILDIR
) {
464 safe_signal(SIGHUP
, SIG_IGN
);
465 safe_signal(SIGINT
, SIG_IGN
);
466 safe_signal(SIGQUIT
, SIG_IGN
);
468 save_mbox_for_possible_quitstuff();
479 fprintf(stderr
, tr(141, "\nInterrupt\n"));
480 siglongjmp(__hdrjmp
, 1);
484 main(int argc
, char *argv
[])
486 static char const optstr
[] = "A:a:Bb:c:DdEeFfHiNnO:q:Rr:S:s:tu:Vv~#",
489 " %s [-BDdEFintv~] [-A acc] [-a attachment] "
490 "[-b bcc-addr] [-c cc-addr]\n"
491 "\t [-O mtaopt [-O mtaopt-arg]] [-q file] [-r from-addr] "
493 "\t [-s subject] to-addr...\n"
494 " %s [-BDdEeHiNnRv~#] [-A acct] "
495 "[-S var[=value]] -f [file]\n"
496 " %s [-BDdEeiNnRv~#] [-A acc] [-S var[=value]] [-u user]\n";
498 struct a_arg
*a_head
= NULL
, *a_curr
= /* silence CC */ NULL
;
499 struct name
*to
= NULL
, *cc
= NULL
, *bcc
= NULL
;
500 struct attachment
*attach
= NULL
;
501 char *cp
= NULL
, *subject
= NULL
, *qf
= NULL
, *Aflag
= NULL
;
502 char const *okey
, **oargs
= NULL
, *folder
= NULL
;
503 int oargs_size
= 0, oargs_count
= 0, smopts_size
= 0, i
;
506 * Start our lengthy setup
510 unset_allow_undefined
= TRU1
;
515 /* Command line parsing */
516 while ((i
= _getopt(argc
, argv
, optstr
)) >= 0) {
519 /* Execute an account command later on */
523 { struct a_arg
*nap
= ac_alloc(sizeof(struct a_arg
));
527 a_curr
->aa_next
= nap
;
529 nap
->aa_file
= _oarg
;
532 options
|= OPT_SENDMODE
;
535 /* Make 0/1 line buffered */
536 setvbuf(stdin
, NULL
, _IOLBF
, 0);
537 setvbuf(stdout
, NULL
, _IOLBF
, 0);
540 /* Get Blind Carbon Copy Recipient list */
541 bcc
= cat(bcc
, checkaddrs(lextract(_oarg
, GBCC
| GFULL
)));
542 options
|= OPT_SENDMODE
;
545 /* Get Carbon Copy Recipient list */
546 cc
= cat(cc
, checkaddrs(lextract(_oarg
, GCC
| GFULL
)));
547 options
|= OPT_SENDMODE
;
551 okey
= "disconnected";
563 okey
= "skipemptybody";
566 options
|= OPT_EXISTONLY
;
569 options
|= OPT_F_FLAG
| OPT_SENDMODE
;
572 /* User is specifying file to "edit" with Mail, as opposed to reading
573 * system mailbox. If no argument is given, we read his mbox file.
574 * Check for remaining arguments later */
578 options
|= OPT_HEADERSONLY
;
581 /* Ignore interrupts */
585 /* Avoid initial header printing */
589 /* Don't source "unspecified system start-up file" */
590 options
|= OPT_NOSRC
;
593 /* Additional options to pass-through to MTA */
594 if (smopts_count
== (size_t)smopts_size
)
595 smopts_size
= _grow_cpp(&smopts
, smopts_size
, (int)smopts_count
);
596 smopts
[smopts_count
++] = skin(_oarg
);
599 /* Quote file TODO drop? -Q with real quote?? what ? */
602 options
|= OPT_SENDMODE
;
605 /* Open folders read-only */
606 options
|= OPT_R_FLAG
;
609 /* Set From address. */
610 options
|= OPT_r_FLAG
;
611 if ((option_r_arg
= _oarg
)[0] != '\0') {
612 struct name
*fa
= nalloc(_oarg
, GFULL
);
614 if (is_addr_invalid(fa
, 1) || is_fileorpipe_addr(fa
)) {
615 fprintf(stderr
, tr(271, "Invalid address argument with -r\n"));
618 option_r_arg
= fa
->n_name
;
619 /* TODO -r options is set in smopts, but may
620 * TODO be overwritten by setting from= in
621 * TODO an interactive session!
622 * TODO Maybe disable setting of from?
623 * TODO Warn user? Update manual!! */
624 okey
= savecat("from=", fa
->n_fullname
);
626 /* ..and fa goes even though it is ready :/ */
630 /* Set variable. We need to do this twice, since the
631 * user surely wants the setting to take effect
632 * immediately, but also doesn't want it to be
633 * overwritten from within resource files */
640 if (oargs_count
== oargs_size
)
641 oargs_size
= _grow_cpp(&oargs
, oargs_size
, oargs_count
);
642 oargs
[oargs_count
++] = okey
;
647 options
|= OPT_SENDMODE
;
650 /* Read defined set of headers from mail to be send */
651 options
|= OPT_SENDMODE
| OPT_t_FLAG
;
654 /* Set user name to pretend to be; don't set OPT_u_FLAG yet, this is
655 * done as necessary in _setup_vars() above */
670 /* Enable tilde escapes even in non-interactive mode */
671 options
|= OPT_TILDE_FLAG
;
674 /* Work in batch mode, even if non-interactive */
675 if (oargs_count
+ 3 >= oargs_size
)
676 oargs_size
= _grow_cpp(&oargs
, oargs_size
, oargs_count
);
677 oargs
[oargs_count
++] = "dot";
678 oargs
[oargs_count
++] = "emptystart";
679 oargs
[oargs_count
++] = "noheader";
680 oargs
[oargs_count
++] = "sendwait";
681 options
|= OPT_TILDE_FLAG
| OPT_BATCH_FLAG
;
685 fprintf(stderr
, tr(135, usagestr
), progname
, progname
, progname
);
690 if (folder
!= NULL
) {
692 if (_oind
+ 1 < argc
) {
693 fprintf(stderr
, tr(205, "More than one file given with -f\n"));
696 folder
= argv
[_oind
];
699 for (i
= _oind
; argv
[i
]; ++i
)
700 to
= cat(to
, checkaddrs(lextract(argv
[i
], GTO
| GFULL
)));
702 options
|= OPT_SENDMODE
;
705 /* Check for inconsistent arguments */
706 if (folder
!= NULL
&& to
!= NULL
) {
707 fprintf(stderr
, tr(137, "Cannot give -f and people to send to.\n"));
710 if ((options
& (OPT_SENDMODE
| OPT_t_FLAG
)) == OPT_SENDMODE
&& to
== NULL
) {
711 fprintf(stderr
, tr(138,
712 "Send options without primary recipient specified.\n"));
715 if ((options
& OPT_R_FLAG
) && to
!= NULL
) {
716 fprintf(stderr
, tr(235, "The -R option is meaningless in send mode.\n"));
721 * Likely to go, perform more setup
726 if (options
& OPT_INTERACTIVE
) {
729 # ifndef TTY_WANTS_SIGWINCH
730 if (safe_signal(SIGWINCH
, SIG_IGN
) != SIG_IGN
)
732 safe_signal(SIGWINCH
, _setscreensize
);
735 scrnheight
= realscreenheight
= 24, scrnwidth
= 80;
737 /* Snapshot our string pools. Memory is auto-reclaimed from now on */
740 if (!(options
& OPT_NOSRC
) && getenv("NAIL_NO_SYSTEM_RC") == NULL
)
742 /* *expand() returns a savestr(), but load only uses the file name for
743 * fopen(), so it's safe to do this */
744 if ((cp
= getenv("MAILRC")) != NULL
)
745 load(file_expand(cp
));
746 else if ((cp
= getenv("NAILRC")) != NULL
)
747 load(file_expand(cp
));
749 load(file_expand(MAILRC
));
750 if (getenv("NAIL_EXTRA_RC") == NULL
&& (cp
= value("NAIL_EXTRA_RC")) != NULL
)
751 load(file_expand(cp
));
753 /* Now we can set the account */
761 /* Ensure the -S and other command line options take precedence over
762 * anything that may have been placed in resource files */
763 for (i
= 0; i
< oargs_count
; ++i
) {
771 * We're finally completely setup and ready to go
775 unset_allow_undefined
= FAL0
;
777 if (options
& OPT_DEBUG
)
778 fprintf(stderr
, tr(199, "user = %s, homedir = %s\n"), myname
, homedir
);
780 if (!(options
& OPT_SENDMODE
)) {
781 exit_status
= _rcv_mode(folder
);
785 /* Now that full mailx(1)-style file expansion is possible handle the
786 * attachments which we had delayed due to this.
787 * This may use savestr(), but since we won't enter the command loop we
788 * don't need to care about that */
789 while (a_head
!= NULL
) {
790 attach
= add_attachment(attach
, a_head
->aa_file
, NULL
);
791 if (attach
!= NULL
) {
793 a_head
= a_head
->aa_next
;
796 perror(a_head
->aa_file
);
801 /* xxx exit_status = EXIT_OK; */
802 if (options
& OPT_INTERACTIVE
)
804 mail(to
, cc
, bcc
, subject
, attach
, qf
, ((options
& OPT_F_FLAG
) != 0));
805 if (options
& OPT_INTERACTIVE
)
811 /* vim:set fenc=utf-8:s-it-mode */