If *record* is set, avoid writing dead content twice..
[s-mailx.git] / main.c
blob49accc89e9fc1a6e53a5677a2c18436ad90d50c8
1 /*
2 * Heirloom mailx - 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 * All rights reserved.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
41 #ifndef lint
42 #ifdef DOSCCS
43 static char copyright[]
44 = "@(#) Copyright (c) 1980, 1993 The Regents of the University of California. All rights reserved.\n";
45 static char sccsid[] = "@(#)main.c 2.51 (gritter) 10/1/07";
46 #endif /* DOSCCS */
47 #endif /* not lint */
50 * Most strcpy/sprintf functions have been changed to strncpy/snprintf to
51 * correct several buffer overruns (at least one ot them was exploitable).
52 * Sat Jun 20 04:58:09 CEST 1998 Alvaro Martinez Echevarria <alvaro@lander.es>
53 * ---
54 * Note: We set egid to realgid ... and only if we need the egid we will
55 * switch back temporary. Nevertheless, I do not like seg faults.
56 * Werner Fink, <werner@suse.de>
60 #include "config.h"
61 #ifdef HAVE_NL_LANGINFO
62 #include <langinfo.h>
63 #endif /* HAVE_NL_LANGINFO */
64 #define _MAIL_GLOBS_
65 #include "rcv.h"
66 #include "extern.h"
67 #include <sys/stat.h>
68 #include <sys/ioctl.h>
69 #include <termios.h>
70 #include <unistd.h>
71 #include <fcntl.h>
72 #ifdef HAVE_SETLOCALE
73 #include <locale.h>
74 #endif /* HAVE_SETLOCALE */
77 * Mail -- a mail program
79 * Startup -- interface with user.
82 static sigjmp_buf hdrjmp;
83 char *progname;
84 sighandler_type dflpipe = SIG_DFL;
86 static void hdrstop(int signo);
87 static void setscreensize(int dummy);
89 int
90 main(int argc, char *argv[])
92 const char optstr[] = "A:BHEFINVT:RS:a:b:c:dDefh:inqr:s:tu:v~O:";
93 int i, existonly = 0, headersonly = 0, sendflag = 0;
94 struct name *to, *cc, *bcc, *smopts;
95 struct attachment *attach;
96 char *subject, *cp, *ef, *qf = NULL, *fromaddr = NULL, *Aflag = NULL;
97 char nosrc = 0;
98 int Eflag = 0, Fflag = 0, Nflag = 0, tflag = 0;
99 sighandler_type prevint;
101 (void)&Nflag;
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 * priveliged.
109 effectivegid = getegid();
110 realgid = getgid();
111 if (setgid(realgid) < 0) {
112 perror("setgid");
113 exit(1);
116 starting = 1;
117 progname = strrchr(argv[0], '/');
118 if (progname != NULL)
119 progname++;
120 else
121 progname = argv[0];
123 * Set up a reasonable environment.
124 * Figure out whether we are being run interactively,
125 * start the SIGCHLD catcher, and so forth.
127 safe_signal(SIGCHLD, sigchild);
128 is_a_tty[0] = isatty(0);
129 is_a_tty[1] = isatty(1);
130 if (is_a_tty[0]) {
131 assign("interactive", "");
132 if (is_a_tty[1])
133 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
135 assign("header", "");
136 assign("save", "");
137 #ifdef HAVE_SETLOCALE
138 setlocale(LC_CTYPE, "");
139 setlocale(LC_COLLATE, "");
140 setlocale(LC_MESSAGES, "");
141 mb_cur_max = MB_CUR_MAX;
142 #if defined (HAVE_NL_LANGINFO) && defined (CODESET)
143 if (value("ttycharset") == NULL && (cp = nl_langinfo(CODESET)) != NULL)
144 assign("ttycharset", cp);
145 #endif /* HAVE_NL_LANGINFO && CODESET */
146 #if defined (HAVE_MBTOWC) && defined (HAVE_WCTYPE_H)
147 if (mb_cur_max > 1) {
148 wchar_t wc;
149 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
150 mbtowc(&wc, "\342\202\254", 3) == 3 &&
151 wc == 0x20AC)
152 utf8 = 1;
154 #endif /* HAVE_MBTOWC && HAVE_WCTYPE_H */
155 #else /* !HAVE_SETLOCALE */
156 mb_cur_max = 1;
157 #endif /* !HAVE_SETLOCALE */
158 #ifdef HAVE_CATGETS
159 #ifdef NL_CAT_LOCALE
160 i = NL_CAT_LOCALE;
161 #else
162 i = 0;
163 #endif
164 catd = catopen(CATNAME, i);
165 #endif /* HAVE_CATGETS */
166 #ifdef HAVE_ICONV
167 iconvd = (iconv_t) -1;
168 #endif
169 image = -1;
171 * Now, determine how we are being used.
172 * We successively pick off - flags.
173 * If there is anything left, it is the base of the list
174 * of users to mail to. Argp will be set to point to the
175 * first of these users.
177 ef = NULL;
178 to = NULL;
179 cc = NULL;
180 bcc = NULL;
181 attach = NULL;
182 smopts = NULL;
183 subject = NULL;
184 while ((i = getopt(argc, argv, optstr)) != EOF) {
185 switch (i) {
186 case 'V':
187 puts(version);
188 exit(0);
189 /*NOTREACHED*/
190 case 'B':
191 setvbuf(stdin, NULL, _IOLBF, 0);
192 setvbuf(stdout, NULL, _IOLBF, 0);
193 break;
194 case 'H':
195 headersonly = 1;
196 break;
197 case 'E':
198 Eflag = 1;
199 break;
200 case 'F':
201 Fflag = 1;
202 sendflag++;
203 break;
204 case 'S': {
205 char *args[] = { NULL, NULL };
206 args[0] = optarg;
207 set(args);
209 break;
210 case 'T':
212 * Next argument is temp file to write which
213 * articles have been read/deleted for netnews.
215 Tflag = optarg;
216 if ((i = creat(Tflag, 0600)) < 0) {
217 perror(Tflag);
218 exit(1);
220 close(i);
221 /*FALLTHRU*/
222 case 'I':
224 * Show Newsgroups: field in header summary
226 Iflag = 1;
227 break;
228 case 'u':
230 * Next argument is person to pretend to be.
232 uflag = myname = optarg;
233 break;
234 case 'i':
236 * User wants to ignore interrupts.
237 * Set the variable "ignore"
239 assign("ignore", "");
240 break;
241 case 'd':
242 debug++;
243 break;
244 case 'D':
245 assign("disconnected", "");
246 break;
247 case 'e':
248 existonly++;
249 break;
250 case 's':
252 * Give a subject field for sending from
253 * non terminal
255 subject = optarg;
256 sendflag++;
257 break;
258 case 'f':
260 * User is specifying file to "edit" with Mail,
261 * as opposed to reading system mailbox.
262 * If no argument is given, we read his
263 * mbox file.
265 * Check for remaining arguments later.
267 ef = "&";
268 break;
269 case 'q':
271 * User is specifying file to quote in front of
272 * the mail to be collected.
274 if ((argv[optind]) && (argv[optind][0] != '-'))
275 qf = argv[optind++];
276 else
277 qf = NULL;
278 sendflag++;
279 break;
280 case 'n':
282 * User doesn't want to source /usr/lib/Mail.rc
284 nosrc++;
285 break;
286 case 'N':
288 * Avoid initial header printing.
290 Nflag = 1;
291 unset_internal("header");
292 break;
293 case 'v':
295 * Send mailer verbose flag
297 assign("verbose", "");
298 break;
299 case 'r':
301 * Set From address.
303 fromaddr = optarg;
304 smopts = cat(smopts, nalloc("-r", 0));
305 smopts = cat(smopts, nalloc(optarg, 0));
306 tildeflag = -1;
307 sendflag++;
308 break;
309 case 'a':
311 * Get attachment filenames
313 attach = add_attachment(attach, optarg, 0);
314 if (attach == NULL) {
315 perror(optarg);
316 exit(1);
318 sendflag++;
319 break;
320 case 'c':
322 * Get Carbon Copy Recipient list
324 cc = checkaddrs(cat(cc, extract(optarg, GCC|GFULL)));
325 sendflag++;
326 break;
327 case 'b':
329 * Get Blind Carbon Copy Recipient list
331 bcc = checkaddrs(cat(bcc, extract(optarg, GBCC|GFULL)));
332 sendflag++;
333 break;
334 case 'h':
336 * Hop count for sendmail
338 smopts = cat(smopts, nalloc("-h", 0));
339 smopts = cat(smopts, nalloc(optarg, 0));
340 sendflag++;
341 break;
342 case 'O':
344 * Additional options to pass-through to MTA
346 smopts = cat(smopts, nalloc(optarg, 0));
347 sendflag++;
348 break;
349 case '~':
350 if (tildeflag == 0)
351 tildeflag = 1;
352 break;
353 case 't':
354 sendflag = 1;
355 tflag = 1;
356 break;
357 case 'A':
358 Aflag = optarg;
359 break;
360 case 'R':
361 Rflag = 1;
362 break;
363 case '?':
364 usage:
365 fprintf(stderr, catgets(catd, CATSET, 135,
366 "Usage: %s -eiIUdEFntBDNHRV~ -T FILE -u USER -h hops -r address -s SUBJECT -a FILE -q FILE -f FILE -A ACCOUNT -b USERS -c USERS -S OPTION users\n"), progname);
367 exit(2);
370 if (ef != NULL) {
371 if (optind < argc) {
372 if (optind + 1 < argc) {
373 fprintf(stderr, catgets(catd, CATSET, 205,
374 "More than one file given with -f\n"));
375 goto usage;
377 ef = argv[optind];
379 } else {
380 for (i = optind; argv[i]; i++)
381 to = checkaddrs(cat(to, extract(argv[i], GTO|GFULL)));
384 * Check for inconsistent arguments.
386 if (ef != NULL && to != NULL) {
387 fprintf(stderr, catgets(catd, CATSET, 137,
388 "Cannot give -f and people to send to.\n"));
389 goto usage;
391 if (sendflag && !tflag && to == NULL) {
392 fprintf(stderr, catgets(catd, CATSET, 138,
393 "Send options without primary recipient specified.\n"));
394 goto usage;
396 if (Rflag && to != NULL) {
397 fprintf(stderr, "The -R option is meaningless in send mode.\n");
398 goto usage;
400 if (Iflag && ef == NULL) {
401 fprintf(stderr, catgets(catd, CATSET, 204,
402 "Need -f with -I.\n"));
403 goto usage;
405 tinit();
406 setscreensize(0);
407 #ifdef SIGWINCH
408 if (value("interactive"))
409 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
410 safe_signal(SIGWINCH, setscreensize);
411 #endif /* SIGWINCH */
412 input = stdin;
413 rcvmode = !to && !tflag;
414 spreserve();
415 if (!nosrc)
416 load(MAILRC);
418 * Expand returns a savestr, but load only uses the file name
419 * for fopen, so it's safe to do this.
421 if ((cp = getenv("MAILRC")) != NULL)
422 load(expand(cp));
423 else if ((cp = getenv("SNAILRC")) != NULL)
424 load(expand(cp));
425 else
426 load(expand("~/.mailrc"));
427 if (getenv("SNAIL_EXTRA_RC") == NULL &&
428 (cp = value("SNAIL_EXTRA_RC")) != NULL)
429 load(expand(cp));
431 * Now we can set the account.
433 if (Aflag) {
434 char *a[2];
435 a[0] = Aflag;
436 a[1] = NULL;
437 account(a);
441 * Override 'skipemptybody' if '-E' flag was given.
443 if (Eflag)
444 assign("skipemptybody", "");
446 starting = 0;
449 * From address from command line overrides rc files.
451 if (fromaddr)
452 assign("from", fromaddr);
453 if (!rcvmode) {
454 mail(to, cc, bcc, smopts, subject, attach, qf, Fflag, tflag,
455 Eflag);
457 * why wait?
459 exit(senderr ? 1 : 0);
462 * Ok, we are reading mail.
463 * Decide whether we are editing a mailbox or reading
464 * the system mailbox, and open up the right stuff.
466 if (ef == NULL)
467 ef = "%";
468 else if (*ef == '@') {
470 * This must be treated specially to make invocation like
471 * -A imap -f @mailbox work.
473 if ((cp = value("folder")) != NULL &&
474 which_protocol(cp) == PROTO_IMAP)
475 strncpy(mailname, cp, PATHSIZE)[PATHSIZE-1] = '\0';
477 i = setfile(ef, 0);
478 if (i < 0)
479 exit(1); /* error already reported */
480 if (existonly)
481 exit(i);
482 if (headersonly) {
483 if (mb.mb_type == MB_IMAP)
484 imap_getheaders(1, msgCount);
485 for (i = 1; i <= msgCount; i++)
486 printhead(i, stdout, 0);
487 exit(exit_status);
489 callhook(mailname, 0);
490 if (i > 0 && value("emptystart") == NULL)
491 exit(1);
492 if (sigsetjmp(hdrjmp, 1) == 0) {
493 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
494 safe_signal(SIGINT, hdrstop);
495 if (Nflag == 0) {
496 if (value("quiet") == NULL)
497 printf(catgets(catd, CATSET, 140,
498 "%s version %s. "
499 "Type ? for help.\n"),
500 value("bsdcompat") ? "Mail" : "S-nail",
501 version);
502 announce(1);
503 fflush(stdout);
505 safe_signal(SIGINT, prevint);
507 commands();
508 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
509 safe_signal(SIGHUP, SIG_IGN);
510 safe_signal(SIGINT, SIG_IGN);
511 safe_signal(SIGQUIT, SIG_IGN);
513 strncpy(mboxname, expand("&"), sizeof mboxname)[sizeof mboxname-1]='\0';
514 quit();
515 return exit_status;
519 * Interrupt printing of the headers.
521 /*ARGSUSED*/
522 static void
523 hdrstop(int signo)
526 fflush(stdout);
527 fprintf(stderr, catgets(catd, CATSET, 141, "\nInterrupt\n"));
528 siglongjmp(hdrjmp, 1);
532 * Compute what the screen size for printing headers should be.
533 * We use the following algorithm for the height:
534 * If baud rate < 1200, use 9
535 * If baud rate = 1200, use 14
536 * If baud rate > 1200, use 24 or ws_row
537 * Width is either 80 or ws_col;
539 /*ARGSUSED*/
540 static void
541 setscreensize(int dummy)
543 struct termios tbuf;
544 #ifdef TIOCGWINSZ
545 struct winsize ws;
546 #endif
547 speed_t ospeed;
549 #ifdef TIOCGWINSZ
550 if (ioctl(1, TIOCGWINSZ, &ws) < 0)
551 ws.ws_col = ws.ws_row = 0;
552 #endif
553 if (tcgetattr(1, &tbuf) < 0)
554 ospeed = B9600;
555 else
556 ospeed = cfgetospeed(&tbuf);
557 if (ospeed < B1200)
558 scrnheight = 9;
559 else if (ospeed == B1200)
560 scrnheight = 14;
561 #ifdef TIOCGWINSZ
562 else if (ws.ws_row != 0)
563 scrnheight = ws.ws_row;
564 #endif
565 else
566 scrnheight = 24;
567 #ifdef TIOCGWINSZ
568 if ((realscreenheight = ws.ws_row) == 0)
569 realscreenheight = 24;
570 #endif
571 #ifdef TIOCGWINSZ
572 if ((scrnwidth = ws.ws_col) == 0)
573 #endif
574 scrnwidth = 80;