Tweak (Use system getopt(3) if available.., 2012-10-05)..
[s-mailx.git] / main.c
blob1f9ac6ef00d7bfc18f98bc7073b2c9ce202f072b
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.
40 /* TODO longjmp() globbering as in cmd1.c and cmd3.c (see there)
41 * TODO Problem: Popen doesn't encapsulate all cases of open failures,
42 * TODO may leave child running if fdopen() fails! */
45 * Most strcpy/sprintf functions have been changed to strncpy/snprintf to
46 * correct several buffer overruns (at least one ot them was exploitable).
47 * Sat Jun 20 04:58:09 CEST 1998 Alvaro Martinez Echevarria <alvaro@lander.es>
48 * ---
49 * Note: We set egid to realgid ... and only if we need the egid we will
50 * switch back temporary. Nevertheless, I do not like seg faults.
51 * Werner Fink, <werner@suse.de>
55 #include "config.h"
56 #ifdef HAVE_NL_LANGINFO
57 # include <langinfo.h>
58 #endif
59 #define _MAIL_GLOBS_
60 #include "rcv.h"
61 #include "extern.h"
62 #include <sys/stat.h>
63 #include <sys/ioctl.h>
64 #include <termios.h>
65 #include <unistd.h>
66 #include <fcntl.h>
67 #ifdef HAVE_SETLOCALE
68 # include <locale.h>
69 #endif
72 * Mail -- a mail program
74 * Startup -- interface with user.
77 static sigjmp_buf hdrjmp;
79 char *progname;
80 sighandler_type dflpipe = SIG_DFL;
82 static void hdrstop(int signo);
83 static void setscreensize(int dummy);
85 int
86 main(int argc, char *argv[])
88 const char optstr[] = "A:a:Bb:c:DdEeFfHIiNnO:q:Rr:S:s:T:tu:Vv~",
89 usagestr[] =
90 "Usage:\t%s [-BDdEFintv~] [-A acc] [-a attachment]\n"
91 "\t\t[-b bcc-addr] [-c cc-addr] [-O mtaopt [-O mtaopt-arg]]\n"
92 "\t\t[-q file] [-r from-addr] [-S var[=value]]\n"
93 "\t\t[-s subject] to-addr...\n"
94 "\t%s [-BDdEeHIiNnRv~] [-A acct]\n"
95 "\t\t[-S var[=value]] [-T name] -f [file]\n"
96 "\t%s [-BDdEeiNnRv~] [-A acc] [-S var[=value]] [-u user]\n";
98 int scnt, i, existonly = 0, headersonly = 0, sendflag = 0;
99 struct name *to, *cc, *bcc, *smopts;
100 struct attachment *attach;
101 char *subject, *cp, *ef, *qf = NULL, *fromaddr = NULL, *Aflag = NULL;
102 char nosrc = 0;
103 int Eflag = 0, Fflag = 0, tflag = 0;
104 int volatile Nflag = 0;
105 sighandler_type prevint;
107 (void)&Nflag;
109 * Absolutely the first thing we do is save our egid
110 * and set it to the rgid, so that we can safely run
111 * setgid. We use the sgid (saved set-gid) to allow ourselves
112 * to revert to the egid if we want (temporarily) to become
113 * priveliged.
115 effectivegid = getegid();
116 realgid = getgid();
117 if (setgid(realgid) < 0) {
118 perror("setgid");
119 exit(1);
122 starting = 1;
123 progname = strrchr(argv[0], '/');
124 if (progname != NULL)
125 progname++;
126 else
127 progname = argv[0];
129 * Set up a reasonable environment.
130 * Figure out whether we are being run interactively,
131 * start the SIGCHLD catcher, and so forth.
133 safe_signal(SIGCHLD, sigchild);
134 is_a_tty[0] = isatty(0);
135 is_a_tty[1] = isatty(1);
136 if (is_a_tty[0]) {
137 assign("interactive", "");
138 if (is_a_tty[1])
139 safe_signal(SIGPIPE, dflpipe = SIG_IGN);
141 assign("header", "");
142 assign("save", "");
143 #ifdef HAVE_SETLOCALE
144 setlocale(LC_ALL, "");
145 mb_cur_max = MB_CUR_MAX;
146 # if defined HAVE_NL_LANGINFO && defined CODESET
147 if (value("ttycharset") == NULL && (cp = nl_langinfo(CODESET)) != NULL)
148 assign("ttycharset", cp);
149 # endif
150 # if defined HAVE_MBTOWC && defined HAVE_WCTYPE_H
151 if (mb_cur_max > 1) {
152 wchar_t wc;
153 if (mbtowc(&wc, "\303\266", 2) == 2 && wc == 0xF6 &&
154 mbtowc(&wc, "\342\202\254", 3) == 3 &&
155 wc == 0x20AC)
156 utf8 = 1;
158 # endif
159 #else
160 mb_cur_max = 1;
161 #endif
162 #ifdef HAVE_CATGETS
163 # ifdef NL_CAT_LOCALE
164 i = NL_CAT_LOCALE;
165 # else
166 i = 0;
167 # endif
168 catd = catopen(CATNAME, i);
169 #endif
170 #ifdef HAVE_ICONV
171 iconvd = (iconv_t) -1;
172 #endif
173 image = -1;
175 * Now, determine how we are being used.
176 * We successively pick off - flags.
177 * If there is anything left, it is the base of the list
178 * of users to mail to. Argp will be set to point to the
179 * first of these users.
181 ef = NULL;
182 to = NULL;
183 cc = NULL;
184 bcc = NULL;
185 attach = NULL;
186 smopts = NULL;
187 subject = NULL;
188 scnt = 0;
189 while ((i = getopt(argc, argv, optstr)) != EOF) {
190 switch (i) {
191 case 'A':
192 /* Execute an account command later on */
193 Aflag = optarg;
194 break;
195 case 'a':
196 /* Get attachment filenames */
197 attach = add_attachment(attach, optarg, 0);
198 if (attach == NULL) {
199 perror(optarg);
200 exit(1);
202 sendflag++;
203 break;
204 case 'B':
205 /* Make 0/1 line buffered */
206 setvbuf(stdin, NULL, _IOLBF, 0);
207 setvbuf(stdout, NULL, _IOLBF, 0);
208 break;
209 case 'b':
210 /* Get Blind Carbon Copy Recipient list */
211 bcc = cat(bcc, checkaddrs(lextract(optarg,GBCC|GFULL)));
212 sendflag++;
213 break;
214 case 'c':
215 /* Get Carbon Copy Recipient list */
216 cc = cat(cc, checkaddrs(lextract(optarg, GCC|GFULL)));
217 sendflag++;
218 break;
219 case 'D':
220 assign("disconnected", "");
221 break;
222 case 'd':
223 debug++;
224 break;
225 case 'E':
226 Eflag = 1;
227 break;
228 case 'e':
229 existonly++;
230 break;
231 case 'F':
232 Fflag = 1;
233 sendflag++;
234 break;
235 case 'f':
237 * User is specifying file to "edit" with Mail,
238 * as opposed to reading system mailbox.
239 * If no argument is given, we read his mbox file.
240 * Check for remaining arguments later.
242 ef = "&";
243 break;
244 case 'H':
245 headersonly = 1;
246 break;
247 jIflag: case 'I':
248 /* Show Newsgroups: field in header summary */
249 Iflag = 1;
250 break;
252 case 'i':
253 /* Ignore interrupts */
254 assign("ignore", "");
255 break;
256 case 'N':
257 /* Avoid initial header printing */
258 Nflag = 1;
259 unset_internal("header");
260 break;
261 case 'n':
262 /* Don't source "unspecified system start-up file" */
263 ++nosrc;
264 break;
265 case 'O':
266 /* Additional options to pass-through to MTA */
267 smopts = cat(smopts, nalloc(optarg, 0));
268 sendflag++;
269 break;
270 case 'q':
271 /* Quote file TODO drop? -Q with real quote?? what ? */
272 if (*optarg != '-')
273 qf = optarg;
274 sendflag++;
275 break;
276 case 'R':
277 /* Open folders read-only */
278 Rflag = 1;
279 break;
280 case 'r':
281 /* Set From address. */
282 i = count(smopts);
283 fromaddr = optarg;
284 smopts = cat(smopts, nalloc("-r", 0));
285 smopts = cat(smopts, lextract(optarg, GFULL));
286 if (count(smopts) != i + 2) {
287 fprintf(stderr, tr(271,
288 "More than one address "
289 "given with -r\n"));
290 goto usage;
292 tildeflag = -1;
293 sendflag++;
294 break;
295 case 'S':
296 /* Set variable (do so later, after RC loading..) */
297 argv[scnt++] = optarg;
298 break;
299 case 's':
300 /* Subject: */
301 subject = optarg;
302 sendflag++;
303 break;
304 case 'T':
306 * Next argument is temp file to write which
307 * articles have been read/deleted for netnews.
309 Tflag = optarg;
310 if ((i = creat(Tflag, 0600)) < 0) {
311 perror(Tflag);
312 exit(1);
314 close(i);
315 goto jIflag;
316 case 't':
317 /* Read defined set of headers from mail to be send */
318 sendflag = 1;
319 tflag = 1;
320 break;
321 case 'u':
322 /* Set user name to pretend to be */
323 uflag = myname = optarg;
324 break;
325 case 'V':
326 puts(version);
327 exit(0);
328 /*NOTREACHED*/
329 case 'v':
330 /* Be verbose */
331 assign("verbose", "");
332 break;
333 case '~':
334 /* Enable tilde escapes even in non-interactive mode */
335 if (tildeflag == 0)
336 tildeflag = 1;
337 break;
338 case '?':
339 usage: fprintf(stderr, tr(135, usagestr),
340 progname, progname, progname);
341 exit(2);
345 if (ef != NULL) {
346 if (optind < argc) {
347 if (optind + 1 < argc) {
348 fprintf(stderr, tr(205,
349 "More than one file given with -f\n"));
350 goto usage;
352 ef = argv[optind];
354 } else {
355 for (i = optind; argv[i]; i++)
356 to = cat(to, checkaddrs(lextract(argv[i], GTO|GFULL)));
359 /* Check for inconsistent arguments */
360 if (ef != NULL && to != NULL) {
361 fprintf(stderr, tr(137,
362 "Cannot give -f and people to send to.\n"));
363 goto usage;
365 if (sendflag && !tflag && to == NULL) {
366 fprintf(stderr, tr(138,
367 "Send options without primary recipient specified.\n"));
368 goto usage;
370 if (Rflag && to != NULL) {
371 fprintf(stderr, "The -R option is meaningless in send mode.\n");
372 goto usage;
374 if (Iflag && ef == NULL) {
375 fprintf(stderr, tr(204, "Need -f with -I.\n"));
376 goto usage;
379 tinit();
380 setscreensize(0);
381 #ifdef SIGWINCH
382 if (value("interactive"))
383 if (safe_signal(SIGWINCH, SIG_IGN) != SIG_IGN)
384 safe_signal(SIGWINCH, setscreensize);
385 #endif
386 input = stdin;
387 rcvmode = !to && !tflag;
388 spreserve();
390 if (! nosrc)
391 load(SYSCONFRC);
393 * Expand returns a savestr, but load only uses the file name
394 * for fopen, so it's safe to do this.
396 if ((cp = getenv("MAILRC")) != NULL)
397 load(expand(cp));
398 else if ((cp = getenv("NAILRC")) != NULL)
399 load(expand(cp));
400 else
401 load(expand("~/.mailrc"));
402 if (getenv("NAIL_EXTRA_RC") == NULL &&
403 (cp = value("NAIL_EXTRA_RC")) != NULL)
404 load(expand(cp));
407 * Now we can set the account.
409 if (Aflag) {
410 char *a[2];
411 a[0] = Aflag;
412 a[1] = NULL;
413 account(a);
416 * Override 'skipemptybody' if '-E' flag was given.
418 if (Eflag)
419 assign("skipemptybody", "");
421 * -S arguments override rc files.
423 for (i = 0; i < scnt; ++i) {
424 char *a[2];
425 a[0] = argv[i];
426 a[1] = NULL;
427 set(a);
430 starting = 0;
433 * From address from command line overrides rc files.
435 if (fromaddr)
436 assign("from", fromaddr);
437 if (!rcvmode) {
438 mail(to, cc, bcc, smopts, subject, attach, qf, Fflag, tflag,
439 Eflag);
441 * why wait?
443 exit(senderr ? 1 : 0);
446 * Ok, we are reading mail.
447 * Decide whether we are editing a mailbox or reading
448 * the system mailbox, and open up the right stuff.
450 if (ef == NULL)
451 ef = "%";
452 else if (*ef == '@') {
454 * This must be treated specially to make invocation like
455 * -A imap -f @mailbox work.
457 if ((cp = value("folder")) != NULL &&
458 which_protocol(cp) == PROTO_IMAP)
459 strncpy(mailname, cp, PATHSIZE)[PATHSIZE-1] = '\0';
461 i = setfile(ef, 0);
462 if (i < 0)
463 exit(1); /* error already reported */
464 if (existonly)
465 exit(i);
466 if (headersonly) {
467 if (mb.mb_type == MB_IMAP)
468 imap_getheaders(1, msgCount);
469 for (i = 1; i <= msgCount; i++)
470 printhead(i, stdout, 0);
471 exit(exit_status);
473 callhook(mailname, 0);
474 if (i > 0 && value("emptystart") == NULL)
475 exit(1);
476 if (sigsetjmp(hdrjmp, 1) == 0) {
477 if ((prevint = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN)
478 safe_signal(SIGINT, hdrstop);
479 if (Nflag == 0) {
480 if (value("quiet") == NULL)
481 printf(tr(140,
482 "%s version %s. Type ? for help.\n"),
483 value("bsdcompat") ? "Mail" : uagent,
484 version);
485 announce(1);
486 fflush(stdout);
488 safe_signal(SIGINT, prevint);
490 commands();
491 if (mb.mb_type == MB_FILE || mb.mb_type == MB_MAILDIR) {
492 safe_signal(SIGHUP, SIG_IGN);
493 safe_signal(SIGINT, SIG_IGN);
494 safe_signal(SIGQUIT, SIG_IGN);
496 strncpy(mboxname, expand("&"), sizeof mboxname)[sizeof mboxname-1]='\0';
497 quit();
498 return exit_status;
502 * Interrupt printing of the headers.
504 /*ARGSUSED*/
505 static void
506 hdrstop(int signo)
508 (void)signo;
510 fflush(stdout);
511 fprintf(stderr, tr(141, "\nInterrupt\n"));
512 siglongjmp(hdrjmp, 1);
516 * Compute what the screen size for printing headers should be.
517 * We use the following algorithm for the height:
518 * If baud rate < 1200, use 9
519 * If baud rate = 1200, use 14
520 * If baud rate > 1200, use 24 or ws_row
521 * Width is either 80 or ws_col;
523 /*ARGSUSED*/
524 static void
525 setscreensize(int dummy)
527 struct termios tbuf;
528 #ifdef TIOCGWINSZ
529 struct winsize ws;
530 #endif
531 speed_t ospeed;
532 (void)dummy;
534 #ifdef TIOCGWINSZ
535 if (ioctl(1, TIOCGWINSZ, &ws) < 0)
536 ws.ws_col = ws.ws_row = 0;
537 #endif
538 if (tcgetattr(1, &tbuf) < 0)
539 ospeed = B9600;
540 else
541 ospeed = cfgetospeed(&tbuf);
542 if (ospeed < B1200)
543 scrnheight = 9;
544 else if (ospeed == B1200)
545 scrnheight = 14;
546 #ifdef TIOCGWINSZ
547 else if (ws.ws_row != 0)
548 scrnheight = ws.ws_row;
549 #endif
550 else
551 scrnheight = 24;
552 #ifdef TIOCGWINSZ
553 if ((realscreenheight = ws.ws_row) == 0)
554 realscreenheight = 24;
555 #endif
556 #ifdef TIOCGWINSZ
557 if ((scrnwidth = ws.ws_col) == 0)
558 #endif
559 scrnwidth = 80;