nail.1: last fixes
[s-mailx.git] / go.c
blob372ef7b1290600865f019ec0bea2f7bbfc04b164
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 n_exit_status = n_EXIT_OK;
271 flags = a_NONE;
272 rv = 1;
273 nerrn = n_ERR_NONE;
274 nexn = n_EXIT_OK;
275 cdp = NULL;
276 alias_name = NULL;
277 n_UNINIT(alias_exp, NULL);
278 arglist =
279 arglist_base = n_autorec_alloc(sizeof(*arglist_base) * n_MAXARGC);
280 line = gecp->gec_line; /* TODO const-ify original (buffer)! */
281 assert(line.s[line.l] == '\0');
283 if(line.l > 0 && spacechar(line.s[0]))
284 gecp->gec_hist_flags = a_GO_HIST_NONE;
285 else if(gecp->gec_hist_flags & a_GO_HIST_ADD)
286 gecp->gec_hist_cmd = gecp->gec_hist_args = NULL;
287 sp = NULL;
289 /* Aliases that refer to shell commands or macro expansion restart */
290 jrestart:
291 if(n_str_trim_ifs(&line, TRU1)->l == 0){
292 line.s[0] = '\0';
293 gecp->gec_hist_flags = a_GO_HIST_NONE;
294 goto jempty;
296 (cp = line.s)[line.l] = '\0';
298 /* No-expansion modifier? */
299 if(!(flags & a_NOPREFIX) && *cp == '\\'){
300 line.s = ++cp;
301 --line.l;
302 flags |= a_NOALIAS;
305 /* Note: adding more special treatments must be reflected in the `help' etc.
306 * output in cmd-tab.c! */
308 /* Ignore null commands (comments) */
309 if(*cp == '#'){
310 gecp->gec_hist_flags = a_GO_HIST_NONE;
311 goto jret0;
314 /* Handle ! differently to get the correct lexical conventions */
315 if(*cp == '!')
316 ++cp;
317 /* Isolate the actual command; since it may not necessarily be
318 * separated from the arguments (as in `p1') we need to duplicate it to
319 * be able to create a NUL terminated version.
320 * We must be aware of several special one letter commands here */
321 else if((cp = n_UNCONST(n_cmd_isolate(cp))) == line.s &&
322 (*cp == '|' || *cp == '?'))
323 ++cp;
324 c = (int)PTR2SIZE(cp - line.s);
325 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : n_autorec_alloc(c +1);
326 memcpy(word, arglist[0] = line.s, c);
327 word[c] = '\0';
328 line.l -= c;
329 line.s = cp;
331 /* It may be a modifier.
332 * Note: adding modifiers must be reflected in commandalias handling code */
333 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
334 flags |= a_NOPREFIX | a_IGNERR;
335 goto jrestart;
336 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
337 flags |= a_NOPREFIX | a_WYSH;
338 goto jrestart;
339 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
340 flags |= a_NOPREFIX | a_VPUT;
341 goto jrestart;
342 }else if(c == sizeof("u") -1 && *word == 'u'){
343 n_err(_("Ignoring yet unused `u' command modifier!"));
344 flags |= a_NOPREFIX;
345 goto jrestart;
348 /* We need to trim for a possible history entry, but do it anyway and insert
349 * a space for argument separation in case of alias expansion. Also, do
350 * terminate again because nothing prevents aliases from introducing WS */
351 n_str_trim_ifs(&line, TRU1);
352 line.s[line.l] = '\0';
354 /* Lengthy history entry setup, possibly even redundant. But having
355 * normalized history entries is a good thing, and this is maybe still
356 * cheaper than parsing a StrList of words per se */
357 if((gecp->gec_hist_flags & (a_GO_HIST_ADD | a_GO_HIST_INIT)
358 ) == a_GO_HIST_ADD){
359 if(line.l > 0){
360 sp = n_string_creat_auto(&s);
361 sp = n_string_assign_buf(sp, line.s, line.l);
362 gecp->gec_hist_args = n_string_cp(sp);
365 sp = n_string_creat_auto(&s);
366 sp = n_string_reserve(sp, 32);
368 if(flags & a_NOALIAS)
369 sp = n_string_push_c(sp, '\\');
370 if(flags & a_IGNERR)
371 sp = n_string_push_buf(sp, "ignerr ", sizeof("ignerr ") -1);
372 if(flags & a_WYSH)
373 sp = n_string_push_buf(sp, "wysh ", sizeof("wysh ") -1);
374 if(flags & a_VPUT)
375 sp = n_string_push_buf(sp, "vput ", sizeof("vput ") -1);
376 gecp->gec_hist_flags = a_GO_HIST_ADD | a_GO_HIST_INIT;
379 /* Look up the command; if not found, bitch.
380 * Normally, a blank command would map to the first command in the
381 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
382 * confusion; act just the same for aliases */
383 if(*word == '\0'){
384 jempty:
385 if((n_pstate & n_PS_ROBOT) || !(n_psonce & n_PSO_INTERACTIVE) ||
386 alias_name != NULL){
387 gecp->gec_hist_flags = a_GO_HIST_NONE;
388 goto jret0;
390 cdp = n_cmd_default();
391 goto jexec;
394 if(!(flags & a_NOALIAS) && (flags & a_ALIAS_MASK) != a_ALIAS_MASK){
395 ui8_t expcnt;
397 expcnt = (flags & a_ALIAS_MASK);
398 ++expcnt;
399 flags = (flags & ~(a_ALIAS_MASK | a_NOPREFIX)) | expcnt;
401 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
402 if(alias_name != NULL && !strcmp(word, alias_name)){
403 if(n_poption & n_PO_D_V)
404 n_err(_("Actively avoiding self-recursion of `commandalias': %s\n"),
405 word);
406 }else if((alias_name = n_commandalias_exists(word, &alias_exp)) != NULL){
407 size_t i;
409 if(sp != NULL){
410 sp = n_string_push_cp(sp, word);
411 gecp->gec_hist_cmd = n_string_cp(sp);
412 sp = NULL;
415 /* And join arguments onto alias expansion */
416 alias_name = word;
417 i = alias_exp->l;
418 cp = line.s;
419 line.s = n_autorec_alloc(i + 1 + line.l +1);
420 memcpy(line.s, alias_exp->s, i);
421 if(line.l > 0){
422 line.s[i++] = ' ';
423 memcpy(&line.s[i], cp, line.l);
425 line.s[i += line.l] = '\0';
426 line.l = i;
427 goto jrestart;
431 if((cdp = n_cmd_firstfit(word)) == NULL){
432 bool_t doskip;
434 if(!(doskip = n_cnd_if_isskip()) || (n_poption & n_PO_D_V))
435 n_err(_("Unknown command%s: `%s'\n"),
436 (doskip ? _(" (ignored due to `if' condition)") : n_empty),
437 prstr(word));
438 gecp->gec_hist_flags = a_GO_HIST_NONE;
439 if(doskip)
440 goto jret0;
441 nerrn = n_ERR_NOSYS;
442 goto jleave;
445 /* See if we should execute the command -- if a conditional we always
446 * execute it, otherwise, check the state of cond */
447 jexec:
448 if(!(cdp->cd_caflags & n_CMD_ARG_F) && n_cnd_if_isskip()){
449 gecp->gec_hist_flags = a_GO_HIST_NONE;
450 goto jret0;
453 if(sp != NULL){
454 sp = n_string_push_cp(sp, cdp->cd_name);
455 gecp->gec_hist_cmd = n_string_cp(sp);
456 sp = NULL;
459 nerrn = n_ERR_INVAL;
461 /* Process the arguments to the command, depending on the type it expects */
462 if((cdp->cd_caflags & n_CMD_ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
463 !(n_poption & n_PO_BATCH_FLAG)){
464 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
465 cdp->cd_name);
466 goto jleave;
468 if(!(cdp->cd_caflags & n_CMD_ARG_M) && (n_psonce & n_PSO_SENDMODE)){
469 n_err(_("May not execute `%s' while sending\n"), cdp->cd_name);
470 goto jleave;
472 if(cdp->cd_caflags & n_CMD_ARG_R){
473 if(n_pstate & n_PS_COMPOSE_MODE){
474 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
475 n_err(_("Cannot invoke `%s' when in compose mode\n"), cdp->cd_name);
476 goto jleave;
478 /* TODO Nothing should prevent n_CMD_ARG_R in conjunction with
479 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
480 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING) && n_go_may_yield_control()){
481 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
482 cdp->cd_name);
483 goto jleave;
486 if((cdp->cd_caflags & n_CMD_ARG_S) && !(n_psonce & n_PSO_STARTED)){
487 n_err(_("May not execute `%s' during startup\n"), cdp->cd_name);
488 goto jleave;
490 if(!(cdp->cd_caflags & n_CMD_ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
491 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
492 cdp->cd_name);
493 goto jleave;
496 if((cdp->cd_caflags & n_CMD_ARG_A) && mb.mb_type == MB_VOID){
497 n_err(_("Cannot execute `%s' without active mailbox\n"), cdp->cd_name);
498 goto jleave;
500 if((cdp->cd_caflags & n_CMD_ARG_W) && !(mb.mb_perm & MB_DELE)){
501 n_err(_("May not execute `%s' -- message file is read only\n"),
502 cdp->cd_name);
503 goto jleave;
506 if(cdp->cd_caflags & n_CMD_ARG_O)
507 n_OBSOLETE2(_("this command will be removed"), cdp->cd_name);
509 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
510 * TODO doesn't use any of those list commands which strip this mask,
511 * TODO and for now we misuse bits for checking relation to history;
512 * TODO argument state should be property of a per-command carrier instead */
513 n_pstate &= ~n_PS_ARGLIST_MASK;
515 if((flags & a_WYSH) &&
516 (cdp->cd_caflags & n_CMD_ARG_TYPE_MASK) != n_CMD_ARG_TYPE_WYRA){
517 n_err(_("`wysh' prefix does not affect `%s'\n"), cdp->cd_name);
518 flags &= ~a_WYSH;
521 if(flags & a_VPUT){
522 if(cdp->cd_caflags & n_CMD_ARG_V){
523 char const *emsg;
525 emsg = line.s; /* xxx Cannot pass &char* as char const**, so no cp */
526 arglist[0] = n_shexp_parse_token_cp((n_SHEXP_PARSE_TRIM_SPACE |
527 n_SHEXP_PARSE_TRIM_IFSSPACE | n_SHEXP_PARSE_LOG |
528 n_SHEXP_PARSE_META_KEEP), &emsg);
529 line.l -= PTR2SIZE(emsg - line.s);
530 line.s = cp = n_UNCONST(emsg);
531 if(cp == NULL)
532 emsg = N_("could not parse input token");
533 else if(!n_shexp_is_valid_varname(arglist[0]))
534 emsg = N_("not a valid variable name");
535 else if(!n_var_is_user_writable(arglist[0]))
536 emsg = N_("either not a user writable, or a boolean variable");
537 else
538 emsg = NULL;
539 if(emsg != NULL){
540 n_err("`%s': vput: %s: %s\n",
541 cdp->cd_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
542 nerrn = n_ERR_NOTSUP;
543 rv = -1;
544 goto jleave;
546 ++arglist;
547 n_pstate |= n_PS_ARGMOD_VPUT; /* TODO YET useless since stripped later
548 * TODO on in getrawlist() etc., i.e., the argument vector producers,
549 * TODO therefore yet needs to be set again based on flags&a_VPUT! */
550 }else{
551 n_err(_("`vput' prefix does not affect `%s'\n"), cdp->cd_name);
552 flags &= ~a_VPUT;
556 switch(cdp->cd_caflags & n_CMD_ARG_TYPE_MASK){
557 case n_CMD_ARG_TYPE_MSGLIST:
558 /* Message list defaulting to nearest forward legal message */
559 if(n_msgvec == NULL)
560 goto jemsglist;
561 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
562 nerrn = n_ERR_NOMSG;
563 flags |= a_NO_ERRNO;
564 break;
566 if(c == 0){
567 if((n_msgvec[0] = first(cdp->cd_msgflag, cdp->cd_msgmask)) != 0)
568 n_msgvec[1] = 0;
570 if(n_msgvec[0] == 0){
571 jemsglist:
572 if(!(n_pstate & n_PS_HOOK_MASK))
573 fprintf(n_stdout, _("No applicable messages\n"));
574 nerrn = n_ERR_NOMSG;
575 flags |= a_NO_ERRNO;
576 break;
578 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
579 n_err_no = 0;
580 rv = (*cdp->cd_func)(n_msgvec);
581 break;
583 case n_CMD_ARG_TYPE_NDMLIST:
584 /* Message list with no defaults, but no error if none exist */
585 if(n_msgvec == NULL)
586 goto jemsglist;
587 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
588 nerrn = n_ERR_NOMSG;
589 flags |= a_NO_ERRNO;
590 break;
592 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
593 n_err_no = 0;
594 rv = (*cdp->cd_func)(n_msgvec);
595 break;
597 case n_CMD_ARG_TYPE_STRING:
598 /* Just the straight string, old style, with leading blanks removed */
599 for(cp = line.s; spacechar(*cp);)
600 ++cp;
601 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
602 n_err_no = 0;
603 rv = (*cdp->cd_func)(cp);
604 break;
605 case n_CMD_ARG_TYPE_RAWDAT:
606 /* Just the straight string, placed in argv[] */
607 *arglist++ = line.s;
608 *arglist = NULL;
609 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
610 n_err_no = 0;
611 rv = (*cdp->cd_func)(arglist_base);
612 break;
614 case n_CMD_ARG_TYPE_WYSH:
615 c = 1;
616 if(0){
617 /* FALLTHRU */
618 case n_CMD_ARG_TYPE_WYRA:
619 c = (flags & a_WYSH) ? 1 : 0;
620 if(0){
621 case n_CMD_ARG_TYPE_RAWLIST:
622 c = 0;
625 if((c = getrawlist((c != 0), arglist,
626 n_MAXARGC - PTR2SIZE(arglist - arglist_base), line.s, line.l)) < 0){
627 n_err(_("Invalid argument list\n"));
628 flags |= a_NO_ERRNO;
629 break;
632 if(c < cdp->cd_minargs){
633 n_err(_("`%s' requires at least %u arg(s)\n"),
634 cdp->cd_name, (ui32_t)cdp->cd_minargs);
635 flags |= a_NO_ERRNO;
636 break;
638 #undef cd_minargs
639 if(c > cdp->cd_maxargs){
640 n_err(_("`%s' takes no more than %u arg(s)\n"),
641 cdp->cd_name, (ui32_t)cdp->cd_maxargs);
642 flags |= a_NO_ERRNO;
643 break;
645 #undef cd_maxargs
647 if(flags & a_VPUT)
648 n_pstate |= n_PS_ARGMOD_VPUT;
650 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
651 n_err_no = 0;
652 rv = (*cdp->cd_func)(arglist_base);
653 if(a_go_xcall != NULL)
654 goto jret0;
655 break;
657 case n_CMD_ARG_TYPE_ARG:{
658 /* TODO The _ARG_TYPE_ARG is preliminary, in the end we should have a
659 * TODO per command-ctx carrier that also has slots for it arguments,
660 * TODO and that should be passed along all the way. No more arglists
661 * TODO here, etc. */
662 struct n_cmd_arg_ctx cac;
664 cac.cac_desc = cdp->cd_cadp;
665 cac.cac_indat = line.s;
666 cac.cac_inlen = line.l;
667 if(!n_cmd_arg_parse(&cac)){
668 flags |= a_NO_ERRNO;
669 break;
672 if(flags & a_VPUT){
673 cac.cac_vput = *arglist_base;
674 n_pstate |= n_PS_ARGMOD_VPUT;
675 }else
676 cac.cac_vput = NULL;
678 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
679 n_err_no = 0;
680 rv = (*cdp->cd_func)(&cac);
681 if(a_go_xcall != NULL)
682 goto jret0;
683 } break;
685 default:
686 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
687 cdp->cd_caflags & n_CMD_ARG_TYPE_MASK); )
688 nerrn = n_ERR_NOTOBACCO;
689 nexn = 1;
690 goto jret0;
693 if(gecp->gec_hist_flags & a_GO_HIST_ADD){
694 if(cdp->cd_caflags & n_CMD_ARG_H)
695 gecp->gec_hist_flags = a_GO_HIST_NONE;
696 else if((cdp->cd_caflags & n_CMD_ARG_G) ||
697 (n_pstate & n_PS_MSGLIST_GABBY))
698 gecp->gec_hist_flags |= a_GO_HIST_GABBY;
701 if(rv != 0){
702 if(!(flags & a_NO_ERRNO)){
703 if(cdp->cd_caflags & n_CMD_ARG_EM)
704 flags |= a_NO_ERRNO;
705 else if((nerrn = n_err_no) == 0)
706 nerrn = n_ERR_INVAL;
707 }else
708 flags ^= a_NO_ERRNO;
709 }else if(cdp->cd_caflags & n_CMD_ARG_EM)
710 flags |= a_NO_ERRNO;
711 else
712 nerrn = n_ERR_NONE;
713 jleave:
714 nexn = rv;
716 if(flags & a_IGNERR){
717 n_pstate &= ~n_PS_ERR_EXIT_MASK;
718 n_exit_status = n_EXIT_OK;
719 }else if(rv != 0){
720 bool_t bo;
722 if((bo = ok_blook(batch_exit_on_error))){
723 n_OBSOLETE(_("please use *errexit*, not *batch-exit-on-error*"));
724 if(!(n_poption & n_PO_BATCH_FLAG))
725 bo = FAL0;
727 if(ok_blook(errexit) || bo) /* TODO v15: drop bo */
728 n_pstate |= n_PS_ERR_QUIT;
729 else if(ok_blook(posix)){
730 if(n_psonce & n_PSO_STARTED)
731 rv = 0;
732 else if(!(n_psonce & n_PSO_INTERACTIVE))
733 n_pstate |= n_PS_ERR_XIT;
734 }else
735 rv = 0;
737 if(rv != 0){
738 if(n_exit_status == n_EXIT_OK)
739 n_exit_status = n_EXIT_ERR;
740 if((n_poption & n_PO_D_V) &&
741 !(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)))
742 n_alert(_("Non-interactive, bailing out due to errors "
743 "in startup load phase"));
744 goto jret;
748 if(cdp == NULL)
749 goto jret0;
750 if((cdp->cd_caflags & n_CMD_ARG_P) && ok_blook(autoprint))
751 if(visible(dot))
752 n_go_input_inject(n_GO_INPUT_INJECT_COMMIT, "\\type",
753 sizeof("\\type") -1);
755 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
756 !(cdp->cd_caflags & n_CMD_ARG_T))
757 n_pstate |= n_PS_SAW_COMMAND;
758 jret0:
759 rv = 0;
760 jret:
761 if(!(flags & a_NO_ERRNO))
762 n_pstate_err_no = nerrn;
763 n_pstate_ex_no = nexn;
764 NYD_LEAVE;
765 return (rv == 0);
768 static void
769 a_go_hangup(int s){
770 NYD_X; /* Signal handler */
771 n_UNUSED(s);
772 /* nothing to do? */
773 exit(n_EXIT_ERR);
776 #ifdef HAVE_IMAP
777 FL void n_go_onintr_for_imap(void){a_go_onintr(0);}
778 #endif
779 static void
780 a_go_onintr(int s){ /* TODO block signals while acting */
781 NYD_X; /* Signal handler */
782 n_UNUSED(s);
784 safe_signal(SIGINT, a_go_onintr);
786 termios_state_reset();
788 a_go_cleanup(a_GO_CLEANUP_UNWIND | /* XXX FAKE */a_GO_CLEANUP_HOLDALLSIGS);
790 if(interrupts != 1)
791 n_err_sighdl(_("Interrupt\n"));
792 safe_signal(SIGPIPE, a_go_oldpipe);
793 siglongjmp(a_go_srbuf, 0); /* FIXME get rid */
796 static void
797 a_go_cleanup(enum a_go_cleanup_mode gcm){
798 /* Signals blocked */
799 struct a_go_ctx *gcp;
800 NYD_ENTER;
802 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
803 hold_all_sigs();
804 jrestart:
805 gcp = a_go_ctx;
807 /* Free input injections of this level first */
808 if(!(gcm & a_GO_CLEANUP_LOOPTICK)){
809 struct a_go_input_inject **giipp, *giip;
811 for(giipp = &gcp->gc_inject; (giip = *giipp) != NULL;){
812 *giipp = giip->gii_next;
813 n_free(giip);
817 /* Cleanup non-crucial external stuff */
818 n_COLOUR(
819 if(gcp->gc_data.gdc_colour != NULL)
820 n_colour_stack_del(&gcp->gc_data);
823 /* Work the actual context (according to cleanup mode) */
824 if(gcp->gc_outer == NULL){
825 if(gcm & (a_GO_CLEANUP_UNWIND | a_GO_CLEANUP_SIGINT)){
826 if(a_go_xcall != NULL){
827 n_free(a_go_xcall);
828 a_go_xcall = NULL;
830 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
831 n_pstate &= ~n_PS_ERR_EXIT_MASK;
832 close_all_files();
833 }else{
834 if(!(n_pstate & n_PS_SOURCING))
835 close_all_files();
838 n_memory_reset();
840 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
841 assert(a_go_xcall == NULL);
842 assert(!(gcp->gc_flags & a_GO_XCALL_LOOP_MASK));
843 assert(gcp->gc_on_finalize == NULL);
844 assert(gcp->gc_data.gdc_colour == NULL);
845 goto jxleave;
846 }else if(gcm & a_GO_CLEANUP_LOOPTICK){
847 n_memory_reset();
848 goto jxleave;
849 }else if(gcp->gc_flags & a_GO_SPLICE){ /* TODO Temporary hack */
850 n_stdin = gcp->gc_splice_stdin;
851 n_stdout = gcp->gc_splice_stdout;
852 n_psonce = gcp->gc_splice_psonce;
853 goto jstackpop;
856 /* Cleanup crucial external stuff */
857 if(gcp->gc_data.gdc_ifcond != NULL){
858 n_cnd_if_stack_del(&gcp->gc_data);
859 if(!(gcm & (a_GO_CLEANUP_ERROR | a_GO_CLEANUP_SIGINT)) &&
860 !(gcp->gc_flags & a_GO_FORCE_EOF) && a_go_xcall == NULL &&
861 !(n_psonce & n_PSO_EXIT_MASK)){
862 n_err(_("Unmatched `if' at end of %s %s\n"),
863 ((gcp->gc_flags & a_GO_MACRO
864 ? (gcp->gc_flags & a_GO_MACRO_CMD ? _("command") : _("macro"))
865 : _("`source'd file"))),
866 gcp->gc_name);
867 gcm |= a_GO_CLEANUP_ERROR;
871 /* Teardown context */
872 if(gcp->gc_flags & a_GO_MACRO){
873 if(gcp->gc_flags & a_GO_MACRO_FREE_DATA){
874 char **lp;
876 while(*(lp = &gcp->gc_lines[gcp->gc_loff]) != NULL){
877 n_free(*lp);
878 ++gcp->gc_loff;
880 /* Part of gcp's memory chunk, then */
881 if(!(gcp->gc_flags & a_GO_MACRO_CMD))
882 n_free(gcp->gc_lines);
884 }else if(gcp->gc_flags & a_GO_PIPE)
885 /* XXX command manager should -TERM then -KILL instead of hoping
886 * XXX for exit of provider due to n_ERR_PIPE / SIGPIPE */
887 Pclose(gcp->gc_file, TRU1);
888 else if(gcp->gc_flags & a_GO_FILE)
889 Fclose(gcp->gc_file);
891 if(!(gcp->gc_flags & a_GO_MEMPOOL_INHERITED)){
892 if(gcp->gc_data.gdc_mempool != NULL)
893 n_memory_pool_pop(NULL);
894 }else
895 n_memory_reset();
897 jstackpop:
898 /* Update a_go_ctx and n_go_data, n_pstate ... */
899 a_go_ctx = gcp->gc_outer;
900 assert(a_go_ctx != NULL);
901 /* C99 */{
902 struct a_go_ctx *x;
904 for(x = a_go_ctx; x->gc_flags & a_GO_DATACTX_INHERITED;){
905 x = x->gc_outer;
906 assert(x != NULL);
908 n_go_data = &x->gc_data;
911 if((a_go_ctx->gc_flags & (a_GO_MACRO | a_GO_SUPER_MACRO)) ==
912 (a_GO_MACRO | a_GO_SUPER_MACRO)){
913 n_pstate &= ~n_PS_SOURCING;
914 assert(n_pstate & n_PS_ROBOT);
915 }else if(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK))
916 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
917 else
918 assert(n_pstate & n_PS_ROBOT);
920 if(gcp->gc_on_finalize != NULL)
921 (*gcp->gc_on_finalize)(gcp->gc_finalize_arg);
923 if(gcm & a_GO_CLEANUP_ERROR){
924 if(a_go_ctx->gc_flags & a_GO_XCALL_LOOP)
925 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP_ERROR;
926 goto jerr;
928 jleave:
929 if(gcp->gc_flags & a_GO_FREE)
930 n_free(gcp);
932 if(n_UNLIKELY((gcm & a_GO_CLEANUP_UNWIND) && gcp != a_go_ctx))
933 goto jrestart;
935 jxleave:
936 NYD_LEAVE;
937 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
938 rele_all_sigs();
939 return;
941 jerr:
942 /* With *posix* we follow what POSIX says:
943 * Any errors in the start-up file shall either cause mailx to
944 * terminate with a diagnostic message and a non-zero status or to
945 * continue after writing a diagnostic message, ignoring the
946 * remainder of the lines in the start-up file
947 * Print the diagnostic only for the outermost resource unless the user
948 * is debugging or in verbose mode */
949 if((n_poption & n_PO_D_V) ||
950 (!(n_psonce & n_PSO_STARTED) &&
951 !(gcp->gc_flags & (a_GO_SPLICE | a_GO_MACRO)) &&
952 !(gcp->gc_outer->gc_flags & a_GO_TYPE_MASK)))
953 /* I18N: file inclusion, macro etc. evaluation has been stopped */
954 n_alert(_("Stopped %s %s due to errors%s"),
955 (n_psonce & n_PSO_STARTED
956 ? (gcp->gc_flags & a_GO_SPLICE ? _("spliced in program")
957 : (gcp->gc_flags & a_GO_MACRO
958 ? (gcp->gc_flags & a_GO_MACRO_CMD
959 ? _("evaluating command") : _("evaluating macro"))
960 : (gcp->gc_flags & a_GO_PIPE
961 ? _("executing `source'd pipe")
962 : (gcp->gc_flags & a_GO_FILE
963 ? _("loading `source'd file") : _(a_GO_MAINCTX_NAME))))
965 : (gcp->gc_flags & a_GO_MACRO
966 ? (gcp->gc_flags & a_GO_MACRO_X_OPTION
967 ? _("evaluating command line") : _("evaluating macro"))
968 : _("loading initialization resource"))),
969 gcp->gc_name,
970 (n_poption & n_PO_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
971 goto jleave;
974 static bool_t
975 a_go_file(char const *file, bool_t silent_open_error){
976 struct a_go_ctx *gcp;
977 sigset_t osigmask;
978 size_t nlen;
979 char *nbuf;
980 bool_t ispipe;
981 FILE *fip;
982 NYD_ENTER;
984 fip = NULL;
986 /* Being a command argument file is space-trimmed *//* TODO v15 with
987 * TODO WYRALIST this is no longer necessary true, and for that we
988 * TODO don't set _PARSE_TRIM_SPACE because we cannot! -> cmd-tab.h!! */
989 #if 0
990 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
991 file[--nlen] == '|')))
992 #else
993 ispipe = FAL0;
994 if(!silent_open_error){
995 for(nlen = strlen(file); nlen > 0;){
996 char c;
998 c = file[--nlen];
999 if(!spacechar(c)){
1000 if(c == '|'){
1001 nbuf = savestrbuf(file, nlen);
1002 ispipe = TRU1;
1004 break;
1008 #endif
1010 if(ispipe){
1011 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1012 ok_vlook(SHELL), NULL, n_CHILD_FD_NULL)) == NULL)
1013 goto jeopencheck;
1014 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1015 goto jeopencheck;
1016 else if((fip = Fopen(nbuf, "r")) == NULL){
1017 jeopencheck:
1018 if(!silent_open_error || (n_poption & n_PO_D_V))
1019 n_perr(nbuf, 0);
1020 if(silent_open_error)
1021 fip = (FILE*)-1;
1022 goto jleave;
1025 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1027 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1028 (nlen = strlen(nbuf) +1));
1029 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1031 hold_all_sigs();
1033 gcp->gc_outer = a_go_ctx;
1034 gcp->gc_osigmask = osigmask;
1035 gcp->gc_file = fip;
1036 gcp->gc_flags = (ispipe ? a_GO_FREE | a_GO_PIPE : a_GO_FREE | a_GO_FILE) |
1037 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO ? a_GO_SUPER_MACRO : 0);
1038 memcpy(gcp->gc_name, nbuf, nlen);
1040 a_go_ctx = gcp;
1041 n_go_data = &gcp->gc_data;
1042 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1043 if(!a_go_event_loop(gcp, n_GO_INPUT_NONE | n_GO_INPUT_NL_ESC))
1044 fip = NULL;
1045 jleave:
1046 NYD_LEAVE;
1047 return (fip != NULL);
1050 static bool_t
1051 a_go_load(struct a_go_ctx *gcp){
1052 NYD2_ENTER;
1054 assert(!(n_psonce & n_PSO_STARTED));
1055 assert(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK));
1057 gcp->gc_flags |= a_GO_MEMPOOL_INHERITED;
1058 gcp->gc_data.gdc_mempool = n_go_data->gdc_mempool;
1060 hold_all_sigs();
1062 /* POSIX:
1063 * Any errors in the start-up file shall either cause mailx to terminate
1064 * with a diagnostic message and a non-zero status or to continue after
1065 * writing a diagnostic message, ignoring the remainder of the lines in
1066 * the start-up file. */
1067 gcp->gc_outer = a_go_ctx;
1068 a_go_ctx = gcp;
1069 n_go_data = &gcp->gc_data;
1070 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1071 n_pstate |= n_PS_ROBOT |
1072 (gcp->gc_flags & a_GO_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1074 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1076 rele_all_sigs();
1078 n_go_main_loop();
1079 NYD2_LEAVE;
1080 return (((n_psonce & n_PSO_EXIT_MASK) |
1081 (n_pstate & n_PS_ERR_EXIT_MASK)) == 0);
1084 static void
1085 a_go__eloopint(int sig){ /* TODO one day, we don't need it no more */
1086 NYD_X; /* Signal handler */
1087 n_UNUSED(sig);
1088 siglongjmp(a_go_ctx->gc_eloop_jmp, 1);
1091 static bool_t
1092 a_go_event_loop(struct a_go_ctx *gcp, enum n_go_input_flags gif){
1093 sighandler_type soldhdl;
1094 struct a_go_eval_ctx gec;
1095 enum {a_RETOK = TRU1, a_TICKED = 1<<1} volatile f;
1096 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1097 sigset_t osigmask;
1098 NYD2_ENTER;
1100 memset(&gec, 0, sizeof gec);
1101 osigmask = gcp->gc_osigmask;
1102 hadint = FAL0;
1103 f = a_RETOK;
1105 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1106 safe_signal(SIGINT, &a_go__eloopint);
1107 if(sigsetjmp(gcp->gc_eloop_jmp, 1)){
1108 hold_all_sigs();
1109 hadint = TRU1;
1110 f &= ~a_RETOK;
1111 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1112 goto jjump;
1116 for(;; f |= a_TICKED){
1117 int n;
1119 if(f & a_TICKED)
1120 n_memory_reset();
1122 /* Read a line of commands and handle end of file specially */
1123 gec.gec_line.l = gec.gec_line_size;
1124 rele_all_sigs();
1125 n = n_go_input(gif, NULL, &gec.gec_line.s, &gec.gec_line.l, NULL, NULL);
1126 hold_all_sigs();
1127 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1128 gec.gec_line.l = (ui32_t)n;
1130 if(n < 0)
1131 break;
1133 rele_all_sigs();
1134 assert(gec.gec_hist_flags == a_GO_HIST_NONE);
1135 if(!a_go_evaluate(&gec))
1136 f &= ~a_RETOK;
1137 hold_all_sigs();
1139 if(!(f & a_RETOK) || a_go_xcall != NULL ||
1140 (n_psonce & n_PSO_EXIT_MASK) || (n_pstate & n_PS_ERR_EXIT_MASK))
1141 break;
1144 jjump: /* TODO Should be _CLEANUP_UNWIND not _TEARDOWN on signal if DOABLE! */
1145 a_go_cleanup(a_GO_CLEANUP_TEARDOWN |
1146 (f & a_RETOK ? 0 : a_GO_CLEANUP_ERROR) |
1147 (hadint ? a_GO_CLEANUP_SIGINT : 0) | a_GO_CLEANUP_HOLDALLSIGS);
1149 if(gec.gec_line.s != NULL)
1150 n_free(gec.gec_line.s);
1152 if(soldhdl != SIG_IGN)
1153 safe_signal(SIGINT, soldhdl);
1154 NYD2_LEAVE;
1155 rele_all_sigs();
1156 if(hadint){
1157 sigprocmask(SIG_SETMASK, &osigmask, NULL);
1158 n_raise(SIGINT);
1160 return (f & a_RETOK);
1163 FL void
1164 n_go_init(void){
1165 struct a_go_ctx *gcp;
1166 NYD2_ENTER;
1168 assert(n_stdin != NULL);
1170 gcp = (void*)a_go__mainctx_b.uf;
1171 DBGOR( memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name)),
1172 memset(&gcp->gc_data, 0, sizeof gcp->gc_data) );
1173 gcp->gc_file = n_stdin;
1174 memcpy(gcp->gc_name, a_GO_MAINCTX_NAME, sizeof(a_GO_MAINCTX_NAME));
1175 a_go_ctx = gcp;
1176 n_go_data = &gcp->gc_data;
1178 n_child_manager_start();
1179 NYD2_LEAVE;
1182 FL bool_t
1183 n_go_main_loop(void){ /* FIXME */
1184 struct a_go_eval_ctx gec;
1185 int n, eofcnt;
1186 bool_t volatile rv;
1187 NYD_ENTER;
1189 rv = TRU1;
1191 if (!(n_pstate & n_PS_SOURCING)) {
1192 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1193 safe_signal(SIGINT, &a_go_onintr);
1194 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1195 safe_signal(SIGHUP, &a_go_hangup);
1197 a_go_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1198 safe_signal(SIGPIPE, a_go_oldpipe);
1200 memset(&gec, 0, sizeof gec);
1202 (void)sigsetjmp(a_go_srbuf, 1); /* FIXME get rid */
1203 hold_all_sigs();
1205 for (eofcnt = 0;; gec.gec_ever_seen = TRU1) {
1206 interrupts = 0;
1208 if(gec.gec_ever_seen)
1209 a_go_cleanup(a_GO_CLEANUP_LOOPTICK | a_GO_CLEANUP_HOLDALLSIGS);
1211 if (!(n_pstate & n_PS_SOURCING)) {
1212 char *cp;
1214 /* TODO Note: this buffer may contain a password. We should redefine
1215 * TODO the code flow which has to do that */
1216 if ((cp = termios_state.ts_linebuf) != NULL) {
1217 termios_state.ts_linebuf = NULL;
1218 termios_state.ts_linesize = 0;
1219 n_free(cp); /* TODO pool give-back */
1221 if (gec.gec_line.l > LINESIZE * 3) {
1222 n_free(gec.gec_line.s);
1223 gec.gec_line.s = NULL;
1224 gec.gec_line.l = gec.gec_line_size = 0;
1228 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1229 char *cp;
1231 if ((cp = ok_vlook(newmail)) != NULL) { /* TODO bla */
1232 struct stat st;
1234 if(mb.mb_type == MB_FILE){
1235 if(!stat(mailname, &st) && st.st_size > mailsize) Jnewmail:{
1236 ui32_t odid;
1237 size_t odot;
1239 odot = PTR2SIZE(dot - message);
1240 odid = (n_pstate & n_PS_DID_PRINT_DOT);
1242 rele_all_sigs();
1243 n = setfile(mailname,
1244 (FEDIT_NEWMAIL |
1245 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)));
1246 hold_all_sigs();
1248 if(n < 0) {
1249 n_exit_status |= n_EXIT_ERR;
1250 rv = FAL0;
1251 break;
1253 #ifdef HAVE_IMAP
1254 if(mb.mb_type != MB_IMAP){
1255 #endif
1256 dot = &message[odot];
1257 n_pstate |= odid;
1258 #ifdef HAVE_IMAP
1260 #endif
1262 }else{
1263 n = (cp != NULL && strcmp(cp, "nopoll"));
1265 if(mb.mb_type == MB_MAILDIR){
1266 if(n != 0)
1267 goto Jnewmail;
1269 #ifdef HAVE_IMAP
1270 else if(mb.mb_type == MB_IMAP){
1271 if(!n)
1272 n = (cp != NULL && strcmp(cp, "noimap"));
1274 if(imap_newmail(n) > (cp == NULL))
1275 goto Jnewmail;
1277 #endif
1282 /* Read a line of commands and handle end of file specially */
1283 gec.gec_line.l = gec.gec_line_size;
1284 /* C99 */{
1285 bool_t histadd;
1287 histadd = (!(n_pstate & n_PS_SOURCING) &&
1288 (n_psonce & n_PSO_INTERACTIVE));
1289 rele_all_sigs();
1290 n = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, NULL,
1291 &gec.gec_line.s, &gec.gec_line.l, NULL, &histadd);
1292 hold_all_sigs();
1294 gec.gec_hist_flags = histadd ? a_GO_HIST_ADD : a_GO_HIST_NONE;
1296 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1297 gec.gec_line.l = (ui32_t)n;
1299 if (n < 0) {
1300 if (!(n_pstate & n_PS_ROBOT) &&
1301 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1302 ++eofcnt < 4) {
1303 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1304 n_go_input_clearerr();
1305 continue;
1307 break;
1310 n_pstate &= ~n_PS_HOOK_MASK;
1311 rele_all_sigs();
1312 rv = a_go_evaluate(&gec);
1313 hold_all_sigs();
1315 if(gec.gec_hist_flags & a_GO_HIST_ADD){
1316 char const *cc, *ca;
1318 cc = gec.gec_hist_cmd;
1319 ca = gec.gec_hist_args;
1320 if(cc != NULL && ca != NULL)
1321 cc = savecatsep(cc, ' ', ca);
1322 else if(ca != NULL)
1323 cc = ca;
1324 assert(cc != NULL);
1325 n_tty_addhist(cc, ((gec.gec_hist_flags & a_GO_HIST_GABBY) != 0));
1328 switch(n_pstate & n_PS_ERR_EXIT_MASK){
1329 case n_PS_ERR_XIT: n_psonce |= n_PSO_XIT; break;
1330 case n_PS_ERR_QUIT: n_psonce |= n_PSO_QUIT; break;
1331 default: break;
1333 if(n_psonce & n_PSO_EXIT_MASK)
1334 break;
1336 if(!rv)
1337 break;
1340 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS |
1341 (rv ? 0 : a_GO_CLEANUP_ERROR));
1343 if (gec.gec_line.s != NULL)
1344 n_free(gec.gec_line.s);
1346 rele_all_sigs();
1347 NYD_LEAVE;
1348 return rv;
1351 FL void
1352 n_go_input_clearerr(void){
1353 FILE *fp;
1354 NYD2_ENTER;
1356 fp = NULL;
1358 if(!(a_go_ctx->gc_flags & (a_GO_FORCE_EOF |
1359 a_GO_PIPE | a_GO_MACRO | a_GO_SPLICE)))
1360 fp = a_go_ctx->gc_file;
1362 if(fp != NULL){
1363 a_go_ctx->gc_flags &= ~a_GO_IS_EOF;
1364 clearerr(fp);
1366 NYD2_LEAVE;
1369 FL void
1370 n_go_input_force_eof(void){
1371 NYD2_ENTER;
1372 a_go_ctx->gc_flags |= a_GO_FORCE_EOF;
1373 NYD2_LEAVE;
1376 FL bool_t
1377 n_go_input_is_eof(void){
1378 bool_t rv;
1379 NYD2_ENTER;
1381 rv = ((a_go_ctx->gc_flags & a_GO_IS_EOF) != 0);
1382 NYD2_LEAVE;
1383 return rv;
1386 FL void
1387 n_go_input_inject(enum n_go_input_inject_flags giif, char const *buf,
1388 size_t len){
1389 NYD_ENTER;
1390 if(len == UIZ_MAX)
1391 len = strlen(buf);
1393 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat) -1 > len &&
1394 len > 0){
1395 struct a_go_input_inject *giip, **giipp;
1397 hold_all_sigs();
1399 giip = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat
1400 ) + 1 + len +1);
1401 giipp = &a_go_ctx->gc_inject;
1402 giip->gii_next = *giipp;
1403 giip->gii_commit = ((giif & n_GO_INPUT_INJECT_COMMIT) != 0);
1404 giip->gii_no_history = ((giif & n_GO_INPUT_INJECT_HISTORY) == 0);
1405 memcpy(&giip->gii_dat[0], buf, len);
1406 giip->gii_dat[giip->gii_len = len] = '\0';
1407 *giipp = giip;
1409 rele_all_sigs();
1411 NYD_LEAVE;
1414 FL int
1415 (n_go_input)(enum n_go_input_flags gif, char const *prompt, char **linebuf,
1416 size_t *linesize, char const *string, bool_t *histok_or_null
1417 n_MEMORY_DEBUG_ARGS){
1418 /* TODO readline: linebuf pool!; n_go_input should return si64_t */
1419 struct n_string xprompt;
1420 FILE *ifile;
1421 bool_t doprompt, dotty;
1422 char const *iftype;
1423 struct a_go_input_inject *giip;
1424 int nold, n;
1425 bool_t histok;
1426 NYD2_ENTER;
1428 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1429 hold_all_sigs();
1431 histok = FAL0;
1433 if(a_go_ctx->gc_flags & a_GO_FORCE_EOF){
1434 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1435 n = -1;
1436 goto jleave;
1439 if(gif & n_GO_INPUT_FORCE_STDIN)
1440 goto jforce_stdin;
1442 /* Special case macro mode: never need to prompt, lines have always been
1443 * unfolded already */
1444 if(a_go_ctx->gc_flags & a_GO_MACRO){
1445 if(*linebuf != NULL)
1446 n_free(*linebuf);
1448 /* Injection in progress? Don't care about the autocommit state here */
1449 if((giip = a_go_ctx->gc_inject) != NULL){
1450 a_go_ctx->gc_inject = giip->gii_next;
1452 /* Simply "reuse" allocation, copy string to front of it */
1453 jinject:
1454 *linesize = giip->gii_len;
1455 *linebuf = (char*)giip;
1456 memmove(*linebuf, giip->gii_dat, giip->gii_len +1);
1457 iftype = "INJECTION";
1458 }else{
1459 if((*linebuf = a_go_ctx->gc_lines[a_go_ctx->gc_loff]) == NULL){
1460 *linesize = 0;
1461 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1462 n = -1;
1463 goto jleave;
1466 ++a_go_ctx->gc_loff;
1467 *linesize = strlen(*linebuf);
1468 if(!(a_go_ctx->gc_flags & a_GO_MACRO_FREE_DATA))
1469 *linebuf = sbufdup(*linebuf, *linesize);
1471 iftype = (a_go_ctx->gc_flags & a_GO_MACRO_X_OPTION)
1472 ? "-X OPTION"
1473 : (a_go_ctx->gc_flags & a_GO_MACRO_CMD) ? "CMD" : "MACRO";
1475 n = (int)*linesize;
1476 n_pstate |= n_PS_READLINE_NL;
1477 goto jhave_dat;
1478 }else{
1479 /* Injection in progress? */
1480 struct a_go_input_inject **giipp;
1482 giipp = &a_go_ctx->gc_inject;
1484 if((giip = *giipp) != NULL){
1485 *giipp = giip->gii_next;
1487 if(giip->gii_commit){
1488 if(*linebuf != NULL)
1489 n_free(*linebuf);
1490 histok = !giip->gii_no_history;
1491 goto jinject; /* (above) */
1492 }else{
1493 string = savestrbuf(giip->gii_dat, giip->gii_len);
1494 n_free(giip);
1499 jforce_stdin:
1500 n_pstate &= ~n_PS_READLINE_NL;
1501 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1502 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1503 histok = (n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1504 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT);
1505 doprompt = !(gif & n_GO_INPUT_FORCE_STDIN) && histok;
1506 dotty = (doprompt && !ok_blook(line_editor_disable));
1507 if(!doprompt)
1508 gif |= n_GO_INPUT_PROMPT_NONE;
1509 else{
1510 if(!dotty)
1511 n_string_creat_auto(&xprompt);
1512 if(prompt == NULL)
1513 gif |= n_GO_INPUT_PROMPT_EVAL;
1516 /* Ensure stdout is flushed first anyway (partial lines, maybe?) */
1517 if(!dotty && (gif & n_GO_INPUT_PROMPT_NONE))
1518 fflush(n_stdout);
1520 if(gif & n_GO_INPUT_FORCE_STDIN){
1521 struct a_go_readctl_ctx *grcp;
1523 grcp = n_readctl_overlay;
1524 ifile = (grcp == NULL || grcp->grc_fp == NULL) ? n_stdin : grcp->grc_fp;
1525 }else
1526 ifile = a_go_ctx->gc_file;
1527 if(ifile == NULL){
1528 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1529 (a_go_ctx->gc_flags & a_GO_MACRO));
1530 ifile = n_stdin;
1533 for(nold = n = 0;;){
1534 if(dotty){
1535 assert(ifile == n_stdin);
1536 if(string != NULL && (n = (int)strlen(string)) > 0){
1537 if(*linesize > 0)
1538 *linesize += n +1;
1539 else
1540 *linesize = (size_t)n + LINESIZE +1;
1541 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1542 memcpy(*linebuf, string, (size_t)n +1);
1544 string = NULL;
1546 rele_all_sigs();
1548 n = (n_tty_readline)(gif, prompt, linebuf, linesize, n, histok_or_null
1549 n_MEMORY_DEBUG_ARGSCALL);
1551 hold_all_sigs();
1552 }else{
1553 if(!(gif & n_GO_INPUT_PROMPT_NONE))
1554 n_tty_create_prompt(&xprompt, prompt, gif);
1556 rele_all_sigs();
1558 if(!(gif & n_GO_INPUT_PROMPT_NONE) && xprompt.s_len > 0){
1559 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1560 fflush(n_stdout);
1563 n = (readline_restart)(ifile, linebuf, linesize, n
1564 n_MEMORY_DEBUG_ARGSCALL);
1566 hold_all_sigs();
1568 if(n < 0 && feof(ifile))
1569 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1571 if(n > 0 && nold > 0){
1572 char const *cp;
1573 int i;
1575 i = 0;
1576 cp = &(*linebuf)[nold];
1577 while(spacechar(*cp) && n - i >= nold)
1578 ++cp, ++i;
1579 if(i > 0){
1580 memmove(&(*linebuf)[nold], cp, n - nold - i);
1581 n -= i;
1582 (*linebuf)[n] = '\0';
1587 if(n <= 0)
1588 break;
1590 /* POSIX says:
1591 * An unquoted <backslash> at the end of a command line shall
1592 * be discarded and the next line shall continue the command */
1593 if(!(gif & n_GO_INPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1594 if(dotty)
1595 n_pstate |= n_PS_READLINE_NL;
1596 break;
1598 /* Definitely outside of quotes, thus the quoting rules are so that an
1599 * uneven number of successive reverse solidus at EOL is a continuation */
1600 if(n > 1){
1601 size_t i, j;
1603 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1604 if((*linebuf)[i] != '\\')
1605 break;
1606 if(!(j & 1))
1607 break;
1609 (*linebuf)[nold = --n] = '\0';
1610 gif |= n_GO_INPUT_NL_FOLLOW;
1613 if(n < 0)
1614 goto jleave;
1615 (*linebuf)[*linesize = n] = '\0';
1617 jhave_dat:
1618 if(n_poption & n_PO_D_VV)
1619 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1620 jleave:
1621 if (n_pstate & n_PS_PSTATE_PENDMASK)
1622 a_go_update_pstate();
1624 /* TODO We need to special case a_GO_SPLICE, since that is not managed by us
1625 * TODO but only established from the outside and we need to drop this
1626 * TODO overlay context somehow */
1627 if(n < 0 && (a_go_ctx->gc_flags & a_GO_SPLICE))
1628 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS);
1630 if(histok_or_null != NULL && !histok)
1631 *histok_or_null = FAL0;
1633 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1634 rele_all_sigs();
1635 NYD2_LEAVE;
1636 return n;
1639 FL char *
1640 n_go_input_cp(enum n_go_input_flags gif, char const *prompt,
1641 char const *string){
1642 struct n_sigman sm;
1643 bool_t histadd;
1644 size_t linesize;
1645 char *linebuf, * volatile rv;
1646 int n;
1647 NYD2_ENTER;
1649 linesize = 0;
1650 linebuf = NULL;
1651 rv = NULL;
1653 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL){
1654 case 0:
1655 break;
1656 default:
1657 goto jleave;
1660 histadd = TRU1;
1661 n = n_go_input(gif, prompt, &linebuf, &linesize, string, &histadd);
1662 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1663 (gif & n_GO_INPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE) &&
1664 histadd)
1665 n_tty_addhist(rv, ((gif & n_GO_INPUT_HIST_GABBY) != 0));
1667 n_sigman_cleanup_ping(&sm);
1668 jleave:
1669 if(linebuf != NULL)
1670 n_free(linebuf);
1671 NYD2_LEAVE;
1672 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
1673 return rv;
1676 FL bool_t
1677 n_go_load(char const *name){
1678 struct a_go_ctx *gcp;
1679 size_t i;
1680 FILE *fip;
1681 bool_t rv;
1682 NYD_ENTER;
1684 rv = TRU1;
1686 if(name == NULL || *name == '\0')
1687 goto jleave;
1688 else if((fip = Fopen(name, "r")) == NULL){
1689 if(n_poption & n_PO_D_V)
1690 n_err(_("No such file to load: %s\n"), n_shexp_quote_cp(name, FAL0));
1691 goto jleave;
1694 i = strlen(name) +1;
1695 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + i);
1696 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1698 gcp->gc_file = fip;
1699 gcp->gc_flags = a_GO_FREE | a_GO_FILE;
1700 memcpy(gcp->gc_name, name, i);
1702 if(n_poption & n_PO_D_V)
1703 n_err(_("Loading %s\n"), n_shexp_quote_cp(gcp->gc_name, FAL0));
1704 rv = a_go_load(gcp);
1705 jleave:
1706 NYD_LEAVE;
1707 return rv;
1710 FL bool_t
1711 n_go_Xargs(char const **lines, size_t cnt){
1712 static char const name[] = "-X";
1714 union{
1715 bool_t rv;
1716 ui64_t align;
1717 char uf[n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + sizeof(name)];
1718 } b;
1719 char const *srcp, *xsrcp;
1720 char *cp;
1721 size_t imax, i, len;
1722 struct a_go_ctx *gcp;
1723 NYD_ENTER;
1725 gcp = (void*)b.uf;
1726 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1728 gcp->gc_flags = a_GO_MACRO | a_GO_MACRO_X_OPTION |
1729 a_GO_SUPER_MACRO | a_GO_MACRO_FREE_DATA;
1730 memcpy(gcp->gc_name, name, sizeof name);
1732 /* The problem being that we want to support reverse solidus newline
1733 * escaping also within multiline -X, i.e., POSIX says:
1734 * An unquoted <backslash> at the end of a command line shall
1735 * be discarded and the next line shall continue the command
1736 * Therefore instead of "gcp->gc_lines = n_UNCONST(lines)", duplicate the
1737 * entire lines array and set _MACRO_FREE_DATA */
1738 imax = cnt + 1;
1739 gcp->gc_lines = n_alloc(sizeof(*gcp->gc_lines) * imax);
1741 /* For each of the input lines.. */
1742 for(i = len = 0, cp = NULL; cnt > 0;){
1743 bool_t keep;
1744 size_t j;
1746 if((j = strlen(srcp = *lines)) == 0){
1747 ++lines, --cnt;
1748 continue;
1751 /* Separate one line from a possible multiline input string */
1752 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1753 *lines = &xsrcp[1];
1754 j = PTR2SIZE(xsrcp - srcp);
1755 }else
1756 ++lines, --cnt;
1758 /* The (separated) string may itself indicate soft newline escaping */
1759 if((keep = (srcp[j - 1] == '\\'))){
1760 size_t xj, xk;
1762 /* Need an uneven number of reverse solidus */
1763 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1764 if(srcp[xj] != '\\')
1765 break;
1766 if(xk & 1)
1767 --j;
1768 else
1769 keep = FAL0;
1772 /* Strip any leading WS from follow lines, then */
1773 if(cp != NULL)
1774 while(j > 0 && spacechar(*srcp))
1775 ++srcp, --j;
1777 if(j > 0){
1778 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1779 imax += 4;
1780 gcp->gc_lines = n_realloc(gcp->gc_lines, sizeof(*gcp->gc_lines) *
1781 imax);
1783 gcp->gc_lines[i] = cp = n_realloc(cp, len + j +1);
1784 memcpy(&cp[len], srcp, j);
1785 cp[len += j] = '\0';
1787 if(!keep)
1788 ++i;
1790 if(!keep)
1791 cp = NULL, len = 0;
1793 if(cp != NULL){
1794 assert(i + 1 < imax);
1795 gcp->gc_lines[i++] = cp;
1797 gcp->gc_lines[i] = NULL;
1799 b.rv = a_go_load(gcp);
1800 NYD_LEAVE;
1801 return b.rv;
1804 FL int
1805 c_source(void *v){
1806 int rv;
1807 NYD_ENTER;
1809 rv = (a_go_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1810 NYD_LEAVE;
1811 return rv;
1814 FL int
1815 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1816 int rv;
1817 NYD_ENTER;
1819 rv = (a_go_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
1820 NYD_LEAVE;
1821 return rv;
1824 FL bool_t
1825 n_go_macro(enum n_go_input_flags gif, char const *name, char **lines,
1826 void (*on_finalize)(void*), void *finalize_arg){
1827 struct a_go_ctx *gcp;
1828 size_t i;
1829 int rv;
1830 sigset_t osigmask;
1831 NYD_ENTER;
1833 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1835 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1836 (i = strlen(name) +1));
1837 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1839 hold_all_sigs();
1841 gcp->gc_outer = a_go_ctx;
1842 gcp->gc_osigmask = osigmask;
1843 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_FREE_DATA |
1844 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1845 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0) |
1846 ((gif & n_GO_INPUT_NO_XCALL) ? a_GO_XCALL_IS_CALL : 0);
1847 gcp->gc_lines = lines;
1848 gcp->gc_on_finalize = on_finalize;
1849 gcp->gc_finalize_arg = finalize_arg;
1850 memcpy(gcp->gc_name, name, i);
1852 a_go_ctx = gcp;
1853 n_go_data = &gcp->gc_data;
1854 n_pstate |= n_PS_ROBOT;
1855 rv = a_go_event_loop(gcp, gif);
1857 /* Shall this enter a `xcall' stack avoidance optimization (loop)? */
1858 if(a_go_xcall != NULL){
1859 void *vp;
1860 struct n_cmd_arg_ctx *cacp;
1862 if(a_go_xcall == (void*)-1)
1863 a_go_xcall = NULL;
1864 else if(((void const*)(cacp = a_go_xcall)->cac_indat) == gcp){
1865 /* Indicate that "our" (ex-) parent now hosts xcall optimization */
1866 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP;
1867 while(a_go_xcall != NULL){
1868 hold_all_sigs();
1870 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_ERROR;
1872 vp = a_go_xcall;
1873 a_go_xcall = NULL;
1874 cacp = n_cmd_arg_restore_from_heap(vp);
1875 n_free(vp);
1877 rele_all_sigs();
1879 (void)c_call(cacp);
1881 rv = ((a_go_ctx->gc_flags & a_GO_XCALL_LOOP_ERROR) == 0);
1882 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1885 NYD_LEAVE;
1886 return rv;
1889 FL bool_t
1890 n_go_command(enum n_go_input_flags gif, char const *cmd){
1891 struct a_go_ctx *gcp;
1892 bool_t rv;
1893 size_t i, ial;
1894 sigset_t osigmask;
1895 NYD_ENTER;
1897 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1899 i = strlen(cmd) +1;
1900 ial = n_ALIGN(i);
1901 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1902 ial + 2*sizeof(char*));
1903 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1905 hold_all_sigs();
1907 gcp->gc_outer = a_go_ctx;
1908 gcp->gc_osigmask = osigmask;
1909 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_CMD |
1910 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1911 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0);
1912 gcp->gc_lines = (void*)&gcp->gc_name[ial];
1913 memcpy(gcp->gc_lines[0] = &gcp->gc_name[0], cmd, i);
1914 gcp->gc_lines[1] = NULL;
1916 a_go_ctx = gcp;
1917 n_go_data = &gcp->gc_data;
1918 n_pstate |= n_PS_ROBOT;
1919 rv = a_go_event_loop(gcp, gif);
1920 NYD_LEAVE;
1921 return rv;
1924 FL void
1925 n_go_splice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
1926 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
1927 struct a_go_ctx *gcp;
1928 size_t i;
1929 sigset_t osigmask;
1930 NYD_ENTER;
1932 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1934 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1935 (i = strlen(cmd) +1));
1936 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1938 hold_all_sigs();
1940 gcp->gc_outer = a_go_ctx;
1941 gcp->gc_osigmask = osigmask;
1942 gcp->gc_file = new_stdin;
1943 gcp->gc_flags = a_GO_FREE | a_GO_SPLICE | a_GO_DATACTX_INHERITED;
1944 gcp->gc_on_finalize = on_finalize;
1945 gcp->gc_finalize_arg = finalize_arg;
1946 gcp->gc_splice_stdin = n_stdin;
1947 gcp->gc_splice_stdout = n_stdout;
1948 gcp->gc_splice_psonce = n_psonce;
1949 memcpy(gcp->gc_name, cmd, i);
1951 n_stdin = new_stdin;
1952 n_stdout = new_stdout;
1953 n_psonce = new_psonce;
1954 a_go_ctx = gcp;
1955 /* Do NOT touch n_go_data! */
1956 n_pstate |= n_PS_ROBOT;
1958 rele_all_sigs();
1959 NYD_LEAVE;
1962 FL void
1963 n_go_splice_hack_remove_after_jump(void){
1964 a_go_cleanup(a_GO_CLEANUP_TEARDOWN);
1967 FL bool_t
1968 n_go_may_yield_control(void){ /* TODO this is a terrible hack */
1969 struct a_go_ctx *gcp;
1970 bool_t rv;
1971 NYD2_ENTER;
1973 rv = FAL0;
1975 /* Only when startup completed */
1976 if(!(n_psonce & n_PSO_STARTED))
1977 goto jleave;
1978 /* Only interactive or batch mode (assuming that is ok) */
1979 if(!(n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_BATCH_FLAG))
1980 goto jleave;
1982 /* Not when running any hook */
1983 if(n_pstate & n_PS_HOOK_MASK)
1984 goto jleave;
1986 /* Traverse up the stack:
1987 * . not when controlled by a child process
1988 * TODO . not when there are pipes involved, we neither handle job control,
1989 * TODO nor process groups, that is, controlling terminal acceptably
1990 * . not when sourcing a file */
1991 for(gcp = a_go_ctx; gcp != NULL; gcp = gcp->gc_outer){
1992 if(gcp->gc_flags & (a_GO_PIPE | a_GO_FILE | a_GO_SPLICE))
1993 goto jleave;
1996 rv = TRU1;
1997 jleave:
1998 NYD2_LEAVE;
1999 return rv;
2002 FL int
2003 c_eval(void *vp){
2004 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
2005 * TODO ARGV with shell rules, but if that is not possible then simply
2006 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
2007 struct a_go_eval_ctx gec;
2008 struct n_string s_b, *sp;
2009 size_t i, j;
2010 char const **argv, *cp;
2011 NYD_ENTER;
2013 argv = vp;
2015 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
2016 j += strlen(cp);
2018 sp = n_string_creat_auto(&s_b);
2019 sp = n_string_reserve(sp, j);
2021 for(i = 0; (cp = argv[i]) != NULL; ++i){
2022 if(i > 0)
2023 sp = n_string_push_c(sp, ' ');
2024 sp = n_string_push_cp(sp, cp);
2027 memset(&gec, 0, sizeof gec);
2028 gec.gec_line.s = n_string_cp(sp);
2029 gec.gec_line.l = sp->s_len;
2030 if(n_poption & n_PO_D_VV)
2031 n_err(_("EVAL %" PRIuZ " bytes <%s>\n"), gec.gec_line.l, gec.gec_line.s);
2032 (void)/* XXX */a_go_evaluate(&gec);
2033 NYD_LEAVE;
2034 return (a_go_xcall != NULL ? 0 : n_pstate_ex_no);
2037 FL int
2038 c_xcall(void *vp){
2039 int rv;
2040 struct a_go_ctx *gcp;
2041 NYD2_ENTER;
2043 /* The context can only be a macro context, except that possibly a single
2044 * level of `eval' (TODO: yet) was used to double-expand our arguments */
2045 if((gcp = a_go_ctx)->gc_flags & a_GO_MACRO_CMD)
2046 gcp = gcp->gc_outer;
2047 if((gcp->gc_flags & (a_GO_MACRO | a_GO_MACRO_X_OPTION | a_GO_MACRO_CMD)
2048 ) != a_GO_MACRO){
2049 if(n_poption & n_PO_D_V_VV)
2050 n_err(_("`xcall': can only be used inside a macro, using `call'\n"));
2051 rv = c_call(vp);
2052 goto jleave;
2055 /* Try to roll up the stack as much as possible.
2056 * See a_GO_XCALL_LOOP flag description for more */
2057 if(!(gcp->gc_flags & a_GO_XCALL_IS_CALL) && gcp->gc_outer != NULL){
2058 if(gcp->gc_outer->gc_flags & a_GO_XCALL_LOOP)
2059 gcp = gcp->gc_outer;
2060 }else{
2061 /* Otherwise this macro is "invoked from the top level", in which case we
2062 * silently act as if we were `call'... */
2063 rv = c_call(vp);
2064 /* ...which means we must ensure the rest of the macro that was us
2065 * doesn't become evaluated! */
2066 a_go_xcall = (void*)-1;
2067 goto jleave;
2070 /* C99 */{
2071 struct n_cmd_arg_ctx *cacp;
2073 cacp = n_cmd_arg_save_to_heap(vp);
2074 cacp->cac_indat = (char*)gcp;
2075 a_go_xcall = cacp;
2077 rv = 0;
2078 jleave:
2079 NYD2_LEAVE;
2080 return rv;
2083 FL int
2084 c_exit(void *vp){
2085 char const **argv;
2086 NYD_ENTER;
2088 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2089 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2090 ) != n_IDEC_STATE_CONSUMED)
2091 n_exit_status |= n_EXIT_ERR;
2093 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2094 fflush(NULL);
2095 _exit(n_exit_status);
2096 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2097 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2098 n_psonce |= n_PSO_XIT;
2099 NYD_LEAVE;
2100 return 0;
2103 FL int
2104 c_quit(void *vp){
2105 char const **argv;
2106 NYD_ENTER;
2108 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2109 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2110 ) != n_IDEC_STATE_CONSUMED)
2111 n_exit_status |= n_EXIT_ERR;
2113 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2114 fflush(NULL);
2115 _exit(n_exit_status);
2116 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2117 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2118 n_psonce |= n_PSO_QUIT;
2119 NYD_LEAVE;
2120 return 0;
2123 FL int
2124 c_readctl(void *vp){
2125 /* TODO We would need OnForkEvent and then simply remove some internal
2126 * TODO management; we don't have this, therefore we need global
2127 * TODO n_readctl_overlay to be accessible via =NULL, and to make that
2128 * TODO work in turn we need an instance for default STDIN! Sigh. */
2129 static ui8_t a_buf[n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name)+1 +1];
2130 static struct a_go_readctl_ctx *a_stdin;
2132 struct a_go_readctl_ctx *grcp;
2133 char const *emsg;
2134 enum{
2135 a_NONE = 0,
2136 a_ERR = 1u<<0,
2137 a_SET = 1u<<1,
2138 a_CREATE = 1u<<2,
2139 a_REMOVE = 1u<<3
2140 } f;
2141 struct n_cmd_arg *cap;
2142 struct n_cmd_arg_ctx *cacp;
2143 NYD_ENTER;
2145 if(a_stdin == NULL){
2146 a_stdin = (struct a_go_readctl_ctx*)a_buf;
2147 a_stdin->grc_name[0] = '-';
2148 n_readctl_overlay = a_stdin;
2151 n_pstate_err_no = n_ERR_NONE;
2152 cacp = vp;
2153 cap = cacp->cac_arg;
2155 if(cacp->cac_no == 0 || is_asccaseprefix(cap->ca_arg.ca_str.s, "show"))
2156 goto jshow;
2157 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "set"))
2158 f = a_SET;
2159 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "create"))
2160 f = a_CREATE;
2161 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "remove"))
2162 f = a_REMOVE;
2163 else{
2164 emsg = N_("`readctl': invalid subcommand: %s\n");
2165 goto jeinval_quote;
2168 if(cacp->cac_no == 1){ /* TODO better option parser <> subcommand */
2169 n_err(_("`readctl': %s: requires argument\n"), cap->ca_arg.ca_str.s);
2170 goto jeinval;
2172 cap = cap->ca_next;
2174 /* - is special TODO unfortunately also regarding storage */
2175 if(cap->ca_arg.ca_str.l == 1 && *cap->ca_arg.ca_str.s == '-'){
2176 if(f & (a_CREATE | a_REMOVE)){
2177 n_err(_("`readctl': cannot create nor remove -\n"));
2178 goto jeinval;
2180 n_readctl_overlay = a_stdin;
2181 goto jleave;
2184 /* Try to find a yet existing instance */
2185 if((grcp = n_readctl_overlay) != NULL){
2186 for(; grcp != NULL; grcp = grcp->grc_next)
2187 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2188 goto jfound;
2189 for(grcp = n_readctl_overlay; (grcp = grcp->grc_last) != NULL;)
2190 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2191 goto jfound;
2194 if(f & (a_SET | a_REMOVE)){
2195 emsg = N_("`readctl': no such channel: %s\n");
2196 goto jeinval_quote;
2199 jfound:
2200 if(f & a_SET)
2201 n_readctl_overlay = grcp;
2202 else if(f & a_REMOVE){
2203 if(n_readctl_overlay == grcp)
2204 n_readctl_overlay = a_stdin;
2206 if(grcp->grc_last != NULL)
2207 grcp->grc_last->grc_next = grcp->grc_next;
2208 if(grcp->grc_next != NULL)
2209 grcp->grc_next->grc_last = grcp->grc_last;
2210 fclose(grcp->grc_fp);
2211 n_free(grcp);
2212 }else{
2213 FILE *fp;
2214 size_t elen;
2215 si32_t fd;
2217 if(grcp != NULL){
2218 n_err(_("`readctl': channel already exists: %s\n"), /* TODO reopen */
2219 n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2220 n_pstate_err_no = n_ERR_EXIST;
2221 f = a_ERR;
2222 goto jleave;
2225 if((n_idec_si32_cp(&fd, cap->ca_arg.ca_str.s, 0, NULL
2226 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2227 ) != n_IDEC_STATE_CONSUMED){
2228 if((emsg = fexpand(cap->ca_arg.ca_str.s, FEXP_LOCAL | FEXP_NVAR)
2229 ) == NULL){
2230 emsg = N_("`readctl': cannot expand filename %s\n");
2231 goto jeinval_quote;
2233 fd = -1;
2234 elen = strlen(emsg);
2235 fp = safe_fopen(emsg, "r", NULL);
2236 }else if(fd == STDIN_FILENO || fd == STDOUT_FILENO ||
2237 fd == STDERR_FILENO){
2238 n_err(_("`readctl': create: standard descriptors are not allowed"));
2239 goto jeinval;
2240 }else{
2241 /* xxx Avoid */
2242 _CLOEXEC_SET(fd);
2243 emsg = NULL;
2244 elen = 0;
2245 fp = fdopen(fd, "r");
2248 if(fp != NULL){
2249 size_t i;
2251 if((i = UIZ_MAX - elen) <= cap->ca_arg.ca_str.l ||
2252 (i -= cap->ca_arg.ca_str.l) <=
2253 n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +2){
2254 n_err(_("`readctl': failed to create storage for %s\n"),
2255 cap->ca_arg.ca_str.s);
2256 n_pstate_err_no = n_ERR_OVERFLOW;
2257 f = a_ERR;
2258 goto jleave;
2261 grcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +
2262 cap->ca_arg.ca_str.l +1 + elen +1);
2263 grcp->grc_last = NULL;
2264 if((grcp->grc_next = n_readctl_overlay) != NULL)
2265 grcp->grc_next->grc_last = grcp;
2266 n_readctl_overlay = grcp;
2267 grcp->grc_fp = fp;
2268 grcp->grc_fd = fd;
2269 memcpy(grcp->grc_name, cap->ca_arg.ca_str.s, cap->ca_arg.ca_str.l +1);
2270 if(elen == 0)
2271 grcp->grc_expand = NULL;
2272 else{
2273 char *cp;
2275 grcp->grc_expand = cp = &grcp->grc_name[cap->ca_arg.ca_str.l +1];
2276 memcpy(cp, emsg, ++elen);
2278 }else{
2279 emsg = N_("`readctl': failed to create file for %s\n");
2280 goto jeinval_quote;
2284 jleave:
2285 NYD_LEAVE;
2286 return (f & a_ERR) ? 1 : 0;
2287 jeinval_quote:
2288 n_err(V_(emsg), n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2289 jeinval:
2290 n_pstate_err_no = n_ERR_INVAL;
2291 f = a_ERR;
2292 goto jleave;
2294 jshow:
2295 if((grcp = n_readctl_overlay) == NULL)
2296 fprintf(n_stdout, _("`readctl': no channels registered\n"));
2297 else{
2298 while(grcp->grc_last != NULL)
2299 grcp = grcp->grc_last;
2301 fprintf(n_stdout, _("`readctl': registered channels:\n"));
2302 for(; grcp != NULL; grcp = grcp->grc_next)
2303 fprintf(n_stdout, _("%c%s %s%s%s%s\n"),
2304 (grcp == n_readctl_overlay ? '*' : ' '),
2305 (grcp->grc_fd != -1 ? _("descriptor") : _("name")),
2306 n_shexp_quote_cp(grcp->grc_name, FAL0),
2307 (grcp->grc_expand != NULL ? " (" : n_empty),
2308 (grcp->grc_expand != NULL ? grcp->grc_expand : n_empty),
2309 (grcp->grc_expand != NULL ? ")" : n_empty));
2311 f = a_NONE;
2312 goto jleave;
2315 /* s-it-mode */