Readd auto-detection of compressed boxes; fix maildir code
[s-mailx.git] / lex.c
blob1c618d58420b989c8eaf16273321e66e2ffe22f8
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ (Lexical processing of) Commands, and the (blocking) "event mainloop".
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 <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 char const *doc; /* One line doc for command */
54 #endif
56 /* Yechh, can't initialize unions */
57 #define minargs msgflag /* Minimum argcount for RAWLIST */
58 #define maxargs msgmask /* Max argcount for RAWLIST */
60 struct cmd_ghost {
61 struct cmd_ghost *next;
62 struct str cmd; /* Data follows after .name */
63 char name[VFIELD_SIZE(sizeof(size_t))];
66 static int *_msgvec;
67 static int _reset_on_stop; /* do a reset() if stopped */
68 static sighandler_type _oldpipe;
69 static struct cmd_ghost *_cmd_ghosts;
70 /* _cmd_tab[] after fun protos */
71 static int _lex_inithdr; /* am printing startup headers */
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_C90AMEND1 /* TODO unite __narrow_suffix() into one fun! */
77 SINLINE size_t __narrow_suffix(char const *cp, size_t cpl, size_t maxl);
78 #endif
80 /* Isolate the command from the arguments */
81 static char * _lex_isolate(char const *comm);
83 /* Get first-fit, or NULL */
84 static struct cmd const * _lex(char const *comm);
86 /* Command ghost handling */
87 static int _ghost(void *v);
88 static int _unghost(void *v);
90 /* Print a list of all commands */
91 static int _pcmdlist(void *v);
92 static int __pcmd_cmp(void const *s1, void const *s2);
94 /* Print the binaries compiled-in features */
95 static int _features(void *v);
97 /* Print the binaries version number */
98 static int _version(void *v);
100 /* When we wake up after ^Z, reprint the prompt */
101 static void stop(int s);
103 /* Branch here on hangup signal and simulate "exit" */
104 static void hangup(int s);
106 /* List of all commands */
107 static struct cmd const _cmd_tab[] = {
108 #include "cmd_tab.h"
111 #ifdef HAVE_C90AMEND1
112 SINLINE size_t
113 __narrow_suffix(char const *cp, size_t cpl, size_t maxl)
115 int err;
116 size_t i, ok;
117 NYD_ENTER;
119 for (err = ok = i = 0; cpl > maxl || err;) {
120 int ml = mblen(cp, cpl);
121 if (ml < 0) { /* XXX _narrow_suffix(): mblen() error; action? */
122 (void)mblen(NULL, 0);
123 err = 1;
124 ml = 1;
125 } else {
126 if (!err)
127 ok = i;
128 err = 0;
129 if (ml == 0)
130 break;
132 cp += ml;
133 i += ml;
134 cpl -= ml;
136 NYD_LEAVE;
137 return ok;
139 #endif /* HAVE_C90AMEND1 */
141 static bool_t
142 _update_mailname(char const *name)
144 char tbuf[PATH_MAX], *mailp, *dispp;
145 size_t i, j;
146 bool_t rv = TRU1;
147 NYD_ENTER;
149 /* Don't realpath(3) if it's only an update request */
150 if (name != NULL) {
151 #ifdef HAVE_REALPATH
152 enum protocol p = which_protocol(name);
153 if (p == PROTO_FILE || p == PROTO_MAILDIR) {
154 if (realpath(name, mailname) == NULL) {
155 fprintf(stderr, _("Can't canonicalize `%s'\n"), name);
156 rv = FAL0;
157 goto jdocopy;
159 } else
160 jdocopy:
161 #endif
162 n_strlcpy(mailname, name, sizeof(mailname));
165 mailp = mailname;
166 dispp = displayname;
168 /* Don't display an absolute path but "+FOLDER" if under *folder* */
169 if (getfold(tbuf, sizeof tbuf)) {
170 i = strlen(tbuf);
171 if (i < sizeof(tbuf) -1)
172 tbuf[i++] = '/';
173 if (!strncmp(tbuf, mailp, i)) {
174 mailp += i;
175 *dispp++ = '+';
179 /* We want to see the name of the folder .. on the screen */
180 i = strlen(mailp);
181 if (i < sizeof(displayname) -1)
182 memcpy(dispp, mailp, i +1);
183 else {
184 rv = FAL0;
185 /* Avoid disrupting multibyte sequences (if possible) */
186 #ifndef HAVE_C90AMEND1
187 j = sizeof(displayname) / 3 - 1;
188 i -= sizeof(displayname) - (1/* + */ + 3) - j;
189 #else
190 j = field_detect_clip(sizeof(displayname) / 3, mailp, i);
191 i = j + __narrow_suffix(mailp + j, i - j,
192 sizeof(displayname) - (1/* + */ + 3 + 1) - j);
193 #endif
194 snprintf(dispp, sizeof(displayname), "%.*s...%s",
195 (int)j, mailp, mailp + i);
197 NYD_LEAVE;
198 return rv;
201 static char *
202 _lex_isolate(char const *comm)
204 NYD_ENTER;
205 while (*comm != '\0' &&
206 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
207 ++comm;
208 NYD_LEAVE;
209 return UNCONST(comm);
212 static struct cmd const *
213 _lex(char const *comm) /* TODO **command hashtable**! linear list search!!! */
215 struct cmd const *cp;
216 NYD_ENTER;
218 for (cp = _cmd_tab; cp->name != NULL; ++cp)
219 if (*comm == *cp->name && is_prefix(comm, cp->name))
220 goto jleave;
221 cp = NULL;
222 jleave:
223 NYD_LEAVE;
224 return cp;
227 static int
228 _ghost(void *v)
230 char const **argv = v;
231 struct cmd_ghost *lcg, *cg;
232 size_t nl, cl;
233 NYD_ENTER;
235 /* Show the list? */
236 if (*argv == NULL) {
237 printf(_("Command ghosts are:\n"));
238 for (nl = 0, cg = _cmd_ghosts; cg != NULL; cg = cg->next) {
239 cl = strlen(cg->name) + 5 + cg->cmd.l + 3;
240 nl += cl;
241 if (UICMP(z, nl, >=, scrnwidth)) {
242 nl = cl;
243 printf("\n");
245 printf((cg->next != NULL ? "%s -> <%s>, " : "%s -> <%s>\n"),
246 cg->name, cg->cmd.s);
248 v = NULL;
249 goto jleave;
252 /* Request to add new ghost */
253 if (argv[1] == NULL || argv[1][0] == '\0' || argv[2] != NULL) {
254 fprintf(stderr, _("Usage: %s\n"),
255 _("Define a <ghost> of <command>, or list all ghosts"));
256 v = NULL;
257 goto jleave;
260 /* Check that we can deal with this one */
261 if (*argv[0] == '\0' || *_lex_isolate(argv[0]) != '\0') {
262 fprintf(stderr, _("Can't canonicalize `%s'\n"), argv[0]);
263 v = NULL;
264 goto jleave;
267 /* Always recreate */
268 for (lcg = NULL, cg = _cmd_ghosts; cg != NULL; lcg = cg, cg = cg->next)
269 if (!strcmp(cg->name, argv[0])) {
270 if (lcg != NULL)
271 lcg->next = cg->next;
272 else
273 _cmd_ghosts = cg->next;
274 free(cg);
275 break;
278 /* Need a new one */
279 nl = strlen(argv[0]) +1;
280 cl = strlen(argv[1]) +1;
281 cg = smalloc(sizeof(*cg) - VFIELD_SIZEOF(struct cmd_ghost, name) + nl + cl);
282 cg->next = _cmd_ghosts;
283 memcpy(cg->name, argv[0], nl);
284 cg->cmd.s = cg->name + nl;
285 cg->cmd.l = cl -1;
286 memcpy(cg->cmd.s, argv[1], cl);
288 _cmd_ghosts = cg;
289 jleave:
290 NYD_LEAVE;
291 return (v == NULL);
294 static int
295 _unghost(void *v)
297 int rv = 0;
298 char const **argv = v, *cp;
299 struct cmd_ghost *lcg, *cg;
300 NYD_ENTER;
302 while ((cp = *argv++) != NULL) {
303 for (lcg = NULL, cg = _cmd_ghosts; cg != NULL; lcg = cg, cg = cg->next)
304 if (!strcmp(cg->name, cp)) {
305 if (lcg != NULL)
306 lcg->next = cg->next;
307 else
308 _cmd_ghosts = cg->next;
309 free(cg);
310 goto jouter;
312 fprintf(stderr, _("Unknown command: `%s'\n"), cp);
313 rv = 1;
314 jouter:
317 NYD_LEAVE;
318 return rv;
321 static int
322 __pcmd_cmp(void const *s1, void const *s2)
324 struct cmd const * const *c1 = s1, * const *c2 = s2;
325 int rv;
326 NYD_ENTER;
328 rv = strcmp((*c1)->name, (*c2)->name);
329 NYD_LEAVE;
330 return rv;
333 static int
334 _pcmdlist(void *v)
336 struct cmd const **cpa, *cp, **cursor;
337 size_t i;
338 NYD_ENTER;
339 UNUSED(v);
341 for (i = 0; _cmd_tab[i].name != NULL; ++i)
343 ++i;
344 cpa = ac_alloc(sizeof(cp) * i);
346 for (i = 0; (cp = _cmd_tab + i)->name != NULL; ++i)
347 cpa[i] = cp;
348 cpa[i] = NULL;
350 qsort(cpa, i, sizeof(cp), &__pcmd_cmp);
352 printf(_("Commands are:\n"));
353 for (i = 0, cursor = cpa; (cp = *cursor++) != NULL;) {
354 size_t j;
355 if (cp->func == &c_cmdnotsupp)
356 continue;
357 j = strlen(cp->name) + 2;
358 if ((i += j) > 72) {
359 i = j;
360 printf("\n");
362 printf((*cursor != NULL ? "%s, " : "%s\n"), cp->name);
365 ac_free(cpa);
366 NYD_LEAVE;
367 return 0;
370 static int
371 _features(void *v)
373 NYD_ENTER;
374 UNUSED(v);
375 printf(_("Features: %s\n"), features);
376 NYD_LEAVE;
377 return 0;
380 static int
381 _version(void *v)
383 NYD_ENTER;
384 UNUSED(v);
385 printf(_("Version %s\n"), version);
386 NYD_LEAVE;
387 return 0;
390 static void
391 stop(int s)
393 sighandler_type old_action;
394 sigset_t nset;
395 NYD_X; /* Signal handler */
397 old_action = safe_signal(s, SIG_DFL);
399 sigemptyset(&nset);
400 sigaddset(&nset, s);
401 sigprocmask(SIG_UNBLOCK, &nset, NULL);
402 kill(0, s);
403 sigprocmask(SIG_BLOCK, &nset, NULL);
404 safe_signal(s, old_action);
405 if (_reset_on_stop) {
406 _reset_on_stop = 0;
407 reset(0);
411 static void
412 hangup(int s)
414 NYD_X; /* Signal handler */
415 UNUSED(s);
416 /* nothing to do? */
417 exit(1);
420 FL int
421 setfile(char const *name, enum fedit_mode fm) /* TODO oh my god */
423 static int shudclob;
425 struct stat stb;
426 struct flock flp;
427 FILE *ibuf = NULL;
428 int rv, i, compressed = 0, omsgCount = 0;
429 char const *who;
430 size_t offset;
431 struct shortcut *sh;
432 NYD_ENTER;
434 /* Note we don't 'userid(myname) != getuid()', preliminary steps are usually
435 * necessary to make a mailbox accessible by a different user, and if that
436 * has happened, let's just let the usual file perms decide */
437 who = (name[1] != '\0') ? name + 1 : myname;
439 #if 1
440 if (name[0] == '%' ||
441 ((sh = get_shortcut(name)) != NULL && *sh->sh_long == '%'))
442 fm |= FEDIT_SYSBOX; /* TODO fexpand() needs to tell is-valid-user! */
443 #else
444 if (name[0] == '%' && (name[1] == '\0' || name[1] == ':'))
445 fm |= FEDIT_SYSBOX;
446 else if ((sh = get_shortcut(name)) != NULL) {
447 char const *x = sh->sh_long;
449 if (x[0] == '%' && (x[1] == '\0' || x[1] == ':'))
450 fm |= FEDIT_SYSBOX;
452 #endif
453 if ((name = expand(name)) == NULL)
454 goto jem1;
456 switch (which_protocol(name)) {
457 case PROTO_FILE:
458 if (temporary_protocol_ext != NULL)
459 name = savecat(name, temporary_protocol_ext);
460 break;
461 case PROTO_MAILDIR:
462 rv = maildir_setfile(name, fm);
463 goto jleave;
464 #ifdef HAVE_POP3
465 case PROTO_POP3:
466 shudclob = 1;
467 rv = pop3_setfile(name, fm);
468 goto jleave;
469 #endif
470 #ifdef HAVE_IMAP
471 case PROTO_IMAP:
472 shudclob = 1;
473 if ((fm & FEDIT_NEWMAIL) && mb.mb_type == MB_CACHE)
474 rv = 1;
475 else
476 rv = imap_setfile(name, fm);
477 goto jleave;
478 #endif
479 default:
480 fprintf(stderr, _("Cannot handle protocol: %s\n"), name);
481 goto jem1;
484 /* FIXME this FILE leaks if quit()->edstop() reset()s! This entire code
485 * FIXME here is total crap, below we open(2) the same name again just to
486 * FIXME close it right away etc. The normal thing would be to (1) finalize
487 * FIXME the current box and (2) open the new box; yet, since (2) may fail
488 * FIXME we terribly need our VOID box to make this logic order possible! */
489 if ((ibuf = Zopen(name, "r", &compressed)) == NULL) {
490 if (((fm & FEDIT_SYSBOX) && errno == ENOENT) || (fm & FEDIT_NEWMAIL)) {
491 if (fm & FEDIT_NEWMAIL)
492 goto jnonmail;
493 goto jnomail;
495 perror(name);
496 goto jem1;
499 if (fstat(fileno(ibuf), &stb) == -1) {
500 if (fm & FEDIT_NEWMAIL)
501 goto jnonmail;
502 perror("fstat");
503 goto jem1;
506 if (S_ISREG(stb.st_mode) ||
507 ((options & OPT_BATCH_FLAG) && !strcmp(name, "/dev/null"))) {
508 /* EMPTY */
509 } else {
510 if (fm & FEDIT_NEWMAIL)
511 goto jnonmail;
512 errno = S_ISDIR(stb.st_mode) ? EISDIR : EINVAL;
513 perror(name);
514 goto jem1;
517 /* Looks like all will be well. We must now relinquish our hold on the
518 * current set of stuff. Must hold signals while we are reading the new
519 * file, else we will ruin the message[] data structure */
521 hold_sigs(); /* TODO note on this one in quit.c:quit() */
522 if (shudclob && !(fm & FEDIT_NEWMAIL))
523 quit();
524 #ifdef HAVE_SOCKETS
525 if (!(fm & FEDIT_NEWMAIL) && mb.mb_sock.s_fd >= 0)
526 sclose(&mb.mb_sock); /* TODO sorry? VMAILFS->close(), thank you */
527 #endif
529 /* Copy the messages into /tmp and set pointers */
530 flp.l_type = F_RDLCK;
531 flp.l_start = 0;
532 flp.l_whence = SEEK_SET;
533 if (!(fm & FEDIT_NEWMAIL)) {
534 mb.mb_type = MB_FILE;
535 mb.mb_perm = (((options & OPT_R_FLAG) || (fm & FEDIT_RDONLY))
536 ? 0 : MB_DELE | MB_EDIT);
537 mb.mb_compressed = compressed;
538 if (compressed) {
539 if (compressed & 0200)
540 mb.mb_perm = 0;
541 } else {
542 if ((i = open(name, O_WRONLY)) == -1)
543 mb.mb_perm = 0;
544 else
545 close(i);
547 if (shudclob) {
548 if (mb.mb_itf) {
549 fclose(mb.mb_itf);
550 mb.mb_itf = NULL;
552 if (mb.mb_otf) {
553 fclose(mb.mb_otf);
554 mb.mb_otf = NULL;
557 shudclob = 1;
558 edit = !(fm & FEDIT_SYSBOX);
559 initbox(name);
560 offset = 0;
561 flp.l_len = 0;
562 if (!edit && fcntl(fileno(ibuf), F_SETLKW, &flp) == -1) {/*TODO dotlock!*/
563 perror("Unable to lock mailbox");
564 rele_sigs();
565 goto jem1;
567 } else /* FEDIT_NEWMAIL */{
568 fseek(mb.mb_otf, 0L, SEEK_END);
569 fseek(ibuf, mailsize, SEEK_SET);
570 offset = mailsize;
571 omsgCount = msgCount;
572 flp.l_len = offset;
573 if (!edit && fcntl(fileno(ibuf), F_SETLKW, &flp) == -1) {/*TODO dotlock!*/
574 rele_sigs();
575 goto jnonmail;
578 mailsize = fsize(ibuf);
580 if ((fm & FEDIT_NEWMAIL) && UICMP(z, mailsize, <=, offset)) {
581 rele_sigs();
582 goto jnonmail;
584 setptr(ibuf, offset);
585 setmsize(msgCount);
586 if ((fm & FEDIT_NEWMAIL) && mb.mb_sorted) {
587 mb.mb_threaded = 0;
588 c_sort((void*)-1);
591 Fclose(ibuf);
592 ibuf = NULL;
593 rele_sigs();
594 if (!(fm & FEDIT_NEWMAIL))
595 sawcom = FAL0;
597 if ((!edit || (fm & FEDIT_NEWMAIL)) && msgCount == 0) {
598 jnonmail:
599 if (!(fm & FEDIT_NEWMAIL)) {
600 if (!ok_blook(emptystart))
601 jnomail:
602 fprintf(stderr, _("No mail for %s\n"), who);
604 rv = 1;
605 goto jleave;
607 if (fm & FEDIT_NEWMAIL)
608 newmailinfo(omsgCount);
610 rv = 0;
611 jleave:
612 if (ibuf != NULL)
613 Fclose(ibuf);
614 NYD_LEAVE;
615 return rv;
616 jem1:
617 rv = -1;
618 goto jleave;
621 FL int
622 newmailinfo(int omsgCount)
624 int mdot, i;
625 NYD_ENTER;
627 for (i = 0; i < omsgCount; ++i)
628 message[i].m_flag &= ~MNEWEST;
629 if (msgCount > omsgCount) {
630 for (i = omsgCount; i < msgCount; ++i)
631 message[i].m_flag |= MNEWEST;
632 printf(_("New mail has arrived.\n"));
633 if ((i = msgCount - omsgCount) == 1)
634 printf(_("Loaded 1 new message.\n"));
635 else
636 printf(_("Loaded %d new messages.\n"), i);
637 } else
638 printf(_("Loaded %d messages.\n"), msgCount);
639 callhook(mailname, 1);
640 mdot = getmdot(1);
641 if (ok_blook(header))
642 print_headers(omsgCount + 1, msgCount, FAL0);
643 NYD_LEAVE;
644 return mdot;
647 FL bool_t
648 commands(void)
650 struct eval_ctx ev;
651 int n;
652 bool_t volatile rv = TRU1;
653 NYD_ENTER;
655 if (!sourcing) {
656 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
657 safe_signal(SIGINT, onintr);
658 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
659 safe_signal(SIGHUP, hangup);
660 /* TODO We do a lot of redundant signal handling, especially
661 * TODO with the command line editor(s); try to merge this */
662 safe_signal(SIGTSTP, stop);
663 safe_signal(SIGTTOU, stop);
664 safe_signal(SIGTTIN, stop);
666 _oldpipe = safe_signal(SIGPIPE, SIG_IGN);
667 safe_signal(SIGPIPE, _oldpipe);
669 memset(&ev, 0, sizeof ev);
671 setexit();
672 for (;;) {
673 interrupts = 0;
674 handlerstacktop = NULL;
676 if (!sourcing && (options & OPT_INTERACTIVE)) {
677 char *cp;
679 cp = ok_vlook(newmail);
680 if ((options & OPT_TTYIN) && (cp != NULL || mb.mb_type == MB_IMAP)) {
681 struct stat st;
683 n = (cp != NULL && strcmp(cp, "noimap") && strcmp(cp, "nopoll"));
684 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
685 st.st_size > mailsize) ||
686 #ifdef HAVE_IMAP
687 (mb.mb_type == MB_IMAP && imap_newmail(n) > (cp == NULL)) ||
688 #endif
689 (mb.mb_type == MB_MAILDIR && n != 0)) {
690 size_t odot = PTR2SIZE(dot - message);
691 bool_t odid = did_print_dot;
693 setfile(mailname, 1);
694 if (mb.mb_type != MB_IMAP) {
695 dot = message + odot;
696 did_print_dot = odid;
701 _reset_on_stop = 1;
702 exit_status = EXIT_OK;
705 #ifdef HAVE_COLOUR
706 colour_table = NULL; /* XXX intermediate hack */
707 #endif
708 if (temporary_localopts_store != NULL) /* XXX intermediate hack */
709 temporary_localopts_free(); /* XXX intermediate hack */
710 sreset(sourcing);
711 if (!sourcing) {
712 char *cp;
714 /* TODO Note: this buffer may contain a password. We should redefine
715 * TODO the code flow which has to do that */
716 if ((cp = termios_state.ts_linebuf) != NULL) {
717 termios_state.ts_linebuf = NULL;
718 termios_state.ts_linesize = 0;
719 free(cp); /* TODO pool give-back */
721 /* TODO Due to expand-on-tab of NCL the buffer may grow */
722 if (ev.ev_line.l > LINESIZE * 3) {
723 free(ev.ev_line.s); /* TODO pool! but what? */
724 ev.ev_line.s = NULL;
725 ev.ev_line.l = 0;
729 /* Read a line of commands and handle end of file specially */
730 jreadline:
731 ev.ev_line.l = ev.ev_line_size;
732 n = readline_input(NULL, TRU1, &ev.ev_line.s, &ev.ev_line.l,
733 ev.ev_new_content);
734 ev.ev_line_size = (ui32_t)ev.ev_line.l;
735 ev.ev_line.l = (ui32_t)n;
736 _reset_on_stop = 0;
737 if (n < 0) {
738 /* EOF */
739 if (loading)
740 break;
741 if (sourcing) {
742 unstack();
743 continue;
745 if ((options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
746 printf(_("Use `quit' to quit.\n"));
747 continue;
749 break;
752 inhook = 0;
753 if (evaluate(&ev)) {
754 if (loading) /* TODO mess; join with exec_last_comm_error etc.. */
755 rv = FAL0;
756 break;
758 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
759 if (exit_status != EXIT_OK)
760 break;
761 /* TODO *batch-exit-on-error*: sourcing and loading MUST BE FLAGS!
762 * TODO the current behaviour is suboptimal AT BEST! */
763 if (exec_last_comm_error != 0 && !sourcing && !loading) {
764 exit_status = EXIT_ERR;
765 break;
768 if (!sourcing && (options & OPT_INTERACTIVE)) {
769 if (ev.ev_new_content != NULL)
770 goto jreadline;
771 tty_addhist(ev.ev_line.s, !ev.ev_add_history);
775 if (ev.ev_line.s != NULL)
776 free(ev.ev_line.s);
777 if (sourcing)
778 sreset(FAL0);
779 NYD_LEAVE;
780 return rv;
783 FL int
784 execute(char *linebuf, int contxt, size_t linesize) /* XXX LEGACY */
786 struct eval_ctx ev;
787 #ifdef HAVE_COLOUR
788 struct colour_table *ct_save;
789 #endif
790 int rv;
791 NYD_ENTER;
793 /* TODO Maybe recursion from within collect.c! As long as we don't have
794 * TODO a value carrier that transports the entire state of a recursion
795 * TODO we need to save away also the colour table */
796 #ifdef HAVE_COLOUR
797 ct_save = colour_table;
798 colour_table = NULL;
799 #endif
801 memset(&ev, 0, sizeof ev);
802 ev.ev_line.s = linebuf;
803 ev.ev_line.l = linesize;
804 ev.ev_is_recursive = (contxt != 0);
805 rv = evaluate(&ev);
807 if (contxt)
808 tty_addhist(ev.ev_line.s, TRU1);
810 #ifdef HAVE_COLOUR
811 colour_table = ct_save;
812 #endif
813 NYD_LEAVE;
814 return rv;
817 FL int
818 evaluate(struct eval_ctx *evp)
820 struct str line;
821 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
822 struct cmd_ghost *cg = NULL;
823 struct cmd const *com = NULL;
824 int muvec[2], c, e = 1;
825 NYD_ENTER;
827 line = evp->ev_line; /* XXX don't change original (buffer pointer) */
828 evp->ev_add_history = FAL0;
829 evp->ev_new_content = NULL;
831 /* Command ghosts that refer to shell commands or macro expansion restart */
832 jrestart:
834 /* Strip the white space away from the beginning of the command */
835 for (cp = line.s; whitechar(*cp); ++cp)
837 line.l -= PTR2SIZE(cp - line.s);
839 /* Ignore comments */
840 if (*cp == '#')
841 goto jleave0;
843 /* Handle ! differently to get the correct lexical conventions */
844 if (*cp == '!') {
845 if (sourcing) {
846 fprintf(stderr, _("Can't `!' while sourcing\n"));
847 goto jleave;
849 c_shell(++cp);
850 evp->ev_add_history = TRU1;
851 goto jleave0;
854 /* Isolate the actual command; since it may not necessarily be
855 * separated from the arguments (as in `p1') we need to duplicate it to
856 * be able to create a NUL terminated version.
857 * We must be aware of several special one letter commands here */
858 arglist[0] = cp;
859 if ((cp = _lex_isolate(cp)) == arglist[0] &&
860 (*cp == '|' || *cp == '~' || *cp == '?'))
861 ++cp;
862 c = (int)PTR2SIZE(cp - arglist[0]);
863 line.l -= c;
864 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
865 memcpy(word, arglist[0], c);
866 word[c] = '\0';
868 /* Look up the command; if not found, bitch.
869 * Normally, a blank command would map to the first command in the
870 * table; while sourcing, however, we ignore blank lines to eliminate
871 * confusion; act just the same for ghosts */
872 if (*word == '\0') {
873 if (sourcing || cg != NULL)
874 goto jleave0;
875 com = _cmd_tab + 0;
876 goto jexec;
879 /* If this is the first evaluation, check command ghosts */
880 if (cg == NULL) {
881 /* TODO relink list head, so it's sorted on usage over time?
882 * TODO in fact, there should be one hashmap over all commands and ghosts
883 * TODO so that the lookup could be made much more efficient than it is
884 * TODO now (two adjacent list searches! */
885 for (cg = _cmd_ghosts; cg != NULL; cg = cg->next)
886 if (!strcmp(word, cg->name)) {
887 if (line.l > 0) {
888 size_t i = cg->cmd.l;
889 line.s = salloc(i + 1 + line.l +1);
890 memcpy(line.s, cg->cmd.s, i);
891 line.s[i++] = ' ';
892 memcpy(line.s + i, cp, line.l);
893 line.s[i += line.l] = '\0';
894 line.l = i;
895 } else {
896 line.s = cg->cmd.s;
897 line.l = cg->cmd.l;
899 goto jrestart;
903 if ((com = _lex(word)) == NULL || com->func == &c_cmdnotsupp) {
904 fprintf(stderr, _("Unknown command: `%s'\n"), word);
905 if (com != NULL) {
906 c_cmdnotsupp(NULL);
907 com = NULL;
909 goto jleave;
912 /* See if we should execute the command -- if a conditional we always
913 * execute it, otherwise, check the state of cond */
914 jexec:
915 if (!(com->argtype & ARG_F) && condstack_isskip())
916 goto jleave0;
918 /* Process the arguments to the command, depending on the type it expects,
919 * default to error. If we're sourcing an interactive command: error */
920 if ((options & OPT_SENDMODE) && !(com->argtype & ARG_M)) {
921 fprintf(stderr, _("May not execute `%s' while sending\n"),
922 com->name);
923 goto jleave;
925 if (sourcing && (com->argtype & ARG_I)) {
926 fprintf(stderr, _("May not execute `%s' while sourcing\n"),
927 com->name);
928 goto jleave;
930 if (!(mb.mb_perm & MB_DELE) && (com->argtype & ARG_W)) {
931 fprintf(stderr, _("May not execute `%s' -- "
932 "message file is read only\n"), com->name);
933 goto jleave;
935 if (evp->ev_is_recursive && (com->argtype & ARG_R)) {
936 fprintf(stderr, _("Cannot recursively invoke `%s'\n"), com->name);
937 goto jleave;
939 if (mb.mb_type == MB_VOID && (com->argtype & ARG_A)) {
940 fprintf(stderr, _("Cannot execute `%s' without active mailbox\n"),
941 com->name);
942 goto jleave;
945 if (com->argtype & ARG_V)
946 temporary_arg_v_store = NULL;
948 switch (com->argtype & ARG_ARGMASK) {
949 case ARG_MSGLIST:
950 /* Message list defaulting to nearest forward legal message */
951 if (_msgvec == NULL)
952 goto je96;
953 if ((c = getmsglist(cp, _msgvec, com->msgflag)) < 0)
954 break;
955 if (c == 0) {
956 *_msgvec = first(com->msgflag, com->msgmask);
957 if (*_msgvec != 0)
958 _msgvec[1] = 0;
960 if (*_msgvec == 0) {
961 if (!inhook)
962 printf(_("No applicable messages\n"));
963 break;
965 e = (*com->func)(_msgvec);
966 break;
968 case ARG_NDMLIST:
969 /* Message list with no defaults, but no error if none exist */
970 if (_msgvec == NULL) {
971 je96:
972 fprintf(stderr, _("Invalid use of `message list'\n"));
973 break;
975 if ((c = getmsglist(cp, _msgvec, com->msgflag)) < 0)
976 break;
977 e = (*com->func)(_msgvec);
978 break;
980 case ARG_STRLIST:
981 /* Just the straight string, with leading blanks removed */
982 while (whitechar(*cp))
983 ++cp;
984 e = (*com->func)(cp);
985 break;
987 case ARG_RAWLIST:
988 case ARG_ECHOLIST:
989 /* A vector of strings, in shell style */
990 if ((c = getrawlist(cp, line.l, arglist, NELEM(arglist),
991 ((com->argtype & ARG_ARGMASK) == ARG_ECHOLIST))) < 0)
992 break;
993 if (c < com->minargs) {
994 fprintf(stderr, _("`%s' requires at least %d arg(s)\n"),
995 com->name, com->minargs);
996 break;
998 if (c > com->maxargs) {
999 fprintf(stderr, _("`%s' takes no more than %d arg(s)\n"),
1000 com->name, com->maxargs);
1001 break;
1003 e = (*com->func)(arglist);
1004 break;
1006 case ARG_NOLIST:
1007 /* Just the constant zero, for exiting, eg. */
1008 e = (*com->func)(0);
1009 break;
1011 default:
1012 panic(_("Unknown argument type"));
1015 if (e == 0 && (com->argtype & ARG_V) &&
1016 (cp = temporary_arg_v_store) != NULL) {
1017 temporary_arg_v_store = NULL;
1018 evp->ev_new_content = cp;
1019 goto jleave0;
1021 if (!(com->argtype & ARG_H) && !list_saw_numbers)
1022 evp->ev_add_history = TRU1;
1024 jleave:
1025 /* Exit the current source file on error TODO what a mess! */
1026 if ((exec_last_comm_error = (e != 0))) {
1027 if (e < 0 || loading) {
1028 e = 1;
1029 goto jret;
1031 if (sourcing)
1032 unstack();
1033 goto jret0;
1035 if (com == NULL)
1036 goto jret0;
1037 if ((com->argtype & ARG_P) && ok_blook(autoprint))
1038 if (visible(dot)) {
1039 muvec[0] = (int)PTR2SIZE(dot - message + 1);
1040 muvec[1] = 0;
1041 c_type(muvec); /* TODO what if error? re-eval! */
1043 if (!sourcing && !inhook && !(com->argtype & ARG_T))
1044 sawcom = TRU1;
1045 jleave0:
1046 exec_last_comm_error = 0;
1047 jret0:
1048 e = 0;
1049 jret:
1050 NYD_LEAVE;
1051 return e;
1054 FL void
1055 setmsize(int sz)
1057 NYD_ENTER;
1058 if (_msgvec != NULL)
1059 free(_msgvec);
1060 _msgvec = scalloc(sz + 1, sizeof *_msgvec);
1061 NYD_LEAVE;
1064 FL void
1065 print_header_summary(char const *Larg)
1067 size_t bot, top, i, j;
1068 NYD_ENTER;
1070 if (Larg != NULL) {
1071 /* Avoid any messages XXX add a make_mua_silent() and use it? */
1072 if ((options & (OPT_VERB | OPT_HEADERSONLY)) == OPT_HEADERSONLY) {
1073 freopen("/dev/null", "w", stdout);
1074 freopen("/dev/null", "w", stderr);
1076 assert(_msgvec != NULL);
1077 i = (getmsglist(/*TODO make arg const */UNCONST(Larg), _msgvec, 0) <= 0);
1078 if (options & OPT_HEADERSONLY) {
1079 exit_status = (int)i;
1080 goto jleave;
1082 if (i)
1083 goto jleave;
1084 for (bot = msgCount, top = 0, i = 0; (j = _msgvec[i]) != 0; ++i) {
1085 if (bot > j)
1086 bot = j;
1087 if (top < j)
1088 top = j;
1090 } else
1091 bot = 1, top = msgCount;
1092 print_headers(bot, top, (Larg != NULL)); /* TODO should take iterator!! */
1093 jleave:
1094 NYD_LEAVE;
1097 FL void
1098 onintr(int s)
1100 NYD_X; /* Signal handler */
1102 if (handlerstacktop != NULL) {
1103 handlerstacktop(s);
1104 return;
1106 safe_signal(SIGINT, onintr);
1107 noreset = 0;
1108 if (!_lex_inithdr)
1109 sawcom = TRU1;
1110 _lex_inithdr = 0;
1111 while (sourcing)
1112 unstack();
1114 termios_state_reset();
1115 close_all_files();
1117 if (image >= 0) {
1118 close(image);
1119 image = -1;
1121 if (interrupts != 1)
1122 fprintf(stderr, _("Interrupt\n"));
1123 safe_signal(SIGPIPE, _oldpipe);
1124 reset(0);
1127 FL void
1128 announce(int printheaders)
1130 int vec[2], mdot;
1131 NYD_ENTER;
1133 mdot = newfileinfo();
1134 vec[0] = mdot;
1135 vec[1] = 0;
1136 dot = message + mdot - 1;
1137 if (printheaders && msgCount > 0 && ok_blook(header)) {
1138 ++_lex_inithdr;
1139 c_headers(vec); /* XXX errors? */
1140 _lex_inithdr = 0;
1142 NYD_LEAVE;
1145 FL int
1146 newfileinfo(void)
1148 struct message *mp;
1149 int u, n, mdot, d, s, hidden, moved;
1150 NYD_ENTER;
1152 if (mb.mb_type == MB_VOID) {
1153 mdot = 1;
1154 goto jleave;
1157 mdot = getmdot(0);
1158 s = d = hidden = moved =0;
1159 for (mp = message, n = 0, u = 0; PTRCMP(mp, <, message + msgCount); ++mp) {
1160 if (mp->m_flag & MNEW)
1161 ++n;
1162 if ((mp->m_flag & MREAD) == 0)
1163 ++u;
1164 if ((mp->m_flag & (MDELETED | MSAVED)) == (MDELETED | MSAVED))
1165 ++moved;
1166 if ((mp->m_flag & (MDELETED | MSAVED)) == MDELETED)
1167 ++d;
1168 if ((mp->m_flag & (MDELETED | MSAVED)) == MSAVED)
1169 ++s;
1170 if (mp->m_flag & MHIDDEN)
1171 ++hidden;
1174 /* If displayname gets truncated the user effectively has no option to see
1175 * the full pathname of the mailbox, so print it at least for '? fi' */
1176 printf(_("\"%s\": "),
1177 (_update_mailname(NULL) ? displayname : mailname));
1178 if (msgCount == 1)
1179 printf(_("1 message"));
1180 else
1181 printf(_("%d messages"), msgCount);
1182 if (n > 0)
1183 printf(_(" %d new"), n);
1184 if (u-n > 0)
1185 printf(_(" %d unread"), u);
1186 if (d > 0)
1187 printf(_(" %d deleted"), d);
1188 if (s > 0)
1189 printf(_(" %d saved"), s);
1190 if (moved > 0)
1191 printf(_(" %d moved"), moved);
1192 if (hidden > 0)
1193 printf(_(" %d hidden"), hidden);
1194 if (mb.mb_type == MB_CACHE)
1195 printf(" [Disconnected]");
1196 else if (mb.mb_perm == 0)
1197 printf(_(" [Read only]"));
1198 printf("\n");
1199 jleave:
1200 NYD_LEAVE;
1201 return mdot;
1204 FL int
1205 getmdot(int nmail)
1207 struct message *mp;
1208 char *cp;
1209 int mdot;
1210 enum mflag avoid = MHIDDEN | MDELETED;
1211 NYD_ENTER;
1213 if (!nmail) {
1214 if (ok_blook(autothread))
1215 c_thread(NULL);
1216 else if ((cp = ok_vlook(autosort)) != NULL) {
1217 free(mb.mb_sorted);
1218 mb.mb_sorted = sstrdup(cp);
1219 c_sort(NULL);
1222 if (mb.mb_type == MB_VOID) {
1223 mdot = 1;
1224 goto jleave;
1227 if (nmail)
1228 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1229 if ((mp->m_flag & (MNEWEST | avoid)) == MNEWEST)
1230 break;
1232 if (!nmail || PTRCMP(mp, >=, message + msgCount)) {
1233 if (mb.mb_threaded) {
1234 for (mp = threadroot; mp != NULL; mp = next_in_thread(mp))
1235 if ((mp->m_flag & (MNEW | avoid)) == MNEW)
1236 break;
1237 } else {
1238 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1239 if ((mp->m_flag & (MNEW | avoid)) == MNEW)
1240 break;
1244 if ((mb.mb_threaded ? (mp == NULL) : PTRCMP(mp, >=, message + msgCount))) {
1245 if (mb.mb_threaded) {
1246 for (mp = threadroot; mp != NULL; mp = next_in_thread(mp))
1247 if (mp->m_flag & MFLAGGED)
1248 break;
1249 } else {
1250 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1251 if (mp->m_flag & MFLAGGED)
1252 break;
1256 if ((mb.mb_threaded ? (mp == NULL) : PTRCMP(mp, >=, message + msgCount))) {
1257 if (mb.mb_threaded) {
1258 for (mp = threadroot; mp != NULL; mp = next_in_thread(mp))
1259 if (!(mp->m_flag & (MREAD | avoid)))
1260 break;
1261 } else {
1262 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1263 if (!(mp->m_flag & (MREAD | avoid)))
1264 break;
1268 if ((mb.mb_threaded ? (mp != NULL) : PTRCMP(mp, <, message + msgCount)))
1269 mdot = (int)PTR2SIZE(mp - message + 1);
1270 else if (ok_blook(showlast)) {
1271 if (mb.mb_threaded) {
1272 for (mp = this_in_thread(threadroot, -1); mp;
1273 mp = prev_in_thread(mp))
1274 if (!(mp->m_flag & avoid))
1275 break;
1276 mdot = (mp != NULL) ? (int)PTR2SIZE(mp - message + 1) : msgCount;
1277 } else {
1278 for (mp = message + msgCount - 1; mp >= message; --mp)
1279 if (!(mp->m_flag & avoid))
1280 break;
1281 mdot = (mp >= message) ? (int)PTR2SIZE(mp - message + 1) : msgCount;
1283 } else if (mb.mb_threaded) {
1284 for (mp = threadroot; mp; mp = next_in_thread(mp))
1285 if (!(mp->m_flag & avoid))
1286 break;
1287 mdot = (mp != NULL) ? (int)PTR2SIZE(mp - message + 1) : 1;
1288 } else {
1289 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1290 if (!(mp->m_flag & avoid))
1291 break;
1292 mdot = PTRCMP(mp, <, message + msgCount)
1293 ? (int)PTR2SIZE(mp - message + 1) : 1;
1295 jleave:
1296 NYD_LEAVE;
1297 return mdot;
1300 FL void
1301 initbox(char const *name)
1303 char *tempMesg;
1304 NYD_ENTER;
1306 if (mb.mb_type != MB_VOID)
1307 n_strlcpy(prevfile, mailname, PATH_MAX);
1309 _update_mailname((name != mailname) ? name : NULL);
1311 if ((mb.mb_otf = Ftmp(&tempMesg, "tmpbox", OF_WRONLY | OF_HOLDSIGS, 0600)) ==
1312 NULL) {
1313 perror(_("temporary mail message file"));
1314 exit(1);
1316 if ((mb.mb_itf = safe_fopen(tempMesg, "r", NULL)) == NULL) {
1317 perror(_("temporary mail message file"));
1318 exit(1);
1320 Ftmp_release(&tempMesg);
1322 message_reset();
1323 mb.mb_threaded = 0;
1324 if (mb.mb_sorted != NULL) {
1325 free(mb.mb_sorted);
1326 mb.mb_sorted = NULL;
1328 #ifdef HAVE_IMAP
1329 mb.mb_flags = MB_NOFLAGS;
1330 #endif
1331 prevdot = NULL;
1332 dot = NULL;
1333 did_print_dot = FAL0;
1334 NYD_LEAVE;
1337 #ifdef HAVE_DOCSTRINGS
1338 FL bool_t
1339 print_comm_docstr(char const *comm)
1341 bool_t rv = FAL0;
1342 struct cmd_ghost *cg;
1343 struct cmd const *cp;
1344 NYD_ENTER;
1346 /* Ghosts take precedence */
1347 for (cg = _cmd_ghosts; cg != NULL; cg = cg->next)
1348 if (!strcmp(comm, cg->name)) {
1349 printf("%s -> <%s>\n", comm, cg->cmd.s);
1350 rv = TRU1;
1351 goto jleave;
1354 for (cp = _cmd_tab; cp->name != NULL; ++cp) {
1355 if (cp->func == &c_cmdnotsupp)
1356 continue;
1357 if (!strcmp(comm, cp->name))
1358 printf("%s: %s\n", comm, V_(cp->doc));
1359 else if (is_prefix(comm, cp->name))
1360 printf("%s (%s): %s\n", comm, cp->name, V_(cp->doc));
1361 else
1362 continue;
1363 rv = TRU1;
1364 break;
1366 jleave:
1367 NYD_LEAVE;
1368 return rv;
1370 #endif
1372 /* s-it-mode */