nail.1: some small tweaks
[s-mailx.git] / lex.c
blobe00515e477a848e56c051abe4d05f8cd43086195
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ (Lexical processing of) Commands, and the event mainloop.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2013 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 <fcntl.h>
46 struct cmd {
47 char const *name; /* Name of command */
48 int (*func)(void*); /* Implementor of command */
49 enum argtype argtype; /* Arglist type (see below) */
50 short msgflag; /* Required flags of msgs*/
51 short msgmask; /* Relevant flags of msgs */
52 #ifdef HAVE_DOCSTRINGS
53 int docid; /* Translation id of .doc */
54 char const *doc; /* One line doc for command */
55 #endif
57 /* Yechh, can't initialize unions */
58 #define minargs msgflag /* Minimum argcount for RAWLIST */
59 #define maxargs msgmask /* Max argcount for RAWLIST */
61 struct cmd_ghost {
62 struct cmd_ghost *next;
63 struct str cmd; /* Data follows after .name */
64 char name[VFIELD_SIZE(sizeof(size_t))];
67 static int *_msgvec;
68 static int _reset_on_stop; /* do a reset() if stopped */
69 static sighandler_type _oldpipe;
70 static struct cmd_ghost *_cmd_ghosts;
71 /* _cmd_tab[] after fun protos */
73 /* Update mailname (if name != NULL) and displayname, return wether displayname
74 * was large enough to swallow mailname */
75 static bool_t _update_mailname(char const *name);
76 #ifdef HAVE_MBLEN /* TODO unite __narrow_{pre,suf}fix() into one function! */
77 SINLINE size_t __narrow_prefix(char const *cp, size_t maxl);
78 SINLINE size_t __narrow_suffix(char const *cp, size_t cpl, size_t maxl);
79 #endif
81 /* Isolate the command from the arguments */
82 static char * _lex_isolate(char const *comm);
84 /* Get first-fit, or NULL */
85 static struct cmd const * _lex(char const *comm);
87 /* Command ghost handling */
88 static int _ghost(void *v);
89 static int _unghost(void *v);
91 /* Print a list of all commands */
92 static int _pcmdlist(void *v);
93 static int __pcmd_cmp(void const *s1, void const *s2);
95 /* Print the binaries compiled-in features */
96 static int _features(void *v);
98 /* Print the binaries version number */
99 static int _version(void *v);
101 static void stop(int s);
102 static void hangup(int s);
104 /* List of all commands */
105 static struct cmd const _cmd_tab[] = {
106 #include "cmd_tab.h"
109 #ifdef HAVE_MBLEN
110 SINLINE size_t
111 __narrow_prefix(char const *cp, size_t maxl)
113 int err;
114 size_t i, ok;
116 for (err = ok = i = 0; i < maxl;) {
117 int ml = mblen(cp, maxl - i);
118 if (ml < 0) { /* XXX _narrow_prefix(): mblen() error; action? */
119 (void)mblen(NULL, 0);
120 err = 1;
121 ml = 1;
122 } else {
123 if (! err)
124 ok = i;
125 err = 0;
126 if (ml == 0)
127 break;
129 cp += ml;
130 i += ml;
132 return ok;
135 SINLINE size_t
136 __narrow_suffix(char const *cp, size_t cpl, size_t maxl)
138 int err;
139 size_t i, ok;
141 for (err = ok = i = 0; cpl > maxl || err;) {
142 int ml = mblen(cp, cpl);
143 if (ml < 0) { /* XXX _narrow_suffix(): mblen() error; action? */
144 (void)mblen(NULL, 0);
145 err = 1;
146 ml = 1;
147 } else {
148 if (! err)
149 ok = i;
150 err = 0;
151 if (ml == 0)
152 break;
154 cp += ml;
155 i += ml;
156 cpl -= ml;
158 return ok;
160 #endif /* HAVE_MBLEN */
162 static bool_t
163 _update_mailname(char const *name)
165 char tbuf[MAXPATHLEN], *mailp, *dispp;
166 size_t i, j;
167 bool_t rv;
169 /* Don't realpath(3) if it's only an update request */
170 if (name != NULL) {
171 #ifdef HAVE_REALPATH
172 enum protocol p = which_protocol(name);
173 if (p == PROTO_FILE || p == PROTO_MAILDIR) {
174 if (realpath(name, mailname) == NULL) {
175 fprintf(stderr, tr(151, "Can't canonicalize `%s'\n"), name);
176 rv = FAL0;
177 goto jleave;
179 } else
180 #endif
181 n_strlcpy(mailname, name, sizeof(mailname));
184 mailp = mailname;
185 dispp = displayname;
187 /* Don't display an absolute path but "+FOLDER" if under *folder* */
188 if (getfold(tbuf, sizeof tbuf)) {
189 i = strlen(tbuf);
190 if (i < sizeof(tbuf) - 1)
191 tbuf[i++] = '/';
192 if (strncmp(tbuf, mailp, i) == 0) {
193 mailp += i;
194 *dispp++ = '+';
198 /* We want to see the name of the folder .. on the screen */
199 i = strlen(mailp);
200 if ((rv = (i < sizeof(displayname) - 1)))
201 memcpy(dispp, mailp, i + 1);
202 else {
203 /* Avoid disrupting multibyte sequences (if possible) */
204 #ifndef HAVE_MBLEN
205 j = sizeof(displayname) / 3 - 1;
206 i -= sizeof(displayname) - (1/* + */ + 3) - j;
207 #else
208 j = __narrow_prefix(mailp, sizeof(displayname) / 3);
209 i = j + __narrow_suffix(mailp + j, i - j,
210 sizeof(displayname) - (1/* + */ + 3 + 1) - j);
211 #endif
212 snprintf(dispp, sizeof(displayname), "%.*s...%s",
213 (int)j, mailp, mailp + i);
215 #ifdef HAVE_REALPATH
216 jleave:
217 #endif
218 return rv;
221 static char *
222 _lex_isolate(char const *comm)
224 while (*comm && strchr(" \t0123456789$^.:/-+*'\",;(`", *comm) == NULL)
225 ++comm;
226 return UNCONST(comm);
229 static struct cmd const *
230 _lex(char const *comm)
232 struct cmd const *cp;
234 for (cp = _cmd_tab; cp->name != NULL; ++cp)
235 if (is_prefix(comm, cp->name))
236 goto jleave;
237 cp = NULL;
238 jleave:
239 return cp;
242 static int
243 _ghost(void *v)
245 char const **argv = (char const **)v;
246 struct cmd_ghost *lcg, *cg;
247 size_t nl, cl;
249 /* Show the list? */
250 if (*argv == NULL) {
251 printf(tr(144, "Command ghosts are:\n"));
252 for (nl = 0, cg = _cmd_ghosts; cg != NULL; cg = cg->next) {
253 cl = strlen(cg->name) + 5 + cg->cmd.l + 3;
254 if ((nl += cl) >= (size_t)scrnwidth) {
255 nl = cl;
256 printf("\n");
258 printf((cg->next != NULL ? "%s -> <%s>, " : "%s -> <%s>\n"),
259 cg->name, cg->cmd.s);
261 v = NULL;
262 goto jleave;
265 /* Request to add new ghost */
266 if (argv[1] == NULL || argv[1][0] == '\0' || argv[2] != NULL) {
267 fprintf(stderr, tr(159, "Usage: %s\n"),
268 tr(425, "Define a <ghost> of <command>, or list all ghosts"));
269 v = NULL;
270 goto jleave;
273 /* Check that we can deal with this one */
274 switch (argv[0][0]) {
275 case '|':
276 case '~':
277 case '?':
278 case '#':
279 /* FALLTHRU */
280 case '\0':
281 goto jecanon;
282 default:
283 if (argv[0] == _lex_isolate(argv[0])) {
284 jecanon:
285 fprintf(stderr, tr(151, "Can't canonicalize `%s'\n"), argv[0]);
286 v = NULL;
287 goto jleave;
289 break;
292 /* Always recreate */
293 for (lcg = NULL, cg = _cmd_ghosts; cg != NULL; lcg = cg, cg = cg->next)
294 if (strcmp(cg->name, argv[0]) == 0) {
295 if (lcg != NULL)
296 lcg->next = cg->next;
297 else
298 _cmd_ghosts = cg->next;
299 free(cg);
300 break;
303 /* Need a new one */
304 nl = strlen(argv[0]) + 1;
305 cl = strlen(argv[1]) + 1;
306 cg = smalloc(sizeof(*cg) - VFIELD_SIZEOF(struct cmd_ghost, name) + nl + cl);
307 cg->next = _cmd_ghosts;
308 memcpy(cg->name, argv[0], nl);
309 cg->cmd.s = cg->name + nl;
310 cg->cmd.l = cl - 1;
311 memcpy(cg->cmd.s, argv[1], cl);
313 _cmd_ghosts = cg;
314 jleave:
315 return (v == NULL);
318 static int
319 _unghost(void *v)
321 int rv = 0;
322 char const **argv = v, *cp;
323 struct cmd_ghost *lcg, *cg;
325 while ((cp = *argv++) != NULL) {
326 for (lcg = NULL, cg = _cmd_ghosts; cg != NULL; lcg = cg, cg = cg->next)
327 if (strcmp(cg->name, cp) == 0) {
328 if (lcg != NULL)
329 lcg->next = cg->next;
330 else
331 _cmd_ghosts = cg->next;
332 free(cg);
333 goto jouter;
335 fprintf(stderr, tr(91, "Unknown command: `%s'\n"), cp);
336 rv = 1;
337 jouter:
340 return rv;
343 static int
344 __pcmd_cmp(void const *s1, void const *s2)
346 struct cmd const * const *c1 = s1, * const *c2 = s2;
347 return (strcmp((*c1)->name, (*c2)->name));
350 static int
351 _pcmdlist(void *v)
353 struct cmd const **cpa, *cp, **cursor;
354 size_t i;
355 (void)v;
357 for (i = 0; _cmd_tab[i].name != NULL; ++i)
359 ++i;
360 cpa = ac_alloc(sizeof(cp) * i);
362 for (i = 0; (cp = _cmd_tab + i)->name != NULL; ++i)
363 cpa[i] = cp;
364 cpa[i] = NULL;
366 qsort(cpa, i, sizeof(cp), &__pcmd_cmp);
368 printf(tr(14, "Commands are:\n"));
369 for (i = 0, cursor = cpa; (cp = *cursor++) != NULL;) {
370 size_t j;
371 if (cp->func == &ccmdnotsupp)
372 continue;
373 j = strlen(cp->name) + 2;
374 if ((i += j) > 72) {
375 i = j;
376 printf("\n");
378 printf((*cursor != NULL ? "%s, " : "%s\n"), cp->name);
381 ac_free(cpa);
382 return 0;
385 static int
386 _features(void *v)
388 UNUSED(v);
389 printf(tr(523, "Features: %s\n"), features);
390 return 0;
393 static int
394 _version(void *v)
396 UNUSED(v);
397 printf(tr(111, "Version %s\n"), version);
398 return 0;
402 * Set up editing on the given file name.
403 * If the first character of name is %, we are considered to be
404 * editing the file, otherwise we are reading our mail which has
405 * signficance for mbox and so forth.
407 * nmail: Check for new mail in the current folder only.
409 FL int
410 setfile(char const *name, int nmail)
412 FILE *ibuf;
413 int i, compressed = 0;
414 struct stat stb;
415 bool_t isedit;
416 char const *who = name[1] ? name + 1 : myname;
417 static int shudclob;
418 size_t offset;
419 int omsgCount = 0;
420 struct shortcut *sh;
421 struct flock flp;
423 /* Note we don't 'userid(myname) != getuid()', preliminary steps are usually
424 * necessary to make a mailbox accessible by a different user, and if that
425 * has happened, let's just let the usual file perms decide */
426 isedit = (*name != '%' && ((sh = get_shortcut(name)) == NULL ||
427 *sh->sh_long != '%'));
428 if ((name = expand(name)) == NULL)
429 return (-1);
431 switch (which_protocol(name)) {
432 case PROTO_FILE:
433 break;
434 case PROTO_MAILDIR:
435 return (maildir_setfile(name, nmail, isedit));
436 #ifdef HAVE_POP3
437 case PROTO_POP3:
438 shudclob = 1;
439 return (pop3_setfile(name, nmail, isedit));
440 #endif
441 #ifdef HAVE_IMAP
442 case PROTO_IMAP:
443 shudclob = 1;
444 if (nmail) {
445 if (mb.mb_type == MB_CACHE)
446 return 1;
448 return imap_setfile(name, nmail, isedit);
449 #endif
450 default:
451 fprintf(stderr, tr(217, "Cannot handle protocol: %s\n"), name);
452 return (-1);
455 if ((ibuf = Zopen(name, "r", &compressed)) == NULL) {
456 if ((!isedit && errno == ENOENT) || nmail) {
457 if (nmail)
458 goto jnonmail;
459 goto nomail;
461 perror(name);
462 return(-1);
465 if (fstat(fileno(ibuf), &stb) < 0) {
466 Fclose(ibuf);
467 if (nmail)
468 goto jnonmail;
469 perror("fstat");
470 return (-1);
473 if (S_ISDIR(stb.st_mode)) {
474 Fclose(ibuf);
475 if (nmail)
476 goto jnonmail;
477 errno = EISDIR;
478 perror(name);
479 return (-1);
480 } else if (S_ISREG(stb.st_mode)) {
481 /*EMPTY*/
482 } else {
483 Fclose(ibuf);
484 if (nmail)
485 goto jnonmail;
486 errno = EINVAL;
487 perror(name);
488 return (-1);
492 * Looks like all will be well. We must now relinquish our
493 * hold on the current set of stuff. Must hold signals
494 * while we are reading the new file, else we will ruin
495 * the message[] data structure.
498 hold_sigs(); /* TODO note on this one in quit.c:quit() */
499 if (shudclob && !nmail)
500 quit();
501 #ifdef HAVE_SOCKETS
502 if (!nmail && mb.mb_sock.s_fd >= 0)
503 sclose(&mb.mb_sock);
504 #endif
507 * Copy the messages into /tmp
508 * and set pointers.
511 flp.l_type = F_RDLCK;
512 flp.l_start = 0;
513 flp.l_whence = SEEK_SET;
514 if (!nmail) {
515 mb.mb_type = MB_FILE;
516 mb.mb_perm = (options & OPT_R_FLAG) ? 0 : MB_DELE|MB_EDIT;
517 mb.mb_compressed = compressed;
518 if (compressed) {
519 if (compressed & 0200)
520 mb.mb_perm = 0;
521 } else {
522 if ((i = open(name, O_WRONLY)) < 0)
523 mb.mb_perm = 0;
524 else
525 close(i);
527 if (shudclob) {
528 if (mb.mb_itf) {
529 fclose(mb.mb_itf);
530 mb.mb_itf = NULL;
532 if (mb.mb_otf) {
533 fclose(mb.mb_otf);
534 mb.mb_otf = NULL;
537 shudclob = 1;
538 edit = isedit;
539 initbox(name);
540 offset = 0;
541 flp.l_len = 0;
542 if (!edit && fcntl(fileno(ibuf), F_SETLKW, &flp) < 0) {
543 perror("Unable to lock mailbox");
544 Fclose(ibuf);
545 return -1;
547 } else /* nmail */{
548 fseek(mb.mb_otf, 0L, SEEK_END);
549 fseek(ibuf, mailsize, SEEK_SET);
550 offset = mailsize;
551 omsgCount = msgCount;
552 flp.l_len = offset;
553 if (!edit && fcntl(fileno(ibuf), F_SETLKW, &flp) < 0)
554 goto jnonmail;
556 mailsize = fsize(ibuf);
557 if (nmail && (size_t)mailsize <= offset) {
558 rele_sigs();
559 goto jnonmail;
561 setptr(ibuf, offset);
562 setmsize(msgCount);
563 if (nmail && mb.mb_sorted) {
564 mb.mb_threaded = 0;
565 sort((void *)-1);
567 Fclose(ibuf);
568 rele_sigs();
569 if (!nmail)
570 sawcom = FAL0;
571 if ((!edit || nmail) && msgCount == 0) {
572 jnonmail:
573 if (!nmail) {
574 if (value("emptystart") == NULL)
575 nomail: fprintf(stderr, tr(88, "No mail for %s\n"),
576 who);
578 return 1;
580 if (nmail) {
581 newmailinfo(omsgCount);
583 return(0);
586 FL int
587 newmailinfo(int omsgCount)
589 int mdot;
590 int i;
592 for (i = 0; i < omsgCount; i++)
593 message[i].m_flag &= ~MNEWEST;
594 if (msgCount > omsgCount) {
595 for (i = omsgCount; i < msgCount; i++)
596 message[i].m_flag |= MNEWEST;
597 printf(tr(158, "New mail has arrived.\n"));
598 if (msgCount - omsgCount == 1)
599 printf(tr(214, "Loaded 1 new message.\n"));
600 else
601 printf(tr(215, "Loaded %d new messages.\n"),
602 msgCount - omsgCount);
603 } else
604 printf(tr(224, "Loaded %d messages.\n"), msgCount);
605 callhook(mailname, 1);
606 mdot = getmdot(1);
607 if (value("header")) {
608 #ifdef HAVE_IMAP
609 if (mb.mb_type == MB_IMAP)
610 imap_getheaders(omsgCount+1, msgCount);
611 #endif
612 time_current_update(&time_current, FAL0);
613 while (++omsgCount <= msgCount)
614 if (visible(&message[omsgCount-1]))
615 printhead(omsgCount, stdout, 0);
617 return mdot;
621 * Interpret user commands one by one. If standard input is not a tty,
622 * print no prompt.
624 FL void
625 commands(void)
627 int eofloop = 0, n;
628 char *linebuf = NULL, *av, *nv;
629 size_t linesize = 0;
630 #ifdef HAVE_IMAP
631 int x;
632 #endif
634 if (!sourcing) {
635 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
636 safe_signal(SIGINT, onintr);
637 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
638 safe_signal(SIGHUP, hangup);
639 /* TODO We do a lot of redundant signal handling, especially
640 * TODO with the command line editor(s); try to merge this */
641 safe_signal(SIGTSTP, stop);
642 safe_signal(SIGTTOU, stop);
643 safe_signal(SIGTTIN, stop);
645 _oldpipe = safe_signal(SIGPIPE, SIG_IGN);
646 safe_signal(SIGPIPE, _oldpipe);
647 setexit();
649 for (;;) {
650 interrupts = 0;
651 handlerstacktop = NULL;
653 * Print the prompt, if needed. Clear out
654 * string space, and flush the output.
656 if (! sourcing && (options & OPT_INTERACTIVE)) {
657 av = (av = value("autoinc")) ? savestr(av) : NULL;
658 nv = (nv = value("newmail")) ? savestr(nv) : NULL;
659 if ((options & OPT_TTYIN) &&
660 (av != NULL || nv != NULL ||
661 mb.mb_type == MB_IMAP)) {
662 struct stat st;
664 n = (av && strcmp(av, "noimap") &&
665 strcmp(av, "nopoll")) |
666 (nv && strcmp(nv, "noimap") &&
667 strcmp(nv, "nopoll"));
668 #ifdef HAVE_IMAP
669 x = !(av || nv);
670 #endif
671 if ((mb.mb_type == MB_FILE &&
672 stat(mailname, &st) == 0 &&
673 st.st_size > mailsize) ||
674 #ifdef HAVE_IMAP
675 (mb.mb_type == MB_IMAP &&
676 imap_newmail(n) > x) ||
677 #endif
678 (mb.mb_type == MB_MAILDIR &&
679 n != 0)) {
680 int odot = dot - &message[0];
681 bool_t odid = did_print_dot;
683 setfile(mailname, 1);
684 if (mb.mb_type != MB_IMAP) {
685 dot = &message[odot];
686 did_print_dot = odid;
690 _reset_on_stop = 1;
691 exit_status = 0;
694 sreset(sourcing);
695 if (!sourcing) {
696 /* TODO Note: this buffer may contain a password
697 * TODO We should redefine the code flow which has
698 * TODO to do that */
699 if ((nv = termios_state.ts_linebuf) != NULL) {
700 termios_state.ts_linebuf = NULL;
701 termios_state.ts_linesize = 0;
702 free(nv); /* TODO pool give-back */
704 /* TODO Due to expand-on-tab of our line editor the
705 * TODO buffer may grow */
706 if (linesize > LINESIZE * 3) {
707 free(linebuf); /* TODO pool! but what? */
708 linebuf = NULL;
709 linesize = 0;
714 * Read a line of commands from the current input
715 * and handle end of file specially.
717 n = readline_input(LNED_LF_ESC | LNED_HIST_ADD, NULL,
718 &linebuf, &linesize);
719 _reset_on_stop = 0;
720 if (n < 0) {
721 /* eof */
722 if (loading)
723 break;
724 if (sourcing) {
725 unstack();
726 continue;
728 if ((options & OPT_INTERACTIVE) &&
729 value("ignoreeof") && ++eofloop < 25) {
730 printf(tr(89, "Use `quit' to quit.\n"));
731 continue;
733 break;
736 eofloop = 0;
737 inhook = 0;
738 if (execute(linebuf, 0, n))
739 break;
740 if (exit_status != EXIT_OK && (options & OPT_BATCH_FLAG) &&
741 boption("batch-exit-on-error"))
742 break;
745 if (linebuf != NULL)
746 free(linebuf);
747 if (sourcing)
748 sreset(FAL0);
752 * Execute a single command.
753 * Command functions return 0 for success, 1 for error, and -1
754 * for abort. A 1 or -1 aborts a load or source. A -1 aborts
755 * the interactive command loop.
756 * Contxt is non-zero if called while composing mail.
758 FL int
759 execute(char *linebuf, int contxt, size_t linesize)
761 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
762 struct cmd_ghost *cg = NULL;
763 struct cmd const *com = NULL;
764 int muvec[2], c, e = 1;
766 /* Command ghosts that refer to shell commands or macro expansion restart */
767 jrestart:
769 /* Strip the white space away from the beginning of the command */
770 for (cp = linebuf; whitechar(*cp); ++cp)
772 linesize -= (size_t)(cp - linebuf);
774 /* Ignore comments */
775 if (*cp == '#')
776 goto jleave0;
778 /* Handle ! differently to get the correct lexical conventions */
779 if (*cp == '!') {
780 if (sourcing) {
781 fprintf(stderr, tr(90, "Can't `!' while sourcing\n"));
782 goto jleave;
784 shell(++cp);
785 goto jleave0;
788 /* Isolate the actual command; since it may not necessarily be
789 * separated from the arguments (as in `p1') we need to duplicate it to
790 * be able to create a NUL terminated version.
791 * We must be aware of special one letter commands here */
792 arglist[0] = cp;
793 switch (*cp) {
794 case '|':
795 case '~':
796 case '?':
797 ++cp;
798 /* FALLTHRU */
799 case '\0':
800 break;
801 default:
802 cp = _lex_isolate(cp);
803 break;
805 c = (int)(cp - arglist[0]);
806 linesize -= c;
807 word = (c < (int)sizeof _wordbuf) ? _wordbuf : salloc(c + 1);
808 memcpy(word, arglist[0], c);
809 word[c] = '\0';
811 /* Look up the command; if not found, bitch.
812 * Normally, a blank command would map to the first command in the
813 * table; while sourcing, however, we ignore blank lines to eliminate
814 * confusion; act just the same for ghosts */
815 if ((sourcing || cg != NULL) && *word == '\0')
816 goto jleave0;
818 /* If this is the first evaluation, check command ghosts */
819 if (cg == NULL) {
820 /* TODO relink list head, so it's sort over time on usage? */
821 for (cg = _cmd_ghosts; cg != NULL; cg = cg->next)
822 if (strcmp(word, cg->name) == 0) {
823 if (linesize > 0) {
824 size_t i = cg->cmd.l;
825 linebuf = salloc(i + 1 + linesize);
826 memcpy(linebuf, cg->cmd.s, i);
827 linebuf[i++] = ' ';
828 memcpy(linebuf + i, cp, linesize);
829 linebuf[i += linesize] = '\0';
830 linesize = i;
831 } else {
832 linebuf = cg->cmd.s;
833 linesize = cg->cmd.l;
835 goto jrestart;
839 if (com == NULL)
840 com = _lex(word);
841 if (com == NULL || com->func == &ccmdnotsupp) {
842 fprintf(stderr, tr(91, "Unknown command: `%s'\n"), word);
843 if (com != NULL) {
844 ccmdnotsupp(NULL);
845 com = NULL;
847 goto jleave;
851 * See if we should execute the command -- if a conditional
852 * we always execute it, otherwise, check the state of cond.
854 if ((com->argtype & F) == 0) {
855 if ((cond == CRCV && (options & OPT_SENDMODE)) ||
856 (cond == CSEND && ! (options & OPT_SENDMODE)) ||
857 (cond == CTERM && ! (options & OPT_TTYIN)) ||
858 (cond == CNONTERM && (options & OPT_TTYIN)))
859 goto jleave0;
863 * Process the arguments to the command, depending
864 * on the type he expects. Default to an error.
865 * If we are sourcing an interactive command, it's
866 * an error.
868 if ((options & OPT_SENDMODE) && (com->argtype & M) == 0) {
869 fprintf(stderr, tr(92,
870 "May not execute `%s' while sending\n"),
871 com->name);
872 goto jleave;
874 if (sourcing && com->argtype & I) {
875 fprintf(stderr, tr(93,
876 "May not execute `%s' while sourcing\n"),
877 com->name);
878 goto jleave;
880 if ((mb.mb_perm & MB_DELE) == 0 && com->argtype & W) {
881 fprintf(stderr, tr(94, "May not execute `%s' -- "
882 "message file is read only\n"),
883 com->name);
884 goto jleave;
886 if (contxt && com->argtype & R) {
887 fprintf(stderr, tr(95,
888 "Cannot recursively invoke `%s'\n"), com->name);
889 goto jleave;
891 if (mb.mb_type == MB_VOID && com->argtype & A) {
892 fprintf(stderr, tr(257,
893 "Cannot execute `%s' without active mailbox\n"),
894 com->name);
895 goto jleave;
898 switch (com->argtype & ~(F|P|I|M|T|W|R|A)) {
899 case MSGLIST:
900 /* Message list defaulting to nearest forward legal message */
901 if (_msgvec == 0)
902 goto je96;
903 if ((c = getmsglist(cp, _msgvec, com->msgflag)) < 0)
904 break;
905 if (c == 0) {
906 *_msgvec = first(com->msgflag, com->msgmask);
907 if (*_msgvec != 0)
908 _msgvec[1] = 0;
910 if (*_msgvec == 0) {
911 if (! inhook)
912 printf(tr(97, "No applicable messages\n"));
913 break;
915 e = (*com->func)(_msgvec);
916 break;
918 case NDMLIST:
919 /* Message list with no defaults, but no error if none exist */
920 if (_msgvec == 0) {
921 je96:
922 fprintf(stderr, tr(96,
923 "Illegal use of `message list'\n"));
924 break;
926 if ((c = getmsglist(cp, _msgvec, com->msgflag)) < 0)
927 break;
928 e = (*com->func)(_msgvec);
929 break;
931 case STRLIST:
932 /* Just the straight string, with leading blanks removed */
933 while (whitechar(*cp))
934 cp++;
935 e = (*com->func)(cp);
936 break;
938 case RAWLIST:
939 case ECHOLIST:
940 /* A vector of strings, in shell style */
941 if ((c = getrawlist(cp, linesize, arglist,
942 sizeof arglist / sizeof *arglist,
943 (com->argtype&~(F|P|I|M|T|W|R|A)) == ECHOLIST)
944 ) < 0)
945 break;
946 if (c < com->minargs) {
947 fprintf(stderr, tr(99,
948 "`%s' requires at least %d arg(s)\n"),
949 com->name, com->minargs);
950 break;
952 if (c > com->maxargs) {
953 fprintf(stderr, tr(100,
954 "`%s' takes no more than %d arg(s)\n"),
955 com->name, com->maxargs);
956 break;
958 e = (*com->func)(arglist);
959 break;
961 case NOLIST:
962 /* Just the constant zero, for exiting, eg. */
963 e = (*com->func)(0);
964 break;
966 default:
967 panic(tr(101, "Unknown argument type"));
970 jleave:
971 /* Exit the current source file on error */
972 if ((exec_last_comm_error = (e != 0))) {
973 if (e < 0)
974 return 1;
975 if (loading)
976 return 1;
977 if (sourcing)
978 unstack();
979 return 0;
981 if (com == (struct cmd*)NULL )
982 return 0;
983 if (boption("autoprint") && com->argtype & P)
984 if (visible(dot)) {
985 muvec[0] = dot - &message[0] + 1;
986 muvec[1] = 0;
987 type(muvec);
989 if (! sourcing && ! inhook && (com->argtype & T) == 0)
990 sawcom = TRU1;
991 jleave0:
992 return 0;
996 * Set the size of the message vector used to construct argument
997 * lists to message list functions.
999 FL void
1000 setmsize(int sz)
1003 if (_msgvec != 0)
1004 free(_msgvec);
1005 _msgvec = (int*)scalloc(sz + 1, sizeof *_msgvec);
1009 * The following gets called on receipt of an interrupt. This is
1010 * to abort printout of a command, mainly.
1011 * Dispatching here when command() is inactive crashes rcv.
1012 * Close all open files except 0, 1, 2, and the temporary.
1013 * Also, unstack all source files.
1016 static int inithdr; /* am printing startup headers */
1018 /*ARGSUSED*/
1019 FL void
1020 onintr(int s)
1022 if (handlerstacktop != NULL) {
1023 handlerstacktop(s);
1024 return;
1026 safe_signal(SIGINT, onintr);
1027 noreset = 0;
1028 if (!inithdr)
1029 sawcom = TRU1;
1030 inithdr = 0;
1031 while (sourcing)
1032 unstack();
1034 termios_state_reset();
1035 close_all_files();
1037 if (image >= 0) {
1038 close(image);
1039 image = -1;
1041 if (interrupts != 1)
1042 fprintf(stderr, tr(102, "Interrupt\n"));
1043 safe_signal(SIGPIPE, _oldpipe);
1044 reset(0);
1048 * When we wake up after ^Z, reprint the prompt.
1050 static void
1051 stop(int s)
1053 sighandler_type old_action = safe_signal(s, SIG_DFL);
1054 sigset_t nset;
1056 sigemptyset(&nset);
1057 sigaddset(&nset, s);
1058 sigprocmask(SIG_UNBLOCK, &nset, (sigset_t *)NULL);
1059 kill(0, s);
1060 sigprocmask(SIG_BLOCK, &nset, (sigset_t *)NULL);
1061 safe_signal(s, old_action);
1062 if (_reset_on_stop) {
1063 _reset_on_stop = 0;
1064 reset(0);
1069 * Branch here on hangup signal and simulate "exit".
1071 /*ARGSUSED*/
1072 static void
1073 hangup(int s)
1075 (void)s;
1076 /* nothing to do? */
1077 exit(1);
1081 * Announce the presence of the current Mail version,
1082 * give the message count, and print a header listing.
1084 FL void
1085 announce(int printheaders)
1087 int vec[2], mdot;
1089 mdot = newfileinfo();
1090 vec[0] = mdot;
1091 vec[1] = 0;
1092 dot = &message[mdot - 1];
1093 if (printheaders && msgCount > 0 && value("header") != NULL) {
1094 inithdr++;
1095 headers(vec);
1096 inithdr = 0;
1101 * Announce information about the file we are editing.
1102 * Return a likely place to set dot.
1104 FL int
1105 newfileinfo(void)
1107 struct message *mp;
1108 int u, n, mdot, d, s, hidden, moved;
1110 if (mb.mb_type == MB_VOID)
1111 return 1;
1112 mdot = getmdot(0);
1113 s = d = hidden = moved =0;
1114 for (mp = &message[0], n = 0, u = 0; mp < &message[msgCount]; mp++) {
1115 if (mp->m_flag & MNEW)
1116 n++;
1117 if ((mp->m_flag & MREAD) == 0)
1118 u++;
1119 if ((mp->m_flag & (MDELETED|MSAVED)) == (MDELETED|MSAVED))
1120 moved++;
1121 if ((mp->m_flag & (MDELETED|MSAVED)) == MDELETED)
1122 d++;
1123 if ((mp->m_flag & (MDELETED|MSAVED)) == MSAVED)
1124 s++;
1125 if (mp->m_flag & MHIDDEN)
1126 hidden++;
1129 /* If displayname gets truncated the user effectively has no option to see
1130 * the full pathname of the mailbox, so print it at least for '? fi' */
1131 printf(tr(103, "\"%s\": "),
1132 (_update_mailname(NULL) ? displayname : mailname));
1133 if (msgCount == 1)
1134 printf(tr(104, "1 message"));
1135 else
1136 printf(tr(105, "%d messages"), msgCount);
1137 if (n > 0)
1138 printf(tr(106, " %d new"), n);
1139 if (u-n > 0)
1140 printf(tr(107, " %d unread"), u);
1141 if (d > 0)
1142 printf(tr(108, " %d deleted"), d);
1143 if (s > 0)
1144 printf(tr(109, " %d saved"), s);
1145 if (moved > 0)
1146 printf(tr(136, " %d moved"), moved);
1147 if (hidden > 0)
1148 printf(tr(139, " %d hidden"), hidden);
1149 if (mb.mb_type == MB_CACHE)
1150 printf(" [Disconnected]");
1151 else if (mb.mb_perm == 0)
1152 printf(tr(110, " [Read only]"));
1153 printf("\n");
1154 return(mdot);
1157 FL int
1158 getmdot(int nmail)
1160 struct message *mp;
1161 char *cp;
1162 int mdot;
1163 enum mflag avoid = MHIDDEN|MDELETED;
1165 if (!nmail) {
1166 if (value("autothread"))
1167 thread(NULL);
1168 else if ((cp = value("autosort")) != NULL) {
1169 free(mb.mb_sorted);
1170 mb.mb_sorted = sstrdup(cp);
1171 sort(NULL);
1174 if (mb.mb_type == MB_VOID)
1175 return 1;
1176 if (nmail)
1177 for (mp = &message[0]; mp < &message[msgCount]; mp++)
1178 if ((mp->m_flag & (MNEWEST|avoid)) == MNEWEST)
1179 break;
1180 if (!nmail || mp >= &message[msgCount]) {
1181 for (mp = mb.mb_threaded ? threadroot : &message[0];
1182 mb.mb_threaded ?
1183 mp != NULL : mp < &message[msgCount];
1184 mb.mb_threaded ?
1185 mp = next_in_thread(mp) : mp++)
1186 if ((mp->m_flag & (MNEW|avoid)) == MNEW)
1187 break;
1189 if (mb.mb_threaded ? mp == NULL : mp >= &message[msgCount])
1190 for (mp = mb.mb_threaded ? threadroot : &message[0];
1191 mb.mb_threaded ? mp != NULL:
1192 mp < &message[msgCount];
1193 mb.mb_threaded ? mp = next_in_thread(mp) : mp++)
1194 if (mp->m_flag & MFLAGGED)
1195 break;
1196 if (mb.mb_threaded ? mp == NULL : mp >= &message[msgCount])
1197 for (mp = mb.mb_threaded ? threadroot : &message[0];
1198 mb.mb_threaded ? mp != NULL:
1199 mp < &message[msgCount];
1200 mb.mb_threaded ? mp = next_in_thread(mp) : mp++)
1201 if ((mp->m_flag & (MREAD|avoid)) == 0)
1202 break;
1203 if (mb.mb_threaded ? mp != NULL : mp < &message[msgCount])
1204 mdot = mp - &message[0] + 1;
1205 else if (value("showlast")) {
1206 if (mb.mb_threaded) {
1207 for (mp = this_in_thread(threadroot, -1); mp;
1208 mp = prev_in_thread(mp))
1209 if ((mp->m_flag & avoid) == 0)
1210 break;
1211 mdot = mp ? mp - &message[0] + 1 : msgCount;
1212 } else {
1213 for (mp = &message[msgCount-1]; mp >= &message[0]; mp--)
1214 if ((mp->m_flag & avoid) == 0)
1215 break;
1216 mdot = mp >= &message[0] ? mp-&message[0]+1 : msgCount;
1218 } else if (mb.mb_threaded) {
1219 for (mp = threadroot; mp; mp = next_in_thread(mp))
1220 if ((mp->m_flag & avoid) == 0)
1221 break;
1222 mdot = mp ? mp - &message[0] + 1 : 1;
1223 } else {
1224 for (mp = &message[0]; mp < &message[msgCount]; mp++)
1225 if ((mp->m_flag & avoid) == 0)
1226 break;
1227 mdot = mp < &message[msgCount] ? mp-&message[0]+1 : 1;
1229 return mdot;
1232 FL void
1233 initbox(const char *name)
1235 char *tempMesg;
1236 int dummy;
1238 if (mb.mb_type != MB_VOID)
1239 (void)n_strlcpy(prevfile, mailname, MAXPATHLEN);
1240 _update_mailname(name != mailname ? name : NULL);
1241 if ((mb.mb_otf = Ftemp(&tempMesg, "tmpbox", "w", 0600, 0)) == NULL) {
1242 perror(tr(87, "temporary mail message file"));
1243 exit(1);
1245 (void)fcntl(fileno(mb.mb_otf), F_SETFD, FD_CLOEXEC);
1246 if ((mb.mb_itf = safe_fopen(tempMesg, "r", &dummy)) == NULL) {
1247 perror(tr(87, "temporary mail message file"));
1248 exit(1);
1250 (void)fcntl(fileno(mb.mb_itf), F_SETFD, FD_CLOEXEC);
1251 rm(tempMesg);
1252 Ftfree(&tempMesg);
1253 msgCount = 0;
1254 if (message) {
1255 free(message);
1256 message = NULL;
1257 msgspace = 0;
1259 mb.mb_threaded = 0;
1260 if (mb.mb_sorted != NULL) {
1261 free(mb.mb_sorted);
1262 mb.mb_sorted = NULL;
1264 #ifdef HAVE_IMAP
1265 mb.mb_flags = MB_NOFLAGS;
1266 #endif
1267 prevdot = NULL;
1268 dot = NULL;
1269 did_print_dot = FAL0;
1272 #ifdef HAVE_DOCSTRINGS
1273 FL bool_t
1274 print_comm_docstr(char const *comm)
1276 bool_t rv = FAL0;
1277 struct cmd_ghost *cg;
1278 struct cmd const *cp;
1280 /* Ghosts take precedence */
1281 for (cg = _cmd_ghosts; cg != NULL; cg = cg->next)
1282 if (strcmp(comm, cg->name) == 0) {
1283 printf("%s -> <%s>\n", comm, cg->cmd.s);
1284 rv = TRU1;
1285 goto jleave;
1288 for (cp = _cmd_tab; cp->name != NULL; ++cp) {
1289 if (cp->func == &ccmdnotsupp)
1290 continue;
1291 if (strcmp(comm, cp->name) == 0)
1292 printf("%s: %s\n", comm, tr(cp->docid, cp->doc));
1293 else if (is_prefix(comm, cp->name))
1294 printf("%s (%s): %s\n", comm, cp->name, tr(cp->docid, cp->doc));
1295 else
1296 continue;
1297 rv = TRU1;
1298 break;
1300 jleave:
1301 return rv;
1303 #endif
1305 /* vim:set fenc=utf-8:s-it-mode (TODO only partial true) */