Fix *editalong* with new [okeys] interface (introduced reverso)
[s-mailx.git] / fio.c
bloba3c00cfda309dd2925473a1d60ad98a961ab8e66
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ File I/O.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2014 Steffen "Daode" Nurpmeso <sdaoden@users.sf.net>.
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 #ifndef HAVE_AMALGAMATION
41 # include "nail.h"
42 #endif
44 #include <sys/wait.h>
46 #include <fcntl.h>
48 #ifdef HAVE_WORDEXP
49 # include <wordexp.h>
50 #endif
52 #ifdef HAVE_SOCKETS
53 # include <sys/socket.h>
55 # include <netdb.h>
57 # include <netinet/in.h>
59 # ifdef HAVE_ARPA_INET_H
60 # include <arpa/inet.h>
61 # endif
62 #endif
64 #ifdef HAVE_OPENSSL
65 # include <openssl/err.h>
66 # include <openssl/rand.h>
67 # include <openssl/ssl.h>
68 # include <openssl/x509v3.h>
69 # include <openssl/x509.h>
70 #endif
72 struct {
73 FILE *s_file; /* File we were in. */
74 enum condition s_cond; /* Saved state of conditionals */
75 int s_loading; /* Loading .mailrc, etc. */
76 #define SSTACK 20
77 } _sstack[SSTACK];
78 static size_t _ssp; /* Top of file stack */
79 static FILE * _input;
81 /* Locate the user's mailbox file (where new, unread mail is queued) */
82 static void _findmail(char *buf, size_t bufsize, char const *user,
83 bool_t force);
85 /* Perform shell meta character expansion */
86 static char * _globname(char const *name, enum fexp_mode fexpm);
88 /* *line* is a buffer with the result of fgets().
89 * Returns the first newline or the last character read */
90 static size_t _length_of_line(const char *line, size_t linesize);
92 /* Read a line, one character at a time */
93 static char * _fgetline_byone(char **line, size_t *linesize, size_t *llen,
94 FILE *fp, int appendnl, size_t n SMALLOC_DEBUG_ARGS);
96 static void makemessage(void);
97 static void _fio_append(struct message *mp);
98 static enum okay get_header(struct message *mp);
100 static void
101 _findmail(char *buf, size_t bufsize, char const *user, bool_t force)
103 char *cp;
105 if (strcmp(user, myname) == 0 && ! force &&
106 (cp = ok_vlook(folder)) != NULL) {
107 switch (which_protocol(cp)) {
108 case PROTO_IMAP:
109 if (strcmp(cp, protbase(cp)) != 0)
110 goto jcopy;
111 snprintf(buf, bufsize, "%s/INBOX", cp);
112 goto jleave;
113 default:
114 break;
118 if (force || (cp = ok_vlook(MAIL)) == NULL)
119 snprintf(buf, bufsize, "%s/%s", MAILSPOOL, user);
120 else {
121 jcopy:
122 n_strlcpy(buf, cp, bufsize);
124 jleave:
128 static char *
129 _globname(char const *name, enum fexp_mode fexpm)
131 #ifdef HAVE_WORDEXP
132 wordexp_t we;
133 char *cp = NULL;
134 sigset_t nset;
135 int i;
137 /* Mac OS X Snow Leopard and Linux don't init fields on error, causing
138 * SIGSEGV in wordfree(3); so let's just always zero it ourselfs */
139 memset(&we, 0, sizeof we);
141 /* Some systems (notably Open UNIX 8.0.0) fork a shell for wordexp()
142 * and wait, which will fail if our SIGCHLD handler is active */
143 sigemptyset(&nset);
144 sigaddset(&nset, SIGCHLD);
145 sigprocmask(SIG_BLOCK, &nset, NULL);
146 i = wordexp(name, &we, 0);
147 sigprocmask(SIG_UNBLOCK, &nset, NULL);
149 switch (i) {
150 case 0:
151 break;
152 case WRDE_NOSPACE:
153 if (!(fexpm & FEXP_SILENT))
154 fprintf(stderr,
155 tr(83, "\"%s\": Expansion buffer overflow.\n"),
156 name);
157 goto jleave;
158 case WRDE_BADCHAR:
159 case WRDE_SYNTAX:
160 default:
161 if (!(fexpm & FEXP_SILENT))
162 fprintf(stderr, tr(242, "Syntax error in \"%s\"\n"),
163 name);
164 goto jleave;
167 switch (we.we_wordc) {
168 case 1:
169 cp = savestr(we.we_wordv[0]);
170 break;
171 case 0:
172 if (!(fexpm & FEXP_SILENT))
173 fprintf(stderr, tr(82, "\"%s\": No match.\n"), name);
174 break;
175 default:
176 if (fexpm & FEXP_MULTIOK) {
177 size_t j, l;
179 for (l = 0, j = 0; j < we.we_wordc; ++j)
180 l += strlen(we.we_wordv[j]) + 1;
181 ++l;
182 cp = salloc(l);
183 for (l = 0, j = 0; j < we.we_wordc; ++j) {
184 size_t x = strlen(we.we_wordv[j]);
185 memcpy(cp + l, we.we_wordv[j], x);
186 l += x;
187 cp[l++] = ' ';
189 cp[l] = '\0';
190 } else if (!(fexpm & FEXP_SILENT))
191 fprintf(stderr, tr(84, "\"%s\": Ambiguous.\n"), name);
192 break;
194 jleave:
195 wordfree(&we);
196 return cp;
198 #else /* !HAVE_WORDEXP */
199 struct stat sbuf;
200 char xname[MAXPATHLEN], cmdbuf[MAXPATHLEN], /* also used for files */
201 *cp, *shellp;
202 int pivec[2], pid, l, waits;
204 if (pipe(pivec) < 0) {
205 perror("pipe");
206 return NULL;
208 snprintf(cmdbuf, sizeof cmdbuf, "echo %s", name);
209 if ((shellp = ok_vlook(SHELL)) == NULL)
210 shellp = UNCONST(XSHELL);
211 pid = start_command(shellp, 0, -1, pivec[1], "-c", cmdbuf, NULL);
212 if (pid < 0) {
213 close(pivec[0]);
214 close(pivec[1]);
215 return NULL;
217 close(pivec[1]);
219 again:
220 l = read(pivec[0], xname, sizeof xname);
221 if (l < 0) {
222 if (errno == EINTR)
223 goto again;
224 perror("read");
225 close(pivec[0]);
226 return NULL;
228 close(pivec[0]);
229 if (!wait_child(pid, &waits) && WTERMSIG(waits) != SIGPIPE) {
230 if (!(fexpm & FEXP_SILENT))
231 fprintf(stderr, tr(81, "\"%s\": Expansion failed.\n"),
232 name);
233 return NULL;
235 if (l == 0) {
236 if (!(fexpm & FEXP_SILENT))
237 fprintf(stderr, tr(82, "\"%s\": No match.\n"), name);
238 return NULL;
240 if (l == sizeof xname) {
241 if (!(fexpm & FEXP_SILENT))
242 fprintf(stderr,
243 tr(83, "\"%s\": Expansion buffer overflow.\n"),
244 name);
245 return NULL;
247 xname[l] = 0;
248 for (cp = &xname[l - 1]; *cp == '\n' && cp > xname; --cp)
250 cp[1] = '\0';
251 if (!(fexpm & FEXP_MULTIOK) && strchr(xname, ' ') &&
252 stat(xname, &sbuf) < 0) {
253 if (!(fexpm & FEXP_SILENT))
254 fprintf(stderr, tr(84, "\"%s\": Ambiguous.\n"), name);
255 return NULL;
257 return savestr(xname);
258 #endif /* !HAVE_WORDEXP */
262 * line is a buffer with the result of fgets(). Returns the first
263 * newline or the last character read.
265 static size_t
266 _length_of_line(const char *line, size_t linesize)
268 size_t i;
270 /* Last character is always '\0' and was added by fgets() */
271 for (--linesize, i = 0; i < linesize; i++)
272 if (line[i] == '\n')
273 break;
274 return (i < linesize) ? i + 1 : linesize;
277 static char *
278 _fgetline_byone(char **line, size_t *linesize, size_t *llen,
279 FILE *fp, int appendnl, size_t n SMALLOC_DEBUG_ARGS)
281 int c;
283 assert(*linesize == 0 || *line != NULL);
284 for (;;) {
285 if (*linesize <= LINESIZE || n >= *linesize - 128) {
286 *linesize += ((*line == NULL)
287 ? LINESIZE + n + 1 : 256);
288 *line = (srealloc)(*line, *linesize
289 SMALLOC_DEBUG_ARGSCALL);
291 c = getc(fp);
292 if (c != EOF) {
293 (*line)[n++] = c;
294 (*line)[n] = '\0';
295 if (c == '\n')
296 break;
297 } else {
298 if (n > 0) {
299 if (appendnl) {
300 (*line)[n++] = '\n';
301 (*line)[n] = '\0';
303 break;
304 } else
305 return NULL;
308 if (llen)
309 *llen = n;
310 return *line;
313 FL char *
314 (fgetline)(char **line, size_t *linesize, size_t *cnt, size_t *llen,
315 FILE *fp, int appendnl SMALLOC_DEBUG_ARGS)
317 size_t i_llen, sz;
319 if (cnt == NULL)
321 * If we have no count, we cannot determine where the
322 * characters returned by fgets() end if there was no
323 * newline. We have to read one character at one.
325 return _fgetline_byone(line, linesize, llen, fp, appendnl, 0
326 SMALLOC_DEBUG_ARGSCALL);
327 if (*line == NULL || *linesize < LINESIZE)
328 *line = (srealloc)(*line, *linesize = LINESIZE
329 SMALLOC_DEBUG_ARGSCALL);
330 sz = *linesize <= *cnt ? *linesize : *cnt + 1;
331 if (sz <= 1 || fgets(*line, sz, fp) == NULL)
333 * Leave llen untouched; it is used to determine whether
334 * the last line was \n-terminated in some callers.
336 return NULL;
337 i_llen = _length_of_line(*line, sz);
338 *cnt -= i_llen;
339 while ((*line)[i_llen - 1] != '\n') {
340 *line = (srealloc)(*line, *linesize += 256
341 SMALLOC_DEBUG_ARGSCALL);
342 sz = *linesize - i_llen;
343 sz = (sz <= *cnt ? sz : *cnt + 1);
344 if (sz <= 1 || fgets(&(*line)[i_llen], sz, fp) == NULL) {
345 if (appendnl) {
346 (*line)[i_llen++] = '\n';
347 (*line)[i_llen] = '\0';
349 break;
351 sz = _length_of_line(&(*line)[i_llen], sz);
352 i_llen += sz;
353 *cnt -= sz;
355 if (llen)
356 *llen = i_llen;
357 return *line;
360 FL int
361 (readline_restart)(FILE *ibuf, char **linebuf, size_t *linesize, size_t n
362 SMALLOC_DEBUG_ARGS)
364 /* TODO readline_restart(): always *appends* LF just to strip it again;
365 * TODO should be configurable just as for fgetline(); ..or whatevr.. */
366 long sz;
368 clearerr(ibuf);
370 * Interrupts will cause trouble if we are inside a stdio call. As
371 * this is only relevant if input comes from a terminal, we can simply
372 * bypass it by read() then.
374 if (fileno(ibuf) == 0 && (options & OPT_TTYIN)) {
375 assert(*linesize == 0 || *linebuf != NULL);
376 for (;;) {
377 if (*linesize <= LINESIZE || n >= *linesize - 128) {
378 *linesize += ((*linebuf == NULL)
379 ? LINESIZE + n + 1 : 256);
380 *linebuf = (srealloc)(*linebuf, *linesize
381 SMALLOC_DEBUG_ARGSCALL);
383 again:
384 sz = read(0, *linebuf + n, *linesize - n - 1);
385 if (sz > 0) {
386 n += sz;
387 (*linebuf)[n] = '\0';
388 if (n > 0 && (*linebuf)[n - 1] == '\n')
389 break;
390 } else {
391 if (sz < 0 && errno == EINTR)
392 goto again;
393 if (n > 0) {
394 if ((*linebuf)[n - 1] != '\n') {
395 (*linebuf)[n++] = '\n';
396 (*linebuf)[n] = '\0';
398 break;
399 } else
400 return -1;
403 } else {
405 * Not reading from standard input or standard input not
406 * a terminal. We read one char at a time as it is the
407 * only way to get lines with embedded NUL characters in
408 * standard stdio.
410 if (_fgetline_byone(linebuf, linesize, &n, ibuf, 1, n
411 SMALLOC_DEBUG_ARGSCALL) == NULL)
412 return -1;
414 if (n > 0 && (*linebuf)[n - 1] == '\n')
415 (*linebuf)[--n] = '\0';
416 return n;
419 FL int
420 (readline_input)(enum lned_mode lned, char const *prompt, char **linebuf,
421 size_t *linesize SMALLOC_DEBUG_ARGS)
423 FILE *ifile = (_input != NULL) ? _input : stdin;
424 bool_t doprompt, dotty;
425 int n;
427 doprompt = (!sourcing && (options & OPT_INTERACTIVE));
428 dotty = (doprompt && !ok_blook(line_editor_disable));
429 if (!doprompt)
430 prompt = NULL;
431 else if (prompt == NULL)
432 prompt = getprompt();
434 for (n = 0;;) {
435 if (dotty) {
436 assert(ifile == stdin);
437 n = (tty_readline)(prompt, linebuf, linesize, n
438 SMALLOC_DEBUG_ARGSCALL);
439 } else {
440 if (prompt != NULL && *prompt != '\0') {
441 fputs(prompt, stdout);
442 fflush(stdout);
444 n = (readline_restart)(ifile, linebuf, linesize, n
445 SMALLOC_DEBUG_ARGSCALL);
447 if (n <= 0)
448 break;
450 * POSIX says:
451 * An unquoted <backslash> at the end of a command line
452 * shall be discarded and the next line shall continue the
453 * command.
455 if ((lned & LNED_LF_ESC) && (*linebuf)[n - 1] == '\\') {
456 (*linebuf)[--n] = '\0';
457 if (prompt != NULL && *prompt != '\0')
458 prompt = ".. "; /* XXX PS2 .. */
459 continue;
461 if (dotty && (lned & LNED_HIST_ADD))
462 tty_addhist(*linebuf);
463 break;
465 return n;
468 FL char *
469 readstr_input(char const *prompt, char const *string) /* FIXME SIGS<->leaks */
471 /* TODO readstr_input(): linebuf pool */
472 size_t linesize = 0, slen;
473 char *linebuf = NULL, *rv = NULL;
474 bool_t doprompt, dotty;
476 doprompt = (!sourcing && (options & OPT_INTERACTIVE));
477 dotty = (doprompt && !ok_blook(line_editor_disable));
478 if (!doprompt)
479 prompt = NULL;
480 else if (prompt == NULL)
481 prompt = getprompt();
483 /* If STDIN is not a terminal, simply read from it */
484 if (dotty) {
485 slen = (string != NULL) ? strlen(string) : 0;
486 if (slen) {
487 linesize = slen + LINESIZE + 1;
488 linebuf = smalloc(linesize);
489 if (slen)
490 memcpy(linebuf, string, slen + 1);
492 if (tty_readline(prompt, &linebuf, &linesize, slen) >= 0)
493 rv = linebuf;
494 } else {
495 if (prompt != NULL && *prompt != '\0') {
496 fputs(prompt, stdout);
497 fflush(stdout);
499 linesize = slen = 0;
500 linebuf = NULL;
501 if (readline_restart(stdin, &linebuf, &linesize, slen) >= 0)
502 rv = linebuf;
505 if (rv != NULL)
506 rv = (*rv == '\0') ? NULL : savestr(rv);
507 if (linebuf != NULL)
508 free(linebuf);
509 return rv;
512 * Set up the input pointers while copying the mail file into /tmp.
514 FL void
515 setptr(FILE *ibuf, off_t offset)
517 int c;
518 char *cp, *linebuf = NULL;
519 char const *cp2;
520 struct message this;
521 int maybe, inhead, thiscnt;
522 size_t linesize = 0, filesize, cnt;
524 maybe = 1;
525 inhead = 0;
526 thiscnt = 0;
527 memset(&this, 0, sizeof this);
528 this.m_flag = MUSED|MNEW|MNEWEST;
529 filesize = mailsize - offset;
530 offset = ftell(mb.mb_otf);
531 for (;;) {
532 if (fgetline(&linebuf, &linesize, &filesize, &cnt, ibuf, 0)
533 == NULL) {
534 this.m_xsize = this.m_size;
535 this.m_xlines = this.m_lines;
536 this.m_have = HAVE_HEADER|HAVE_BODY;
537 if (thiscnt > 0)
538 _fio_append(&this);
539 makemessage();
540 if (linebuf)
541 free(linebuf);
542 return;
544 #ifdef notdef
545 if (linebuf[0] == '\0')
546 linebuf[0] = '.';
547 #endif
548 /* XXX Convert CRLF to LF; this should be rethought in that
549 * XXX CRLF input should possibly end as CRLF output? */
550 if (cnt >= 2 && linebuf[cnt - 1] == '\n' &&
551 linebuf[cnt - 2] == '\r')
552 linebuf[--cnt - 1] = '\n';
553 fwrite(linebuf, sizeof *linebuf, cnt, mb.mb_otf);
554 if (ferror(mb.mb_otf)) {
555 perror("/tmp");
556 exit(1);
558 if (linebuf[cnt - 1] == '\n')
559 linebuf[cnt - 1] = '\0';
560 if (maybe && linebuf[0] == 'F' && is_head(linebuf, cnt)) {
561 /* TODO
562 * TODO char date[FROM_DATEBUF];
563 * TODO extract_date_from_from_(linebuf, cnt, date);
564 * TODO this.m_time = 10000;
566 this.m_xsize = this.m_size;
567 this.m_xlines = this.m_lines;
568 this.m_have = HAVE_HEADER|HAVE_BODY;
569 if (thiscnt++ > 0)
570 _fio_append(&this);
571 msgCount++;
572 this.m_flag = MUSED|MNEW|MNEWEST;
573 this.m_size = 0;
574 this.m_lines = 0;
575 this.m_block = mailx_blockof(offset);
576 this.m_offset = mailx_offsetof(offset);
577 inhead = 1;
578 } else if (linebuf[0] == 0) {
579 inhead = 0;
580 } else if (inhead) {
581 for (cp = linebuf, cp2 = "status";; cp++) {
582 if ((c = *cp2++) == 0) {
583 while (c = *cp++, whitechar(c));
584 if (cp[-1] != ':')
585 break;
586 while ((c = *cp++) != '\0')
587 if (c == 'R')
588 this.m_flag |= MREAD;
589 else if (c == 'O')
590 this.m_flag &= ~MNEW;
591 break;
593 if (*cp != c && *cp != upperconv(c))
594 break;
596 for (cp = linebuf, cp2 = "x-status";; cp++) {
597 if ((c = *cp2++) == 0) {
598 while (c = *cp++, whitechar(c));
599 if (cp[-1] != ':')
600 break;
601 while ((c = *cp++) != '\0')
602 if (c == 'F')
603 this.m_flag |= MFLAGGED;
604 else if (c == 'A')
605 this.m_flag|=MANSWERED;
606 else if (c == 'T')
607 this.m_flag|=MDRAFTED;
608 break;
610 if (*cp != c && *cp != upperconv(c))
611 break;
614 offset += cnt;
615 this.m_size += cnt;
616 this.m_lines++;
617 maybe = linebuf[0] == 0;
619 /*NOTREACHED*/
623 * Drop the passed line onto the passed output buffer.
624 * If a write error occurs, return -1, else the count of
625 * characters written, including the newline.
627 FL int
628 putline(FILE *obuf, char *linebuf, size_t cnt)
630 fwrite(linebuf, sizeof *linebuf, cnt, obuf);
631 putc('\n', obuf);
632 if (ferror(obuf))
633 return (-1);
634 return (cnt + 1);
638 * Return a file buffer all ready to read up the
639 * passed message pointer.
641 FL FILE *
642 setinput(struct mailbox *mp, struct message *m, enum needspec need)
644 enum okay ok = STOP;
646 switch (need) {
647 case NEED_HEADER:
648 if (m->m_have & HAVE_HEADER)
649 ok = OKAY;
650 else
651 ok = get_header(m);
652 break;
653 case NEED_BODY:
654 if (m->m_have & HAVE_BODY)
655 ok = OKAY;
656 else
657 ok = get_body(m);
658 break;
659 case NEED_UNSPEC:
660 ok = OKAY;
661 break;
663 if (ok != OKAY)
664 return NULL;
665 fflush(mp->mb_otf);
666 if (fseek(mp->mb_itf, (long)mailx_positionof(m->m_block,
667 m->m_offset), SEEK_SET) < 0) {
668 perror("fseek");
669 panic(tr(77, "temporary file seek"));
671 return (mp->mb_itf);
674 FL struct message *
675 setdot(struct message *mp)
677 if (dot != mp) {
678 prevdot = dot;
679 did_print_dot = FAL0;
681 dot = mp;
682 uncollapse1(dot, 0);
683 return dot;
687 * Take the data out of the passed ghost file and toss it into
688 * a dynamically allocated message structure.
690 static void
691 makemessage(void)
693 if (msgCount == 0)
694 _fio_append(NULL);
695 setdot(message);
696 message[msgCount].m_size = 0;
697 message[msgCount].m_lines = 0;
701 * Append the passed message descriptor onto the message structure.
703 static void
704 _fio_append(struct message *mp)
706 if (msgCount + 1 >= msgspace)
707 message = srealloc(message, (msgspace += 64) * sizeof *message);
708 if (msgCount > 0)
709 message[msgCount - 1] = *mp;
713 * Delete a file, but only if the file is a plain file.
715 FL int
716 rm(char *name) /* TODO TOCTOU; but i'm out of ideas today */
718 struct stat sb;
719 int ret = -1;
721 if (stat(name, &sb) < 0)
723 else if (! S_ISREG(sb.st_mode))
724 errno = EISDIR;
725 else
726 ret = unlink(name);
727 return ret;
731 * Determine the size of the file possessed by
732 * the passed buffer.
734 FL off_t
735 fsize(FILE *iob)
737 struct stat sbuf;
739 if (fstat(fileno(iob), &sbuf) < 0)
740 return 0;
741 return sbuf.st_size;
744 FL char *
745 fexpand(char const *name, enum fexp_mode fexpm)
747 char cbuf[MAXPATHLEN], *res;
748 struct str s;
749 struct shortcut *sh;
750 bool_t dyn;
753 * The order of evaluation is "%" and "#" expand into constants.
754 * "&" can expand into "+". "+" can expand into shell meta characters.
755 * Shell meta characters expand into constants.
756 * This way, we make no recursive expansion.
758 res = UNCONST(name);
759 if (! (fexpm & FEXP_NSHORTCUT) && (sh = get_shortcut(res)) != NULL)
760 res = sh->sh_long;
762 if (fexpm & FEXP_SHELL) {
763 dyn = FAL0;
764 goto jshell;
766 jnext:
767 dyn = FAL0;
768 switch (*res) {
769 case '%':
770 if (res[1] == ':' && res[2] != '\0') {
771 res = &res[2];
772 goto jnext;
774 _findmail(cbuf, sizeof cbuf,
775 (res[1] != '\0') ? res + 1 : myname,
776 (res[1] != '\0' || (options & OPT_u_FLAG)));
777 res = cbuf;
778 goto jislocal;
779 case '#':
780 if (res[1] != '\0')
781 break;
782 if (prevfile[0] == '\0') {
783 fprintf(stderr, tr(80, "No previous file\n"));
784 res = NULL;
785 goto jleave;
787 res = prevfile;
788 goto jislocal;
789 case '&':
790 if (res[1] == '\0') {
791 if ((res = ok_vlook(MBOX)) == NULL)
792 res = UNCONST("~/mbox");
793 else if (res[0] != '&' || res[1] != '\0')
794 goto jnext;
796 break;
799 if (res[0] == '@' && which_protocol(mailname) == PROTO_IMAP) {
800 res = str_concat_csvl(&s,
801 protbase(mailname), "/", res + 1, NULL)->s;
802 dyn = TRU1;
805 if (res[0] == '+' && getfold(cbuf, sizeof cbuf)) {
806 size_t i = strlen(cbuf);
808 res = str_concat_csvl(&s, cbuf,
809 (i > 0 && cbuf[i - 1] == '/') ? "" : "/",
810 res + 1, NULL)->s;
811 dyn = TRU1;
813 if (res[0] == '%' && res[1] == ':') {
814 res += 2;
815 goto jnext;
819 /* Catch the most common shell meta character */
820 jshell:
821 if (res[0] == '~' && (res[1] == '/' || res[1] == '\0')) {
822 res = str_concat_csvl(&s, homedir, res + 1, NULL)->s;
823 dyn = TRU1;
826 if (anyof(res, "|&;<>~{}()[]*?$`'\"\\") &&
827 which_protocol(res) == PROTO_FILE) {
828 res = _globname(res, fexpm);
829 dyn = TRU1;
830 goto jleave;
833 jislocal:
834 if (fexpm & FEXP_LOCAL)
835 switch (which_protocol(res)) {
836 case PROTO_FILE:
837 case PROTO_MAILDIR: /* XXX Really? ok MAILDIR for local? */
838 break;
839 default:
840 fprintf(stderr, tr(280,
841 "`%s': only a local file or directory may "
842 "be used\n"), name);
843 res = NULL;
844 break;
846 jleave:
847 if (res && ! dyn)
848 res = savestr(res);
849 return res;
852 FL void
853 demail(void)
856 if (ok_blook(keep) || rm(mailname) < 0) {
857 int fd = open(mailname, O_WRONLY|O_CREAT|O_TRUNC, 0600);
858 if (fd >= 0)
859 close(fd);
863 FL bool_t
864 var_folder_updated(char const *name, char **store)
866 char rv = TRU1;
867 char *folder, *unres = NULL, *res = NULL;
869 if ((folder = UNCONST(name)) == NULL)
870 goto jleave;
872 /* Expand the *folder*; skip `%:' prefix for simplicity of use */
873 /* XXX This *only* works because we do NOT
874 * XXX update environment variables via the "set" mechanism */
875 if (folder[0] == '%' && folder[1] == ':')
876 folder += 2;
877 if ((folder = fexpand(folder, FEXP_FULL)) == NULL) /* XXX error? */
878 goto jleave;
880 switch (which_protocol(folder)) {
881 case PROTO_POP3:
882 /* Ooops. This won't work */
883 fprintf(stderr, tr(501, "`folder' cannot be set to a flat, "
884 "readonly POP3 account\n"));
885 rv = FAL0;
886 goto jleave;
887 case PROTO_IMAP:
888 /* Simply assign what we have, even including `%:' prefix */
889 if (folder != name)
890 goto jvcopy;
891 goto jleave;
892 default:
893 /* Further expansion desired */
894 break;
897 /* All non-absolute paths are relative to our home directory */
898 if (*folder != '/') {
899 size_t l1 = strlen(homedir), l2 = strlen(folder);
900 unres = ac_alloc(l1 + l2 + 2);
901 memcpy(unres, homedir, l1);
902 unres[l1] = '/';
903 memcpy(unres + l1 + 1, folder, l2);
904 unres[l1 + 1 + l2] = '\0';
905 folder = unres;
908 /* Since lex.c:_update_mailname() uses realpath(3) if available to
909 * avoid that we loose track of our currently open folder in case we
910 * chdir away, but still checks the leading path portion against
911 * getfold() to be able to abbreviate to the +FOLDER syntax if
912 * possible, we need to realpath(3) the folder, too */
913 #ifdef HAVE_REALPATH
914 res = ac_alloc(MAXPATHLEN);
915 if (realpath(folder, res) == NULL)
916 fprintf(stderr, tr(151, "Can't canonicalize `%s'\n"), folder);
917 else
918 folder = res;
919 #endif
921 jvcopy:
922 *store = sstrdup(folder);
924 if (res != NULL)
925 ac_free(res);
926 if (unres != NULL)
927 ac_free(unres);
928 jleave:
929 return rv;
932 FL bool_t
933 getfold(char *name, size_t size)
935 char const *folder;
937 if ((folder = ok_vlook(folder)) != NULL)
938 (void)n_strlcpy(name, folder, size);
939 return (folder != NULL);
943 * Return the name of the dead.letter file.
945 FL char const *
946 getdeadletter(void)
948 char const *cp;
950 if ((cp = ok_vlook(DEAD)) == NULL ||
951 (cp = fexpand(cp, FEXP_LOCAL)) == NULL)
952 cp = fexpand("~/dead.letter", FEXP_LOCAL|FEXP_SHELL);
953 else if (*cp != '/') {
954 size_t sz = strlen(cp) + 3;
955 char *buf = ac_alloc(sz);
957 snprintf(buf, sz, "~/%s", cp);
958 cp = fexpand(buf, FEXP_LOCAL|FEXP_SHELL);
959 ac_free(buf);
961 if (cp == NULL)
962 cp = "dead.letter";
963 return cp;
966 static enum okay
967 get_header(struct message *mp)
969 (void)mp;
970 switch (mb.mb_type) {
971 case MB_FILE:
972 case MB_MAILDIR:
973 return (OKAY);
974 #ifdef HAVE_POP3
975 case MB_POP3:
976 return (pop3_header(mp));
977 #endif
978 #ifdef HAVE_IMAP
979 case MB_IMAP:
980 case MB_CACHE:
981 return imap_header(mp);
982 #endif
983 case MB_VOID:
984 default:
985 return (STOP);
989 FL enum okay
990 get_body(struct message *mp)
992 (void)mp;
993 switch (mb.mb_type) {
994 case MB_FILE:
995 case MB_MAILDIR:
996 return (OKAY);
997 #ifdef HAVE_POP3
998 case MB_POP3:
999 return (pop3_body(mp));
1000 #endif
1001 #ifdef HAVE_IMAP
1002 case MB_IMAP:
1003 case MB_CACHE:
1004 return imap_body(mp);
1005 #endif
1006 case MB_VOID:
1007 default:
1008 return (STOP);
1012 #ifdef HAVE_SOCKETS
1013 static long xwrite(int fd, const char *data, size_t sz);
1015 static long
1016 xwrite(int fd, const char *data, size_t sz)
1018 long wo;
1019 size_t wt = 0;
1021 do {
1022 if ((wo = write(fd, data + wt, sz - wt)) < 0) {
1023 if (errno == EINTR)
1024 continue;
1025 else
1026 return -1;
1028 wt += wo;
1029 } while (wt < sz);
1030 return sz;
1033 FL int
1034 sclose(struct sock *sp)
1036 int i;
1038 if (sp->s_fd > 0) {
1039 if (sp->s_onclose != NULL)
1040 (*sp->s_onclose)();
1041 #ifdef HAVE_OPENSSL
1042 if (sp->s_use_ssl) {
1043 sp->s_use_ssl = 0;
1044 SSL_shutdown(sp->s_ssl);
1045 SSL_free(sp->s_ssl);
1046 sp->s_ssl = NULL;
1047 SSL_CTX_free(sp->s_ctx);
1048 sp->s_ctx = NULL;
1050 #endif
1052 i = close(sp->s_fd);
1054 sp->s_fd = -1;
1055 return i;
1057 sp->s_fd = -1;
1058 return 0;
1061 FL enum okay
1062 swrite(struct sock *sp, const char *data)
1064 return swrite1(sp, data, strlen(data), 0);
1067 FL enum okay
1068 swrite1(struct sock *sp, const char *data, int sz, int use_buffer)
1070 int x;
1072 if (use_buffer > 0) {
1073 int di;
1074 enum okay ok;
1076 if (sp->s_wbuf == NULL) {
1077 sp->s_wbufsize = 4096;
1078 sp->s_wbuf = smalloc(sp->s_wbufsize);
1079 sp->s_wbufpos = 0;
1081 while (sp->s_wbufpos + sz > sp->s_wbufsize) {
1082 di = sp->s_wbufsize - sp->s_wbufpos;
1083 sz -= di;
1084 if (sp->s_wbufpos > 0) {
1085 memcpy(&sp->s_wbuf[sp->s_wbufpos], data, di);
1086 ok = swrite1(sp, sp->s_wbuf,
1087 sp->s_wbufsize, -1);
1088 } else
1089 ok = swrite1(sp, data,
1090 sp->s_wbufsize, -1);
1091 if (ok != OKAY)
1092 return STOP;
1093 data += di;
1094 sp->s_wbufpos = 0;
1096 if (sz == sp->s_wbufsize) {
1097 ok = swrite1(sp, data, sp->s_wbufsize, -1);
1098 if (ok != OKAY)
1099 return STOP;
1100 } else if (sz) {
1101 memcpy(&sp->s_wbuf[sp->s_wbufpos], data, sz);
1102 sp->s_wbufpos += sz;
1104 return OKAY;
1105 } else if (use_buffer == 0 && sp->s_wbuf != NULL &&
1106 sp->s_wbufpos > 0) {
1107 x = sp->s_wbufpos;
1108 sp->s_wbufpos = 0;
1109 if (swrite1(sp, sp->s_wbuf, x, -1) != OKAY)
1110 return STOP;
1112 if (sz == 0)
1113 return OKAY;
1114 #ifdef HAVE_OPENSSL
1115 if (sp->s_use_ssl) {
1116 ssl_retry: x = SSL_write(sp->s_ssl, data, sz);
1117 if (x < 0) {
1118 switch (SSL_get_error(sp->s_ssl, x)) {
1119 case SSL_ERROR_WANT_READ:
1120 case SSL_ERROR_WANT_WRITE:
1121 goto ssl_retry;
1124 } else
1125 #endif
1127 x = xwrite(sp->s_fd, data, sz);
1129 if (x != sz) {
1130 char o[512];
1131 snprintf(o, sizeof o, "%s write error",
1132 sp->s_desc ? sp->s_desc : "socket");
1133 #ifdef HAVE_OPENSSL
1134 sp->s_use_ssl ? ssl_gen_err("%s", o) : perror(o);
1135 #else
1136 perror(o);
1137 #endif
1138 if (x < 0)
1139 sclose(sp);
1140 return STOP;
1142 return OKAY;
1145 FL enum okay
1146 sopen(const char *xserver, struct sock *sp, int use_ssl,
1147 const char *uhp, const char *portstr, int verbose)
1149 #ifdef HAVE_SO_SNDTIMEO
1150 struct timeval tv;
1151 #endif
1152 #ifdef HAVE_SO_LINGER
1153 struct linger li;
1154 #endif
1155 #ifdef HAVE_IPV6
1156 char hbuf[NI_MAXHOST];
1157 struct addrinfo hints, *res0, *res;
1158 #else
1159 struct sockaddr_in servaddr;
1160 struct in_addr **pptr;
1161 struct hostent *hp;
1162 struct servent *ep;
1163 unsigned short port = 0;
1164 #endif
1165 int sockfd;
1166 char *cp;
1167 char *server = UNCONST(xserver);
1168 (void)use_ssl;
1169 (void)uhp;
1171 if ((cp = strchr(server, ':')) != NULL) { /* TODO URI parse! IPv6! */
1172 portstr = &cp[1];
1173 #ifndef HAVE_IPV6
1174 port = strtol(portstr, NULL, 10);
1175 #endif
1176 server = salloc(cp - xserver + 1);
1177 memcpy(server, xserver, cp - xserver);
1178 server[cp - xserver] = '\0';
1181 /* Connect timeouts after 30 seconds */
1182 #ifdef HAVE_SO_SNDTIMEO
1183 tv.tv_sec = 30;
1184 tv.tv_usec = 0;
1185 #endif
1187 #ifdef HAVE_IPV6
1188 if (verbose)
1189 fprintf(stderr, "Resolving host %s . . .", server);
1190 memset(&hints, 0, sizeof hints);
1191 hints.ai_socktype = SOCK_STREAM;
1192 if (getaddrinfo(server, portstr, &hints, &res0) != 0) {
1193 fprintf(stderr, tr(252, " lookup of `%s' failed.\n"), server);
1194 return STOP;
1195 } else if (verbose)
1196 fprintf(stderr, tr(500, " done.\n"));
1198 sockfd = -1;
1199 for (res = res0; res != NULL && sockfd < 0; res = res->ai_next) {
1200 if (verbose) {
1201 if (getnameinfo(res->ai_addr, res->ai_addrlen,
1202 hbuf, sizeof hbuf, NULL, 0,
1203 NI_NUMERICHOST) != 0)
1204 strcpy(hbuf, "unknown host");
1205 fprintf(stderr, tr(192,
1206 "%sConnecting to %s:%s . . ."),
1207 (res == res0) ? "" : "\n",
1208 hbuf, portstr);
1210 if ((sockfd = socket(res->ai_family, res->ai_socktype,
1211 res->ai_protocol)) >= 0) {
1212 # ifdef HAVE_SO_SNDTIMEO
1213 setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO,
1214 &tv, sizeof tv);
1215 # endif
1216 if (connect(sockfd, res->ai_addr, res->ai_addrlen)!=0) {
1217 close(sockfd);
1218 sockfd = -1;
1222 if (sockfd < 0) {
1223 perror(tr(254, " could not connect"));
1224 freeaddrinfo(res0);
1225 return STOP;
1227 freeaddrinfo(res0);
1229 #else /* HAVE_IPV6 */
1230 if (port == 0) {
1231 if (strcmp(portstr, "smtp") == 0)
1232 port = htons(25);
1233 else if (strcmp(portstr, "smtps") == 0)
1234 port = htons(465);
1235 # ifdef HAVE_IMAP
1236 else if (strcmp(portstr, "imap") == 0)
1237 port = htons(143);
1238 else if (strcmp(portstr, "imaps") == 0)
1239 port = htons(993);
1240 # endif
1241 # ifdef HAVE_POP3
1242 else if (strcmp(portstr, "pop3") == 0)
1243 port = htons(110);
1244 else if (strcmp(portstr, "pop3s") == 0)
1245 port = htons(995);
1246 # endif
1247 else if ((ep = getservbyname(UNCONST(portstr), "tcp")) != NULL)
1248 port = ep->s_port;
1249 else {
1250 fprintf(stderr, tr(251, "Unknown service: %s\n"),
1251 portstr);
1252 return (STOP);
1254 } else
1255 port = htons(port);
1257 if (verbose)
1258 fprintf(stderr, "Resolving host %s . . .", server);
1259 if ((hp = gethostbyname(server)) == NULL) {
1260 fprintf(stderr, tr(252, " lookup of `%s' failed.\n"), server);
1261 return STOP;
1262 } else if (verbose)
1263 fprintf(stderr, tr(500, " done.\n"));
1265 pptr = (struct in_addr **)hp->h_addr_list;
1266 if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
1267 perror(tr(253, "could not create socket"));
1268 return STOP;
1270 memset(&servaddr, 0, sizeof servaddr);
1271 servaddr.sin_family = AF_INET;
1272 servaddr.sin_port = port;
1273 memcpy(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));
1274 if (verbose)
1275 fprintf(stderr, tr(192, "%sConnecting to %s:%d . . ."),
1276 "", inet_ntoa(**pptr), ntohs(port));
1278 # ifdef HAVE_SO_SNDTIMEO
1279 setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
1280 # endif
1281 if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof servaddr)
1282 != 0) {
1283 perror(tr(254, " could not connect"));
1284 return STOP;
1286 #endif /* HAVE_IPV6 */
1287 if (verbose)
1288 fputs(tr(193, " connected.\n"), stderr);
1290 /* And the regular timeouts */
1291 #ifdef HAVE_SO_SNDTIMEO
1292 tv.tv_sec = 42;
1293 tv.tv_usec = 0;
1294 setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
1295 setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
1296 #endif
1297 #ifdef HAVE_SO_LINGER
1298 li.l_onoff = 1;
1299 li.l_linger = 42;
1300 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &li, sizeof li);
1301 #endif
1303 memset(sp, 0, sizeof *sp);
1304 sp->s_fd = sockfd;
1305 #ifdef HAVE_SSL
1306 if (use_ssl && ssl_open(server, sp, uhp) != OKAY) {
1307 sclose(sp);
1308 return STOP;
1310 #endif
1311 return OKAY;
1314 FL int
1315 (sgetline)(char **line, size_t *linesize, size_t *linelen, struct sock *sp
1316 SMALLOC_DEBUG_ARGS)
1318 char *lp = *line;
1320 if (sp->s_rsz < 0) {
1321 sclose(sp);
1322 return sp->s_rsz;
1324 do {
1325 if (*line == NULL || lp > &(*line)[*linesize - 128]) {
1326 size_t diff = lp - *line;
1327 *line = (srealloc)(*line, *linesize += 256
1328 SMALLOC_DEBUG_ARGSCALL);
1329 lp = &(*line)[diff];
1331 if (sp->s_rbufptr == NULL ||
1332 sp->s_rbufptr >= &sp->s_rbuf[sp->s_rsz]) {
1333 #ifdef HAVE_OPENSSL
1334 if (sp->s_use_ssl) {
1335 ssl_retry: if ((sp->s_rsz = SSL_read(sp->s_ssl,
1336 sp->s_rbuf,
1337 sizeof sp->s_rbuf)) <= 0) {
1338 if (sp->s_rsz < 0) {
1339 char o[512];
1340 switch(SSL_get_error(sp->s_ssl,
1341 sp->s_rsz)) {
1342 case SSL_ERROR_WANT_READ:
1343 case SSL_ERROR_WANT_WRITE:
1344 goto ssl_retry;
1346 snprintf(o, sizeof o, "%s",
1347 sp->s_desc ?
1348 sp->s_desc :
1349 "socket");
1350 ssl_gen_err("%s", o);
1353 break;
1355 } else
1356 #endif
1358 again: if ((sp->s_rsz = read(sp->s_fd, sp->s_rbuf,
1359 sizeof sp->s_rbuf)) <= 0) {
1360 if (sp->s_rsz < 0) {
1361 char o[512];
1362 if (errno == EINTR)
1363 goto again;
1364 snprintf(o, sizeof o, "%s",
1365 sp->s_desc ?
1366 sp->s_desc :
1367 "socket");
1368 perror(o);
1370 break;
1373 sp->s_rbufptr = sp->s_rbuf;
1375 } while ((*lp++ = *sp->s_rbufptr++) != '\n');
1376 *lp = '\0';
1377 if (linelen)
1378 *linelen = lp - *line;
1379 return lp - *line;
1381 #endif /* HAVE_SOCKETS */
1383 FL void
1384 load(char const *name)
1386 FILE *in, *oldin;
1388 if (name == NULL || (in = Fopen(name, "r")) == NULL)
1389 return;
1390 oldin = _input;
1391 _input = in;
1392 loading = TRU1;
1393 sourcing = TRU1;
1394 commands();
1395 loading = FAL0;
1396 sourcing = FAL0;
1397 _input = oldin;
1398 Fclose(in);
1401 FL int
1402 csource(void *v)
1404 int rv = 1;
1405 char **arglist = v;
1406 FILE *fi;
1407 char *cp;
1409 if ((cp = fexpand(*arglist, FEXP_LOCAL)) == NULL)
1410 goto jleave;
1411 if ((fi = Fopen(cp, "r")) == NULL) {
1412 perror(cp);
1413 goto jleave;
1415 if (_ssp >= SSTACK - 1) {
1416 fprintf(stderr, tr(3, "Too much \"sourcing\" going on.\n"));
1417 Fclose(fi);
1418 goto jleave;
1421 _sstack[_ssp].s_file = _input;
1422 _sstack[_ssp].s_cond = cond_state;
1423 _sstack[_ssp].s_loading = loading;
1424 ++_ssp;
1425 loading = FAL0;
1426 cond_state = COND_ANY;
1427 _input = fi;
1428 sourcing = TRU1;
1429 rv = 0;
1430 jleave:
1431 return rv;
1434 FL int
1435 unstack(void)
1437 int rv = 1;
1439 if (_ssp <= 0) {
1440 fprintf(stderr, tr(4, "\"Source\" stack over-pop.\n"));
1441 sourcing = FAL0;
1442 goto jleave;
1445 Fclose(_input);
1446 if (cond_state != COND_ANY)
1447 fprintf(stderr, tr(5, "Unmatched \"if\"\n"));
1448 --_ssp;
1449 cond_state = _sstack[_ssp].s_cond;
1450 loading = _sstack[_ssp].s_loading;
1451 _input = _sstack[_ssp].s_file;
1452 if (_ssp == 0)
1453 sourcing = loading;
1454 rv = 0;
1455 jleave:
1456 return rv;