Add *{smime,ssl}-ca-flags*..
[s-mailx.git] / lex_input.c
blob2f3cb88240a4b61f4675c4fc0ef619596fe8587a
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Command input, lexing and evaluation, resource file loading and `source'ing.
3 *@ TODO n_PS_ROBOT requires yet n_PS_SOURCING, which REALLY sucks.
4 *@ TODO Commands and ghosts deserve a hashmap. Or so.
6 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
7 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
8 */
9 /*
10 * Copyright (c) 1980, 1993
11 * The Regents of the University of California. All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
37 #undef n_FILE
38 #define n_FILE lex_input
40 #ifndef HAVE_AMALGAMATION
41 # include "nail.h"
42 #endif
44 enum a_lex_input_flags{
45 a_LEX_NONE,
46 a_LEX_FREE = 1<<0, /* Structure was allocated, free() it */
47 a_LEX_PIPE = 1<<1, /* Open on a pipe */
48 a_LEX_MACRO = 1<<2, /* Running a macro */
49 a_LEX_MACRO_FREE_DATA = 1<<3, /* Lines are allocated, free(3) once done */
50 /* TODO For simplicity this is yet _MACRO plus specialization overlay
51 * TODO (_X_OPTION, _CMD) -- these should be types on their own! */
52 a_LEX_MACRO_X_OPTION = 1<<4, /* Macro indeed command line -X option */
53 a_LEX_MACRO_CMD = 1<<5, /* Macro indeed single-line: ~:COMMAND */
54 /* TODO a_LEX_SLICE: the right way to support *on-compose-done-shell* would
55 * TODO be a command_loop object that emits an on_read_line event, and
56 * TODO have a special handler for the compose mode; with that, then,
57 * TODO commands_recursive() would not call lex_evaluate() but
58 * TODO CTX->on_read_line, and lex_evaluate() would be the standard impl.,
59 * TODO whereas the COMMAND ESCAPE switch in collect.c would be another one.
60 * TODO With this generic accmacvar.c:temporary_compose_mode_hook_call()
61 * TODO could be dropped, and n_source_macro() could become extended,
62 * TODO and/or we would add a n_source_anything(), which would allow special
63 * TODO input handlers, special I/O input and output, special `localopts'
64 * TODO etc., to be glued to the new execution context. And all I/O all
65 * TODO over this software should not use stdin/stdout, but CTX->in/out.
66 * TODO The pstate must be a property of the current execution context, too.
67 * TODO This not today. :( For now we invent a special SLICE execution
68 * TODO context overlay that at least allows to temporarily modify the
69 * TODO global pstate, and the global stdin and stdout pointers. HACK!
70 * TODO This slice thing is very special and has to go again. HACK!!
71 * TODO a_lex_input() will drop it once it sees EOF (HACK!), but care for
72 * TODO jumps must be taken by slice creators. HACK!!! But works. ;} */
73 a_LEX_SLICE = 1<<6,
74 /* TODO If it is none of those, we are sourcing or loading a file */
76 a_LEX_FORCE_EOF = 1<<8, /* lex_input() shall return EOF next */
78 a_LEX_SUPER_MACRO = 1<<16 /* *Not* inheriting n_PS_SOURCING state */
81 struct a_lex_cmd{
82 char const *lc_name; /* Name of command */
83 int (*lc_func)(void*); /* Implementor of command */
84 enum n_cmd_arg_flags lc_caflags;
85 si16_t lc_msgflag; /* Required flags of msgs */
86 si16_t lc_msgmask; /* Relevant flags of msgs */
87 #ifdef HAVE_DOCSTRINGS
88 char const *lc_doc; /* One line doc for command */
89 #endif
91 /* Yechh, can't initialize unions */
92 #define lc_minargs lc_msgflag /* Minimum argcount for RAWLIST */
93 #define lc_maxargs lc_msgmask /* Max argcount for RAWLIST */
95 struct a_lex_ghost{
96 struct a_lex_ghost *lg_next;
97 struct str lg_cmd; /* Data follows after .lg_name */
98 char lg_name[n_VFIELD_SIZE(0)];
101 struct a_lex_eval_ctx{
102 struct str le_line; /* The terminated data to _evaluate() */
103 ui32_t le_line_size; /* May be used to store line memory size */
104 bool_t le_is_recursive; /* Evaluation in evaluation? (collect ~:) */
105 ui8_t __dummy[3];
106 bool_t le_add_history; /* Add command to history (TRUM1=gabby)? */
109 struct a_lex_input_inject{
110 struct a_lex_input_inject *lii_next;
111 size_t lii_len;
112 bool_t lii_commit;
113 char lii_dat[n_VFIELD_SIZE(7)];
116 struct a_lex_input{
117 struct a_lex_input *li_outer;
118 FILE *li_file; /* File we were in */
119 void *li_cond; /* Saved state of conditional stack */
120 ui32_t li_flags; /* enum a_lex_input_flags */
121 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
122 char **li_lines; /* Pseudo content, lines unfolded */
123 struct a_lex_input_inject *li_inject; /* To be consumed first */
124 void (*li_on_finalize)(void *);
125 void *li_finalize_arg;
126 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
127 sigjmp_buf li_cmdrec_jmp; /* TODO one day... for command_recursive */
128 /* SLICE hacks: saved stdin/stdout, saved pstate */
129 FILE *li_slice_stdin;
130 FILE *li_slice_stdout;
131 ui32_t li_slice_psonce;
132 ui8_t li_slice__dummy[4];
133 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
135 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
136 "Inacceptible size of structure buffer");
138 static sighandler_type a_lex_oldpipe;
139 static struct a_lex_ghost *a_lex_ghosts;
140 /* a_lex_cmd_tab[] after fun protos */
142 /* */
143 static struct a_lex_input *a_lex_input;
145 /* For n_source_inject_input(), if a_lex_input==NULL */
146 static struct a_lex_input_inject *a_lex_input_inject;
148 static sigjmp_buf a_lex_srbuf; /* TODO GET RID */
150 /* Isolate the command from the arguments */
151 static char *a_lex_isolate(char const *comm);
153 /* `eval' */
154 static int a_lex_c_eval(void *v);
156 /* Command ghost handling */
157 static int a_lex_c_ghost(void *v);
158 static int a_lex_c_unghost(void *v);
160 /* Create a multiline info string about all known additional infos for lcp */
161 static char const *a_lex_cmdinfo(struct a_lex_cmd const *lcp);
163 /* Print a list of all commands */
164 static int a_lex_c_list(void *v);
166 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
168 /* `help' / `?' command */
169 static int a_lex_c_help(void *v);
171 /* `exit' and `quit' commands */
172 static int a_lex_c_exit(void *v);
173 static int a_lex_c_quit(void *v);
175 /* Print the binaries version number */
176 static int a_lex_c_version(void *v);
178 static int a_lex__version_cmp(void const *s1, void const *s2);
180 /* n_PS_STATE_PENDMASK requires some actions */
181 static void a_lex_update_pstate(void);
183 /* Evaluate a single command.
184 * .le_add_history will be updated upon success.
185 * Command functions return 0 for success, 1 for error, and -1 for abort.
186 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
187 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
189 /* Get first-fit, or NULL */
190 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
192 /* Branch here on hangup signal and simulate "exit" */
193 static void a_lex_hangup(int s);
195 /* The following gets called on receipt of an interrupt. Close all open files
196 * except 0, 1, 2, and the temporary. Also, unstack all source files */
197 static void a_lex_onintr(int s);
199 /* Pop the current input back to the previous level. Update the program state.
200 * If the argument is TRUM1 then we don't alert and error out if the stack
201 * doesn't exist at all */
202 static void a_lex_unstack(bool_t eval_error);
204 /* `source' and `source_if' (if silent_open_error: no pipes allowed, then).
205 * Returns FAL0 if file is somehow not usable (unless silent_open_error) or
206 * upon evaluation error, and TRU1 on success */
207 static bool_t a_lex_source_file(char const *file, bool_t silent_open_error);
209 /* System resource file load()ing or -X command line option array traversal */
210 static bool_t a_lex_load(struct a_lex_input *lip);
212 /* A simplified command loop for recursed state machines */
213 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
215 /* `read' */
216 static int a_lex_c_read(void *v);
218 static bool_t a_lex__read_set(char const *cp, char const *value);
220 /* List of all commands, and list of commands which are specially treated
221 * and deduced in _evaluate(), but we need a list for _c_list() and
222 * print_comm_docstr() */
223 #ifdef HAVE_DOCSTRINGS
224 # define DS(S) , S
225 #else
226 # define DS(S)
227 #endif
228 static struct a_lex_cmd const a_lex_cmd_tab[] = {
229 #include "cmd_tab.h"
231 a_lex_special_cmd_tab[] = {
232 { "#", NULL, n_CMD_ARG_TYPE_STRING, 0, 0
233 DS(N_("Comment command: ignore remaining (continuable) line")) },
234 { "-", NULL, n_CMD_ARG_TYPE_WYSH, 0, 0
235 DS(N_("Print out the preceding message")) }
237 #undef DS
239 static char *
240 a_lex_isolate(char const *comm){
241 NYD2_ENTER;
242 while(*comm != '\0' &&
243 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
244 ++comm;
245 NYD2_LEAVE;
246 return n_UNCONST(comm);
249 static int
250 a_lex_c_eval(void *v){
251 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
252 * TODO ARGV with shell rules, but if that is not possible then simply
253 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
254 struct n_string s_b, *sp;
255 si32_t rv;
256 size_t i, j;
257 char const **argv, *cp;
258 NYD_ENTER;
260 argv = v;
262 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
263 j += strlen(cp);
265 sp = n_string_creat_auto(&s_b);
266 sp = n_string_reserve(sp, j);
268 for(i = 0; (cp = argv[i]) != NULL; ++i){
269 if(i > 0)
270 sp = n_string_push_c(sp, ' ');
271 sp = n_string_push_cp(sp, cp);
274 /* TODO HACK! We should inherit the current n_lexinput_flags via CmdCtx,
275 * TODO for now we don't have such sort of! n_PS_COMPOSE_MODE is a hack
276 * TODO by itself, since ever: misuse the hack for a hack.
277 * TODO Further more, exit handling is very grazy */
278 (void)/*XXX*/n_source_command((n_pstate & n_PS_COMPOSE_MODE
279 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT), n_string_cp(sp));
280 cp = ok_vlook(__qm);
281 if(cp == n_0) /* This is a hack, but since anything is a hack, be hacky */
282 rv = 0;
283 else if(cp == n_1)
284 rv = 1;
285 else if(cp == n_m1)
286 rv = -1;
287 else
288 n_idec_si32_cp(&rv, cp, 10, NULL);
289 NYD_LEAVE;
290 return rv;
293 static int
294 a_lex_c_ghost(void *v){
295 struct a_lex_ghost *lgp, *gp;
296 size_t i, cl, nl;
297 char *cp;
298 char const **argv;
299 NYD_ENTER;
301 argv = v;
303 /* Show the list? */
304 if(*argv == NULL){
305 FILE *fp;
307 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
308 fp = n_stdout;
310 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
311 fprintf(fp, "wysh ghost %s %s\n",
312 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
314 if(fp != n_stdout){
315 page_or_print(fp, i);
316 Fclose(fp);
318 goto jleave;
321 /* Verify the ghost name is a valid one, and not a command modifier */
322 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0' ||
323 !asccasecmp(argv[0], "ignerr") || !asccasecmp(argv[0], "wysh") ||
324 !asccasecmp(argv[0], "vput")){
325 n_err(_("`ghost': can't canonicalize %s\n"),
326 n_shexp_quote_cp(argv[0], FAL0));
327 v = NULL;
328 goto jleave;
331 /* Show command of single ghost? */
332 if(argv[1] == NULL){
333 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
334 if(!strcmp(argv[0], gp->lg_name)){
335 fprintf(n_stdout, "wysh ghost %s %s\n",
336 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
337 goto jleave;
339 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
340 v = NULL;
341 goto jleave;
344 /* Define command for ghost: verify command content */
345 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
346 if(*cp != '\0')
347 cl += strlen(cp) +1; /* SP or NUL */
348 if(cl == 0){
349 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
350 v = NULL;
351 goto jleave;
354 /* If the ghost already exists, recreate */
355 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
356 if(!strcmp(gp->lg_name, argv[0])){
357 if(lgp != NULL)
358 lgp->lg_next = gp->lg_next;
359 else
360 a_lex_ghosts = gp->lg_next;
361 free(gp);
362 break;
365 nl = strlen(argv[0]) +1;
366 gp = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_ghost, lg_name) + nl + cl);
367 gp->lg_next = a_lex_ghosts;
368 a_lex_ghosts = gp;
369 memcpy(gp->lg_name, argv[0], nl);
370 cp = gp->lg_cmd.s = gp->lg_name + nl;
371 gp->lg_cmd.l = --cl;
373 while(*++argv != NULL)
374 if((i = strlen(*argv)) > 0){
375 memcpy(cp, *argv, i);
376 cp += i;
377 *cp++ = ' ';
379 *--cp = '\0';
380 jleave:
381 NYD_LEAVE;
382 return v == NULL;
385 static int
386 a_lex_c_unghost(void *v){
387 struct a_lex_ghost *lgp, *gp;
388 char const **argv, *cp;
389 int rv;
390 NYD_ENTER;
392 rv = 0;
393 argv = v;
395 while((cp = *argv++) != NULL){
396 if(cp[0] == '*' && cp[1] == '\0'){
397 while((gp = a_lex_ghosts) != NULL){
398 a_lex_ghosts = gp->lg_next;
399 free(gp);
401 }else{
402 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
403 lgp = gp, gp = gp->lg_next)
404 if(!strcmp(gp->lg_name, cp)){
405 if(lgp != NULL)
406 lgp->lg_next = gp->lg_next;
407 else
408 a_lex_ghosts = gp->lg_next;
409 free(gp);
410 goto jouter;
412 n_err(_("`unghost': no such alias: %s\n"),
413 n_shexp_quote_cp(cp, FAL0));
414 rv = 1;
415 jouter: ;
418 NYD_LEAVE;
419 return rv;
422 static char const *
423 a_lex_cmdinfo(struct a_lex_cmd const *lcp){
424 struct n_string rvb, *rv;
425 char const *cp;
426 NYD2_ENTER;
428 rv = n_string_creat_auto(&rvb);
429 rv = n_string_reserve(rv, 80);
431 switch(lcp->lc_caflags & n_CMD_ARG_TYPE_MASK){
432 case n_CMD_ARG_TYPE_MSGLIST:
433 cp = N_("message-list");
434 break;
435 case n_CMD_ARG_TYPE_STRING:
436 case n_CMD_ARG_TYPE_RAWDAT:
437 cp = N_("string data");
438 break;
439 case n_CMD_ARG_TYPE_RAWLIST:
440 cp = N_("old-style quoting");
441 break;
442 case n_CMD_ARG_TYPE_NDMLIST:
443 cp = N_("message-list (no default)");
444 break;
445 case n_CMD_ARG_TYPE_WYRA:
446 cp = N_("`wysh' for sh(1)ell-style quoting");
447 break;
448 default:
449 case n_CMD_ARG_TYPE_WYSH:
450 cp = (lcp->lc_minargs == 0 && lcp->lc_maxargs == 0)
451 ? N_("sh(1)ell-style quoting (takes no arguments)")
452 : N_("sh(1)ell-style quoting");
453 break;
455 rv = n_string_push_cp(rv, V_(cp));
457 if(lcp->lc_caflags & n_CMD_ARG_V)
458 rv = n_string_push_cp(rv, _(" | vput modifier"));
459 if(lcp->lc_caflags & n_CMD_ARG_EM)
460 rv = n_string_push_cp(rv, _(" | status in *!*"));
462 if(lcp->lc_caflags & n_CMD_ARG_A)
463 rv = n_string_push_cp(rv, _(" | needs box"));
464 if(lcp->lc_caflags & n_CMD_ARG_I)
465 rv = n_string_push_cp(rv, _(" | ok: batch or interactive"));
466 if(lcp->lc_caflags & n_CMD_ARG_M)
467 rv = n_string_push_cp(rv, _(" | ok: send mode"));
468 if(lcp->lc_caflags & n_CMD_ARG_R)
469 rv = n_string_push_cp(rv, _(" | not ok: compose mode"));
470 if(lcp->lc_caflags & n_CMD_ARG_S)
471 rv = n_string_push_cp(rv, _(" | not ok: during startup"));
472 if(lcp->lc_caflags & n_CMD_ARG_X)
473 rv = n_string_push_cp(rv, _(" | ok: in subprocess"));
475 if(lcp->lc_caflags & n_CMD_ARG_G)
476 rv = n_string_push_cp(rv, _(" | gabby history"));
478 cp = n_string_cp(rv);
479 NYD2_LEAVE;
480 return cp;
483 static int
484 a_lex_c_list(void *v){
485 FILE *fp;
486 struct a_lex_cmd const **cpa, *cp, **cursor;
487 size_t l, i;
488 NYD_ENTER;
490 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
491 cpa = salloc(sizeof(cp) * i);
493 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
494 cpa[i] = &a_lex_cmd_tab[i];
495 /* C99 */{
496 size_t j;
498 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
499 cpa[i] = &a_lex_special_cmd_tab[j];
501 cpa[i] = NULL;
503 /* C99 */{
504 char const *xcp = v;
506 if(*xcp == '\0')
507 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
510 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
511 fp = n_stdout;
513 fprintf(fp, _("Commands are:\n"));
514 l = 1;
515 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
516 if(cp->lc_func == &c_cmdnotsupp)
517 continue;
518 if(n_poption & n_PO_D_V){
519 fprintf(fp, "%s\n", cp->lc_name);
520 ++l;
521 #ifdef HAVE_DOCSTRINGS
522 fprintf(fp, " : %s\n", V_(cp->lc_doc));
523 ++l;
524 #endif
525 fprintf(fp, " : %s\n", a_lex_cmdinfo(cp));
526 ++l;
527 }else{
528 size_t j = strlen(cp->lc_name) + 2;
530 if((i += j) > 72){
531 i = j;
532 fprintf(fp, "\n");
533 ++l;
535 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
539 if(fp != n_stdout){
540 page_or_print(fp, l);
541 Fclose(fp);
543 NYD_LEAVE;
544 return 0;
547 static int
548 a_lex__pcmd_cmp(void const *s1, void const *s2){
549 struct a_lex_cmd const * const *cp1, * const *cp2;
550 int rv;
551 NYD2_ENTER;
553 cp1 = s1;
554 cp2 = s2;
555 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
556 NYD2_LEAVE;
557 return rv;
560 static int
561 a_lex_c_help(void *v){
562 int rv;
563 char *arg;
564 NYD_ENTER;
566 /* Help for a single command? */
567 if((arg = *(char**)v) != NULL){
568 struct a_lex_ghost const *gp;
569 struct a_lex_cmd const *lcp, *lcpmax;
571 /* Ghosts take precedence */
572 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
573 if(!strcmp(arg, gp->lg_name)){
574 fprintf(n_stdout, "%s -> ", arg);
575 arg = gp->lg_cmd.s;
576 break;
579 lcpmax = &(lcp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
580 jredo:
581 for(; lcp < lcpmax; ++lcp){
582 if(is_prefix(arg, lcp->lc_name)){
583 fputs(arg, n_stdout);
584 if(strcmp(arg, lcp->lc_name))
585 fprintf(n_stdout, " (%s)", lcp->lc_name);
586 }else
587 continue;
589 #ifdef HAVE_DOCSTRINGS
590 fprintf(n_stdout, ": %s", V_(lcp->lc_doc));
591 #endif
592 if(n_poption & n_PO_D_V)
593 fprintf(n_stdout, "\n : %s", a_lex_cmdinfo(lcp));
594 putc('\n', n_stdout);
595 rv = 0;
596 goto jleave;
599 if(PTRCMP(lcpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
600 lcpmax = &(lcp =
601 a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
602 goto jredo;
605 if(gp != NULL){
606 fprintf(n_stdout, "%s\n", n_shexp_quote_cp(arg, TRU1));
607 rv = 0;
608 }else{
609 n_err(_("Unknown command: `%s'\n"), arg);
610 rv = 1;
612 }else{
613 /* Very ugly, but take care for compiler supported string lengths :( */
614 fputs(n_progname, n_stdout);
615 fputs(_(
616 " commands -- <msglist> denotes message specifications,\n"
617 "e.g., 1-5, :n or ., separated by spaces:\n"), n_stdout);
618 fputs(_(
619 "\n"
620 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
621 "Type <msglist> like `type' but always show all headers\n"
622 "next goto and type next message\n"
623 "from <msglist> (search and) print header summary for the given list\n"
624 "headers header summary for messages surrounding \"dot\"\n"
625 "delete <msglist> delete messages (can be `undelete'd)\n"),
626 n_stdout);
628 fputs(_(
629 "\n"
630 "save <msglist> folder append messages to folder and mark as saved\n"
631 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
632 "write <msglist> file write message contents to file (prompts for parts)\n"
633 "Reply <msglist> reply to message senders only\n"
634 "reply <msglist> like `Reply', but address all recipients\n"
635 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
636 n_stdout);
638 fputs(_(
639 "\n"
640 "mail <recipients> compose a mail for the given recipients\n"
641 "file folder change to another mailbox\n"
642 "File folder like `file', but open readonly\n"
643 "quit quit and apply changes to the current mailbox\n"
644 "xit or exit like `quit', but discard changes\n"
645 "!shell command shell escape\n"
646 "list [<anything>] all available commands [in search order]\n"),
647 n_stdout);
649 rv = (ferror(n_stdout) != 0);
651 jleave:
652 NYD_LEAVE;
653 return rv;
656 static int
657 a_lex_c_exit(void *v){
658 NYD_ENTER;
659 n_UNUSED(v);
661 if(n_psonce & n_PSO_STARTED){
662 /* In recursed state, return error to just pop the input level */
663 if(!(n_pstate & n_PS_SOURCING)){
664 #ifdef n_HAVE_TCAP
665 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
666 n_termcap_destroy();
667 #endif
668 exit(n_EXIT_OK);
671 n_pstate |= n_PS_EXIT;
672 NYD_LEAVE;
673 return 0;
676 static int
677 a_lex_c_quit(void *v){
678 NYD_ENTER;
679 n_UNUSED(v);
681 /* If we are n_PS_SOURCING, then return 1 so _evaluate() can handle it.
682 * Otherwise return -1 to abort command loop */
683 n_pstate |= n_PS_EXIT;
684 NYD_LEAVE;
685 return 0;
688 static int
689 a_lex_c_version(void *v){
690 int longest, rv;
691 char *iop;
692 char const *cp, **arr;
693 size_t i, i2;
694 NYD_ENTER;
695 n_UNUSED(v);
697 fprintf(n_stdout, _("%s version %s\nFeatures included (+) or not (-)\n"),
698 n_uagent, ok_vlook(version));
700 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
701 i = strlen(cp = &ok_vlook(features)[1]) +1;
702 iop = salloc(i);
703 memcpy(iop, cp, i);
705 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
706 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
707 arr[i] = cp;
708 i2 = strlen(cp);
709 longest = n_MAX(longest, (int)i2);
711 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
713 for(++longest, i2 = 0; i-- > 0;){
714 cp = *(arr++);
715 fprintf(n_stdout, "%-*s ", longest, cp);
716 i2 += longest;
717 if(UICMP(z, ++i2 + longest, >=, n_scrnwidth) || i == 0){
718 i2 = 0;
719 putc('\n', n_stdout);
723 if((rv = ferror(n_stdout) != 0))
724 clearerr(n_stdout);
725 NYD_LEAVE;
726 return rv;
729 static int
730 a_lex__version_cmp(void const *s1, void const *s2){
731 char const * const *cp1, * const *cp2;
732 int rv;
733 NYD2_ENTER;
735 cp1 = s1;
736 cp2 = s2;
737 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
738 NYD2_LEAVE;
739 return rv;
742 static void
743 a_lex_update_pstate(void){
744 NYD_ENTER;
746 if(n_pstate & n_PS_SIGWINCH_PEND){
747 char buf[32];
749 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
750 ok_vset(COLUMNS, buf);
751 snprintf(buf, sizeof buf, "%d", n_scrnheight);
752 ok_vset(LINES, buf);
755 n_pstate &= ~n_PS_PSTATE_PENDMASK;
756 NYD_LEAVE;
759 static int
760 a_lex_evaluate(struct a_lex_eval_ctx *evp){
761 /* xxx old style(9), but also old code */
762 struct str line;
763 char _wordbuf[2], *arglist_base[MAXARGC], **arglist, *cp, *word;
764 struct a_lex_ghost *gp;
765 struct a_lex_cmd const *cmd;
766 int rv, c;
767 enum {
768 a_NONE = 0,
769 a_GHOST_MASK = (1<<3) - 1, /* Ghost recursion counter bits */
770 a_NOPREFIX = 1<<4, /* Modifier prefix not allowed right now */
771 a_NOGHOST = 1<<5, /* No ghost expansion modifier */
772 /* New command modifier prefixes must be reflected in a_lex_c_ghost()! */
773 a_IGNERR = 1<<6, /* ignerr modifier prefix */
774 a_WYSH = 1<<7, /* XXX v15+ drop wysh modifier prefix */
775 a_VPUT = 1<<8 /* vput modifier prefix */
776 } flags;
777 NYD_ENTER;
779 flags = a_NONE;
780 rv = 1;
781 cmd = NULL;
782 gp = NULL;
783 arglist = arglist_base;
784 line = evp->le_line; /* XXX don't change original (buffer pointer) */
785 assert(line.s[line.l] == '\0');
786 evp->le_add_history = FAL0;
788 /* Command ghosts that refer to shell commands or macro expansion restart */
789 jrestart:
791 /* Strip the white space away from end and beginning of command */
792 if(line.l > 0){
793 size_t i = line.l;
795 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
796 --i;
797 line.l = i;
799 for(cp = line.s; spacechar(*cp); ++cp)
801 line.l -= PTR2SIZE(cp - line.s);
803 /* Ignore null commands (comments) */
804 if(*cp == '#')
805 goto jerr0;
807 /* Handle ! differently to get the correct lexical conventions */
808 arglist[0] = cp;
809 if(*cp == '!')
810 ++cp;
811 /* Isolate the actual command; since it may not necessarily be
812 * separated from the arguments (as in `p1') we need to duplicate it to
813 * be able to create a NUL terminated version.
814 * We must be aware of several special one letter commands here */
815 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
816 (*cp == '|' || *cp == '~' || *cp == '?'))
817 ++cp;
818 c = (int)PTR2SIZE(cp - arglist[0]);
819 line.l -= c;
820 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
821 memcpy(word, arglist[0], c);
822 word[c] = '\0';
824 /* No-expansion modifier? */
825 if(!(flags & a_NOPREFIX) && *word == '\\'){
826 ++word;
827 --c;
828 flags |= a_NOGHOST;
831 /* It may be a modifier prefix */
832 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
833 flags |= a_NOPREFIX | a_IGNERR;
834 line.s = cp;
835 goto jrestart;
836 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
837 flags |= a_NOPREFIX | a_WYSH;
838 line.s = cp;
839 goto jrestart;
840 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
841 flags |= a_NOPREFIX | a_VPUT;
842 line.s = cp;
843 goto jrestart;
846 /* Look up the command; if not found, bitch.
847 * Normally, a blank command would map to the first command in the
848 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
849 * confusion; act just the same for ghosts */
850 if(*word == '\0'){
851 if((n_pstate & n_PS_ROBOT) || gp != NULL)
852 goto jerr0;
853 cmd = &a_lex_cmd_tab[0];
854 goto jexec;
857 if(!(flags & a_NOGHOST) && (flags & a_GHOST_MASK) != a_GHOST_MASK){
858 ui8_t expcnt;
860 expcnt = (flags & a_GHOST_MASK);
861 ++expcnt;
862 flags = (flags & ~(a_GHOST_MASK | a_NOPREFIX)) | expcnt;
864 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
865 if(gp != NULL && !strcmp(word, gp->lg_name)){
866 if(n_poption & n_PO_D_V)
867 n_err(_("Actively avoiding self-recursion of `ghost': %s\n"), word);
868 }else for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)/* TODO BSRCH */
869 if(!strcmp(word, gp->lg_name)){
870 if(line.l > 0){
871 size_t i;
873 i = gp->lg_cmd.l;
874 line.s = salloc(i + line.l +1);
875 memcpy(line.s, gp->lg_cmd.s, i);
876 memcpy(line.s + i, cp, line.l);
877 line.s[i += line.l] = '\0';
878 line.l = i;
879 }else{
880 line.s = gp->lg_cmd.s;
881 line.l = gp->lg_cmd.l;
883 goto jrestart;
887 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
888 bool_t s;
890 if(!(s = condstack_isskip()) || (n_poption & n_PO_D_V))
891 n_err(_("Unknown command%s: `%s'\n"),
892 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
893 if(s)
894 goto jerr0;
895 if(cmd != NULL){
896 c_cmdnotsupp(NULL);
897 cmd = NULL;
899 n_pstate_var__em = n_m1;
900 goto jleave;
903 /* See if we should execute the command -- if a conditional we always
904 * execute it, otherwise, check the state of cond */
905 jexec:
906 if(!(cmd->lc_caflags & n_CMD_ARG_F) && condstack_isskip())
907 goto jerr0;
909 n_pstate_var__em = n_1;
911 /* Process the arguments to the command, depending on the type it expects */
912 if((cmd->lc_caflags & n_CMD_ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
913 !(n_poption & n_PO_BATCH_FLAG)){
914 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
915 cmd->lc_name);
916 goto jleave;
918 if(!(cmd->lc_caflags & n_CMD_ARG_M) && (n_psonce & n_PSO_SENDMODE)){
919 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
920 goto jleave;
922 if(cmd->lc_caflags & n_CMD_ARG_R){
923 if(n_pstate & n_PS_COMPOSE_MODE){
924 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
925 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
926 goto jleave;
928 /* TODO Nothing should prevent n_CMD_ARG_R in conjunction with
929 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
930 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING)){
931 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
932 cmd->lc_name);
933 goto jleave;
936 if((cmd->lc_caflags & n_CMD_ARG_S) && !(n_psonce & n_PSO_STARTED)){
937 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
938 goto jleave;
940 if(!(cmd->lc_caflags & n_CMD_ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
941 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
942 cmd->lc_name);
943 goto jleave;
946 if((cmd->lc_caflags & n_CMD_ARG_A) && mb.mb_type == MB_VOID){
947 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
948 goto jleave;
950 if((cmd->lc_caflags & n_CMD_ARG_W) && !(mb.mb_perm & MB_DELE)){
951 n_err(_("May not execute `%s' -- message file is read only\n"),
952 cmd->lc_name);
953 goto jleave;
956 if(cmd->lc_caflags & n_CMD_ARG_O)
957 n_OBSOLETE2(_("this command will be removed"), cmd->lc_name);
959 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
960 * TODO doesn't use any of those list commands which strip this mask,
961 * TODO and for now we misuse bits for checking relation to history;
962 * TODO argument state should be property of a per-command carrier instead */
963 n_pstate &= ~n_PS_ARGLIST_MASK;
965 if((flags & a_WYSH) &&
966 (cmd->lc_caflags & n_CMD_ARG_TYPE_MASK) != n_CMD_ARG_TYPE_WYRA){
967 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
968 flags &= ~a_WYSH;
971 if(flags & a_VPUT){
972 if(cmd->lc_caflags & n_CMD_ARG_V){
973 char const *xcp;
975 xcp = cp;
976 arglist[0] = n_shexp_parse_token_cp((n_SHEXP_PARSE_TRIMSPACE |
977 n_SHEXP_PARSE_LOG), &xcp);
978 line.l -= PTR2SIZE(xcp - cp);
979 cp = n_UNCONST(xcp);
980 if(cp == NULL)
981 xcp = N_("could not parse input token");
982 else if(!n_shexp_is_valid_varname(arglist[0]))
983 xcp = N_("not a valid variable name");
984 else if(!n_var_is_user_writable(arglist[0]))
985 xcp = N_("either not a user writable, or a boolean variable");
986 else
987 xcp = NULL;
988 if(xcp != NULL){
989 n_err("`%s': vput: %s: %s\n",
990 cmd->lc_name, V_(xcp), n_shexp_quote_cp(arglist[0], FAL0));
991 goto jleave;
993 ++arglist;
994 n_pstate |= n_PS_ARGMOD_VPUT; /* TODO YET useless since stripped later
995 * TODO on in getrawlist() etc., i.e., the argument vector producers,
996 * TODO therefore yet needs to be set again based on flags&a_VPUT! */
997 }else{
998 n_err(_("`vput' prefix doesn't affect `%s'\n"), cmd->lc_name);
999 flags &= ~a_VPUT;
1003 switch(cmd->lc_caflags & n_CMD_ARG_TYPE_MASK){
1004 case n_CMD_ARG_TYPE_MSGLIST:
1005 /* Message list defaulting to nearest forward legal message */
1006 if(n_msgvec == NULL)
1007 goto je96;
1008 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
1009 break;
1010 if(c == 0){
1011 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
1012 n_msgvec[1] = 0;
1014 if(n_msgvec[0] == 0){
1015 if(!(n_pstate & n_PS_HOOK_MASK))
1016 fprintf(n_stdout, _("No applicable messages\n"));
1017 break;
1019 rv = (*cmd->lc_func)(n_msgvec);
1020 break;
1022 case n_CMD_ARG_TYPE_NDMLIST:
1023 /* Message list with no defaults, but no error if none exist */
1024 if(n_msgvec == NULL){
1025 je96:
1026 n_err(_("Invalid use of message list\n"));
1027 break;
1029 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
1030 break;
1031 rv = (*cmd->lc_func)(n_msgvec);
1032 break;
1034 case n_CMD_ARG_TYPE_STRING:
1035 /* Just the straight string, old style, with leading blanks removed */
1036 while(blankspacechar(*cp))
1037 ++cp;
1038 rv = (*cmd->lc_func)(cp);
1039 break;
1040 case n_CMD_ARG_TYPE_RAWDAT:
1041 /* Just the straight string, leading blanks removed, placed in argv[] */
1042 while(blankspacechar(*cp))
1043 ++cp;
1044 *arglist++ = cp;
1045 *arglist = NULL;
1046 rv = (*cmd->lc_func)(arglist_base);
1047 break;
1049 case n_CMD_ARG_TYPE_WYSH:
1050 c = 1;
1051 if(0){
1052 /* FALLTHRU */
1053 case n_CMD_ARG_TYPE_WYRA:
1054 c = (flags & a_WYSH) ? 1 : 0;
1055 if(0){
1056 case n_CMD_ARG_TYPE_RAWLIST:
1057 c = 0;
1060 if((c = getrawlist((c != 0), arglist,
1061 n_NELEM(arglist_base) - PTR2SIZE(arglist - arglist_base),
1062 cp, line.l)) < 0){
1063 n_err(_("Invalid argument list\n"));
1064 break;
1067 if(c < cmd->lc_minargs){
1068 n_err(_("`%s' requires at least %u arg(s)\n"),
1069 cmd->lc_name, (ui32_t)cmd->lc_minargs);
1070 break;
1072 #undef lc_minargs
1073 if(c > cmd->lc_maxargs){
1074 n_err(_("`%s' takes no more than %u arg(s)\n"),
1075 cmd->lc_name, (ui32_t)cmd->lc_maxargs);
1076 break;
1078 #undef lc_maxargs
1080 if(flags & a_VPUT)
1081 n_pstate |= n_PS_ARGMOD_VPUT;
1082 rv = (*cmd->lc_func)(arglist_base);
1083 break;
1085 default:
1086 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
1087 cmd->lc_caflags & n_CMD_ARG_TYPE_MASK); )
1088 goto jerr0;
1091 if(!(cmd->lc_caflags & n_CMD_ARG_H))
1092 evp->le_add_history = (((cmd->lc_caflags & n_CMD_ARG_G) ||
1093 (n_pstate & n_PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
1095 if(!(cmd->lc_caflags & n_CMD_ARG_EM) && rv == 0)
1096 n_pstate_var__em = n_0;
1097 jleave:
1098 n_PS_ROOT_BLOCK(
1099 ok_vset(__qm, (rv == 0 ? n_0 : n_1));
1100 ok_vset(__em, n_pstate_var__em)
1103 if(flags & a_IGNERR){
1104 rv = 0;
1105 n_exit_status = n_EXIT_OK;
1108 /* Exit the current source file on error TODO what a mess! */
1109 if(rv == 0)
1110 n_pstate &= ~n_PS_EVAL_ERROR;
1111 else{
1112 n_pstate |= n_PS_EVAL_ERROR;
1113 if(rv < 0 || (n_pstate & n_PS_ROBOT)){ /* FIXME */
1114 rv = 1;
1115 goto jret;
1117 goto jret0;
1120 if(cmd == NULL)
1121 goto jret0;
1122 if((cmd->lc_caflags & n_CMD_ARG_P) && ok_blook(autoprint))
1123 if(visible(dot))
1124 n_source_inject_input(n_INPUT_INJECT_COMMIT, "\\type",
1125 sizeof("\\type") -1);
1127 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
1128 !(cmd->lc_caflags & n_CMD_ARG_T))
1129 n_pstate |= n_PS_SAW_COMMAND;
1130 jleave0:
1131 n_pstate &= ~n_PS_EVAL_ERROR;
1132 jret0:
1133 rv = 0;
1134 jret:
1135 NYD_LEAVE;
1136 return rv;
1137 jerr0:
1138 n_PS_ROOT_BLOCK(
1139 ok_vset(__qm, n_0);
1140 ok_vset(__em, n_0)
1142 goto jleave0;
1145 static struct a_lex_cmd const *
1146 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
1147 struct a_lex_cmd const *cp;
1148 NYD2_ENTER;
1150 for(cp = a_lex_cmd_tab;
1151 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
1152 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
1153 goto jleave;
1154 cp = NULL;
1155 jleave:
1156 NYD2_LEAVE;
1157 return cp;
1160 static void
1161 a_lex_hangup(int s){
1162 NYD_X; /* Signal handler */
1163 n_UNUSED(s);
1164 /* nothing to do? */
1165 exit(n_EXIT_ERR);
1168 static void
1169 a_lex_onintr(int s){ /* TODO block signals while acting */
1170 NYD_X; /* Signal handler */
1171 n_UNUSED(s);
1173 safe_signal(SIGINT, a_lex_onintr);
1175 termios_state_reset();
1176 close_all_files(); /* FIXME .. of current level ONLU! */
1178 a_lex_unstack(TRUM1);
1180 if(interrupts != 1)
1181 n_err_sighdl(_("Interrupt\n"));
1182 safe_signal(SIGPIPE, a_lex_oldpipe);
1183 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
1186 static void
1187 a_lex_unstack(bool_t eval_error){
1188 struct a_lex_input *lip;
1189 NYD_ENTER;
1191 /* Free input injections of this level first */
1192 /* C99 */{
1193 struct a_lex_input_inject **liipp, *liip;
1195 if((lip = a_lex_input) == NULL)
1196 liipp = &a_lex_input_inject;
1197 else
1198 liipp = &lip->li_inject;
1200 while((liip = *liipp) != NULL){
1201 *liipp = liip->lii_next;
1202 free(liip);
1205 if(lip == NULL || !(lip->li_flags & a_LEX_SLICE))
1206 n_memory_reset();
1209 if(lip == NULL){
1210 /* If called from a_lex_onintr(), be silent FIXME */
1211 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1212 if(eval_error == TRUM1 || !(n_psonce & n_PSO_STARTED))
1213 goto jleave;
1214 goto jerr;
1217 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1218 n_stdin = lip->li_slice_stdin;
1219 n_stdout = lip->li_slice_stdout;
1220 n_psonce = lip->li_slice_psonce;
1221 goto jthe_slice_hack;
1224 if(lip->li_flags & a_LEX_MACRO){
1225 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1226 char **lp;
1228 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1229 free(*lp);
1230 ++lip->li_loff;
1232 /* Part of lip's memory chunk, then */
1233 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1234 free(lip->li_lines);
1236 }else{
1237 if(lip->li_flags & a_LEX_PIPE)
1238 /* XXX command manager should -TERM then -KILL instead of hoping
1239 * XXX for exit of provider due to EPIPE / SIGPIPE */
1240 Pclose(lip->li_file, TRU1);
1241 else
1242 Fclose(lip->li_file);
1245 if(!condstack_take(lip->li_cond)){
1246 n_err(_("Unmatched `if' at end of %s %s\n"),
1247 ((lip->li_flags & a_LEX_MACRO
1248 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1249 : _("`source'd file"))),
1250 lip->li_name);
1251 eval_error = TRU1;
1254 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1256 jthe_slice_hack:
1257 if(lip->li_on_finalize != NULL)
1258 (*lip->li_on_finalize)(lip->li_finalize_arg);
1260 if((a_lex_input = lip->li_outer) == NULL){
1261 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1262 }else{
1263 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1264 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1265 n_pstate &= ~n_PS_SOURCING;
1266 assert(n_pstate & n_PS_ROBOT);
1269 if(eval_error)
1270 goto jerr;
1271 jleave:
1272 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1273 free(lip);
1274 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1275 a_lex_unstack(TRUM1);
1276 NYD_LEAVE;
1277 return;
1279 jerr:
1280 if(lip != NULL){
1281 /* POSIX says
1282 * Any errors in the start-up file shall either cause mailx to
1283 * terminate with a diagnostic message and a non-zero status or to
1284 * continue after writing a diagnostic message, ignoring the
1285 * remainder of the lines in the start-up file
1286 * But print the diagnostic only for the outermost resource unless the
1287 * user is debugging or in verbose mode */
1288 if((n_poption & n_PO_D_V) ||
1289 (!(n_psonce & n_PSO_STARTED) &&
1290 !(lip->li_flags & (a_LEX_SLICE | a_LEX_MACRO)) &&
1291 lip->li_outer == NULL))
1292 n_alert(_("Stopped %s %s due to errors%s"),
1293 (n_psonce & n_PSO_STARTED
1294 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1295 : (lip->li_flags & a_LEX_MACRO
1296 ? (lip->li_flags & a_LEX_MACRO_CMD
1297 ? _("evaluating command") : _("evaluating macro"))
1298 : (lip->li_flags & a_LEX_PIPE
1299 ? _("executing `source'd pipe")
1300 : _("loading `source'd file")))
1302 : (lip->li_flags & a_LEX_MACRO
1303 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1304 ? _("evaluating command line") : _("evaluating macro"))
1305 : _("loading initialization resource"))),
1306 lip->li_name,
1307 (n_poption & n_PO_DEBUG
1308 ? n_empty : _(" (enable *debug* for trace)")));
1311 if(!(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED))){
1312 if(n_poption & n_PO_D_V)
1313 n_alert(_("Non-interactive, bailing out due to errors "
1314 "in startup load phase"));
1315 exit(n_EXIT_ERR);
1317 goto jleave;
1320 static bool_t
1321 a_lex_source_file(char const *file, bool_t silent_open_error){
1322 struct a_lex_input *lip;
1323 size_t nlen;
1324 char *nbuf;
1325 bool_t ispipe;
1326 FILE *fip;
1327 NYD_ENTER;
1329 fip = NULL;
1331 /* Being a command argument file is space-trimmed *//* TODO v15 with
1332 * TODO WYRALIST this is no longer necessary true, and for that we
1333 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1334 #if 0
1335 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1336 file[--nlen] == '|')))
1337 #else
1338 ispipe = FAL0;
1339 if(!silent_open_error)
1340 for(nlen = strlen(file); nlen > 0;){
1341 char c;
1343 c = file[--nlen];
1344 if(!blankchar(c)){
1345 if(c == '|'){
1346 nbuf = savestrbuf(file, nlen);
1347 ispipe = TRU1;
1349 break;
1352 #endif
1354 if(ispipe){
1355 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1356 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL)
1357 goto jeopencheck;
1358 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1359 goto jeopencheck;
1360 else if((fip = Fopen(nbuf, "r")) == NULL){
1361 jeopencheck:
1362 if(!silent_open_error || (n_poption & n_PO_D_V))
1363 n_perr(nbuf, 0);
1364 if(silent_open_error)
1365 fip = (FILE*)-1;
1366 goto jleave;
1369 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
1370 (nlen = strlen(nbuf) +1));
1371 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1372 lip->li_outer = a_lex_input;
1373 lip->li_file = fip;
1374 lip->li_cond = condstack_release();
1375 n_memory_autorec_push(&lip->li_autorecmem[0]);
1376 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1377 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1378 ? a_LEX_SUPER_MACRO : 0);
1379 memcpy(lip->li_name, nbuf, nlen);
1381 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1382 a_lex_input = lip;
1383 if(!a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC))
1384 fip = NULL;
1385 jleave:
1386 NYD_LEAVE;
1387 return (fip != NULL);
1390 static bool_t
1391 a_lex_load(struct a_lex_input *lip){
1392 bool_t rv;
1393 NYD2_ENTER;
1395 assert(!(n_psonce & n_PSO_STARTED));
1396 assert(a_lex_input == NULL);
1398 /* POSIX:
1399 * Any errors in the start-up file shall either cause mailx to terminate
1400 * with a diagnostic message and a non-zero status or to continue after
1401 * writing a diagnostic message, ignoring the remainder of the lines in
1402 * the start-up file. */
1403 lip->li_cond = condstack_release();
1404 n_memory_autorec_push(&lip->li_autorecmem[0]);
1406 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1407 n_pstate |= n_PS_ROBOT |
1408 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1410 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1411 if(n_poption & n_PO_D_V)
1412 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1413 a_lex_input = lip;
1414 if(!(rv = n_commands())){
1415 if(!(n_psonce & n_PSO_INTERACTIVE)){
1416 if(n_poption & n_PO_D_V)
1417 n_alert(_("Non-interactive program mode, forced exit"));
1418 exit(n_EXIT_ERR);
1419 }else if(n_poption & n_PO_BATCH_FLAG){
1420 char const *beoe;
1422 if((beoe = ok_vlook(batch_exit_on_error)) != NULL && *beoe == '1')
1423 n_pstate |= n_PS_EXIT;
1426 /* n_PS_EXIT handled by callers */
1427 NYD2_LEAVE;
1428 return rv;
1431 static void
1432 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1433 NYD_X; /* Signal handler */
1434 n_UNUSED(sig);
1435 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1438 static bool_t
1439 a_commands_recursive(enum n_lexinput_flags lif){
1440 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1441 sighandler_type soldhdl;
1442 sigset_t sintset, soldset;
1443 struct a_lex_eval_ctx ev;
1444 bool_t rv, ever;
1445 NYD2_ENTER;
1447 memset(&ev, 0, sizeof ev);
1449 sigfillset(&sintset);
1450 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1451 hadint = FAL0;
1452 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1453 safe_signal(SIGINT, &a_lex__cmdrecint);
1454 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1455 hadint = TRU1;
1456 goto jjump;
1459 sigprocmask(SIG_SETMASK, &soldset, NULL);
1461 n_COLOUR( n_colour_env_push(); )
1462 rv = TRU1;
1463 for(ever = FAL0;; ever = TRU1){
1464 char const *beoe;
1465 int n;
1467 if(ever)
1468 n_memory_reset();
1470 /* Read a line of commands and handle end of file specially */
1471 ev.le_line.l = ev.le_line_size;
1472 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l, NULL);
1473 ev.le_line_size = (ui32_t)ev.le_line.l;
1474 ev.le_line.l = (ui32_t)n;
1476 if(n < 0)
1477 break;
1479 n = a_lex_evaluate(&ev);
1480 beoe = (n_poption & n_PO_BATCH_FLAG)
1481 ? ok_vlook(batch_exit_on_error) : NULL;
1483 if(n){
1484 if(beoe != NULL && *beoe == '1'){
1485 if(n_exit_status == n_EXIT_OK)
1486 n_exit_status = n_EXIT_ERR;
1488 rv = FAL0;
1489 break;
1491 if(beoe != NULL){
1492 if(n_exit_status != n_EXIT_OK)
1493 break;
1496 jjump: /* TODO */
1497 a_lex_unstack(!rv);
1498 n_COLOUR( n_colour_env_pop(FAL0); )
1500 if(ev.le_line.s != NULL)
1501 free(ev.le_line.s);
1503 if(soldhdl != SIG_IGN)
1504 safe_signal(SIGINT, soldhdl);
1505 NYD2_LEAVE;
1506 if(hadint){
1507 sigprocmask(SIG_SETMASK, &soldset, NULL);
1508 n_raise(SIGINT);
1510 return rv;
1513 static int
1514 a_lex_c_read(void *v){ /* TODO IFS? how? -r */
1515 struct n_sigman sm;
1516 char const **argv, *cp, *cp2;
1517 char *linebuf;
1518 size_t linesize;
1519 int rv;
1520 NYD2_ENTER;
1522 rv = 0;
1523 linesize = 0;
1524 linebuf = NULL;
1525 argv = v;
1527 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL){
1528 case 0:
1529 break;
1530 default:
1531 rv = 1;
1532 goto jleave;
1534 rv = n_lex_input(((n_pstate & n_PS_COMPOSE_MODE
1535 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1536 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1537 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1538 NULL, &linebuf, &linesize, NULL);
1539 if(rv < 0)
1540 goto jleave;
1542 if(rv > 0){
1543 cp = linebuf;
1545 for(rv = 0; *argv != NULL; ++argv){
1546 char c;
1548 while(blankspacechar(*cp))
1549 ++cp;
1550 if(*cp == '\0')
1551 break;
1553 /* The last variable gets the remaining line less trailing IFS */
1554 if(argv[1] == NULL){
1555 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1557 for(; cp2 > cp; --cp2){
1558 c = cp2[-1];
1559 if(!blankspacechar(c))
1560 break;
1562 }else
1563 for(cp2 = cp; (c = *++cp2) != '\0';)
1564 if(blankspacechar(c))
1565 break;
1567 /* C99 xxx This is a CC warning workaround (-Wbad-function-cast) */{
1568 char *vcp;
1570 vcp = savestrbuf(cp, PTR2SIZE(cp2 - cp));
1571 if(!a_lex__read_set(*argv, vcp)){
1572 rv = 1;
1573 break;
1577 cp = cp2;
1581 /* Set the remains to the empty string */
1582 for(; *argv != NULL; ++argv)
1583 if(!a_lex__read_set(*argv, n_empty)){
1584 rv = 1;
1585 break;
1588 if(rv == 0)
1589 n_pstate_var__em = n_0;
1591 n_sigman_cleanup_ping(&sm);
1592 jleave:
1593 if(linebuf != NULL)
1594 free(linebuf);
1595 NYD2_LEAVE;
1596 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
1597 return rv;
1600 static bool_t
1601 a_lex__read_set(char const *cp, char const *value){
1602 bool_t rv;
1603 NYD2_ENTER;
1605 if(!n_shexp_is_valid_varname(cp))
1606 value = N_("not a valid variable name");
1607 else if(!n_var_is_user_writable(cp))
1608 value = N_("variable is read-only");
1609 else if(!n_var_vset(cp, (uintptr_t)value))
1610 value = N_("failed to update variable value");
1611 else{
1612 rv = TRU1;
1613 goto jleave;
1615 n_err("`read': %s: %s\n", V_(value), n_shexp_quote_cp(cp, FAL0));
1616 rv = FAL0;
1617 jleave:
1618 NYD2_LEAVE;
1619 return rv;
1622 FL int
1623 c_cmdnotsupp(void *vp){
1624 NYD_ENTER;
1625 n_UNUSED(vp);
1626 n_err(_("The requested feature is not compiled in\n"));
1627 NYD_LEAVE;
1628 return 1;
1631 FL bool_t
1632 n_commands(void){ /* FIXME */
1633 struct a_lex_eval_ctx ev;
1634 int n, eofcnt;
1635 bool_t volatile rv;
1636 NYD_ENTER;
1638 rv = TRU1;
1640 if (!(n_pstate & n_PS_SOURCING)) {
1641 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1642 safe_signal(SIGINT, &a_lex_onintr);
1643 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1644 safe_signal(SIGHUP, &a_lex_hangup);
1646 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1647 safe_signal(SIGPIPE, a_lex_oldpipe);
1649 memset(&ev, 0, sizeof ev);
1651 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1652 for (eofcnt = 0;;) {
1653 n_COLOUR( n_colour_env_pop(TRU1); )
1655 /* TODO Unless we have our signal manager (or however we do it) child
1656 * TODO processes may have time slots where their execution isn't
1657 * TODO protected by signal handlers (in between start and setup
1658 * TODO completed). close_all_files() is only called from onintr()
1659 * TODO so those may linger possibly forever */
1660 if(!(n_pstate & n_PS_SOURCING))
1661 close_all_files();
1663 interrupts = 0;
1665 n_memory_reset();
1667 if (!(n_pstate & n_PS_SOURCING)) {
1668 char *cp;
1670 /* TODO Note: this buffer may contain a password. We should redefine
1671 * TODO the code flow which has to do that */
1672 if ((cp = termios_state.ts_linebuf) != NULL) {
1673 termios_state.ts_linebuf = NULL;
1674 termios_state.ts_linesize = 0;
1675 free(cp); /* TODO pool give-back */
1677 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1678 if (ev.le_line.l > LINESIZE * 3) {
1679 free(ev.le_line.s); /* TODO pool! but what? */
1680 ev.le_line.s = NULL;
1681 ev.le_line.l = ev.le_line_size = 0;
1685 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1686 char *cp;
1688 if ((cp = ok_vlook(newmail)) != NULL) {
1689 struct stat st;
1691 /* FIXME TEST WITH NOPOLL ETC. !!! */
1692 n = (cp != NULL && strcmp(cp, "nopoll"));
1693 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1694 st.st_size > mailsize) ||
1695 (mb.mb_type == MB_MAILDIR && n != 0)) {
1696 size_t odot = PTR2SIZE(dot - message);
1697 ui32_t odid = (n_pstate & n_PS_DID_PRINT_DOT);
1699 if (setfile(mailname,
1700 FEDIT_NEWMAIL |
1701 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1702 n_exit_status |= n_EXIT_ERR;
1703 rv = FAL0;
1704 break;
1706 dot = message + odot;
1707 n_pstate |= odid;
1711 n_exit_status = n_EXIT_OK;
1714 /* Read a line of commands and handle end of file specially */
1715 ev.le_line.l = ev.le_line_size;
1716 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1717 &ev.le_line.s, &ev.le_line.l, NULL);
1718 ev.le_line_size = (ui32_t)ev.le_line.l;
1719 ev.le_line.l = (ui32_t)n;
1721 if (n < 0) {
1722 /* FIXME did unstack() when n_PS_SOURCING, only break with n_PS_LOADING */
1723 if (!(n_pstate & n_PS_ROBOT) &&
1724 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1725 ++eofcnt < 4) {
1726 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1727 n_lex_input_clearerr();
1728 continue;
1730 break;
1733 n_pstate &= ~n_PS_HOOK_MASK;
1734 /* C99 */{
1735 char const *beoe;
1736 int estat;
1738 estat = a_lex_evaluate(&ev);
1739 beoe = (n_poption & n_PO_BATCH_FLAG)
1740 ? ok_vlook(batch_exit_on_error) : NULL;
1742 if(estat){
1743 if(beoe != NULL && *beoe == '1'){
1744 if(n_exit_status == n_EXIT_OK)
1745 n_exit_status = n_EXIT_ERR;
1746 rv = FAL0;
1747 break;
1749 if(!(n_psonce & n_PSO_STARTED)){ /* TODO join n_PS_EVAL_ERROR */
1750 if(a_lex_input == NULL ||
1751 !(a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)){
1752 rv = FAL0;
1753 break;
1755 }else
1756 break;
1759 if(beoe != NULL){
1760 if(n_exit_status != n_EXIT_OK)
1761 break;
1762 /* TODO n_PS_EVAL_ERROR and n_PS_SOURCING! Sigh!! */
1763 if((n_pstate & (n_PS_SOURCING | n_PS_EVAL_ERROR)
1764 ) == n_PS_EVAL_ERROR){
1765 n_exit_status = n_EXIT_ERR;
1766 break;
1771 if(!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE) &&
1772 ev.le_add_history)
1773 n_tty_addhist(ev.le_line.s, (ev.le_add_history != TRU1));
1775 if(n_pstate & n_PS_EXIT)
1776 break;
1779 a_lex_unstack(!rv);
1781 if (ev.le_line.s != NULL)
1782 free(ev.le_line.s);
1783 NYD_LEAVE;
1784 return rv;
1787 FL void
1788 n_lex_input_clearerr(void){
1789 FILE *fp;
1790 NYD2_ENTER;
1792 fp = NULL;
1794 if(a_lex_input == NULL)
1795 fp = n_stdin;
1796 else if(!(a_lex_input->li_flags & (a_LEX_FORCE_EOF |
1797 a_LEX_PIPE | a_LEX_MACRO | a_LEX_SLICE)))
1798 fp = a_lex_input->li_file;
1800 if(fp != NULL)
1801 clearerr(fp);
1802 NYD2_LEAVE;
1805 FL int
1806 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1807 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1808 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1809 struct n_string xprompt;
1810 FILE *ifile;
1811 bool_t doprompt, dotty;
1812 char const *iftype;
1813 int nold, n;
1814 NYD2_ENTER;
1816 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_FORCE_EOF)){
1817 n = -1;
1818 goto jleave;
1821 /* Special case macro mode: never need to prompt, lines have always been
1822 * unfolded already */
1823 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1824 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1825 struct a_lex_input_inject *liip;
1827 if(*linebuf != NULL)
1828 free(*linebuf);
1830 /* Injection in progress? Don't care about the autocommit state here */
1831 if((liip = a_lex_input->li_inject) != NULL){
1832 a_lex_input->li_inject = liip->lii_next;
1834 *linesize = liip->lii_len;
1835 *linebuf = (char*)liip;
1836 memmove(*linebuf, liip->lii_dat, liip->lii_len +1);
1837 iftype = "INJECTION";
1838 }else{
1839 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1840 *linesize = 0;
1841 n = -1;
1842 goto jleave;
1845 ++a_lex_input->li_loff;
1846 *linesize = strlen(*linebuf);
1847 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1848 *linebuf = sbufdup(*linebuf, *linesize);
1850 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1851 ? "-X OPTION"
1852 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1854 n = (int)*linesize;
1855 n_pstate |= n_PS_READLINE_NL;
1856 goto jhave_dat;
1859 /* Injection in progress? */
1860 if(!(lif & n_LEXINPUT_FORCE_STDIN)){
1861 struct a_lex_input_inject **liipp, *liip;
1863 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
1864 : &a_lex_input->li_inject;
1866 if((liip = *liipp) != NULL){
1867 *liipp = liip->lii_next;
1869 if(liip->lii_commit){
1870 if(*linebuf != NULL)
1871 free(*linebuf);
1873 /* Simply reuse the buffer */
1874 n = (int)(*linesize = liip->lii_len);
1875 *linebuf = (char*)liip;
1876 memmove(*linebuf, liip->lii_dat, liip->lii_len +1);
1877 iftype = "INJECTION";
1878 n_pstate |= n_PS_READLINE_NL;
1879 goto jhave_dat;
1880 }else{
1881 string = savestrbuf(liip->lii_dat, liip->lii_len);
1882 free(liip);
1887 n_pstate &= ~n_PS_READLINE_NL;
1888 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1889 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1890 doprompt = ((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1891 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT));
1892 dotty = (doprompt && !ok_blook(line_editor_disable));
1893 if(!doprompt)
1894 lif |= n_LEXINPUT_PROMPT_NONE;
1895 else{
1896 if(!dotty)
1897 n_string_creat_auto(&xprompt);
1898 if(prompt == NULL)
1899 lif |= n_LEXINPUT_PROMPT_EVAL;
1902 /* Ensure stdout is flushed first anyway */
1903 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1904 fflush(n_stdout);
1906 ifile = ((lif & n_LEXINPUT_FORCE_STDIN) || a_lex_input == NULL) ? n_stdin
1907 : a_lex_input->li_file;
1908 if(ifile == NULL){
1909 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1910 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO));
1911 ifile = n_stdin;
1914 for(nold = n = 0;;){
1915 if(dotty){
1916 assert(ifile == n_stdin);
1917 if(string != NULL && (n = (int)strlen(string)) > 0){
1918 if(*linesize > 0)
1919 *linesize += n +1;
1920 else
1921 *linesize = (size_t)n + LINESIZE +1;
1922 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1923 memcpy(*linebuf, string, (size_t)n +1);
1925 string = NULL;
1926 /* TODO if nold>0, don't redisplay the entire line!
1927 * TODO needs complete redesign ... */
1928 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1929 n_MEMORY_DEBUG_ARGSCALL);
1930 }else{
1931 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1932 n_tty_create_prompt(&xprompt, prompt, lif);
1933 if(xprompt.s_len > 0){
1934 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1935 fflush(n_stdout);
1939 n = (readline_restart)(ifile, linebuf, linesize, n
1940 n_MEMORY_DEBUG_ARGSCALL);
1942 if(n > 0 && nold > 0){
1943 int i = 0;
1944 char const *cp = *linebuf + nold;
1946 while(blankspacechar(*cp) && nold + i < n)
1947 ++cp, ++i;
1948 if(i > 0){
1949 memmove(*linebuf + nold, cp, n - nold - i);
1950 n -= i;
1951 (*linebuf)[n] = '\0';
1956 if(n <= 0)
1957 break;
1959 /* POSIX says:
1960 * An unquoted <backslash> at the end of a command line shall
1961 * be discarded and the next line shall continue the command */
1962 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1963 if(dotty)
1964 n_pstate |= n_PS_READLINE_NL;
1965 break;
1967 /* Definitely outside of quotes, thus the quoting rules are so that an
1968 * uneven number of successive reverse solidus at EOL is a continuation */
1969 if(n > 1){
1970 size_t i, j;
1972 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1973 if((*linebuf)[i] != '\\')
1974 break;
1975 if(!(j & 1))
1976 break;
1978 (*linebuf)[nold = --n] = '\0';
1979 lif |= n_LEXINPUT_NL_FOLLOW;
1982 if(n < 0)
1983 goto jleave;
1984 (*linebuf)[*linesize = n] = '\0';
1986 jhave_dat:
1987 #if 0
1988 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1989 char *cp, c;
1990 size_t i;
1992 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1993 c = *--cp;
1994 if(!blankspacechar(c))
1995 break;
1997 (*linebuf)[n = (int)i] = '\0';
2000 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
2001 char *cp, c;
2002 size_t j, i;
2004 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
2005 c = *cp++;
2006 if(!blankspacechar(c))
2007 break;
2009 if(i > 0){
2010 memmove(&(*linebuf)[0], &(*linebuf)[i], j -= i);
2011 (*linebuf)[n = (int)j] = '\0';
2014 #endif /* 0 (notyet - must take care for reverse solidus escaped space) */
2016 if(n_poption & n_PO_D_VV)
2017 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
2018 jleave:
2019 if (n_pstate & n_PS_PSTATE_PENDMASK)
2020 a_lex_update_pstate();
2022 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
2023 * TODO but only established from the outside and we need to drop this
2024 * TODO overlay context somehow */
2025 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
2026 a_lex_unstack(FAL0);
2027 NYD2_LEAVE;
2028 return n;
2031 FL char *
2032 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
2033 char const *string){
2034 struct n_sigman sm;
2035 size_t linesize;
2036 char *linebuf, *rv;
2037 int n;
2038 NYD2_ENTER;
2040 linesize = 0;
2041 linebuf = NULL;
2042 rv = NULL;
2044 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL) {
2045 case 0:
2046 break;
2047 default:
2048 goto jleave;
2051 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
2052 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
2053 (lif & n_LEXINPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE))
2054 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
2056 n_sigman_cleanup_ping(&sm);
2057 jleave:
2058 if(linebuf != NULL)
2059 free(linebuf);
2060 NYD2_LEAVE;
2061 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
2062 return rv;
2065 FL void
2066 n_load(char const *name){
2067 struct a_lex_input *lip;
2068 size_t i;
2069 FILE *fip;
2070 NYD_ENTER;
2072 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
2073 goto jleave;
2075 i = strlen(name) +1;
2076 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) + i);
2077 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2078 lip->li_file = fip;
2079 lip->li_flags = a_LEX_FREE;
2080 memcpy(lip->li_name, name, i);
2082 a_lex_load(lip);
2083 n_pstate &= ~n_PS_EXIT;
2084 jleave:
2085 NYD_LEAVE;
2088 FL void
2089 n_load_Xargs(char const **lines, size_t cnt){
2090 static char const name[] = "-X";
2092 ui8_t buf[sizeof(struct a_lex_input) + sizeof name];
2093 char const *srcp, *xsrcp;
2094 char *cp;
2095 size_t imax, i, len;
2096 struct a_lex_input *lip;
2097 NYD_ENTER;
2099 lip = (void*)buf;
2100 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2101 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2102 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
2103 memcpy(lip->li_name, name, sizeof name);
2105 /* The problem being that we want to support reverse solidus newline
2106 * escaping also within multiline -X, i.e., POSIX says:
2107 * An unquoted <backslash> at the end of a command line shall
2108 * be discarded and the next line shall continue the command
2109 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
2110 * entire lines array and set _MACRO_FREE_DATA */
2111 imax = cnt + 1;
2112 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
2114 /* For each of the input lines.. */
2115 for(i = len = 0, cp = NULL; cnt > 0;){
2116 bool_t keep;
2117 size_t j;
2119 if((j = strlen(srcp = *lines)) == 0){
2120 ++lines, --cnt;
2121 continue;
2124 /* Separate one line from a possible multiline input string */
2125 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
2126 *lines = &xsrcp[1];
2127 j = PTR2SIZE(xsrcp - srcp);
2128 }else
2129 ++lines, --cnt;
2131 /* The (separated) string may itself indicate soft newline escaping */
2132 if((keep = (srcp[j - 1] == '\\'))){
2133 size_t xj, xk;
2135 /* Need an uneven number of reverse solidus */
2136 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
2137 if(srcp[xj] != '\\')
2138 break;
2139 if(xk & 1)
2140 --j;
2141 else
2142 keep = FAL0;
2145 /* Strip any leading WS from follow lines, then */
2146 if(cp != NULL)
2147 while(j > 0 && blankspacechar(*srcp))
2148 ++srcp, --j;
2150 if(j > 0){
2151 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
2152 imax += 4;
2153 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
2154 imax);
2156 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
2157 memcpy(&cp[len], srcp, j);
2158 cp[len += j] = '\0';
2160 if(!keep)
2161 ++i;
2163 if(!keep)
2164 cp = NULL, len = 0;
2166 if(cp != NULL){
2167 assert(i + 1 < imax);
2168 lip->li_lines[i++] = cp;
2170 lip->li_lines[i] = NULL;
2172 a_lex_load(lip);
2173 if(n_pstate & n_PS_EXIT)
2174 exit(n_exit_status);
2175 NYD_LEAVE;
2178 FL int
2179 c_source(void *v){
2180 int rv;
2181 NYD_ENTER;
2183 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
2184 NYD_LEAVE;
2185 return rv;
2188 FL int
2189 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
2190 int rv;
2191 NYD_ENTER;
2193 rv = (a_lex_source_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
2194 NYD_LEAVE;
2195 return rv;
2198 FL bool_t
2199 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
2200 void (*on_finalize)(void*), void *finalize_arg){
2201 struct a_lex_input *lip;
2202 size_t i;
2203 int rv;
2204 NYD_ENTER;
2206 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2207 (i = strlen(name) +1));
2208 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2209 lip->li_outer = a_lex_input;
2210 lip->li_file = NULL;
2211 lip->li_cond = condstack_release();
2212 n_memory_autorec_push(&lip->li_autorecmem[0]);
2213 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2214 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2215 ? a_LEX_SUPER_MACRO : 0);
2216 lip->li_lines = lines;
2217 lip->li_on_finalize = on_finalize;
2218 lip->li_finalize_arg = finalize_arg;
2219 memcpy(lip->li_name, name, i);
2221 n_pstate |= n_PS_ROBOT;
2222 a_lex_input = lip;
2223 rv = a_commands_recursive(lif);
2224 NYD_LEAVE;
2225 return rv;
2228 FL bool_t
2229 n_source_command(enum n_lexinput_flags lif, char const *cmd){
2230 struct a_lex_input *lip;
2231 size_t i, ial;
2232 bool_t rv;
2233 NYD_ENTER;
2235 i = strlen(cmd) +1;
2236 ial = n_ALIGN(i);
2238 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2239 ial + 2*sizeof(char*));
2240 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2241 lip->li_outer = a_lex_input;
2242 lip->li_cond = condstack_release();
2243 n_memory_autorec_push(&lip->li_autorecmem[0]);
2244 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
2245 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2246 ? a_LEX_SUPER_MACRO : 0);
2247 lip->li_lines = (void*)&lip->li_name[ial];
2248 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
2249 lip->li_lines[1] = NULL;
2251 n_pstate |= n_PS_ROBOT;
2252 a_lex_input = lip;
2253 rv = a_commands_recursive(lif);
2254 NYD_LEAVE;
2255 return rv;
2258 FL void
2259 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
2260 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
2261 struct a_lex_input *lip;
2262 size_t i;
2263 NYD_ENTER;
2265 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2266 (i = strlen(cmd) +1));
2267 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2268 lip->li_outer = a_lex_input;
2269 lip->li_file = new_stdin;
2270 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
2271 lip->li_on_finalize = on_finalize;
2272 lip->li_finalize_arg = finalize_arg;
2273 lip->li_slice_stdin = n_stdin;
2274 lip->li_slice_stdout = n_stdout;
2275 lip->li_slice_psonce = n_psonce;
2276 memcpy(lip->li_name, cmd, i);
2278 n_stdin = new_stdin;
2279 n_stdout = new_stdout;
2280 n_psonce = new_psonce;
2281 n_pstate |= n_PS_ROBOT;
2282 a_lex_input = lip;
2283 NYD_LEAVE;
2286 FL void
2287 n_source_slice_hack_remove_after_jump(void){
2288 a_lex_unstack(FAL0);
2291 FL bool_t
2292 n_source_may_yield_control(void){ /* TODO this is a terrible hack */
2293 /* TODO This is obviously hacky in that it depends on _input_stack not
2294 * TODO loosing any flags when creating new contexts... Maybe this
2295 * TODO function should instead walk all up the context stack when
2296 * TODO there is one, and verify neither level prevents yielding! */
2297 struct a_lex_input *lip;
2298 bool_t rv;
2299 NYD2_ENTER;
2301 rv = FAL0;
2303 /* Only when interactive and startup completed */
2304 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) !=
2305 (n_PSO_INTERACTIVE | n_PSO_STARTED))
2306 goto jleave;
2308 /* Not when running any hook */
2309 if(n_pstate & n_PS_HOOK_MASK)
2310 goto jleave;
2312 /* Traverse up the stack:
2313 * . not when controlled by a child process
2314 * TODO . not when there are pipes involved, we neither handle job control,
2315 * TODO nor process groups, that is, controlling terminal acceptably
2316 * . not when sourcing a file */
2317 for(lip = a_lex_input; lip != NULL; lip = lip->li_outer){
2318 ui32_t f;
2320 if((f = lip->li_flags) & (a_LEX_PIPE | a_LEX_SLICE))
2321 goto jleave;
2322 if(!(f & a_LEX_MACRO))
2323 goto jleave;
2326 rv = TRU1;
2327 jleave:
2328 NYD2_LEAVE;
2329 return rv;
2332 FL void
2333 n_source_inject_input(enum n_input_inject_flags iif, char const *buf,
2334 size_t len){
2335 NYD_ENTER;
2336 if(len == UIZ_MAX)
2337 len = strlen(buf);
2339 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat) -1 > len &&
2340 len > 0){
2341 size_t i;
2342 struct a_lex_input_inject *liip, **liipp;
2344 liip = n_alloc(n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat
2345 ) + 1 + len +1);
2346 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
2347 : &a_lex_input->li_inject;
2348 liip->lii_next = *liipp;
2349 liip->lii_commit = ((iif & n_INPUT_INJECT_COMMIT) != 0);
2350 if(buf[i = 0] != ' ' && !(iif & n_INPUT_INJECT_HISTORY))
2351 liip->lii_dat[i++] = ' '; /* TODO prim. hack to avoid history put! */
2352 memcpy(&liip->lii_dat[i], buf, len);
2353 i += len;
2354 liip->lii_dat[liip->lii_len = i] = '\0';
2355 *liipp = liip;
2357 NYD_LEAVE;
2360 FL void
2361 n_source_force_eof(void){
2362 NYD_ENTER;
2363 assert(a_lex_input != NULL);
2364 a_lex_input->li_flags |= a_LEX_FORCE_EOF;
2365 NYD_LEAVE;
2368 /* s-it-mode */