Do not use non-compiler-builtin alloca(3)s..
[s-mailx.git] / main.c
blobb60c92796e54950f84a2ab2a2cf21356a4bf04e6
1 /*
2 * S-nail - a mail user agent derived from Berkeley Mail.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 Steffen "Daode" Nurpmeso.
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>
51 #include "config.h"
52 #ifdef HAVE_NL_LANGINFO
53 # include <langinfo.h>
54 #endif
55 #define _MAIL_GLOBS_
56 #include "rcv.h"
57 #include "extern.h"
58 #include <sys/stat.h>
59 #include <sys/ioctl.h>
60 #include <termios.h>
61 #include <unistd.h>
62 #include <fcntl.h>
63 #ifdef HAVE_SETLOCALE
64 # include <locale.h>
65 #endif
68 * Mail -- a mail program
70 * Startup -- interface with user.
73 static sigjmp_buf hdrjmp;
75 char *progname;
76 sighandler_type dflpipe = SIG_DFL;
78 /* Add an option for sendmail(1) */
79 static void add_smopt(int argc_left, char *arg);
80 static void hdrstop(int signo);
81 static void setscreensize(int dummy);
83 static void
84 add_smopt(int argc_left, char *arg)
86 if (smopts == NULL)
87 smopts = salloc((argc_left + 1) * sizeof(char*));
88 smopts[smopts_count++] = arg;
91 int
92 main(int argc, char *argv[])
94 const char optstr[] = "A:a:Bb:c:DdEeFfHIiNnO:q:Rr:S:s:T:tu:Vv~",
95 usagestr[] =
96 "Usage:\t%s [-BDdEFintv~] [-A acc] [-a attachment]\n"
97 "\t\t[-b bcc-addr] [-c cc-addr] [-O mtaopt [-O mtaopt-arg]]\n"
98 "\t\t[-q file] [-r from-addr] [-S var[=value]]\n"
99 "\t\t[-s subject] to-addr...\n"
100 "\t%s [-BDdEeHIiNnRv~] [-A acct]\n"
101 "\t\t[-S var[=value]] [-T name] -f [file]\n"
102 "\t%s [-BDdEeiNnRv~] [-A acc] [-S var[=value]] [-u user]\n";
104 int scnt, i;
105 struct name *to, *cc, *bcc;
106 struct attachment *attach;
107 char *cp, *subject, *ef, *qf, *fromaddr, *Aflag;
108 char existonly, headersonly, sendflag, nosrc, Eflag, Fflag, tflag;
109 char volatile Nflag;
110 sighandler_type prevint;
113 * Absolutely the first thing we do is save our egid
114 * and set it to the rgid, so that we can safely run
115 * setgid. We use the sgid (saved set-gid) to allow ourselves
116 * to revert to the egid if we want (temporarily) to become
117 * priveliged.
119 effectivegid = getegid();
120 realgid = getgid();
121 if (setgid(realgid) < 0) {
122 perror("setgid");
123 exit(1);
126 starting = 1;
127 progname = strrchr(argv[0], '/');
128 if (progname != NULL)
129 progname++;
130 else
131 progname = argv[0];
133 * Set up a reasonable environment.
134 * Figure out whether we are being run interactively,
135 * start the SIGCHLD catcher, and so forth.
137 safe_signal(SIGCHLD, sigchild);
138 is_a_tty[0] = isatty(0);
139 is_a_tty[1] = isatty(1);
140 if (is_a_tty[0]) {
141 assign("interactive", "");
142 if (is_a_tty[1])
143 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
145 assign("header", "");
146 assign("save", "");
147 #ifdef HAVE_SETLOCALE
148 setlocale(LC_ALL, "");
149 mb_cur_max = MB_CUR_MAX;
150 # if defined HAVE_NL_LANGINFO && defined CODESET
151 if (value("ttycharset") == NULL && (cp = nl_langinfo(CODESET)) != NULL)
152 assign("ttycharset", cp);
153 # endif
154 # if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
155 if (mb_cur_max > 1) {
156 wchar_t wc;
157 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
158 mbtowc(&wc, "\342\202\254", 3) == 3 &&
159 wc == 0x20AC)
160 utf8 = 1;
162 # endif
163 #else
164 mb_cur_max = 1;
165 #endif
166 #ifdef HAVE_CATGETS
167 # ifdef NL_CAT_LOCALE
168 i = NL_CAT_LOCALE;
169 # else
170 i = 0;
171 # endif
172 catd = catopen(CATNAME, i);
173 #endif
174 #ifdef HAVE_ICONV
175 iconvd = (iconv_t) -1;
176 #endif
177 image = -1;
179 * Now, determine how we are being used.
180 * We successively pick off - flags.
181 * If there is anything left, it is the base of the list
182 * of users to mail to. Argp will be set to point to the
183 * first of these users.
185 scnt = 0;
186 to = cc = bcc = NULL;
187 attach = NULL;
188 subject = ef = qf = fromaddr = Aflag = NULL;
189 existonly = headersonly = sendflag = nosrc =
190 Eflag = Fflag = tflag = 0;
191 Nflag = 0;
193 while ((i = getopt(argc, argv, optstr)) != EOF) {
194 switch (i) {
195 case 'A':
196 /* Execute an account command later on */
197 Aflag = optarg;
198 break;
199 case 'a':
200 /* Get attachment filenames */
201 attach = add_attachment(attach, optarg, 0);
202 if (attach == NULL) {
203 perror(optarg);
204 exit(1);
206 sendflag = 1;
207 break;
208 case 'B':
209 /* Make 0/1 line buffered */
210 setvbuf(stdin, NULL, _IOLBF, 0);
211 setvbuf(stdout, NULL, _IOLBF, 0);
212 break;
213 case 'b':
214 /* Get Blind Carbon Copy Recipient list */
215 bcc = cat(bcc, checkaddrs(lextract(optarg,GBCC|GFULL)));
216 sendflag = 1;
217 break;
218 case 'c':
219 /* Get Carbon Copy Recipient list */
220 cc = cat(cc, checkaddrs(lextract(optarg, GCC|GFULL)));
221 sendflag = 1;
222 break;
223 case 'D':
224 assign("disconnected", "");
225 break;
226 case 'd':
227 ++debug;
228 break;
229 case 'E':
230 Eflag = 1;
231 break;
232 case 'e':
233 existonly = 1;
234 break;
235 case 'F':
236 Fflag = 1;
237 sendflag = 1;
238 break;
239 case 'f':
241 * User is specifying file to "edit" with Mail,
242 * as opposed to reading system mailbox.
243 * If no argument is given, we read his mbox file.
244 * Check for remaining arguments later.
246 ef = "&";
247 break;
248 case 'H':
249 headersonly = 1;
250 break;
251 jIflag: case 'I':
252 /* Show Newsgroups: field in header summary */
253 Iflag = 1;
254 break;
255 case 'i':
256 /* Ignore interrupts */
257 assign("ignore", "");
258 break;
259 case 'N':
260 /* Avoid initial header printing */
261 Nflag = 1;
262 unset_internal("header");
263 break;
264 case 'n':
265 /* Don't source "unspecified system start-up file" */
266 nosrc = 1;
267 break;
268 case 'O':
269 /* Additional options to pass-through to MTA */
270 add_smopt(argc - optind, skin(optarg));
271 break;
272 case 'q':
273 /* Quote file TODO drop? -Q with real quote?? what ? */
274 if (*optarg != '-')
275 qf = optarg;
276 sendflag = 1;
277 break;
278 case 'R':
279 /* Open folders read-only */
280 Rflag = 1;
281 break;
282 case 'r':
283 /* Set From address. */
284 { struct name *fa = nalloc(optarg, GFULL);
285 if (is_addr_invalid(fa, 1) ||
286 is_fileorpipe_addr(fa)) {
287 fprintf(stderr, tr(271,
288 "Invalid address argument "
289 "with -r\n"));
290 goto usage;
292 fromaddr = fa->n_fullname;
293 add_smopt(argc - optind, "-r");
294 add_smopt(-1, fa->n_name);
295 /* ..and fa goes even though it is ready :/ */
297 tildeflag = -1;
298 break;
299 case 'S':
300 /* Set variable (do so later, after RC loading..) */
301 argv[scnt++] = optarg;
302 /* TODO Also set -S directly (see TODO) */
303 { char *a[2];
304 a[0] = optarg;
305 a[1] = NULL;
306 unset_allow_undefined = 1;
307 set(a);
308 unset_allow_undefined = 0;
310 break;
311 case 's':
312 /* Subject: */
313 subject = optarg;
314 sendflag = 1;
315 break;
316 case 'T':
318 * Next argument is temp file to write which
319 * articles have been read/deleted for netnews.
321 Tflag = optarg;
322 if ((i = creat(Tflag, 0600)) < 0) {
323 perror(Tflag);
324 exit(1);
326 close(i);
327 goto jIflag;
328 case 't':
329 /* Read defined set of headers from mail to be send */
330 sendflag = 1;
331 tflag = 1;
332 break;
333 case 'u':
334 /* Set user name to pretend to be */
335 uflag = myname = optarg;
336 break;
337 case 'V':
338 puts(version);
339 exit(0);
340 /*NOTREACHED*/
341 case 'v':
342 /* Be verbose */
343 assign("verbose", "");
344 break;
345 case '~':
346 /* Enable tilde escapes even in non-interactive mode */
347 if (tildeflag == 0)
348 tildeflag = 1;
349 break;
350 case '?':
351 usage: fprintf(stderr, tr(135, usagestr),
352 progname, progname, progname);
353 exit(2);
357 if (ef != NULL) {
358 if (optind < argc) {
359 if (optind + 1 < argc) {
360 fprintf(stderr, tr(205,
361 "More than one file given with -f\n"));
362 goto usage;
364 ef = argv[optind];
366 } else {
367 for (i = optind; argv[i]; i++)
368 to = cat(to, checkaddrs(lextract(argv[i], GTO|GFULL)));
371 /* Check for inconsistent arguments */
372 if (ef != NULL && to != NULL) {
373 fprintf(stderr, tr(137,
374 "Cannot give -f and people to send to.\n"));
375 goto usage;
377 if (sendflag && ! tflag && to == NULL) {
378 fprintf(stderr, tr(138,
379 "Send options without primary recipient specified.\n"));
380 goto usage;
382 if (Rflag && to != NULL) {
383 fprintf(stderr, "The -R option is meaningless in send mode.\n");
384 goto usage;
386 if (Iflag && ef == NULL) {
387 fprintf(stderr, tr(204, "Need -f with -I.\n"));
388 goto usage;
391 tinit();
392 setscreensize(0);
393 #ifdef SIGWINCH
394 if (value("interactive"))
395 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
396 safe_signal(SIGWINCH, setscreensize);
397 #endif
398 input = stdin;
399 rcvmode = !to && !tflag;
400 spreserve();
402 if (! nosrc)
403 load(SYSCONFRC);
405 * Expand returns a savestr, but load only uses the file name
406 * for fopen, so it's safe to do this.
408 if ((cp = getenv("MAILRC")) != NULL)
409 load(file_expand(cp));
410 else if ((cp = getenv("NAILRC")) != NULL)
411 load(file_expand(cp));
412 else
413 load(file_expand("~/.mailrc"));
414 if (getenv("NAIL_EXTRA_RC") == NULL &&
415 (cp = value("NAIL_EXTRA_RC")) != NULL)
416 load(file_expand(cp));
418 /* Now we can set the account */
419 if (Aflag) {
420 char *a[2];
421 a[0] = Aflag;
422 a[1] = NULL;
423 account(a);
425 /* Override 'skipemptybody' if '-E' flag was given */
426 if (Eflag)
427 assign("skipemptybody", "");
428 /* -S arguments override rc files */
429 for (i = 0; i < scnt; ++i) {
430 char *a[2];
431 a[0] = argv[i];
432 a[1] = NULL;
433 set(a);
435 /* From address from command line overrides rc files */
436 if (fromaddr)
437 assign("from", fromaddr);
439 starting = 0;
441 if (!rcvmode) {
442 mail(to, cc, bcc, subject, attach, qf, Fflag, tflag, Eflag);
444 * why wait?
446 exit(senderr ? 1 : 0);
449 * Ok, we are reading mail.
450 * Decide whether we are editing a mailbox or reading
451 * the system mailbox, and open up the right stuff.
453 if (ef == NULL)
454 ef = "%";
455 else if (*ef == '@') {
457 * This must be treated specially to make invocation like
458 * -A imap -f @mailbox work.
460 if ((cp = value("folder")) != NULL &&
461 which_protocol(cp) == PROTO_IMAP)
462 strncpy(mailname, cp, PATHSIZE)[PATHSIZE-1] = '\0';
464 i = setfile(ef, 0);
465 if (i < 0)
466 exit(1); /* error already reported */
467 if (existonly)
468 exit(i);
469 if (headersonly) {
470 if (mb.mb_type == MB_IMAP)
471 imap_getheaders(1, msgCount);
472 for (i = 1; i <= msgCount; i++)
473 printhead(i, stdout, 0);
474 exit(exit_status);
476 callhook(mailname, 0);
477 if (i > 0 && value("emptystart") == NULL)
478 exit(1);
479 if (sigsetjmp(hdrjmp, 1) == 0) {
480 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
481 safe_signal(SIGINT, hdrstop);
482 if (Nflag == 0) {
483 if (value("quiet") == NULL)
484 printf(tr(140,
485 "%s version %s. Type ? for help.\n"),
486 value("bsdcompat") ? "Mail" : uagent,
487 version);
488 announce(1);
489 fflush(stdout);
491 safe_signal(SIGINT, prevint);
493 commands();
494 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
495 safe_signal(SIGHUP, SIG_IGN);
496 safe_signal(SIGINT, SIG_IGN);
497 safe_signal(SIGQUIT, SIG_IGN);
499 strncpy(mboxname, expand("&"), sizeof mboxname)[sizeof mboxname-1]='\0';
500 quit();
501 return exit_status;
505 * Interrupt printing of the headers.
507 /*ARGSUSED*/
508 static void
509 hdrstop(int signo)
511 (void)signo;
513 fflush(stdout);
514 fprintf(stderr, tr(141, "\nInterrupt\n"));
515 siglongjmp(hdrjmp, 1);
519 * Compute what the screen size for printing headers should be.
520 * We use the following algorithm for the height:
521 * If baud rate < 1200, use 9
522 * If baud rate = 1200, use 14
523 * If baud rate > 1200, use 24 or ws_row
524 * Width is either 80 or ws_col;
526 /*ARGSUSED*/
527 static void
528 setscreensize(int dummy)
530 struct termios tbuf;
531 #ifdef TIOCGWINSZ
532 struct winsize ws;
533 #endif
534 speed_t ospeed;
535 (void)dummy;
537 #ifdef TIOCGWINSZ
538 if (ioctl(1, TIOCGWINSZ, &ws) < 0)
539 ws.ws_col = ws.ws_row = 0;
540 #endif
541 if (tcgetattr(1, &tbuf) < 0)
542 ospeed = B9600;
543 else
544 ospeed = cfgetospeed(&tbuf);
545 if (ospeed < B1200)
546 scrnheight = 9;
547 else if (ospeed == B1200)
548 scrnheight = 14;
549 #ifdef TIOCGWINSZ
550 else if (ws.ws_row != 0)
551 scrnheight = ws.ws_row;
552 #endif
553 else
554 scrnheight = 24;
555 #ifdef TIOCGWINSZ
556 if ((realscreenheight = ws.ws_row) == 0)
557 realscreenheight = 24;
558 #endif
559 #ifdef TIOCGWINSZ
560 if ((scrnwidth = ws.ws_col) == 0)
561 #endif
562 scrnwidth = 80;