Restore historical behaviour of *askb?cc* (Norman Ramsey)
[s-mailx.git] / go.c
blob1db7f7c9c6646e1f9c0c10db38851848b5c85f0c
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Program input of all sorts, input lexing, event loops, command evaluation.
3 *@ TODO n_PS_ROBOT requires yet n_PS_SOURCING, which REALLY sucks.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 #undef n_FILE
37 #define n_FILE go
39 #ifndef HAVE_AMALGAMATION
40 # include "nail.h"
41 #endif
43 enum a_go_flags{
44 a_GO_NONE,
45 a_GO_FREE = 1u<<0, /* Structure was allocated, n_free() it */
46 a_GO_PIPE = 1u<<1, /* Open on a pipe */
47 a_GO_FILE = 1u<<2, /* Loading or sourcing a file */
48 a_GO_MACRO = 1u<<3, /* Running a macro */
49 a_GO_MACRO_FREE_DATA = 1u<<4, /* Lines are allocated, n_free() 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_GO_MACRO_X_OPTION = 1u<<5, /* Macro indeed command line -X option */
53 a_GO_MACRO_CMD = 1u<<6, /* Macro indeed single-line: ~:COMMAND */
54 /* TODO a_GO_SPLICE: the right way to support *on-compose-splice(-shell)?*
55 * TODO would 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 _event_loop() would not call _evaluate() but CTX->on_read_line,
58 * TODO and _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_go_macro() could become extended,
62 * TODO and/or we would add a n_go_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 SPLICE 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 splice thing is very special and has to go again. HACK!!
71 * TODO a_go_input() will drop it once it sees EOF (HACK!), but care for
72 * TODO jumps must be taken by splice creators. HACK!!! But works. ;} */
73 a_GO_SPLICE = 1u<<7,
74 /* If it is none of those, it must be the outermost, the global one */
75 a_GO_TYPE_MASK = a_GO_PIPE | a_GO_FILE | a_GO_MACRO |
76 /* a_GO_MACRO_X_OPTION | a_GO_MACRO_CMD | */ a_GO_SPLICE,
78 a_GO_FORCE_EOF = 1u<<8, /* go_input() shall return EOF next */
79 a_GO_IS_EOF = 1u<<9,
81 a_GO_SUPER_MACRO = 1u<<16, /* *Not* inheriting n_PS_SOURCING state */
82 /* This context has inherited the memory pool from its parent.
83 * In practice only used for resource file loading and -X args, which enter
84 * a top level n_go_main_loop() and should (re)use the in practice already
85 * allocated memory pool of the global context */
86 a_GO_MEMPOOL_INHERITED = 1u<<17,
88 /* This context has inherited the entire data context from its parent */
89 a_GO_DATACTX_INHERITED = 1u<<18,
91 a_GO_XCALL_IS_CALL = 1u<<24, /* n_GO_INPUT_NO_XCALL */
92 /* `xcall' optimization barrier: n_go_macro() has been finished with
93 * a `xcall' request, and `xcall' set this in the parent a_go_input of the
94 * said n_go_macro() to indicate a barrier: we teardown the a_go_input of
95 * the n_go_macro() away after leaving its _event_loop(), but then,
96 * back in n_go_macro(), that enters a for(;;) loop that directly calls
97 * c_call() -- our `xcall' stack avoidance optimization --, yet this call
98 * will itself end up in a new n_go_macro(), and if that again ends up with
99 * `xcall' this should teardown and leave its own n_go_macro(), unrolling the
100 * stack "up to the barrier level", but which effectively still is the
101 * n_go_macro() that lost its a_go_input and is looping the `xcall'
102 * optimization loop. If no `xcall' is desired that loop is simply left and
103 * the _event_loop() of the outer a_go_ctx will perform a loop tick and
104 * clear this bit again OR become teardown itself */
105 a_GO_XCALL_LOOP = 1u<<25, /* `xcall' optimization barrier level */
106 a_GO_XCALL_LOOP_ERROR = 1u<<26, /* .. state machine error transporter */
107 a_GO_XCALL_LOOP_MASK = a_GO_XCALL_LOOP | a_GO_XCALL_LOOP_ERROR
110 enum a_go_cleanup_mode{
111 a_GO_CLEANUP_UNWIND = 1u<<0, /* Teardown all contexts except outermost */
112 a_GO_CLEANUP_TEARDOWN = 1u<<1, /* Teardown current context */
113 a_GO_CLEANUP_LOOPTICK = 1u<<2, /* Normal looptick cleanup */
114 a_GO_CLEANUP_MODE_MASK = n_BITENUM_MASK(0, 2),
116 a_GO_CLEANUP_ERROR = 1u<<8, /* Error occurred on level */
117 a_GO_CLEANUP_SIGINT = 1u<<9, /* Interrupt signal received */
118 a_GO_CLEANUP_HOLDALLSIGS = 1u<<10 /* hold_all_sigs() active TODO */
121 enum a_go_hist_flags{
122 a_GO_HIST_NONE = 0,
123 a_GO_HIST_ADD = 1u<<0,
124 a_GO_HIST_GABBY = 1u<<1,
125 a_GO_HIST_INIT = 1u<<2
128 struct a_go_eval_ctx{
129 struct str gec_line; /* The terminated data to _evaluate() */
130 ui32_t gec_line_size; /* May be used to store line memory size */
131 bool_t gec_ever_seen; /* Has ever been used (main_loop() only) */
132 ui8_t gec__dummy[2];
133 ui8_t gec_hist_flags; /* enum a_go_hist_flags */
134 char const *gec_hist_cmd; /* If a_GO_HIST_ADD only, cmd and args */
135 char const *gec_hist_args;
138 struct a_go_input_inject{
139 struct a_go_input_inject *gii_next;
140 size_t gii_len;
141 bool_t gii_commit;
142 bool_t gii_no_history;
143 char gii_dat[n_VFIELD_SIZE(6)];
146 struct a_go_ctx{
147 struct a_go_ctx *gc_outer;
148 sigset_t gc_osigmask;
149 ui32_t gc_flags; /* enum a_go_flags */
150 ui32_t gc_loff; /* Pseudo (macro): index in .gc_lines */
151 char **gc_lines; /* Pseudo content, lines unfolded */
152 FILE *gc_file; /* File we were in, if applicable */
153 struct a_go_input_inject *gc_inject; /* To be consumed first */
154 void (*gc_on_finalize)(void *);
155 void *gc_finalize_arg;
156 sigjmp_buf gc_eloop_jmp; /* TODO one day... for _event_loop() */
157 /* SPLICE hacks: saved stdin/stdout, saved pstate */
158 FILE *gc_splice_stdin;
159 FILE *gc_splice_stdout;
160 ui32_t gc_splice_psonce;
161 ui8_t gc_splice__dummy[4];
162 struct n_go_data_ctx gc_data;
163 char gc_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
166 struct a_go_readctl_ctx{ /* TODO localize n_readctl_overlay, use OnForkEvent! */
167 struct a_go_readctl_ctx *grc_last;
168 struct a_go_readctl_ctx *grc_next;
169 char const *grc_expand; /* If filename based, expanded string */
170 FILE *grc_fp;
171 si32_t grc_fd; /* Based upon file-descriptor */
172 char grc_name[n_VFIELD_SIZE(4)]; /* User input for identification purposes */
175 static sighandler_type a_go_oldpipe;
176 /* a_go_cmd_tab[] after fun protos */
178 /* Our current execution context, and the buffer backing the outermost level */
179 static struct a_go_ctx *a_go_ctx;
181 #define a_GO_MAINCTX_NAME "Main event loop"
182 static union{
183 ui64_t align;
184 char uf[n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
185 sizeof(a_GO_MAINCTX_NAME)];
186 } a_go__mainctx_b;
188 /* `xcall' stack-avoidance bypass optimization. This actually is
189 * a n_cmd_arg_save_to_heap() buffer with n_cmd_arg_ctx.cac_indat misused to
190 * point to the a_go_ctx to unroll up to */
191 static void *a_go_xcall;
193 static sigjmp_buf a_go_srbuf; /* TODO GET RID */
195 /* n_PS_STATE_PENDMASK requires some actions */
196 static void a_go_update_pstate(void);
198 /* Evaluate a single command */
199 static bool_t a_go_evaluate(struct a_go_eval_ctx *gecp);
201 /* Branch here on hangup signal and simulate "exit" */
202 static void a_go_hangup(int s);
204 /* The following gets called on receipt of an interrupt */
205 static void a_go_onintr(int s);
207 /* Cleanup current execution context, update the program state.
208 * If _CLEANUP_ERROR is set then we don't alert and error out if the stack
209 * doesn't exist at all, unless _CLEANUP_HOLDALLSIGS we hold_all_sigs() */
210 static void a_go_cleanup(enum a_go_cleanup_mode gcm);
212 /* `source' and `source_if' (if silent_open_error: no pipes allowed, then).
213 * Returns FAL0 if file is somehow not usable (unless silent_open_error) or
214 * upon evaluation error, and TRU1 on success */
215 static bool_t a_go_file(char const *file, bool_t silent_open_error);
217 /* System resource file load()ing or -X command line option array traversal */
218 static bool_t a_go_load(struct a_go_ctx *gcp);
220 /* A simplified command loop for recursed state machines */
221 static bool_t a_go_event_loop(struct a_go_ctx *gcp, enum n_go_input_flags gif);
223 static void
224 a_go_update_pstate(void){
225 bool_t act;
226 NYD_ENTER;
228 act = ((n_pstate & n_PS_SIGWINCH_PEND) != 0);
229 n_pstate &= ~n_PS_PSTATE_PENDMASK;
231 if(act){
232 char buf[32];
234 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
235 ok_vset(COLUMNS, buf);
236 snprintf(buf, sizeof buf, "%d", n_scrnheight);
237 ok_vset(LINES, buf);
239 NYD_LEAVE;
242 static bool_t
243 a_go_evaluate(struct a_go_eval_ctx *gecp){
244 /* xxx old style(9), but also old code */
245 /* TODO a_go_evaluate() should be splitted in multiple subfunctions,
246 * TODO `eval' should be a prefix, etc., a Ctx should be passed along */
247 struct str line;
248 struct n_string s, *sp;
249 struct str const *alias_exp;
250 char _wordbuf[2], **arglist_base/*[n_MAXARGC]*/, **arglist, *cp, *word;
251 char const *alias_name;
252 struct n_cmd_desc const *cdp;
253 si32_t nerrn, nexn; /* TODO n_pstate_ex_no -> si64_t! */
254 int rv, c;
255 enum{
256 a_NONE = 0,
257 a_ALIAS_MASK = n_BITENUM_MASK(0, 2), /* Alias recursion counter bits */
258 a_NOPREFIX = 1u<<4, /* Modifier prefix not allowed right now */
259 a_NOALIAS = 1u<<5, /* "No alias!" expansion modifier */
260 /* New modifier prefixes must be reflected in `commandalias' handling! */
261 a_IGNERR = 1u<<6, /* ignerr modifier prefix */
262 a_WYSH = 1u<<7, /* XXX v15+ drop wysh modifier prefix */
263 a_VPUT = 1u<<8, /* vput modifier prefix */
264 a_MODE_MASK = n_BITENUM_MASK(5, 8),
265 a_NO_ERRNO = 1u<<16 /* Don't set n_pstate_err_no */
266 } flags;
267 NYD_ENTER;
269 if(!(n_pstate & n_PS_ERR_EXIT_MASK))
270 n_exit_status = n_EXIT_OK;
272 flags = a_NONE;
273 rv = 1;
274 nerrn = n_ERR_NONE;
275 nexn = n_EXIT_OK;
276 cdp = NULL;
277 alias_name = NULL;
278 n_UNINIT(alias_exp, NULL);
279 arglist =
280 arglist_base = n_autorec_alloc(sizeof(*arglist_base) * n_MAXARGC);
281 line = gecp->gec_line; /* TODO const-ify original (buffer)! */
282 assert(line.s[line.l] == '\0');
284 if(line.l > 0 && spacechar(line.s[0]))
285 gecp->gec_hist_flags = a_GO_HIST_NONE;
286 else if(gecp->gec_hist_flags & a_GO_HIST_ADD)
287 gecp->gec_hist_cmd = gecp->gec_hist_args = NULL;
288 sp = NULL;
290 /* Aliases that refer to shell commands or macro expansion restart */
291 jrestart:
292 if(n_str_trim_ifs(&line, TRU1)->l == 0){
293 line.s[0] = '\0';
294 gecp->gec_hist_flags = a_GO_HIST_NONE;
295 goto jempty;
297 (cp = line.s)[line.l] = '\0';
299 /* No-expansion modifier? */
300 if(!(flags & a_NOPREFIX) && *cp == '\\'){
301 line.s = ++cp;
302 --line.l;
303 flags |= a_NOALIAS;
306 /* Note: adding more special treatments must be reflected in the `help' etc.
307 * output in cmd-tab.c! */
309 /* Ignore null commands (comments) */
310 if(*cp == '#'){
311 gecp->gec_hist_flags = a_GO_HIST_NONE;
312 goto jret0;
315 /* Handle ! differently to get the correct lexical conventions */
316 if(*cp == '!')
317 ++cp;
318 /* Isolate the actual command; since it may not necessarily be
319 * separated from the arguments (as in `p1') we need to duplicate it to
320 * be able to create a NUL terminated version.
321 * We must be aware of several special one letter commands here */
322 else if((cp = n_UNCONST(n_cmd_isolate(cp))) == line.s &&
323 (*cp == '|' || *cp == '?'))
324 ++cp;
325 c = (int)PTR2SIZE(cp - line.s);
326 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : n_autorec_alloc(c +1);
327 memcpy(word, arglist[0] = line.s, c);
328 word[c] = '\0';
329 line.l -= c;
330 line.s = cp;
332 /* It may be a modifier.
333 * Note: adding modifiers must be reflected in commandalias handling code */
334 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
335 flags |= a_NOPREFIX | a_IGNERR;
336 goto jrestart;
337 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
338 flags |= a_NOPREFIX | a_WYSH;
339 goto jrestart;
340 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
341 flags |= a_NOPREFIX | a_VPUT;
342 goto jrestart;
343 }else if(c == sizeof("u") -1 && *word == 'u'){
344 n_err(_("Ignoring yet unused `u' command modifier!"));
345 flags |= a_NOPREFIX;
346 goto jrestart;
349 /* We need to trim for a possible history entry, but do it anyway and insert
350 * a space for argument separation in case of alias expansion. Also, do
351 * terminate again because nothing prevents aliases from introducing WS */
352 n_str_trim_ifs(&line, TRU1);
353 line.s[line.l] = '\0';
355 /* Lengthy history entry setup, possibly even redundant. But having
356 * normalized history entries is a good thing, and this is maybe still
357 * cheaper than parsing a StrList of words per se */
358 if((gecp->gec_hist_flags & (a_GO_HIST_ADD | a_GO_HIST_INIT)
359 ) == a_GO_HIST_ADD){
360 if(line.l > 0){
361 sp = n_string_creat_auto(&s);
362 sp = n_string_assign_buf(sp, line.s, line.l);
363 gecp->gec_hist_args = n_string_cp(sp);
366 sp = n_string_creat_auto(&s);
367 sp = n_string_reserve(sp, 32);
369 if(flags & a_NOALIAS)
370 sp = n_string_push_c(sp, '\\');
371 if(flags & a_IGNERR)
372 sp = n_string_push_buf(sp, "ignerr ", sizeof("ignerr ") -1);
373 if(flags & a_WYSH)
374 sp = n_string_push_buf(sp, "wysh ", sizeof("wysh ") -1);
375 if(flags & a_VPUT)
376 sp = n_string_push_buf(sp, "vput ", sizeof("vput ") -1);
377 gecp->gec_hist_flags = a_GO_HIST_ADD | a_GO_HIST_INIT;
380 /* Look up the command; if not found, bitch.
381 * Normally, a blank command would map to the first command in the
382 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
383 * confusion; act just the same for aliases */
384 if(*word == '\0'){
385 jempty:
386 if((n_pstate & n_PS_ROBOT) || !(n_psonce & n_PSO_INTERACTIVE) ||
387 alias_name != NULL){
388 gecp->gec_hist_flags = a_GO_HIST_NONE;
389 goto jret0;
391 cdp = n_cmd_default();
392 goto jexec;
395 if(!(flags & a_NOALIAS) && (flags & a_ALIAS_MASK) != a_ALIAS_MASK){
396 ui8_t expcnt;
398 expcnt = (flags & a_ALIAS_MASK);
399 ++expcnt;
400 flags = (flags & ~(a_ALIAS_MASK | a_NOPREFIX)) | expcnt;
402 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
403 if(alias_name != NULL && !strcmp(word, alias_name)){
404 if(n_poption & n_PO_D_V)
405 n_err(_("Actively avoiding self-recursion of `commandalias': %s\n"),
406 word);
407 }else if((alias_name = n_commandalias_exists(word, &alias_exp)) != NULL){
408 size_t i;
410 if(sp != NULL){
411 sp = n_string_push_cp(sp, word);
412 gecp->gec_hist_cmd = n_string_cp(sp);
413 sp = NULL;
416 /* And join arguments onto alias expansion */
417 alias_name = word;
418 i = alias_exp->l;
419 cp = line.s;
420 line.s = n_autorec_alloc(i + 1 + line.l +1);
421 memcpy(line.s, alias_exp->s, i);
422 if(line.l > 0){
423 line.s[i++] = ' ';
424 memcpy(&line.s[i], cp, line.l);
426 line.s[i += line.l] = '\0';
427 line.l = i;
428 goto jrestart;
432 if((cdp = n_cmd_firstfit(word)) == NULL){
433 bool_t doskip;
435 if(!(doskip = n_cnd_if_isskip()) || (n_poption & n_PO_D_V))
436 n_err(_("Unknown command%s: `%s'\n"),
437 (doskip ? _(" (ignored due to `if' condition)") : n_empty),
438 prstr(word));
439 gecp->gec_hist_flags = a_GO_HIST_NONE;
440 if(doskip)
441 goto jret0;
442 nerrn = n_ERR_NOSYS;
443 goto jleave;
446 /* See if we should execute the command -- if a conditional we always
447 * execute it, otherwise, check the state of cond */
448 jexec:
449 if(!(cdp->cd_caflags & n_CMD_ARG_F) && n_cnd_if_isskip()){
450 gecp->gec_hist_flags = a_GO_HIST_NONE;
451 goto jret0;
454 if(sp != NULL){
455 sp = n_string_push_cp(sp, cdp->cd_name);
456 gecp->gec_hist_cmd = n_string_cp(sp);
457 sp = NULL;
460 nerrn = n_ERR_INVAL;
462 /* Process the arguments to the command, depending on the type it expects */
463 if((cdp->cd_caflags & n_CMD_ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
464 !(n_poption & n_PO_BATCH_FLAG)){
465 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
466 cdp->cd_name);
467 goto jleave;
469 if(!(cdp->cd_caflags & n_CMD_ARG_M) && (n_psonce & n_PSO_SENDMODE)){
470 n_err(_("May not execute `%s' while sending\n"), cdp->cd_name);
471 goto jleave;
473 if(cdp->cd_caflags & n_CMD_ARG_R){
474 if(n_pstate & n_PS_COMPOSE_MODE){
475 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
476 n_err(_("Cannot invoke `%s' when in compose mode\n"), cdp->cd_name);
477 goto jleave;
479 /* TODO Nothing should prevent n_CMD_ARG_R in conjunction with
480 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
481 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING) && !n_go_may_yield_control()){
482 n_err(_("Cannot invoke `%s' in this program state\n"),
483 cdp->cd_name);
484 goto jleave;
487 if((cdp->cd_caflags & n_CMD_ARG_S) && !(n_psonce & n_PSO_STARTED)){
488 n_err(_("May not execute `%s' during startup\n"), cdp->cd_name);
489 goto jleave;
491 if(!(cdp->cd_caflags & n_CMD_ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
492 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
493 cdp->cd_name);
494 goto jleave;
497 if((cdp->cd_caflags & n_CMD_ARG_A) && mb.mb_type == MB_VOID){
498 n_err(_("Cannot execute `%s' without active mailbox\n"), cdp->cd_name);
499 goto jleave;
501 if((cdp->cd_caflags & n_CMD_ARG_W) && !(mb.mb_perm & MB_DELE)){
502 n_err(_("May not execute `%s' -- message file is read only\n"),
503 cdp->cd_name);
504 goto jleave;
507 if(cdp->cd_caflags & n_CMD_ARG_O)
508 n_OBSOLETE2(_("this command will be removed"), cdp->cd_name);
510 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
511 * TODO doesn't use any of those list commands which strip this mask,
512 * TODO and for now we misuse bits for checking relation to history;
513 * TODO argument state should be property of a per-command carrier instead */
514 n_pstate &= ~n_PS_ARGLIST_MASK;
516 if((flags & a_WYSH) &&
517 (cdp->cd_caflags & n_CMD_ARG_TYPE_MASK) != n_CMD_ARG_TYPE_WYRA){
518 n_err(_("`wysh' prefix does not affect `%s'\n"), cdp->cd_name);
519 flags &= ~a_WYSH;
522 if(flags & a_VPUT){
523 if(cdp->cd_caflags & n_CMD_ARG_V){
524 char const *emsg;
526 emsg = line.s; /* xxx Cannot pass &char* as char const**, so no cp */
527 arglist[0] = n_shexp_parse_token_cp((n_SHEXP_PARSE_TRIM_SPACE |
528 n_SHEXP_PARSE_TRIM_IFSSPACE | n_SHEXP_PARSE_LOG |
529 n_SHEXP_PARSE_META_SEMICOLON | n_SHEXP_PARSE_META_KEEP), &emsg);
530 line.l -= PTR2SIZE(emsg - line.s);
531 line.s = cp = n_UNCONST(emsg);
532 if(cp == NULL)
533 emsg = N_("could not parse input token");
534 else if(!n_shexp_is_valid_varname(arglist[0]))
535 emsg = N_("not a valid variable name");
536 else if(!n_var_is_user_writable(arglist[0]))
537 emsg = N_("either not a user writable, or a boolean variable");
538 else
539 emsg = NULL;
540 if(emsg != NULL){
541 n_err("`%s': vput: %s: %s\n",
542 cdp->cd_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
543 nerrn = n_ERR_NOTSUP;
544 rv = -1;
545 goto jleave;
547 ++arglist;
548 n_pstate |= n_PS_ARGMOD_VPUT; /* TODO YET useless since stripped later
549 * TODO on in getrawlist() etc., i.e., the argument vector producers,
550 * TODO therefore yet needs to be set again based on flags&a_VPUT! */
551 }else{
552 n_err(_("`vput' prefix does not affect `%s'\n"), cdp->cd_name);
553 flags &= ~a_VPUT;
557 switch(cdp->cd_caflags & n_CMD_ARG_TYPE_MASK){
558 case n_CMD_ARG_TYPE_MSGLIST:
559 /* Message list defaulting to nearest forward legal message */
560 if(n_msgvec == NULL)
561 goto jemsglist;
562 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
563 nerrn = n_ERR_NOMSG;
564 flags |= a_NO_ERRNO;
565 break;
567 if(c == 0){
568 if((n_msgvec[0] = first(cdp->cd_msgflag, cdp->cd_msgmask)) != 0)
569 n_msgvec[1] = 0;
571 if(n_msgvec[0] == 0){
572 jemsglist:
573 if(!(n_pstate & n_PS_HOOK_MASK))
574 fprintf(n_stdout, _("No applicable messages\n"));
575 nerrn = n_ERR_NOMSG;
576 flags |= a_NO_ERRNO;
577 break;
579 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
580 n_err_no = 0;
581 rv = (*cdp->cd_func)(n_msgvec);
582 break;
584 case n_CMD_ARG_TYPE_NDMLIST:
585 /* Message list with no defaults, but no error if none exist */
586 if(n_msgvec == NULL)
587 goto jemsglist;
588 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
589 nerrn = n_ERR_NOMSG;
590 flags |= a_NO_ERRNO;
591 break;
593 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
594 n_err_no = 0;
595 rv = (*cdp->cd_func)(n_msgvec);
596 break;
598 case n_CMD_ARG_TYPE_STRING:
599 /* Just the straight string, old style, with leading blanks removed */
600 for(cp = line.s; spacechar(*cp);)
601 ++cp;
602 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
603 n_err_no = 0;
604 rv = (*cdp->cd_func)(cp);
605 break;
606 case n_CMD_ARG_TYPE_RAWDAT:
607 /* Just the straight string, placed in argv[] */
608 *arglist++ = line.s;
609 *arglist = NULL;
610 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
611 n_err_no = 0;
612 rv = (*cdp->cd_func)(arglist_base);
613 break;
615 case n_CMD_ARG_TYPE_WYSH:
616 c = 1;
617 if(0){
618 /* FALLTHRU */
619 case n_CMD_ARG_TYPE_WYRA:
620 c = (flags & a_WYSH) ? 1 : 0;
621 if(0){
622 case n_CMD_ARG_TYPE_RAWLIST:
623 c = 0;
626 if((c = getrawlist((c != 0), arglist,
627 n_MAXARGC - PTR2SIZE(arglist - arglist_base), line.s, line.l)) < 0){
628 n_err(_("Invalid argument list\n"));
629 flags |= a_NO_ERRNO;
630 break;
633 if(c < cdp->cd_minargs){
634 n_err(_("`%s' requires at least %u arg(s)\n"),
635 cdp->cd_name, (ui32_t)cdp->cd_minargs);
636 flags |= a_NO_ERRNO;
637 break;
639 #undef cd_minargs
640 if(c > cdp->cd_maxargs){
641 n_err(_("`%s' takes no more than %u arg(s)\n"),
642 cdp->cd_name, (ui32_t)cdp->cd_maxargs);
643 flags |= a_NO_ERRNO;
644 break;
646 #undef cd_maxargs
648 if(flags & a_VPUT)
649 n_pstate |= n_PS_ARGMOD_VPUT;
651 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
652 n_err_no = 0;
653 rv = (*cdp->cd_func)(arglist_base);
654 if(a_go_xcall != NULL)
655 goto jret0;
656 break;
658 case n_CMD_ARG_TYPE_ARG:{
659 /* TODO The _ARG_TYPE_ARG is preliminary, in the end we should have a
660 * TODO per command-ctx carrier that also has slots for it arguments,
661 * TODO and that should be passed along all the way. No more arglists
662 * TODO here, etc. */
663 struct n_cmd_arg_ctx cac;
665 cac.cac_desc = cdp->cd_cadp;
666 cac.cac_indat = line.s;
667 cac.cac_inlen = line.l;
668 if(!n_cmd_arg_parse(&cac)){
669 flags |= a_NO_ERRNO;
670 break;
673 if(flags & a_VPUT){
674 cac.cac_vput = *arglist_base;
675 n_pstate |= n_PS_ARGMOD_VPUT;
676 }else
677 cac.cac_vput = NULL;
679 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
680 n_err_no = 0;
681 rv = (*cdp->cd_func)(&cac);
682 if(a_go_xcall != NULL)
683 goto jret0;
684 } break;
686 default:
687 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
688 cdp->cd_caflags & n_CMD_ARG_TYPE_MASK); )
689 nerrn = n_ERR_NOTOBACCO;
690 nexn = 1;
691 goto jret0;
694 if(gecp->gec_hist_flags & a_GO_HIST_ADD){
695 if(cdp->cd_caflags & n_CMD_ARG_H)
696 gecp->gec_hist_flags = a_GO_HIST_NONE;
697 else if((cdp->cd_caflags & n_CMD_ARG_G) ||
698 (n_pstate & n_PS_MSGLIST_GABBY))
699 gecp->gec_hist_flags |= a_GO_HIST_GABBY;
702 if(rv != 0){
703 if(!(flags & a_NO_ERRNO)){
704 if(cdp->cd_caflags & n_CMD_ARG_EM)
705 flags |= a_NO_ERRNO;
706 else if((nerrn = n_err_no) == 0)
707 nerrn = n_ERR_INVAL;
708 }else
709 flags ^= a_NO_ERRNO;
710 }else if(cdp->cd_caflags & n_CMD_ARG_EM)
711 flags |= a_NO_ERRNO;
712 else
713 nerrn = n_ERR_NONE;
714 jleave:
715 nexn = rv;
717 if(flags & a_IGNERR){
718 n_pstate &= ~n_PS_ERR_EXIT_MASK;
719 if(!(n_pstate & n_PS_ERR_EXIT_MASK))
720 n_exit_status = n_EXIT_OK;
721 }else if(rv != 0){
722 bool_t bo;
724 if((bo = ok_blook(batch_exit_on_error))){
725 n_OBSOLETE(_("please use *errexit*, not *batch-exit-on-error*"));
726 if(!(n_poption & n_PO_BATCH_FLAG))
727 bo = FAL0;
729 if(ok_blook(errexit) || bo) /* TODO v15: drop bo */
730 n_pstate |= n_PS_ERR_QUIT;
731 else if(ok_blook(posix)){
732 if(n_psonce & n_PSO_STARTED)
733 rv = 0;
734 else if(!(n_psonce & n_PSO_INTERACTIVE))
735 n_pstate |= n_PS_ERR_XIT;
736 }else
737 rv = 0;
739 if(rv != 0){
740 if(n_exit_status == n_EXIT_OK)
741 n_exit_status = n_EXIT_ERR;
742 if((n_poption & n_PO_D_V) &&
743 !(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)))
744 n_alert(_("Non-interactive, bailing out due to errors "
745 "in startup load phase"));
746 goto jret;
750 if(cdp == NULL)
751 goto jret0;
752 if((cdp->cd_caflags & n_CMD_ARG_P) && ok_blook(autoprint))
753 if(visible(dot))
754 n_go_input_inject(n_GO_INPUT_INJECT_COMMIT, "\\type",
755 sizeof("\\type") -1);
757 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
758 !(cdp->cd_caflags & n_CMD_ARG_T))
759 n_pstate |= n_PS_SAW_COMMAND;
760 jret0:
761 rv = 0;
762 jret:
763 if(!(flags & a_NO_ERRNO))
764 n_pstate_err_no = nerrn;
765 n_pstate_ex_no = nexn;
766 NYD_LEAVE;
767 return (rv == 0);
770 static void
771 a_go_hangup(int s){
772 NYD_X; /* Signal handler */
773 n_UNUSED(s);
774 /* nothing to do? */
775 exit(n_EXIT_ERR);
778 #ifdef HAVE_IMAP
779 FL void n_go_onintr_for_imap(void){a_go_onintr(0);}
780 #endif
781 static void
782 a_go_onintr(int s){ /* TODO block signals while acting */
783 NYD_X; /* Signal handler */
784 n_UNUSED(s);
786 safe_signal(SIGINT, a_go_onintr);
788 termios_state_reset();
790 a_go_cleanup(a_GO_CLEANUP_UNWIND | /* XXX FAKE */a_GO_CLEANUP_HOLDALLSIGS);
792 if(interrupts != 1)
793 n_err_sighdl(_("Interrupt\n"));
794 safe_signal(SIGPIPE, a_go_oldpipe);
795 siglongjmp(a_go_srbuf, 0); /* FIXME get rid */
798 static void
799 a_go_cleanup(enum a_go_cleanup_mode gcm){
800 /* Signals blocked */
801 struct a_go_ctx *gcp;
802 NYD_ENTER;
804 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
805 hold_all_sigs();
806 jrestart:
807 gcp = a_go_ctx;
809 /* Free input injections of this level first */
810 if(!(gcm & a_GO_CLEANUP_LOOPTICK)){
811 struct a_go_input_inject **giipp, *giip;
813 for(giipp = &gcp->gc_inject; (giip = *giipp) != NULL;){
814 *giipp = giip->gii_next;
815 n_free(giip);
819 /* Cleanup non-crucial external stuff */
820 n_COLOUR(
821 if(gcp->gc_data.gdc_colour != NULL)
822 n_colour_stack_del(&gcp->gc_data);
825 /* Work the actual context (according to cleanup mode) */
826 if(gcp->gc_outer == NULL){
827 if(gcm & (a_GO_CLEANUP_UNWIND | a_GO_CLEANUP_SIGINT)){
828 if(a_go_xcall != NULL){
829 n_free(a_go_xcall);
830 a_go_xcall = NULL;
832 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
833 n_pstate &= ~n_PS_ERR_EXIT_MASK;
834 close_all_files();
835 }else{
836 if(!(n_pstate & n_PS_SOURCING))
837 close_all_files();
840 n_memory_reset();
842 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
843 assert(a_go_xcall == NULL);
844 assert(!(gcp->gc_flags & a_GO_XCALL_LOOP_MASK));
845 assert(gcp->gc_on_finalize == NULL);
846 assert(gcp->gc_data.gdc_colour == NULL);
847 goto jxleave;
848 }else if(gcm & a_GO_CLEANUP_LOOPTICK){
849 n_memory_reset();
850 goto jxleave;
851 }else if(gcp->gc_flags & a_GO_SPLICE){ /* TODO Temporary hack */
852 n_stdin = gcp->gc_splice_stdin;
853 n_stdout = gcp->gc_splice_stdout;
854 n_psonce = gcp->gc_splice_psonce;
855 goto jstackpop;
858 /* Cleanup crucial external stuff */
859 if(gcp->gc_data.gdc_ifcond != NULL){
860 n_cnd_if_stack_del(&gcp->gc_data);
861 if(!(gcm & (a_GO_CLEANUP_ERROR | a_GO_CLEANUP_SIGINT)) &&
862 !(gcp->gc_flags & a_GO_FORCE_EOF) && a_go_xcall == NULL &&
863 !(n_psonce & n_PSO_EXIT_MASK)){
864 n_err(_("Unmatched `if' at end of %s %s\n"),
865 ((gcp->gc_flags & a_GO_MACRO
866 ? (gcp->gc_flags & a_GO_MACRO_CMD ? _("command") : _("macro"))
867 : _("`source'd file"))),
868 gcp->gc_name);
869 gcm |= a_GO_CLEANUP_ERROR;
873 /* Teardown context */
874 if(gcp->gc_flags & a_GO_MACRO){
875 if(gcp->gc_flags & a_GO_MACRO_FREE_DATA){
876 char **lp;
878 while(*(lp = &gcp->gc_lines[gcp->gc_loff]) != NULL){
879 n_free(*lp);
880 ++gcp->gc_loff;
882 /* Part of gcp's memory chunk, then */
883 if(!(gcp->gc_flags & a_GO_MACRO_CMD))
884 n_free(gcp->gc_lines);
886 }else if(gcp->gc_flags & a_GO_PIPE)
887 /* XXX command manager should -TERM then -KILL instead of hoping
888 * XXX for exit of provider due to n_ERR_PIPE / SIGPIPE */
889 Pclose(gcp->gc_file, TRU1);
890 else if(gcp->gc_flags & a_GO_FILE)
891 Fclose(gcp->gc_file);
893 if(!(gcp->gc_flags & a_GO_MEMPOOL_INHERITED)){
894 if(gcp->gc_data.gdc_mempool != NULL)
895 n_memory_pool_pop(NULL);
896 }else
897 n_memory_reset();
899 jstackpop:
900 /* Update a_go_ctx and n_go_data, n_pstate ... */
901 a_go_ctx = gcp->gc_outer;
902 assert(a_go_ctx != NULL);
903 /* C99 */{
904 struct a_go_ctx *x;
906 for(x = a_go_ctx; x->gc_flags & a_GO_DATACTX_INHERITED;){
907 x = x->gc_outer;
908 assert(x != NULL);
910 n_go_data = &x->gc_data;
913 if((a_go_ctx->gc_flags & (a_GO_MACRO | a_GO_SUPER_MACRO)) ==
914 (a_GO_MACRO | a_GO_SUPER_MACRO)){
915 n_pstate &= ~n_PS_SOURCING;
916 assert(n_pstate & n_PS_ROBOT);
917 }else if(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK))
918 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
919 else
920 assert(n_pstate & n_PS_ROBOT);
922 if(gcp->gc_on_finalize != NULL)
923 (*gcp->gc_on_finalize)(gcp->gc_finalize_arg);
925 if(gcm & a_GO_CLEANUP_ERROR){
926 if(a_go_ctx->gc_flags & a_GO_XCALL_LOOP)
927 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP_ERROR;
928 goto jerr;
930 jleave:
931 if(gcp->gc_flags & a_GO_FREE)
932 n_free(gcp);
934 if(n_UNLIKELY((gcm & a_GO_CLEANUP_UNWIND) && gcp != a_go_ctx))
935 goto jrestart;
937 jxleave:
938 NYD_LEAVE;
939 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
940 rele_all_sigs();
941 return;
943 jerr:
944 /* With *posix* we follow what POSIX says:
945 * Any errors in the start-up file shall either cause mailx to
946 * terminate with a diagnostic message and a non-zero status or to
947 * continue after writing a diagnostic message, ignoring the
948 * remainder of the lines in the start-up file
949 * Print the diagnostic only for the outermost resource unless the user
950 * is debugging or in verbose mode */
951 if((n_poption & n_PO_D_V) ||
952 (!(n_psonce & n_PSO_STARTED) &&
953 !(gcp->gc_flags & (a_GO_SPLICE | a_GO_MACRO)) &&
954 !(gcp->gc_outer->gc_flags & a_GO_TYPE_MASK)))
955 /* I18N: file inclusion, macro etc. evaluation has been stopped */
956 n_alert(_("Stopped %s %s due to errors%s"),
957 (n_psonce & n_PSO_STARTED
958 ? (gcp->gc_flags & a_GO_SPLICE ? _("spliced in program")
959 : (gcp->gc_flags & a_GO_MACRO
960 ? (gcp->gc_flags & a_GO_MACRO_CMD
961 ? _("evaluating command") : _("evaluating macro"))
962 : (gcp->gc_flags & a_GO_PIPE
963 ? _("executing `source'd pipe")
964 : (gcp->gc_flags & a_GO_FILE
965 ? _("loading `source'd file") : _(a_GO_MAINCTX_NAME))))
967 : (gcp->gc_flags & a_GO_MACRO
968 ? (gcp->gc_flags & a_GO_MACRO_X_OPTION
969 ? _("evaluating command line") : _("evaluating macro"))
970 : _("loading initialization resource"))),
971 n_shexp_quote_cp(gcp->gc_name, FAL0),
972 (n_poption & n_PO_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
973 goto jleave;
976 static bool_t
977 a_go_file(char const *file, bool_t silent_open_error){
978 struct a_go_ctx *gcp;
979 sigset_t osigmask;
980 size_t nlen;
981 char *nbuf;
982 bool_t ispipe;
983 FILE *fip;
984 NYD_ENTER;
986 fip = NULL;
988 /* Being a command argument file is space-trimmed *//* TODO v15 with
989 * TODO WYRALIST this is no longer necessary true, and for that we
990 * TODO don't set _PARSE_TRIM_SPACE because we cannot! -> cmd-tab.h!! */
991 #if 0
992 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
993 file[--nlen] == '|')))
994 #else
995 ispipe = FAL0;
996 if(!silent_open_error){
997 for(nlen = strlen(file); nlen > 0;){
998 char c;
1000 c = file[--nlen];
1001 if(!spacechar(c)){
1002 if(c == '|'){
1003 nbuf = savestrbuf(file, nlen);
1004 ispipe = TRU1;
1006 break;
1010 #endif
1012 if(ispipe){
1013 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1014 ok_vlook(SHELL), NULL, n_CHILD_FD_NULL)) == NULL)
1015 goto jeopencheck;
1016 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1017 goto jeopencheck;
1018 else if((fip = Fopen(nbuf, "r")) == NULL){
1019 jeopencheck:
1020 if(!silent_open_error || (n_poption & n_PO_D_V))
1021 n_perr(nbuf, 0);
1022 if(silent_open_error)
1023 fip = (FILE*)-1;
1024 goto jleave;
1027 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1029 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1030 (nlen = strlen(nbuf) +1));
1031 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1033 hold_all_sigs();
1035 gcp->gc_outer = a_go_ctx;
1036 gcp->gc_osigmask = osigmask;
1037 gcp->gc_file = fip;
1038 gcp->gc_flags = (ispipe ? a_GO_FREE | a_GO_PIPE : a_GO_FREE | a_GO_FILE) |
1039 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO ? a_GO_SUPER_MACRO : 0);
1040 memcpy(gcp->gc_name, nbuf, nlen);
1042 a_go_ctx = gcp;
1043 n_go_data = &gcp->gc_data;
1044 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1045 if(!a_go_event_loop(gcp, n_GO_INPUT_NONE | n_GO_INPUT_NL_ESC))
1046 fip = NULL;
1047 jleave:
1048 NYD_LEAVE;
1049 return (fip != NULL);
1052 static bool_t
1053 a_go_load(struct a_go_ctx *gcp){
1054 NYD2_ENTER;
1056 assert(!(n_psonce & n_PSO_STARTED));
1057 assert(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK));
1059 gcp->gc_flags |= a_GO_MEMPOOL_INHERITED;
1060 gcp->gc_data.gdc_mempool = n_go_data->gdc_mempool;
1062 hold_all_sigs();
1064 /* POSIX:
1065 * Any errors in the start-up file shall either cause mailx to terminate
1066 * with a diagnostic message and a non-zero status or to continue after
1067 * writing a diagnostic message, ignoring the remainder of the lines in
1068 * the start-up file. */
1069 gcp->gc_outer = a_go_ctx;
1070 a_go_ctx = gcp;
1071 n_go_data = &gcp->gc_data;
1072 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1073 n_pstate |= n_PS_ROBOT |
1074 (gcp->gc_flags & a_GO_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1076 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1078 rele_all_sigs();
1080 n_go_main_loop();
1081 NYD2_LEAVE;
1082 return (((n_psonce & n_PSO_EXIT_MASK) |
1083 (n_pstate & n_PS_ERR_EXIT_MASK)) == 0);
1086 static void
1087 a_go__eloopint(int sig){ /* TODO one day, we don't need it no more */
1088 NYD_X; /* Signal handler */
1089 n_UNUSED(sig);
1090 siglongjmp(a_go_ctx->gc_eloop_jmp, 1);
1093 static bool_t
1094 a_go_event_loop(struct a_go_ctx *gcp, enum n_go_input_flags gif){
1095 sighandler_type soldhdl;
1096 struct a_go_eval_ctx gec;
1097 enum {a_RETOK = TRU1, a_TICKED = 1<<1} volatile f;
1098 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1099 sigset_t osigmask;
1100 NYD2_ENTER;
1102 memset(&gec, 0, sizeof gec);
1103 osigmask = gcp->gc_osigmask;
1104 hadint = FAL0;
1105 f = a_RETOK;
1107 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1108 safe_signal(SIGINT, &a_go__eloopint);
1109 if(sigsetjmp(gcp->gc_eloop_jmp, 1)){
1110 hold_all_sigs();
1111 hadint = TRU1;
1112 f &= ~a_RETOK;
1113 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1114 goto jjump;
1118 for(;; f |= a_TICKED){
1119 int n;
1121 if(f & a_TICKED)
1122 n_memory_reset();
1124 /* Read a line of commands and handle end of file specially */
1125 gec.gec_line.l = gec.gec_line_size;
1126 rele_all_sigs();
1127 n = n_go_input(gif, NULL, &gec.gec_line.s, &gec.gec_line.l, NULL, NULL);
1128 hold_all_sigs();
1129 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1130 gec.gec_line.l = (ui32_t)n;
1132 if(n < 0)
1133 break;
1135 rele_all_sigs();
1136 assert(gec.gec_hist_flags == a_GO_HIST_NONE);
1137 if(!a_go_evaluate(&gec))
1138 f &= ~a_RETOK;
1139 hold_all_sigs();
1141 if(!(f & a_RETOK) || a_go_xcall != NULL ||
1142 (n_psonce & n_PSO_EXIT_MASK) || (n_pstate & n_PS_ERR_EXIT_MASK))
1143 break;
1146 jjump: /* TODO Should be _CLEANUP_UNWIND not _TEARDOWN on signal if DOABLE! */
1147 a_go_cleanup(a_GO_CLEANUP_TEARDOWN |
1148 (f & a_RETOK ? 0 : a_GO_CLEANUP_ERROR) |
1149 (hadint ? a_GO_CLEANUP_SIGINT : 0) | a_GO_CLEANUP_HOLDALLSIGS);
1151 if(gec.gec_line.s != NULL)
1152 n_free(gec.gec_line.s);
1154 if(soldhdl != SIG_IGN)
1155 safe_signal(SIGINT, soldhdl);
1156 NYD2_LEAVE;
1157 rele_all_sigs();
1158 if(hadint){
1159 sigprocmask(SIG_SETMASK, &osigmask, NULL);
1160 n_raise(SIGINT);
1162 return (f & a_RETOK);
1165 FL void
1166 n_go_init(void){
1167 struct a_go_ctx *gcp;
1168 NYD2_ENTER;
1170 assert(n_stdin != NULL);
1172 gcp = (void*)a_go__mainctx_b.uf;
1173 DBGOR( memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name)),
1174 memset(&gcp->gc_data, 0, sizeof gcp->gc_data) );
1175 gcp->gc_file = n_stdin;
1176 memcpy(gcp->gc_name, a_GO_MAINCTX_NAME, sizeof(a_GO_MAINCTX_NAME));
1177 a_go_ctx = gcp;
1178 n_go_data = &gcp->gc_data;
1180 n_child_manager_start();
1181 NYD2_LEAVE;
1184 FL bool_t
1185 n_go_main_loop(void){ /* FIXME */
1186 struct a_go_eval_ctx gec;
1187 int n, eofcnt;
1188 bool_t volatile rv;
1189 NYD_ENTER;
1191 rv = TRU1;
1193 if (!(n_pstate & n_PS_SOURCING)) {
1194 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1195 safe_signal(SIGINT, &a_go_onintr);
1196 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1197 safe_signal(SIGHUP, &a_go_hangup);
1199 a_go_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1200 safe_signal(SIGPIPE, a_go_oldpipe);
1202 memset(&gec, 0, sizeof gec);
1204 (void)sigsetjmp(a_go_srbuf, 1); /* FIXME get rid */
1205 hold_all_sigs();
1207 for (eofcnt = 0;; gec.gec_ever_seen = TRU1) {
1208 interrupts = 0;
1210 if(gec.gec_ever_seen)
1211 a_go_cleanup(a_GO_CLEANUP_LOOPTICK | a_GO_CLEANUP_HOLDALLSIGS);
1213 if (!(n_pstate & n_PS_SOURCING)) {
1214 char *cp;
1216 /* TODO Note: this buffer may contain a password. We should redefine
1217 * TODO the code flow which has to do that */
1218 if ((cp = termios_state.ts_linebuf) != NULL) {
1219 termios_state.ts_linebuf = NULL;
1220 termios_state.ts_linesize = 0;
1221 n_free(cp); /* TODO pool give-back */
1223 if (gec.gec_line.l > LINESIZE * 3) {
1224 n_free(gec.gec_line.s);
1225 gec.gec_line.s = NULL;
1226 gec.gec_line.l = gec.gec_line_size = 0;
1230 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1231 char *cp;
1233 if ((cp = ok_vlook(newmail)) != NULL) { /* TODO bla */
1234 struct stat st;
1236 if(mb.mb_type == MB_FILE){
1237 if(!stat(mailname, &st) && st.st_size > mailsize) Jnewmail:{
1238 ui32_t odid;
1239 size_t odot;
1241 odot = PTR2SIZE(dot - message);
1242 odid = (n_pstate & n_PS_DID_PRINT_DOT);
1244 rele_all_sigs();
1245 n = setfile(mailname,
1246 (FEDIT_NEWMAIL |
1247 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)));
1248 hold_all_sigs();
1250 if(n < 0) {
1251 n_exit_status |= n_EXIT_ERR;
1252 rv = FAL0;
1253 break;
1255 #ifdef HAVE_IMAP
1256 if(mb.mb_type != MB_IMAP){
1257 #endif
1258 dot = &message[odot];
1259 n_pstate |= odid;
1260 #ifdef HAVE_IMAP
1262 #endif
1264 }else{
1265 n = (cp != NULL && strcmp(cp, "nopoll"));
1267 if(mb.mb_type == MB_MAILDIR){
1268 if(n != 0)
1269 goto Jnewmail;
1271 #ifdef HAVE_IMAP
1272 else if(mb.mb_type == MB_IMAP){
1273 if(!n)
1274 n = (cp != NULL && strcmp(cp, "noimap"));
1276 if(imap_newmail(n) > (cp == NULL))
1277 goto Jnewmail;
1279 #endif
1284 /* Read a line of commands and handle end of file specially */
1285 gec.gec_line.l = gec.gec_line_size;
1286 /* C99 */{
1287 bool_t histadd;
1289 histadd = (!(n_pstate & n_PS_SOURCING) &&
1290 (n_psonce & n_PSO_INTERACTIVE));
1291 rele_all_sigs();
1292 n = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, NULL,
1293 &gec.gec_line.s, &gec.gec_line.l, NULL, &histadd);
1294 hold_all_sigs();
1296 gec.gec_hist_flags = histadd ? a_GO_HIST_ADD : a_GO_HIST_NONE;
1298 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1299 gec.gec_line.l = (ui32_t)n;
1301 if (n < 0) {
1302 if (!(n_pstate & n_PS_ROBOT) &&
1303 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1304 ++eofcnt < 4) {
1305 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1306 n_go_input_clearerr();
1307 continue;
1309 break;
1312 n_pstate &= ~n_PS_HOOK_MASK;
1313 rele_all_sigs();
1314 rv = a_go_evaluate(&gec);
1315 hold_all_sigs();
1317 if(gec.gec_hist_flags & a_GO_HIST_ADD){
1318 char const *cc, *ca;
1320 cc = gec.gec_hist_cmd;
1321 ca = gec.gec_hist_args;
1322 if(cc != NULL && ca != NULL)
1323 cc = savecatsep(cc, ' ', ca);
1324 else if(ca != NULL)
1325 cc = ca;
1326 assert(cc != NULL);
1327 n_tty_addhist(cc, ((gec.gec_hist_flags & a_GO_HIST_GABBY) != 0));
1330 switch(n_pstate & n_PS_ERR_EXIT_MASK){
1331 case n_PS_ERR_XIT: n_psonce |= n_PSO_XIT; break;
1332 case n_PS_ERR_QUIT: n_psonce |= n_PSO_QUIT; break;
1333 default: break;
1335 if(n_psonce & n_PSO_EXIT_MASK)
1336 break;
1338 if(!rv)
1339 break;
1342 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS |
1343 (rv ? 0 : a_GO_CLEANUP_ERROR));
1345 if (gec.gec_line.s != NULL)
1346 n_free(gec.gec_line.s);
1348 rele_all_sigs();
1349 NYD_LEAVE;
1350 return rv;
1353 FL void
1354 n_go_input_clearerr(void){
1355 FILE *fp;
1356 NYD2_ENTER;
1358 fp = NULL;
1360 if(!(a_go_ctx->gc_flags & (a_GO_FORCE_EOF |
1361 a_GO_PIPE | a_GO_MACRO | a_GO_SPLICE)))
1362 fp = a_go_ctx->gc_file;
1364 if(fp != NULL){
1365 a_go_ctx->gc_flags &= ~a_GO_IS_EOF;
1366 clearerr(fp);
1368 NYD2_LEAVE;
1371 FL void
1372 n_go_input_force_eof(void){
1373 NYD2_ENTER;
1374 a_go_ctx->gc_flags |= a_GO_FORCE_EOF;
1375 NYD2_LEAVE;
1378 FL bool_t
1379 n_go_input_is_eof(void){
1380 bool_t rv;
1381 NYD2_ENTER;
1383 rv = ((a_go_ctx->gc_flags & a_GO_IS_EOF) != 0);
1384 NYD2_LEAVE;
1385 return rv;
1388 FL void
1389 n_go_input_inject(enum n_go_input_inject_flags giif, char const *buf,
1390 size_t len){
1391 NYD_ENTER;
1392 if(len == UIZ_MAX)
1393 len = strlen(buf);
1395 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat) -1 > len &&
1396 len > 0){
1397 struct a_go_input_inject *giip, **giipp;
1399 hold_all_sigs();
1401 giip = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat
1402 ) + 1 + len +1);
1403 giipp = &a_go_ctx->gc_inject;
1404 giip->gii_next = *giipp;
1405 giip->gii_commit = ((giif & n_GO_INPUT_INJECT_COMMIT) != 0);
1406 giip->gii_no_history = ((giif & n_GO_INPUT_INJECT_HISTORY) == 0);
1407 memcpy(&giip->gii_dat[0], buf, len);
1408 giip->gii_dat[giip->gii_len = len] = '\0';
1409 *giipp = giip;
1411 rele_all_sigs();
1413 NYD_LEAVE;
1416 FL int
1417 (n_go_input)(enum n_go_input_flags gif, char const *prompt, char **linebuf,
1418 size_t *linesize, char const *string, bool_t *histok_or_null
1419 n_MEMORY_DEBUG_ARGS){
1420 /* TODO readline: linebuf pool!; n_go_input should return si64_t */
1421 struct n_string xprompt;
1422 FILE *ifile;
1423 bool_t doprompt, dotty;
1424 char const *iftype;
1425 struct a_go_input_inject *giip;
1426 int nold, n;
1427 bool_t histok;
1428 NYD2_ENTER;
1430 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1431 hold_all_sigs();
1433 histok = FAL0;
1435 if(a_go_ctx->gc_flags & a_GO_FORCE_EOF){
1436 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1437 n = -1;
1438 goto jleave;
1441 if(gif & n_GO_INPUT_FORCE_STDIN)
1442 goto jforce_stdin;
1444 /* Special case macro mode: never need to prompt, lines have always been
1445 * unfolded already */
1446 if(a_go_ctx->gc_flags & a_GO_MACRO){
1447 if(*linebuf != NULL)
1448 n_free(*linebuf);
1450 /* Injection in progress? Don't care about the autocommit state here */
1451 if((giip = a_go_ctx->gc_inject) != NULL){
1452 a_go_ctx->gc_inject = giip->gii_next;
1454 /* Simply "reuse" allocation, copy string to front of it */
1455 jinject:
1456 *linesize = giip->gii_len;
1457 *linebuf = (char*)giip;
1458 memmove(*linebuf, giip->gii_dat, giip->gii_len +1);
1459 iftype = "INJECTION";
1460 }else{
1461 if((*linebuf = a_go_ctx->gc_lines[a_go_ctx->gc_loff]) == NULL){
1462 *linesize = 0;
1463 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1464 n = -1;
1465 goto jleave;
1468 ++a_go_ctx->gc_loff;
1469 *linesize = strlen(*linebuf);
1470 if(!(a_go_ctx->gc_flags & a_GO_MACRO_FREE_DATA))
1471 *linebuf = sbufdup(*linebuf, *linesize);
1473 iftype = (a_go_ctx->gc_flags & a_GO_MACRO_X_OPTION)
1474 ? "-X OPTION"
1475 : (a_go_ctx->gc_flags & a_GO_MACRO_CMD) ? "CMD" : "MACRO";
1477 n = (int)*linesize;
1478 n_pstate |= n_PS_READLINE_NL;
1479 goto jhave_dat;
1480 }else{
1481 /* Injection in progress? */
1482 struct a_go_input_inject **giipp;
1484 giipp = &a_go_ctx->gc_inject;
1486 if((giip = *giipp) != NULL){
1487 *giipp = giip->gii_next;
1489 if(giip->gii_commit){
1490 if(*linebuf != NULL)
1491 n_free(*linebuf);
1492 histok = !giip->gii_no_history;
1493 goto jinject; /* (above) */
1494 }else{
1495 string = savestrbuf(giip->gii_dat, giip->gii_len);
1496 n_free(giip);
1501 jforce_stdin:
1502 n_pstate &= ~n_PS_READLINE_NL;
1503 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1504 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1505 histok = (n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1506 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT);
1507 doprompt = !(gif & n_GO_INPUT_FORCE_STDIN) && histok;
1508 dotty = (doprompt && !ok_blook(line_editor_disable));
1509 if(!doprompt)
1510 gif |= n_GO_INPUT_PROMPT_NONE;
1511 else{
1512 if(!dotty)
1513 n_string_creat_auto(&xprompt);
1514 if(prompt == NULL)
1515 gif |= n_GO_INPUT_PROMPT_EVAL;
1518 /* Ensure stdout is flushed first anyway (partial lines, maybe?) */
1519 if(!dotty && (gif & n_GO_INPUT_PROMPT_NONE))
1520 fflush(n_stdout);
1522 if(gif & n_GO_INPUT_FORCE_STDIN){
1523 struct a_go_readctl_ctx *grcp;
1525 grcp = n_readctl_overlay;
1526 ifile = (grcp == NULL || grcp->grc_fp == NULL) ? n_stdin : grcp->grc_fp;
1527 }else
1528 ifile = a_go_ctx->gc_file;
1529 if(ifile == NULL){
1530 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1531 (a_go_ctx->gc_flags & a_GO_MACRO));
1532 ifile = n_stdin;
1535 for(nold = n = 0;;){
1536 if(dotty){
1537 assert(ifile == n_stdin);
1538 if(string != NULL && (n = (int)strlen(string)) > 0){
1539 if(*linesize > 0)
1540 *linesize += n +1;
1541 else
1542 *linesize = (size_t)n + LINESIZE +1;
1543 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1544 memcpy(*linebuf, string, (size_t)n +1);
1546 string = NULL;
1548 rele_all_sigs();
1550 n = (n_tty_readline)(gif, prompt, linebuf, linesize, n, histok_or_null
1551 n_MEMORY_DEBUG_ARGSCALL);
1553 hold_all_sigs();
1555 if(n < 0 && !ferror(ifile)) /* EOF never i guess */
1556 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1557 }else{
1558 if(!(gif & n_GO_INPUT_PROMPT_NONE))
1559 n_tty_create_prompt(&xprompt, prompt, gif);
1561 rele_all_sigs();
1563 if(!(gif & n_GO_INPUT_PROMPT_NONE) && xprompt.s_len > 0){
1564 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1565 fflush(n_stdout);
1568 n = (readline_restart)(ifile, linebuf, linesize, n
1569 n_MEMORY_DEBUG_ARGSCALL);
1571 hold_all_sigs();
1573 if(n < 0 && !ferror(ifile))
1574 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1576 if(n > 0 && nold > 0){
1577 char const *cp;
1578 int i;
1580 i = 0;
1581 cp = &(*linebuf)[nold];
1582 while(spacechar(*cp) && n - i >= nold)
1583 ++cp, ++i;
1584 if(i > 0){
1585 memmove(&(*linebuf)[nold], cp, n - nold - i);
1586 n -= i;
1587 (*linebuf)[n] = '\0';
1592 if(n <= 0)
1593 break;
1595 /* POSIX says:
1596 * An unquoted <backslash> at the end of a command line shall
1597 * be discarded and the next line shall continue the command */
1598 if(!(gif & n_GO_INPUT_NL_ESC) || (*linebuf)[n - 1] != '\\')
1599 break;
1601 /* Definitely outside of quotes, thus the quoting rules are so that an
1602 * uneven number of successive reverse solidus at EOL is a continuation */
1603 if(n > 1){
1604 size_t i, j;
1606 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1607 if((*linebuf)[i] != '\\')
1608 break;
1609 if(!(j & 1))
1610 break;
1612 (*linebuf)[nold = --n] = '\0';
1613 gif |= n_GO_INPUT_NL_FOLLOW;
1616 if(n < 0)
1617 goto jleave;
1618 if(dotty)
1619 n_pstate |= n_PS_READLINE_NL;
1620 (*linebuf)[*linesize = n] = '\0';
1622 jhave_dat:
1623 if(n_poption & n_PO_D_VV)
1624 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1625 jleave:
1626 if (n_pstate & n_PS_PSTATE_PENDMASK)
1627 a_go_update_pstate();
1629 /* TODO We need to special case a_GO_SPLICE, since that is not managed by us
1630 * TODO but only established from the outside and we need to drop this
1631 * TODO overlay context somehow */
1632 if(n < 0 && (a_go_ctx->gc_flags & a_GO_SPLICE))
1633 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS);
1635 if(histok_or_null != NULL && !histok)
1636 *histok_or_null = FAL0;
1638 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1639 rele_all_sigs();
1640 NYD2_LEAVE;
1641 return n;
1644 FL char *
1645 n_go_input_cp(enum n_go_input_flags gif, char const *prompt,
1646 char const *string){
1647 struct n_sigman sm;
1648 bool_t histadd;
1649 size_t linesize;
1650 char *linebuf, * volatile rv;
1651 int n;
1652 NYD2_ENTER;
1654 linesize = 0;
1655 linebuf = NULL;
1656 rv = NULL;
1658 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL){
1659 case 0:
1660 break;
1661 default:
1662 goto jleave;
1665 histadd = TRU1;
1666 n = n_go_input(gif, prompt, &linebuf, &linesize, string, &histadd);
1667 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1668 (gif & n_GO_INPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE) &&
1669 histadd)
1670 n_tty_addhist(rv, ((gif & n_GO_INPUT_HIST_GABBY) != 0));
1672 n_sigman_cleanup_ping(&sm);
1673 jleave:
1674 if(linebuf != NULL)
1675 n_free(linebuf);
1676 NYD2_LEAVE;
1677 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
1678 return rv;
1681 FL bool_t
1682 n_go_load(char const *name){
1683 struct a_go_ctx *gcp;
1684 size_t i;
1685 FILE *fip;
1686 bool_t rv;
1687 NYD_ENTER;
1689 rv = TRU1;
1691 if(name == NULL || *name == '\0')
1692 goto jleave;
1693 else if((fip = Fopen(name, "r")) == NULL){
1694 if(n_poption & n_PO_D_V)
1695 n_err(_("No such file to load: %s\n"), n_shexp_quote_cp(name, FAL0));
1696 goto jleave;
1699 i = strlen(name) +1;
1700 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + i);
1701 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1703 gcp->gc_file = fip;
1704 gcp->gc_flags = a_GO_FREE | a_GO_FILE;
1705 memcpy(gcp->gc_name, name, i);
1707 if(n_poption & n_PO_D_V)
1708 n_err(_("Loading %s\n"), n_shexp_quote_cp(gcp->gc_name, FAL0));
1709 rv = a_go_load(gcp);
1710 jleave:
1711 NYD_LEAVE;
1712 return rv;
1715 FL bool_t
1716 n_go_Xargs(char const **lines, size_t cnt){
1717 static char const name[] = "-X";
1719 union{
1720 bool_t rv;
1721 ui64_t align;
1722 char uf[n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + sizeof(name)];
1723 } b;
1724 char const *srcp, *xsrcp;
1725 char *cp;
1726 size_t imax, i, len;
1727 struct a_go_ctx *gcp;
1728 NYD_ENTER;
1730 gcp = (void*)b.uf;
1731 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1733 gcp->gc_flags = a_GO_MACRO | a_GO_MACRO_X_OPTION |
1734 a_GO_SUPER_MACRO | a_GO_MACRO_FREE_DATA;
1735 memcpy(gcp->gc_name, name, sizeof name);
1737 /* The problem being that we want to support reverse solidus newline
1738 * escaping also within multiline -X, i.e., POSIX says:
1739 * An unquoted <backslash> at the end of a command line shall
1740 * be discarded and the next line shall continue the command
1741 * Therefore instead of "gcp->gc_lines = n_UNCONST(lines)", duplicate the
1742 * entire lines array and set _MACRO_FREE_DATA */
1743 imax = cnt + 1;
1744 gcp->gc_lines = n_alloc(sizeof(*gcp->gc_lines) * imax);
1746 /* For each of the input lines.. */
1747 for(i = len = 0, cp = NULL; cnt > 0;){
1748 bool_t keep;
1749 size_t j;
1751 if((j = strlen(srcp = *lines)) == 0){
1752 ++lines, --cnt;
1753 continue;
1756 /* Separate one line from a possible multiline input string */
1757 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1758 *lines = &xsrcp[1];
1759 j = PTR2SIZE(xsrcp - srcp);
1760 }else
1761 ++lines, --cnt;
1763 /* The (separated) string may itself indicate soft newline escaping */
1764 if((keep = (srcp[j - 1] == '\\'))){
1765 size_t xj, xk;
1767 /* Need an uneven number of reverse solidus */
1768 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1769 if(srcp[xj] != '\\')
1770 break;
1771 if(xk & 1)
1772 --j;
1773 else
1774 keep = FAL0;
1777 /* Strip any leading WS from follow lines, then */
1778 if(cp != NULL)
1779 while(j > 0 && spacechar(*srcp))
1780 ++srcp, --j;
1782 if(j > 0){
1783 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1784 imax += 4;
1785 gcp->gc_lines = n_realloc(gcp->gc_lines, sizeof(*gcp->gc_lines) *
1786 imax);
1788 gcp->gc_lines[i] = cp = n_realloc(cp, len + j +1);
1789 memcpy(&cp[len], srcp, j);
1790 cp[len += j] = '\0';
1792 if(!keep)
1793 ++i;
1795 if(!keep)
1796 cp = NULL, len = 0;
1798 if(cp != NULL){
1799 assert(i + 1 < imax);
1800 gcp->gc_lines[i++] = cp;
1802 gcp->gc_lines[i] = NULL;
1804 b.rv = a_go_load(gcp);
1805 NYD_LEAVE;
1806 return b.rv;
1809 FL int
1810 c_source(void *v){
1811 int rv;
1812 NYD_ENTER;
1814 rv = (a_go_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1815 NYD_LEAVE;
1816 return rv;
1819 FL int
1820 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1821 int rv;
1822 NYD_ENTER;
1824 rv = (a_go_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
1825 NYD_LEAVE;
1826 return rv;
1829 FL bool_t
1830 n_go_macro(enum n_go_input_flags gif, char const *name, char **lines,
1831 void (*on_finalize)(void*), void *finalize_arg){
1832 struct a_go_ctx *gcp;
1833 size_t i;
1834 int rv;
1835 sigset_t osigmask;
1836 NYD_ENTER;
1838 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1840 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1841 (i = strlen(name) +1));
1842 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1844 hold_all_sigs();
1846 gcp->gc_outer = a_go_ctx;
1847 gcp->gc_osigmask = osigmask;
1848 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_FREE_DATA |
1849 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1850 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0) |
1851 ((gif & n_GO_INPUT_NO_XCALL) ? a_GO_XCALL_IS_CALL : 0);
1852 gcp->gc_lines = lines;
1853 gcp->gc_on_finalize = on_finalize;
1854 gcp->gc_finalize_arg = finalize_arg;
1855 memcpy(gcp->gc_name, name, i);
1857 a_go_ctx = gcp;
1858 n_go_data = &gcp->gc_data;
1859 n_pstate |= n_PS_ROBOT;
1860 rv = a_go_event_loop(gcp, gif);
1862 /* Shall this enter a `xcall' stack avoidance optimization (loop)? */
1863 if(a_go_xcall != NULL){
1864 void *vp;
1865 struct n_cmd_arg_ctx *cacp;
1867 if(a_go_xcall == (void*)-1)
1868 a_go_xcall = NULL;
1869 else if(((void const*)(cacp = a_go_xcall)->cac_indat) == gcp){
1870 /* Indicate that "our" (ex-) parent now hosts xcall optimization */
1871 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP;
1872 while(a_go_xcall != NULL){
1873 hold_all_sigs();
1875 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_ERROR;
1877 vp = a_go_xcall;
1878 a_go_xcall = NULL;
1879 cacp = n_cmd_arg_restore_from_heap(vp);
1880 n_free(vp);
1882 rele_all_sigs();
1884 (void)c_call(cacp);
1886 rv = ((a_go_ctx->gc_flags & a_GO_XCALL_LOOP_ERROR) == 0);
1887 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1890 NYD_LEAVE;
1891 return rv;
1894 FL bool_t
1895 n_go_command(enum n_go_input_flags gif, char const *cmd){
1896 struct a_go_ctx *gcp;
1897 bool_t rv;
1898 size_t i, ial;
1899 sigset_t osigmask;
1900 NYD_ENTER;
1902 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1904 i = strlen(cmd) +1;
1905 ial = n_ALIGN(i);
1906 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1907 ial + 2*sizeof(char*));
1908 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1910 hold_all_sigs();
1912 gcp->gc_outer = a_go_ctx;
1913 gcp->gc_osigmask = osigmask;
1914 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_CMD |
1915 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1916 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0);
1917 gcp->gc_lines = (void*)&gcp->gc_name[ial];
1918 memcpy(gcp->gc_lines[0] = &gcp->gc_name[0], cmd, i);
1919 gcp->gc_lines[1] = NULL;
1921 a_go_ctx = gcp;
1922 n_go_data = &gcp->gc_data;
1923 n_pstate |= n_PS_ROBOT;
1924 rv = a_go_event_loop(gcp, gif);
1925 NYD_LEAVE;
1926 return rv;
1929 FL void
1930 n_go_splice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
1931 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
1932 struct a_go_ctx *gcp;
1933 size_t i;
1934 sigset_t osigmask;
1935 NYD_ENTER;
1937 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1939 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1940 (i = strlen(cmd) +1));
1941 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1943 hold_all_sigs();
1945 gcp->gc_outer = a_go_ctx;
1946 gcp->gc_osigmask = osigmask;
1947 gcp->gc_file = new_stdin;
1948 gcp->gc_flags = a_GO_FREE | a_GO_SPLICE | a_GO_DATACTX_INHERITED;
1949 gcp->gc_on_finalize = on_finalize;
1950 gcp->gc_finalize_arg = finalize_arg;
1951 gcp->gc_splice_stdin = n_stdin;
1952 gcp->gc_splice_stdout = n_stdout;
1953 gcp->gc_splice_psonce = n_psonce;
1954 memcpy(gcp->gc_name, cmd, i);
1956 n_stdin = new_stdin;
1957 n_stdout = new_stdout;
1958 n_psonce = new_psonce;
1959 a_go_ctx = gcp;
1960 /* Do NOT touch n_go_data! */
1961 n_pstate |= n_PS_ROBOT;
1963 rele_all_sigs();
1964 NYD_LEAVE;
1967 FL void
1968 n_go_splice_hack_remove_after_jump(void){
1969 a_go_cleanup(a_GO_CLEANUP_TEARDOWN);
1972 FL bool_t
1973 n_go_may_yield_control(void){ /* TODO this is a terrible hack */
1974 struct a_go_ctx *gcp;
1975 bool_t rv;
1976 NYD2_ENTER;
1978 rv = FAL0;
1980 /* Only when startup completed */
1981 if(!(n_psonce & n_PSO_STARTED))
1982 goto jleave;
1983 /* Only interactive or batch mode (assuming that is ok) */
1984 if(!(n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_BATCH_FLAG))
1985 goto jleave;
1987 /* Not when running any hook */
1988 if(n_pstate & n_PS_HOOK_MASK)
1989 goto jleave;
1991 /* Traverse up the stack:
1992 * . not when controlled by a child process
1993 * TODO . not when there are pipes involved, we neither handle job control,
1994 * TODO nor process groups, that is, controlling terminal acceptably
1995 * . not when sourcing a file */
1996 for(gcp = a_go_ctx; gcp != NULL; gcp = gcp->gc_outer){
1997 if(gcp->gc_flags & (a_GO_PIPE | a_GO_FILE | a_GO_SPLICE))
1998 goto jleave;
2001 rv = TRU1;
2002 jleave:
2003 NYD2_LEAVE;
2004 return rv;
2007 FL int
2008 c_eval(void *vp){
2009 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
2010 * TODO ARGV with shell rules, but if that is not possible then simply
2011 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
2012 struct a_go_eval_ctx gec;
2013 struct n_string s_b, *sp;
2014 size_t i, j;
2015 char const **argv, *cp;
2016 NYD_ENTER;
2018 argv = vp;
2020 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
2021 j += strlen(cp);
2023 sp = n_string_creat_auto(&s_b);
2024 sp = n_string_reserve(sp, j);
2026 for(i = 0; (cp = argv[i]) != NULL; ++i){
2027 if(i > 0)
2028 sp = n_string_push_c(sp, ' ');
2029 sp = n_string_push_cp(sp, cp);
2032 memset(&gec, 0, sizeof gec);
2033 gec.gec_line.s = n_string_cp(sp);
2034 gec.gec_line.l = sp->s_len;
2035 if(n_poption & n_PO_D_VV)
2036 n_err(_("EVAL %" PRIuZ " bytes <%s>\n"), gec.gec_line.l, gec.gec_line.s);
2037 (void)/* XXX */a_go_evaluate(&gec);
2038 NYD_LEAVE;
2039 return (a_go_xcall != NULL ? 0 : n_pstate_ex_no);
2042 FL int
2043 c_xcall(void *vp){
2044 int rv;
2045 struct a_go_ctx *gcp;
2046 NYD2_ENTER;
2048 /* The context can only be a macro context, except that possibly a single
2049 * level of `eval' (TODO: yet) was used to double-expand our arguments */
2050 if((gcp = a_go_ctx)->gc_flags & a_GO_MACRO_CMD)
2051 gcp = gcp->gc_outer;
2052 if((gcp->gc_flags & (a_GO_MACRO | a_GO_MACRO_X_OPTION | a_GO_MACRO_CMD)
2053 ) != a_GO_MACRO){
2054 if(n_poption & n_PO_D_V_VV)
2055 n_err(_("`xcall': can only be used inside a macro, using `call'\n"));
2056 rv = c_call(vp);
2057 goto jleave;
2060 /* Try to roll up the stack as much as possible.
2061 * See a_GO_XCALL_LOOP flag description for more */
2062 if(!(gcp->gc_flags & a_GO_XCALL_IS_CALL) && gcp->gc_outer != NULL){
2063 if(gcp->gc_outer->gc_flags & a_GO_XCALL_LOOP)
2064 gcp = gcp->gc_outer;
2065 }else{
2066 /* Otherwise this macro is "invoked from the top level", in which case we
2067 * silently act as if we were `call'... */
2068 rv = c_call(vp);
2069 /* ...which means we must ensure the rest of the macro that was us
2070 * doesn't become evaluated! */
2071 a_go_xcall = (void*)-1;
2072 goto jleave;
2075 /* C99 */{
2076 struct n_cmd_arg_ctx *cacp;
2078 cacp = n_cmd_arg_save_to_heap(vp);
2079 cacp->cac_indat = (char*)gcp;
2080 a_go_xcall = cacp;
2082 rv = 0;
2083 jleave:
2084 NYD2_LEAVE;
2085 return rv;
2088 FL int
2089 c_exit(void *vp){
2090 char const **argv;
2091 NYD_ENTER;
2093 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2094 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2095 ) != n_IDEC_STATE_CONSUMED)
2096 n_exit_status |= n_EXIT_ERR;
2098 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2099 fflush(NULL);
2100 _exit(n_exit_status);
2101 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2102 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2103 n_psonce |= n_PSO_XIT;
2104 NYD_LEAVE;
2105 return 0;
2108 FL int
2109 c_quit(void *vp){
2110 char const **argv;
2111 NYD_ENTER;
2113 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2114 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2115 ) != n_IDEC_STATE_CONSUMED)
2116 n_exit_status |= n_EXIT_ERR;
2118 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2119 fflush(NULL);
2120 _exit(n_exit_status);
2121 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2122 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2123 n_psonce |= n_PSO_QUIT;
2124 NYD_LEAVE;
2125 return 0;
2128 FL int
2129 c_readctl(void *vp){
2130 /* TODO We would need OnForkEvent and then simply remove some internal
2131 * TODO management; we don't have this, therefore we need global
2132 * TODO n_readctl_overlay to be accessible via =NULL, and to make that
2133 * TODO work in turn we need an instance for default STDIN! Sigh. */
2134 static ui8_t a_buf[n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name)+1 +1];
2135 static struct a_go_readctl_ctx *a_stdin;
2137 struct a_go_readctl_ctx *grcp;
2138 char const *emsg;
2139 enum{
2140 a_NONE = 0,
2141 a_ERR = 1u<<0,
2142 a_SET = 1u<<1,
2143 a_CREATE = 1u<<2,
2144 a_REMOVE = 1u<<3
2145 } f;
2146 struct n_cmd_arg *cap;
2147 struct n_cmd_arg_ctx *cacp;
2148 NYD_ENTER;
2150 if(a_stdin == NULL){
2151 a_stdin = (struct a_go_readctl_ctx*)a_buf;
2152 a_stdin->grc_name[0] = '-';
2153 n_readctl_overlay = a_stdin;
2156 n_pstate_err_no = n_ERR_NONE;
2157 cacp = vp;
2158 cap = cacp->cac_arg;
2160 if(cacp->cac_no == 0 || is_asccaseprefix(cap->ca_arg.ca_str.s, "show"))
2161 goto jshow;
2162 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "set"))
2163 f = a_SET;
2164 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "create"))
2165 f = a_CREATE;
2166 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "remove"))
2167 f = a_REMOVE;
2168 else{
2169 emsg = N_("`readctl': invalid subcommand: %s\n");
2170 goto jeinval_quote;
2173 if(cacp->cac_no == 1){ /* TODO better option parser <> subcommand */
2174 n_err(_("`readctl': %s: requires argument\n"), cap->ca_arg.ca_str.s);
2175 goto jeinval;
2177 cap = cap->ca_next;
2179 /* - is special TODO unfortunately also regarding storage */
2180 if(cap->ca_arg.ca_str.l == 1 && *cap->ca_arg.ca_str.s == '-'){
2181 if(f & (a_CREATE | a_REMOVE)){
2182 n_err(_("`readctl': cannot create nor remove -\n"));
2183 goto jeinval;
2185 n_readctl_overlay = a_stdin;
2186 goto jleave;
2189 /* Try to find a yet existing instance */
2190 if((grcp = n_readctl_overlay) != NULL){
2191 for(; grcp != NULL; grcp = grcp->grc_next)
2192 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2193 goto jfound;
2194 for(grcp = n_readctl_overlay; (grcp = grcp->grc_last) != NULL;)
2195 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2196 goto jfound;
2199 if(f & (a_SET | a_REMOVE)){
2200 emsg = N_("`readctl': no such channel: %s\n");
2201 goto jeinval_quote;
2204 jfound:
2205 if(f & a_SET)
2206 n_readctl_overlay = grcp;
2207 else if(f & a_REMOVE){
2208 if(n_readctl_overlay == grcp)
2209 n_readctl_overlay = a_stdin;
2211 if(grcp->grc_last != NULL)
2212 grcp->grc_last->grc_next = grcp->grc_next;
2213 if(grcp->grc_next != NULL)
2214 grcp->grc_next->grc_last = grcp->grc_last;
2215 fclose(grcp->grc_fp);
2216 n_free(grcp);
2217 }else{
2218 FILE *fp;
2219 size_t elen;
2220 si32_t fd;
2222 if(grcp != NULL){
2223 n_err(_("`readctl': channel already exists: %s\n"), /* TODO reopen */
2224 n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2225 n_pstate_err_no = n_ERR_EXIST;
2226 f = a_ERR;
2227 goto jleave;
2230 if((n_idec_si32_cp(&fd, cap->ca_arg.ca_str.s, 0, NULL
2231 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2232 ) != n_IDEC_STATE_CONSUMED){
2233 if((emsg = fexpand(cap->ca_arg.ca_str.s, FEXP_LOCAL | FEXP_NVAR)
2234 ) == NULL){
2235 emsg = N_("`readctl': cannot expand filename %s\n");
2236 goto jeinval_quote;
2238 fd = -1;
2239 elen = strlen(emsg);
2240 fp = safe_fopen(emsg, "r", NULL);
2241 }else if(fd == STDIN_FILENO || fd == STDOUT_FILENO ||
2242 fd == STDERR_FILENO){
2243 n_err(_("`readctl': create: standard descriptors are not allowed\n"));
2244 goto jeinval;
2245 }else{
2246 /* xxx Avoid */
2247 _CLOEXEC_SET(fd);
2248 emsg = NULL;
2249 elen = 0;
2250 fp = fdopen(fd, "r");
2253 if(fp != NULL){
2254 size_t i;
2256 if((i = UIZ_MAX - elen) <= cap->ca_arg.ca_str.l ||
2257 (i -= cap->ca_arg.ca_str.l) <=
2258 n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +2){
2259 n_err(_("`readctl': failed to create storage for %s\n"),
2260 cap->ca_arg.ca_str.s);
2261 n_pstate_err_no = n_ERR_OVERFLOW;
2262 f = a_ERR;
2263 goto jleave;
2266 grcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +
2267 cap->ca_arg.ca_str.l +1 + elen +1);
2268 grcp->grc_last = NULL;
2269 if((grcp->grc_next = n_readctl_overlay) != NULL)
2270 grcp->grc_next->grc_last = grcp;
2271 n_readctl_overlay = grcp;
2272 grcp->grc_fp = fp;
2273 grcp->grc_fd = fd;
2274 memcpy(grcp->grc_name, cap->ca_arg.ca_str.s, cap->ca_arg.ca_str.l +1);
2275 if(elen == 0)
2276 grcp->grc_expand = NULL;
2277 else{
2278 char *cp;
2280 grcp->grc_expand = cp = &grcp->grc_name[cap->ca_arg.ca_str.l +1];
2281 memcpy(cp, emsg, ++elen);
2283 }else{
2284 emsg = N_("`readctl': failed to create file for %s\n");
2285 goto jeinval_quote;
2289 jleave:
2290 NYD_LEAVE;
2291 return (f & a_ERR) ? 1 : 0;
2292 jeinval_quote:
2293 n_err(V_(emsg), n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2294 jeinval:
2295 n_pstate_err_no = n_ERR_INVAL;
2296 f = a_ERR;
2297 goto jleave;
2299 jshow:
2300 if((grcp = n_readctl_overlay) == NULL)
2301 fprintf(n_stdout, _("`readctl': no channels registered\n"));
2302 else{
2303 while(grcp->grc_last != NULL)
2304 grcp = grcp->grc_last;
2306 fprintf(n_stdout, _("`readctl': registered channels:\n"));
2307 for(; grcp != NULL; grcp = grcp->grc_next)
2308 fprintf(n_stdout, _("%c%s %s%s%s%s\n"),
2309 (grcp == n_readctl_overlay ? '*' : ' '),
2310 (grcp->grc_fd != -1 ? _("descriptor") : _("name")),
2311 n_shexp_quote_cp(grcp->grc_name, FAL0),
2312 (grcp->grc_expand != NULL ? " (" : n_empty),
2313 (grcp->grc_expand != NULL ? grcp->grc_expand : n_empty),
2314 (grcp->grc_expand != NULL ? ")" : n_empty));
2316 f = a_NONE;
2317 goto jleave;
2320 /* s-it-mode */