make-config.sh: remove superfluous "feat_def NOMEMDBG"
[s-mailx.git] / go.c
blobed174e2e3c1e9d6d40c441a38649ce00089cc2d1
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 a_IGNERR = 1u<<6, /* ignerr modifier prefix */
261 a_LOCAL = 1u<<7, /* TODO local modifier prefix */
262 a_U = 1u<<8, /* TODO UTF-8 modifier prefix */
263 a_VPUT = 1u<<9, /* vput modifier prefix */
264 a_WYSH = 1u<<10, /* XXX v15+ drop wysh modifier prefix */
265 a_MODE_MASK = n_BITENUM_MASK(5, 10),
266 a_NO_ERRNO = 1u<<16 /* Don't set n_pstate_err_no */
267 } flags;
268 NYD_ENTER;
270 if(!(n_pstate & n_PS_ERR_EXIT_MASK))
271 n_exit_status = n_EXIT_OK;
273 flags = a_NONE;
274 rv = 1;
275 nerrn = n_ERR_NONE;
276 nexn = n_EXIT_OK;
277 cdp = NULL;
278 alias_name = NULL;
279 n_UNINIT(alias_exp, NULL);
280 arglist =
281 arglist_base = n_autorec_alloc(sizeof(*arglist_base) * n_MAXARGC);
282 line = gecp->gec_line; /* TODO const-ify original (buffer)! */
283 assert(line.s[line.l] == '\0');
285 if(line.l > 0 && spacechar(line.s[0]))
286 gecp->gec_hist_flags = a_GO_HIST_NONE;
287 else if(gecp->gec_hist_flags & a_GO_HIST_ADD)
288 gecp->gec_hist_cmd = gecp->gec_hist_args = NULL;
289 sp = NULL;
291 /* Aliases that refer to shell commands or macro expansion restart */
292 jrestart:
293 if(n_str_trim_ifs(&line, TRU1)->l == 0){
294 line.s[0] = '\0';
295 gecp->gec_hist_flags = a_GO_HIST_NONE;
296 goto jempty;
298 (cp = line.s)[line.l] = '\0';
300 /* No-expansion modifier? */
301 if(!(flags & a_NOPREFIX) && *cp == '\\'){
302 line.s = ++cp;
303 --line.l;
304 flags |= a_NOALIAS;
307 /* Note: adding more special treatments must be reflected in the `help' etc.
308 * output in cmd-tab.c! */
310 /* Ignore null commands (comments) */
311 if(*cp == '#'){
312 gecp->gec_hist_flags = a_GO_HIST_NONE;
313 goto jret0;
316 /* Handle ! differently to get the correct lexical conventions */
317 if(*cp == '!')
318 ++cp;
319 /* Isolate the actual command; since it may not necessarily be
320 * separated from the arguments (as in `p1') we need to duplicate it to
321 * be able to create a NUL terminated version.
322 * We must be aware of several special one letter commands here */
323 else if((cp = n_UNCONST(n_cmd_isolate(cp))) == line.s &&
324 (*cp == '|' || *cp == '?'))
325 ++cp;
326 c = (int)PTR2SIZE(cp - line.s);
327 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : n_autorec_alloc(c +1);
328 memcpy(word, arglist[0] = line.s, c);
329 word[c] = '\0';
330 line.l -= c;
331 line.s = cp;
333 /* It may be a modifier.
334 * Note: changing modifiers must be reflected in `commandalias' handling
335 * code as well as in the manual (of course)! */
336 switch(c){
337 default:
338 break;
339 case sizeof("ignerr") -1:
340 if(!asccasecmp(word, "ignerr")){
341 flags |= a_NOPREFIX | a_IGNERR;
342 goto jrestart;
344 break;
345 case sizeof("local") -1:
346 if(!asccasecmp(word, "local")){
347 n_err(_("Ignoring yet unused `local' command modifier!"));
348 flags |= a_NOPREFIX | a_LOCAL;
349 goto jrestart;
351 break;
352 case sizeof("u") -1:
353 if(!asccasecmp(word, "u")){
354 n_err(_("Ignoring yet unused `u' command modifier!"));
355 flags |= a_NOPREFIX | a_U;
356 goto jrestart;
358 break;
359 /*case sizeof("vput") -1:*/
360 case sizeof("wysh") -1:
361 if(!asccasecmp(word, "wysh")){
362 flags |= a_NOPREFIX | a_WYSH;
363 goto jrestart;
364 }else if(!asccasecmp(word, "vput")){
365 flags |= a_NOPREFIX | a_VPUT;
366 goto jrestart;
368 break;
371 /* We need to trim for a possible history entry, but do it anyway and insert
372 * a space for argument separation in case of alias expansion. Also, do
373 * terminate again because nothing prevents aliases from introducing WS */
374 n_str_trim_ifs(&line, TRU1);
375 line.s[line.l] = '\0';
377 /* Lengthy history entry setup, possibly even redundant. But having
378 * normalized history entries is a good thing, and this is maybe still
379 * cheaper than parsing a StrList of words per se */
380 if((gecp->gec_hist_flags & (a_GO_HIST_ADD | a_GO_HIST_INIT)
381 ) == a_GO_HIST_ADD){
382 if(line.l > 0){
383 sp = n_string_creat_auto(&s);
384 sp = n_string_assign_buf(sp, line.s, line.l);
385 gecp->gec_hist_args = n_string_cp(sp);
388 sp = n_string_creat_auto(&s);
389 sp = n_string_reserve(sp, 32);
391 if(flags & a_NOALIAS)
392 sp = n_string_push_c(sp, '\\');
393 if(flags & a_IGNERR)
394 sp = n_string_push_buf(sp, "ignerr ", sizeof("ignerr ") -1);
395 if(flags & a_WYSH)
396 sp = n_string_push_buf(sp, "wysh ", sizeof("wysh ") -1);
397 if(flags & a_VPUT)
398 sp = n_string_push_buf(sp, "vput ", sizeof("vput ") -1);
399 gecp->gec_hist_flags = a_GO_HIST_ADD | a_GO_HIST_INIT;
402 /* Look up the command; if not found, bitch.
403 * Normally, a blank command would map to the first command in the
404 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
405 * confusion; act just the same for aliases */
406 if(*word == '\0'){
407 jempty:
408 if((n_pstate & n_PS_ROBOT) || !(n_psonce & n_PSO_INTERACTIVE) ||
409 alias_name != NULL){
410 gecp->gec_hist_flags = a_GO_HIST_NONE;
411 goto jret0;
413 cdp = n_cmd_default();
414 goto jexec;
417 if(!(flags & a_NOALIAS) && (flags & a_ALIAS_MASK) != a_ALIAS_MASK){
418 ui8_t expcnt;
420 expcnt = (flags & a_ALIAS_MASK);
421 ++expcnt;
422 flags = (flags & ~(a_ALIAS_MASK | a_NOPREFIX)) | expcnt;
424 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
425 if(alias_name != NULL && !strcmp(word, alias_name)){
426 if(n_poption & n_PO_D_V)
427 n_err(_("Actively avoiding self-recursion of `commandalias': %s\n"),
428 word);
429 }else if((alias_name = n_commandalias_exists(word, &alias_exp)) != NULL){
430 size_t i;
432 if(sp != NULL){
433 sp = n_string_push_cp(sp, word);
434 gecp->gec_hist_cmd = n_string_cp(sp);
435 sp = NULL;
438 /* And join arguments onto alias expansion */
439 alias_name = word;
440 i = alias_exp->l;
441 cp = line.s;
442 line.s = n_autorec_alloc(i + 1 + line.l +1);
443 memcpy(line.s, alias_exp->s, i);
444 if(line.l > 0){
445 line.s[i++] = ' ';
446 memcpy(&line.s[i], cp, line.l);
448 line.s[i += line.l] = '\0';
449 line.l = i;
450 goto jrestart;
454 if((cdp = n_cmd_firstfit(word)) == NULL){
455 bool_t doskip;
457 if(!(doskip = n_cnd_if_isskip()) || (n_poption & n_PO_D_V))
458 n_err(_("Unknown command%s: `%s'\n"),
459 (doskip ? _(" (ignored due to `if' condition)") : n_empty),
460 prstr(word));
461 gecp->gec_hist_flags = a_GO_HIST_NONE;
462 if(doskip)
463 goto jret0;
464 nerrn = n_ERR_NOSYS;
465 goto jleave;
468 /* See if we should execute the command -- if a conditional we always
469 * execute it, otherwise, check the state of cond */
470 jexec:
471 if(!(cdp->cd_caflags & n_CMD_ARG_F) && n_cnd_if_isskip()){
472 gecp->gec_hist_flags = a_GO_HIST_NONE;
473 goto jret0;
476 if(sp != NULL){
477 sp = n_string_push_cp(sp, cdp->cd_name);
478 gecp->gec_hist_cmd = n_string_cp(sp);
479 sp = NULL;
482 nerrn = n_ERR_INVAL;
484 /* Process the arguments to the command, depending on the type it expects */
485 if((cdp->cd_caflags & n_CMD_ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
486 !(n_poption & n_PO_BATCH_FLAG)){
487 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
488 cdp->cd_name);
489 goto jleave;
491 if(!(cdp->cd_caflags & n_CMD_ARG_M) && (n_psonce & n_PSO_SENDMODE)){
492 n_err(_("May not execute `%s' while sending\n"), cdp->cd_name);
493 goto jleave;
495 if(cdp->cd_caflags & n_CMD_ARG_R){
496 if(n_pstate & n_PS_COMPOSE_MODE){
497 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
498 n_err(_("Cannot invoke `%s' when in compose mode\n"), cdp->cd_name);
499 goto jleave;
501 /* TODO Nothing should prevent n_CMD_ARG_R in conjunction with
502 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
503 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING) && !n_go_may_yield_control()){
504 n_err(_("Cannot invoke `%s' in this program state\n"),
505 cdp->cd_name);
506 goto jleave;
509 if((cdp->cd_caflags & n_CMD_ARG_S) && !(n_psonce & n_PSO_STARTED_CONFIG)){
510 n_err(_("May not execute `%s' during startup\n"), cdp->cd_name);
511 goto jleave;
513 if(!(cdp->cd_caflags & n_CMD_ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
514 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
515 cdp->cd_name);
516 goto jleave;
519 if((cdp->cd_caflags & n_CMD_ARG_A) && mb.mb_type == MB_VOID){
520 n_err(_("Cannot execute `%s' without active mailbox\n"), cdp->cd_name);
521 goto jleave;
523 if((cdp->cd_caflags & n_CMD_ARG_W) && !(mb.mb_perm & MB_DELE)){
524 n_err(_("May not execute `%s' -- message file is read only\n"),
525 cdp->cd_name);
526 goto jleave;
529 if(cdp->cd_caflags & n_CMD_ARG_O)
530 n_OBSOLETE2(_("this command will be removed"), cdp->cd_name);
532 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
533 * TODO doesn't use any of those list commands which strip this mask,
534 * TODO and for now we misuse bits for checking relation to history;
535 * TODO argument state should be property of a per-command carrier instead */
536 n_pstate &= ~n_PS_ARGLIST_MASK;
538 if((flags & a_WYSH) &&
539 (cdp->cd_caflags & n_CMD_ARG_TYPE_MASK) != n_CMD_ARG_TYPE_WYRA){
540 n_err(_("`wysh' command modifier does not affect `%s'\n"), cdp->cd_name);
541 flags &= ~a_WYSH;
544 if(flags & a_VPUT){
545 if(cdp->cd_caflags & n_CMD_ARG_V){
546 char const *emsg;
548 emsg = line.s; /* xxx Cannot pass &char* as char const**, so no cp */
549 arglist[0] = n_shexp_parse_token_cp((n_SHEXP_PARSE_TRIM_SPACE |
550 n_SHEXP_PARSE_TRIM_IFSSPACE | n_SHEXP_PARSE_LOG |
551 n_SHEXP_PARSE_META_SEMICOLON | n_SHEXP_PARSE_META_KEEP), &emsg);
552 line.l -= PTR2SIZE(emsg - line.s);
553 line.s = cp = n_UNCONST(emsg);
554 if(cp == NULL)
555 emsg = N_("could not parse input token");
556 else if(!n_shexp_is_valid_varname(arglist[0]))
557 emsg = N_("not a valid variable name");
558 else if(!n_var_is_user_writable(arglist[0]))
559 emsg = N_("either not a user writable, or a boolean variable");
560 else
561 emsg = NULL;
562 if(emsg != NULL){
563 n_err("`%s': vput: %s: %s\n",
564 cdp->cd_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
565 nerrn = n_ERR_NOTSUP;
566 rv = -1;
567 goto jleave;
569 ++arglist;
570 n_pstate |= n_PS_ARGMOD_VPUT; /* TODO YET useless since stripped later
571 * TODO on in getrawlist() etc., i.e., the argument vector producers,
572 * TODO therefore yet needs to be set again based on flags&a_VPUT! */
573 }else{
574 n_err(_("`vput' prefix does not affect `%s'\n"), cdp->cd_name);
575 flags &= ~a_VPUT;
579 switch(cdp->cd_caflags & n_CMD_ARG_TYPE_MASK){
580 case n_CMD_ARG_TYPE_MSGLIST:
581 /* Message list defaulting to nearest forward legal message */
582 if(n_msgvec == NULL)
583 goto jemsglist;
584 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
585 nerrn = n_ERR_NOMSG;
586 flags |= a_NO_ERRNO;
587 break;
589 if(c == 0){
590 if((n_msgvec[0] = first(cdp->cd_msgflag, cdp->cd_msgmask)) != 0)
591 n_msgvec[1] = 0;
593 if(n_msgvec[0] == 0){
594 jemsglist:
595 if(!(n_pstate & n_PS_HOOK_MASK))
596 fprintf(n_stdout, _("No applicable messages\n"));
597 nerrn = n_ERR_NOMSG;
598 flags |= a_NO_ERRNO;
599 break;
601 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
602 n_err_no = 0;
603 rv = (*cdp->cd_func)(n_msgvec);
604 break;
606 case n_CMD_ARG_TYPE_NDMLIST:
607 /* Message list with no defaults, but no error if none exist */
608 if(n_msgvec == NULL)
609 goto jemsglist;
610 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
611 nerrn = n_ERR_NOMSG;
612 flags |= a_NO_ERRNO;
613 break;
615 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
616 n_err_no = 0;
617 rv = (*cdp->cd_func)(n_msgvec);
618 break;
620 case n_CMD_ARG_TYPE_STRING:
621 /* Just the straight string, old style, with leading blanks removed */
622 for(cp = line.s; spacechar(*cp);)
623 ++cp;
624 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
625 n_err_no = 0;
626 rv = (*cdp->cd_func)(cp);
627 break;
628 case n_CMD_ARG_TYPE_RAWDAT:
629 /* Just the straight string, placed in argv[] */
630 *arglist++ = line.s;
631 *arglist = NULL;
632 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
633 n_err_no = 0;
634 rv = (*cdp->cd_func)(arglist_base);
635 break;
637 case n_CMD_ARG_TYPE_WYSH:
638 c = 1;
639 if(0){
640 /* FALLTHRU */
641 case n_CMD_ARG_TYPE_WYRA:
642 c = (flags & a_WYSH) ? 1 : 0;
643 if(0){
644 case n_CMD_ARG_TYPE_RAWLIST:
645 c = 0;
648 if((c = getrawlist((c != 0), arglist,
649 n_MAXARGC - PTR2SIZE(arglist - arglist_base), line.s, line.l)) < 0){
650 n_err(_("Invalid argument list\n"));
651 flags |= a_NO_ERRNO;
652 break;
655 if(c < cdp->cd_minargs){
656 n_err(_("`%s' requires at least %u arg(s)\n"),
657 cdp->cd_name, (ui32_t)cdp->cd_minargs);
658 flags |= a_NO_ERRNO;
659 break;
661 #undef cd_minargs
662 if(c > cdp->cd_maxargs){
663 n_err(_("`%s' takes no more than %u arg(s)\n"),
664 cdp->cd_name, (ui32_t)cdp->cd_maxargs);
665 flags |= a_NO_ERRNO;
666 break;
668 #undef cd_maxargs
670 if(flags & a_VPUT)
671 n_pstate |= n_PS_ARGMOD_VPUT;
673 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
674 n_err_no = 0;
675 rv = (*cdp->cd_func)(arglist_base);
676 if(a_go_xcall != NULL)
677 goto jret0;
678 break;
680 case n_CMD_ARG_TYPE_ARG:{
681 /* TODO The _ARG_TYPE_ARG is preliminary, in the end we should have a
682 * TODO per command-ctx carrier that also has slots for it arguments,
683 * TODO and that should be passed along all the way. No more arglists
684 * TODO here, etc. */
685 struct n_cmd_arg_ctx cac;
687 cac.cac_desc = cdp->cd_cadp;
688 cac.cac_indat = line.s;
689 cac.cac_inlen = line.l;
690 if(!n_cmd_arg_parse(&cac)){
691 flags |= a_NO_ERRNO;
692 break;
695 if(flags & a_VPUT){
696 cac.cac_vput = *arglist_base;
697 n_pstate |= n_PS_ARGMOD_VPUT;
698 }else
699 cac.cac_vput = NULL;
701 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
702 n_err_no = 0;
703 rv = (*cdp->cd_func)(&cac);
704 if(a_go_xcall != NULL)
705 goto jret0;
706 } break;
708 default:
709 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
710 cdp->cd_caflags & n_CMD_ARG_TYPE_MASK); )
711 nerrn = n_ERR_NOTOBACCO;
712 nexn = 1;
713 goto jret0;
716 if(gecp->gec_hist_flags & a_GO_HIST_ADD){
717 if(cdp->cd_caflags & n_CMD_ARG_H)
718 gecp->gec_hist_flags = a_GO_HIST_NONE;
719 else if((cdp->cd_caflags & n_CMD_ARG_G) ||
720 (n_pstate & n_PS_MSGLIST_GABBY))
721 gecp->gec_hist_flags |= a_GO_HIST_GABBY;
724 if(rv != 0){
725 if(!(flags & a_NO_ERRNO)){
726 if(cdp->cd_caflags & n_CMD_ARG_EM)
727 flags |= a_NO_ERRNO;
728 else if((nerrn = n_err_no) == 0)
729 nerrn = n_ERR_INVAL;
730 }else
731 flags ^= a_NO_ERRNO;
732 }else if(cdp->cd_caflags & n_CMD_ARG_EM)
733 flags |= a_NO_ERRNO;
734 else
735 nerrn = n_ERR_NONE;
736 jleave:
737 nexn = rv;
739 if(flags & a_IGNERR){
740 n_pstate &= ~n_PS_ERR_EXIT_MASK;
741 if(!(n_pstate & n_PS_ERR_EXIT_MASK))
742 n_exit_status = n_EXIT_OK;
743 }else if(rv != 0){
744 bool_t bo;
746 if((bo = ok_blook(batch_exit_on_error))){
747 n_OBSOLETE(_("please use *errexit*, not *batch-exit-on-error*"));
748 if(!(n_poption & n_PO_BATCH_FLAG))
749 bo = FAL0;
751 if(ok_blook(errexit) || bo) /* TODO v15: drop bo */
752 n_pstate |= n_PS_ERR_QUIT;
753 else if(ok_blook(posix)){
754 if(n_psonce & n_PSO_STARTED)
755 rv = 0;
756 else if(!(n_psonce & n_PSO_INTERACTIVE))
757 n_pstate |= n_PS_ERR_XIT;
758 }else
759 rv = 0;
761 if(rv != 0){
762 if(n_exit_status == n_EXIT_OK)
763 n_exit_status = n_EXIT_ERR;
764 if((n_poption & n_PO_D_V) &&
765 !(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)))
766 n_alert(_("Non-interactive, bailing out due to errors "
767 "in startup load phase"));
768 goto jret;
772 if(cdp == NULL)
773 goto jret0;
774 if((cdp->cd_caflags & n_CMD_ARG_P) && ok_blook(autoprint))
775 if(visible(dot))
776 n_go_input_inject(n_GO_INPUT_INJECT_COMMIT, "\\type",
777 sizeof("\\type") -1);
779 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
780 !(cdp->cd_caflags & n_CMD_ARG_T))
781 n_pstate |= n_PS_SAW_COMMAND;
782 jret0:
783 rv = 0;
784 jret:
785 if(!(flags & a_NO_ERRNO))
786 n_pstate_err_no = nerrn;
787 n_pstate_ex_no = nexn;
788 NYD_LEAVE;
789 return (rv == 0);
792 static void
793 a_go_hangup(int s){
794 NYD_X; /* Signal handler */
795 n_UNUSED(s);
796 /* nothing to do? */
797 exit(n_EXIT_ERR);
800 #ifdef HAVE_IMAP
801 FL void n_go_onintr_for_imap(void){a_go_onintr(0);}
802 #endif
803 static void
804 a_go_onintr(int s){ /* TODO block signals while acting */
805 NYD_X; /* Signal handler */
806 n_UNUSED(s);
808 safe_signal(SIGINT, a_go_onintr);
810 termios_state_reset();
812 a_go_cleanup(a_GO_CLEANUP_UNWIND | /* XXX FAKE */a_GO_CLEANUP_HOLDALLSIGS);
814 if(interrupts != 1)
815 n_err_sighdl(_("Interrupt\n"));
816 safe_signal(SIGPIPE, a_go_oldpipe);
817 siglongjmp(a_go_srbuf, 0); /* FIXME get rid */
820 static void
821 a_go_cleanup(enum a_go_cleanup_mode gcm){
822 /* Signals blocked */
823 struct a_go_ctx *gcp;
824 NYD_ENTER;
826 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
827 hold_all_sigs();
828 jrestart:
829 gcp = a_go_ctx;
831 /* Free input injections of this level first */
832 if(!(gcm & a_GO_CLEANUP_LOOPTICK)){
833 struct a_go_input_inject **giipp, *giip;
835 for(giipp = &gcp->gc_inject; (giip = *giipp) != NULL;){
836 *giipp = giip->gii_next;
837 n_free(giip);
841 /* Cleanup non-crucial external stuff */
842 n_COLOUR(
843 if(gcp->gc_data.gdc_colour != NULL)
844 n_colour_stack_del(&gcp->gc_data);
847 /* Work the actual context (according to cleanup mode) */
848 if(gcp->gc_outer == NULL){
849 if(gcm & (a_GO_CLEANUP_UNWIND | a_GO_CLEANUP_SIGINT)){
850 if(a_go_xcall != NULL){
851 n_free(a_go_xcall);
852 a_go_xcall = NULL;
854 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
855 n_pstate &= ~n_PS_ERR_EXIT_MASK;
856 close_all_files();
857 }else{
858 if(!(n_pstate & n_PS_SOURCING))
859 close_all_files();
862 n_memory_reset();
864 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
865 assert(a_go_xcall == NULL);
866 assert(!(gcp->gc_flags & a_GO_XCALL_LOOP_MASK));
867 assert(gcp->gc_on_finalize == NULL);
868 assert(gcp->gc_data.gdc_colour == NULL);
869 goto jxleave;
870 }else if(gcm & a_GO_CLEANUP_LOOPTICK){
871 n_memory_reset();
872 goto jxleave;
873 }else if(gcp->gc_flags & a_GO_SPLICE){ /* TODO Temporary hack */
874 n_stdin = gcp->gc_splice_stdin;
875 n_stdout = gcp->gc_splice_stdout;
876 n_psonce = gcp->gc_splice_psonce;
877 goto jstackpop;
880 /* Cleanup crucial external stuff */
881 if(gcp->gc_data.gdc_ifcond != NULL){
882 n_cnd_if_stack_del(&gcp->gc_data);
883 if(!(gcm & (a_GO_CLEANUP_ERROR | a_GO_CLEANUP_SIGINT)) &&
884 !(gcp->gc_flags & a_GO_FORCE_EOF) && a_go_xcall == NULL &&
885 !(n_psonce & n_PSO_EXIT_MASK)){
886 n_err(_("Unmatched `if' at end of %s %s\n"),
887 ((gcp->gc_flags & a_GO_MACRO
888 ? (gcp->gc_flags & a_GO_MACRO_CMD ? _("command") : _("macro"))
889 : _("`source'd file"))),
890 gcp->gc_name);
891 gcm |= a_GO_CLEANUP_ERROR;
895 /* Teardown context */
896 if(gcp->gc_flags & a_GO_MACRO){
897 if(gcp->gc_flags & a_GO_MACRO_FREE_DATA){
898 char **lp;
900 while(*(lp = &gcp->gc_lines[gcp->gc_loff]) != NULL){
901 n_free(*lp);
902 ++gcp->gc_loff;
904 /* Part of gcp's memory chunk, then */
905 if(!(gcp->gc_flags & a_GO_MACRO_CMD))
906 n_free(gcp->gc_lines);
908 }else if(gcp->gc_flags & a_GO_PIPE)
909 /* XXX command manager should -TERM then -KILL instead of hoping
910 * XXX for exit of provider due to n_ERR_PIPE / SIGPIPE */
911 Pclose(gcp->gc_file, TRU1);
912 else if(gcp->gc_flags & a_GO_FILE)
913 Fclose(gcp->gc_file);
915 if(!(gcp->gc_flags & a_GO_MEMPOOL_INHERITED)){
916 if(gcp->gc_data.gdc_mempool != NULL)
917 n_memory_pool_pop(NULL);
918 }else
919 n_memory_reset();
921 jstackpop:
922 /* Update a_go_ctx and n_go_data, n_pstate ... */
923 a_go_ctx = gcp->gc_outer;
924 assert(a_go_ctx != NULL);
925 /* C99 */{
926 struct a_go_ctx *x;
928 for(x = a_go_ctx; x->gc_flags & a_GO_DATACTX_INHERITED;){
929 x = x->gc_outer;
930 assert(x != NULL);
932 n_go_data = &x->gc_data;
935 if((a_go_ctx->gc_flags & (a_GO_MACRO | a_GO_SUPER_MACRO)) ==
936 (a_GO_MACRO | a_GO_SUPER_MACRO)){
937 n_pstate &= ~n_PS_SOURCING;
938 assert(n_pstate & n_PS_ROBOT);
939 }else if(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK))
940 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
941 else
942 assert(n_pstate & n_PS_ROBOT);
944 if(gcp->gc_on_finalize != NULL)
945 (*gcp->gc_on_finalize)(gcp->gc_finalize_arg);
947 if(gcm & a_GO_CLEANUP_ERROR){
948 if(a_go_ctx->gc_flags & a_GO_XCALL_LOOP)
949 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP_ERROR;
950 goto jerr;
952 jleave:
953 if(gcp->gc_flags & a_GO_FREE)
954 n_free(gcp);
956 if(n_UNLIKELY((gcm & a_GO_CLEANUP_UNWIND) && gcp != a_go_ctx))
957 goto jrestart;
959 jxleave:
960 NYD_LEAVE;
961 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
962 rele_all_sigs();
963 return;
965 jerr:
966 /* With *posix* we follow what POSIX says:
967 * Any errors in the start-up file shall either cause mailx to
968 * terminate with a diagnostic message and a non-zero status or to
969 * continue after writing a diagnostic message, ignoring the
970 * remainder of the lines in the start-up file
971 * Print the diagnostic only for the outermost resource unless the user
972 * is debugging or in verbose mode */
973 if((n_poption & n_PO_D_V) ||
974 (!(n_psonce & n_PSO_STARTED) &&
975 !(gcp->gc_flags & (a_GO_SPLICE | a_GO_MACRO)) &&
976 !(gcp->gc_outer->gc_flags & a_GO_TYPE_MASK)))
977 /* I18N: file inclusion, macro etc. evaluation has been stopped */
978 n_alert(_("Stopped %s %s due to errors%s"),
979 (n_psonce & n_PSO_STARTED
980 ? (gcp->gc_flags & a_GO_SPLICE ? _("spliced in program")
981 : (gcp->gc_flags & a_GO_MACRO
982 ? (gcp->gc_flags & a_GO_MACRO_CMD
983 ? _("evaluating command") : _("evaluating macro"))
984 : (gcp->gc_flags & a_GO_PIPE
985 ? _("executing `source'd pipe")
986 : (gcp->gc_flags & a_GO_FILE
987 ? _("loading `source'd file") : _(a_GO_MAINCTX_NAME))))
989 : (gcp->gc_flags & a_GO_MACRO
990 ? (gcp->gc_flags & a_GO_MACRO_X_OPTION
991 ? _("evaluating command line") : _("evaluating macro"))
992 : _("loading initialization resource"))),
993 n_shexp_quote_cp(gcp->gc_name, FAL0),
994 (n_poption & n_PO_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
995 goto jleave;
998 static bool_t
999 a_go_file(char const *file, bool_t silent_open_error){
1000 struct a_go_ctx *gcp;
1001 sigset_t osigmask;
1002 size_t nlen;
1003 char *nbuf;
1004 bool_t ispipe;
1005 FILE *fip;
1006 NYD_ENTER;
1008 fip = NULL;
1010 /* Being a command argument file is space-trimmed *//* TODO v15 with
1011 * TODO WYRALIST this is no longer necessary true, and for that we
1012 * TODO don't set _PARSE_TRIM_SPACE because we cannot! -> cmd-tab.h!! */
1013 #if 0
1014 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1015 file[--nlen] == '|')))
1016 #else
1017 ispipe = FAL0;
1018 if(!silent_open_error){
1019 for(nlen = strlen(file); nlen > 0;){
1020 char c;
1022 c = file[--nlen];
1023 if(!spacechar(c)){
1024 if(c == '|'){
1025 nbuf = savestrbuf(file, nlen);
1026 ispipe = TRU1;
1028 break;
1032 #endif
1034 if(ispipe){
1035 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1036 ok_vlook(SHELL), NULL, n_CHILD_FD_NULL)) == NULL)
1037 goto jeopencheck;
1038 }else if((nbuf = fexpand(file, FEXP_LOCAL | FEXP_NVAR)) == NULL)
1039 goto jeopencheck;
1040 else if((fip = Fopen(nbuf, "r")) == NULL){
1041 jeopencheck:
1042 if(!silent_open_error || (n_poption & n_PO_D_V))
1043 n_perr(nbuf, 0);
1044 if(silent_open_error)
1045 fip = (FILE*)-1;
1046 goto jleave;
1049 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1051 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1052 (nlen = strlen(nbuf) +1));
1053 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1055 hold_all_sigs();
1057 gcp->gc_outer = a_go_ctx;
1058 gcp->gc_osigmask = osigmask;
1059 gcp->gc_file = fip;
1060 gcp->gc_flags = (ispipe ? a_GO_FREE | a_GO_PIPE : a_GO_FREE | a_GO_FILE) |
1061 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO ? a_GO_SUPER_MACRO : 0);
1062 memcpy(gcp->gc_name, nbuf, nlen);
1064 a_go_ctx = gcp;
1065 n_go_data = &gcp->gc_data;
1066 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1067 if(!a_go_event_loop(gcp, n_GO_INPUT_NONE | n_GO_INPUT_NL_ESC))
1068 fip = NULL;
1069 jleave:
1070 NYD_LEAVE;
1071 return (fip != NULL);
1074 static bool_t
1075 a_go_load(struct a_go_ctx *gcp){
1076 NYD2_ENTER;
1078 assert(!(n_psonce & n_PSO_STARTED));
1079 assert(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK));
1081 gcp->gc_flags |= a_GO_MEMPOOL_INHERITED;
1082 gcp->gc_data.gdc_mempool = n_go_data->gdc_mempool;
1084 hold_all_sigs();
1086 /* POSIX:
1087 * Any errors in the start-up file shall either cause mailx to terminate
1088 * with a diagnostic message and a non-zero status or to continue after
1089 * writing a diagnostic message, ignoring the remainder of the lines in
1090 * the start-up file. */
1091 gcp->gc_outer = a_go_ctx;
1092 a_go_ctx = gcp;
1093 n_go_data = &gcp->gc_data;
1094 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1095 n_pstate |= n_PS_ROBOT |
1096 (gcp->gc_flags & a_GO_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1098 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1100 rele_all_sigs();
1102 n_go_main_loop();
1103 NYD2_LEAVE;
1104 return (((n_psonce & n_PSO_EXIT_MASK) |
1105 (n_pstate & n_PS_ERR_EXIT_MASK)) == 0);
1108 static void
1109 a_go__eloopint(int sig){ /* TODO one day, we don't need it no more */
1110 NYD_X; /* Signal handler */
1111 n_UNUSED(sig);
1112 siglongjmp(a_go_ctx->gc_eloop_jmp, 1);
1115 static bool_t
1116 a_go_event_loop(struct a_go_ctx *gcp, enum n_go_input_flags gif){
1117 sighandler_type soldhdl;
1118 struct a_go_eval_ctx gec;
1119 enum {a_RETOK = TRU1, a_TICKED = 1<<1} volatile f;
1120 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1121 sigset_t osigmask;
1122 NYD2_ENTER;
1124 memset(&gec, 0, sizeof gec);
1125 osigmask = gcp->gc_osigmask;
1126 hadint = FAL0;
1127 f = a_RETOK;
1129 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1130 safe_signal(SIGINT, &a_go__eloopint);
1131 if(sigsetjmp(gcp->gc_eloop_jmp, 1)){
1132 hold_all_sigs();
1133 hadint = TRU1;
1134 f &= ~a_RETOK;
1135 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1136 goto jjump;
1140 for(;; f |= a_TICKED){
1141 int n;
1143 if(f & a_TICKED)
1144 n_memory_reset();
1146 /* Read a line of commands and handle end of file specially */
1147 gec.gec_line.l = gec.gec_line_size;
1148 rele_all_sigs();
1149 n = n_go_input(gif, NULL, &gec.gec_line.s, &gec.gec_line.l, NULL, NULL);
1150 hold_all_sigs();
1151 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1152 gec.gec_line.l = (ui32_t)n;
1154 if(n < 0)
1155 break;
1157 rele_all_sigs();
1158 assert(gec.gec_hist_flags == a_GO_HIST_NONE);
1159 if(!a_go_evaluate(&gec))
1160 f &= ~a_RETOK;
1161 hold_all_sigs();
1163 if(!(f & a_RETOK) || a_go_xcall != NULL ||
1164 (n_psonce & n_PSO_EXIT_MASK) || (n_pstate & n_PS_ERR_EXIT_MASK))
1165 break;
1168 jjump: /* TODO Should be _CLEANUP_UNWIND not _TEARDOWN on signal if DOABLE! */
1169 a_go_cleanup(a_GO_CLEANUP_TEARDOWN |
1170 (f & a_RETOK ? 0 : a_GO_CLEANUP_ERROR) |
1171 (hadint ? a_GO_CLEANUP_SIGINT : 0) | a_GO_CLEANUP_HOLDALLSIGS);
1173 if(gec.gec_line.s != NULL)
1174 n_free(gec.gec_line.s);
1176 if(soldhdl != SIG_IGN)
1177 safe_signal(SIGINT, soldhdl);
1178 NYD2_LEAVE;
1179 rele_all_sigs();
1180 if(hadint){
1181 sigprocmask(SIG_SETMASK, &osigmask, NULL);
1182 n_raise(SIGINT);
1184 return (f & a_RETOK);
1187 FL void
1188 n_go_init(void){
1189 struct a_go_ctx *gcp;
1190 NYD2_ENTER;
1192 assert(n_stdin != NULL);
1194 gcp = (void*)a_go__mainctx_b.uf;
1195 DBGOR( memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name)),
1196 memset(&gcp->gc_data, 0, sizeof gcp->gc_data) );
1197 gcp->gc_file = n_stdin;
1198 memcpy(gcp->gc_name, a_GO_MAINCTX_NAME, sizeof(a_GO_MAINCTX_NAME));
1199 a_go_ctx = gcp;
1200 n_go_data = &gcp->gc_data;
1202 n_child_manager_start();
1203 NYD2_LEAVE;
1206 FL bool_t
1207 n_go_main_loop(void){ /* FIXME */
1208 struct a_go_eval_ctx gec;
1209 int n, eofcnt;
1210 bool_t volatile rv;
1211 NYD_ENTER;
1213 rv = TRU1;
1215 if (!(n_pstate & n_PS_SOURCING)) {
1216 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1217 safe_signal(SIGINT, &a_go_onintr);
1218 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1219 safe_signal(SIGHUP, &a_go_hangup);
1221 a_go_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1222 safe_signal(SIGPIPE, a_go_oldpipe);
1224 memset(&gec, 0, sizeof gec);
1226 (void)sigsetjmp(a_go_srbuf, 1); /* FIXME get rid */
1227 hold_all_sigs();
1229 for (eofcnt = 0;; gec.gec_ever_seen = TRU1) {
1230 interrupts = 0;
1232 if(gec.gec_ever_seen)
1233 a_go_cleanup(a_GO_CLEANUP_LOOPTICK | a_GO_CLEANUP_HOLDALLSIGS);
1235 if (!(n_pstate & n_PS_SOURCING)) {
1236 char *cp;
1238 /* TODO Note: this buffer may contain a password. We should redefine
1239 * TODO the code flow which has to do that */
1240 if ((cp = termios_state.ts_linebuf) != NULL) {
1241 termios_state.ts_linebuf = NULL;
1242 termios_state.ts_linesize = 0;
1243 n_free(cp); /* TODO pool give-back */
1245 if (gec.gec_line.l > LINESIZE * 3) {
1246 n_free(gec.gec_line.s);
1247 gec.gec_line.s = NULL;
1248 gec.gec_line.l = gec.gec_line_size = 0;
1252 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1253 char *cp;
1255 if ((cp = ok_vlook(newmail)) != NULL) { /* TODO bla */
1256 struct stat st;
1258 if(mb.mb_type == MB_FILE){
1259 if(!stat(mailname, &st) && st.st_size > mailsize) Jnewmail:{
1260 ui32_t odid;
1261 size_t odot;
1263 odot = PTR2SIZE(dot - message);
1264 odid = (n_pstate & n_PS_DID_PRINT_DOT);
1266 rele_all_sigs();
1267 n = setfile(mailname,
1268 (FEDIT_NEWMAIL |
1269 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)));
1270 hold_all_sigs();
1272 if(n < 0) {
1273 n_exit_status |= n_EXIT_ERR;
1274 rv = FAL0;
1275 break;
1277 #ifdef HAVE_IMAP
1278 if(mb.mb_type != MB_IMAP){
1279 #endif
1280 dot = &message[odot];
1281 n_pstate |= odid;
1282 #ifdef HAVE_IMAP
1284 #endif
1286 }else{
1287 n = (cp != NULL && strcmp(cp, "nopoll"));
1289 if(mb.mb_type == MB_MAILDIR){
1290 if(n != 0)
1291 goto Jnewmail;
1293 #ifdef HAVE_IMAP
1294 else if(mb.mb_type == MB_IMAP){
1295 if(!n)
1296 n = (cp != NULL && strcmp(cp, "noimap"));
1298 if(imap_newmail(n) > (cp == NULL))
1299 goto Jnewmail;
1301 #endif
1306 /* Read a line of commands and handle end of file specially */
1307 gec.gec_line.l = gec.gec_line_size;
1308 /* C99 */{
1309 bool_t histadd;
1311 histadd = (!(n_pstate & n_PS_SOURCING) &&
1312 (n_psonce & n_PSO_INTERACTIVE));
1313 rele_all_sigs();
1314 n = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, NULL,
1315 &gec.gec_line.s, &gec.gec_line.l, NULL, &histadd);
1316 hold_all_sigs();
1318 gec.gec_hist_flags = histadd ? a_GO_HIST_ADD : a_GO_HIST_NONE;
1320 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1321 gec.gec_line.l = (ui32_t)n;
1323 if (n < 0) {
1324 if (!(n_pstate & n_PS_ROBOT) &&
1325 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1326 ++eofcnt < 4) {
1327 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1328 n_go_input_clearerr();
1329 continue;
1331 break;
1334 n_pstate &= ~n_PS_HOOK_MASK;
1335 rele_all_sigs();
1336 rv = a_go_evaluate(&gec);
1337 hold_all_sigs();
1339 if(gec.gec_hist_flags & a_GO_HIST_ADD){
1340 char const *cc, *ca;
1342 cc = gec.gec_hist_cmd;
1343 ca = gec.gec_hist_args;
1344 if(cc != NULL && ca != NULL)
1345 cc = savecatsep(cc, ' ', ca);
1346 else if(ca != NULL)
1347 cc = ca;
1348 assert(cc != NULL);
1349 n_tty_addhist(cc, ((gec.gec_hist_flags & a_GO_HIST_GABBY) != 0));
1352 switch(n_pstate & n_PS_ERR_EXIT_MASK){
1353 case n_PS_ERR_XIT: n_psonce |= n_PSO_XIT; break;
1354 case n_PS_ERR_QUIT: n_psonce |= n_PSO_QUIT; break;
1355 default: break;
1357 if(n_psonce & n_PSO_EXIT_MASK)
1358 break;
1360 if(!rv)
1361 break;
1364 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS |
1365 (rv ? 0 : a_GO_CLEANUP_ERROR));
1367 if (gec.gec_line.s != NULL)
1368 n_free(gec.gec_line.s);
1370 rele_all_sigs();
1371 NYD_LEAVE;
1372 return rv;
1375 FL void
1376 n_go_input_clearerr(void){
1377 FILE *fp;
1378 NYD2_ENTER;
1380 fp = NULL;
1382 if(!(a_go_ctx->gc_flags & (a_GO_FORCE_EOF |
1383 a_GO_PIPE | a_GO_MACRO | a_GO_SPLICE)))
1384 fp = a_go_ctx->gc_file;
1386 if(fp != NULL){
1387 a_go_ctx->gc_flags &= ~a_GO_IS_EOF;
1388 clearerr(fp);
1390 NYD2_LEAVE;
1393 FL void
1394 n_go_input_force_eof(void){
1395 NYD2_ENTER;
1396 a_go_ctx->gc_flags |= a_GO_FORCE_EOF;
1397 NYD2_LEAVE;
1400 FL bool_t
1401 n_go_input_is_eof(void){
1402 bool_t rv;
1403 NYD2_ENTER;
1405 rv = ((a_go_ctx->gc_flags & a_GO_IS_EOF) != 0);
1406 NYD2_LEAVE;
1407 return rv;
1410 FL void
1411 n_go_input_inject(enum n_go_input_inject_flags giif, char const *buf,
1412 size_t len){
1413 NYD_ENTER;
1414 if(len == UIZ_MAX)
1415 len = strlen(buf);
1417 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat) -1 > len &&
1418 len > 0){
1419 struct a_go_input_inject *giip, **giipp;
1421 hold_all_sigs();
1423 giip = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat
1424 ) + 1 + len +1);
1425 giipp = &a_go_ctx->gc_inject;
1426 giip->gii_next = *giipp;
1427 giip->gii_commit = ((giif & n_GO_INPUT_INJECT_COMMIT) != 0);
1428 giip->gii_no_history = ((giif & n_GO_INPUT_INJECT_HISTORY) == 0);
1429 memcpy(&giip->gii_dat[0], buf, len);
1430 giip->gii_dat[giip->gii_len = len] = '\0';
1431 *giipp = giip;
1433 rele_all_sigs();
1435 NYD_LEAVE;
1438 FL int
1439 (n_go_input)(enum n_go_input_flags gif, char const *prompt, char **linebuf,
1440 size_t *linesize, char const *string, bool_t *histok_or_null
1441 n_MEMORY_DEBUG_ARGS){
1442 /* TODO readline: linebuf pool!; n_go_input should return si64_t */
1443 struct n_string xprompt;
1444 FILE *ifile;
1445 bool_t doprompt, dotty;
1446 char const *iftype;
1447 struct a_go_input_inject *giip;
1448 int nold, n;
1449 bool_t histok;
1450 NYD2_ENTER;
1452 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1453 hold_all_sigs();
1455 histok = FAL0;
1457 if(a_go_ctx->gc_flags & a_GO_FORCE_EOF){
1458 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1459 n = -1;
1460 goto jleave;
1463 if(gif & n_GO_INPUT_FORCE_STDIN)
1464 goto jforce_stdin;
1466 /* Special case macro mode: never need to prompt, lines have always been
1467 * unfolded already */
1468 if(a_go_ctx->gc_flags & a_GO_MACRO){
1469 if(*linebuf != NULL)
1470 n_free(*linebuf);
1472 /* Injection in progress? Don't care about the autocommit state here */
1473 if((giip = a_go_ctx->gc_inject) != NULL){
1474 a_go_ctx->gc_inject = giip->gii_next;
1476 /* Simply "reuse" allocation, copy string to front of it */
1477 jinject:
1478 *linesize = giip->gii_len;
1479 *linebuf = (char*)giip;
1480 memmove(*linebuf, giip->gii_dat, giip->gii_len +1);
1481 iftype = "INJECTION";
1482 }else{
1483 if((*linebuf = a_go_ctx->gc_lines[a_go_ctx->gc_loff]) == NULL){
1484 *linesize = 0;
1485 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1486 n = -1;
1487 goto jleave;
1490 ++a_go_ctx->gc_loff;
1491 *linesize = strlen(*linebuf);
1492 if(!(a_go_ctx->gc_flags & a_GO_MACRO_FREE_DATA))
1493 *linebuf = sbufdup(*linebuf, *linesize);
1495 iftype = (a_go_ctx->gc_flags & a_GO_MACRO_X_OPTION)
1496 ? "-X OPTION"
1497 : (a_go_ctx->gc_flags & a_GO_MACRO_CMD) ? "CMD" : "MACRO";
1499 n = (int)*linesize;
1500 n_pstate |= n_PS_READLINE_NL;
1501 goto jhave_dat;
1502 }else{
1503 /* Injection in progress? */
1504 struct a_go_input_inject **giipp;
1506 giipp = &a_go_ctx->gc_inject;
1508 if((giip = *giipp) != NULL){
1509 *giipp = giip->gii_next;
1511 if(giip->gii_commit){
1512 if(*linebuf != NULL)
1513 n_free(*linebuf);
1514 histok = !giip->gii_no_history;
1515 goto jinject; /* (above) */
1516 }else{
1517 string = savestrbuf(giip->gii_dat, giip->gii_len);
1518 n_free(giip);
1523 jforce_stdin:
1524 n_pstate &= ~n_PS_READLINE_NL;
1525 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1526 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1527 histok = (n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1528 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT);
1529 doprompt = !(gif & n_GO_INPUT_FORCE_STDIN) && histok;
1530 dotty = (doprompt && !ok_blook(line_editor_disable));
1531 if(!doprompt)
1532 gif |= n_GO_INPUT_PROMPT_NONE;
1533 else{
1534 if(!dotty)
1535 n_string_creat_auto(&xprompt);
1536 if(prompt == NULL)
1537 gif |= n_GO_INPUT_PROMPT_EVAL;
1540 /* Ensure stdout is flushed first anyway (partial lines, maybe?) */
1541 if(!dotty && (gif & n_GO_INPUT_PROMPT_NONE))
1542 fflush(n_stdout);
1544 if(gif & n_GO_INPUT_FORCE_STDIN){
1545 struct a_go_readctl_ctx *grcp;
1547 grcp = n_readctl_overlay;
1548 ifile = (grcp == NULL || grcp->grc_fp == NULL) ? n_stdin : grcp->grc_fp;
1549 }else
1550 ifile = a_go_ctx->gc_file;
1551 if(ifile == NULL){
1552 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1553 (a_go_ctx->gc_flags & a_GO_MACRO));
1554 ifile = n_stdin;
1557 for(nold = n = 0;;){
1558 if(dotty){
1559 assert(ifile == n_stdin);
1560 if(string != NULL && (n = (int)strlen(string)) > 0){
1561 if(*linesize > 0)
1562 *linesize += n +1;
1563 else
1564 *linesize = (size_t)n + LINESIZE +1;
1565 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1566 memcpy(*linebuf, string, (size_t)n +1);
1568 string = NULL;
1570 rele_all_sigs();
1572 n = (n_tty_readline)(gif, prompt, linebuf, linesize, n, histok_or_null
1573 n_MEMORY_DEBUG_ARGSCALL);
1575 hold_all_sigs();
1577 if(n < 0 && !ferror(ifile)) /* EOF never i guess */
1578 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1579 }else{
1580 if(!(gif & n_GO_INPUT_PROMPT_NONE))
1581 n_tty_create_prompt(&xprompt, prompt, gif);
1583 rele_all_sigs();
1585 if(!(gif & n_GO_INPUT_PROMPT_NONE) && xprompt.s_len > 0){
1586 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1587 fflush(n_stdout);
1590 n = (readline_restart)(ifile, linebuf, linesize, n
1591 n_MEMORY_DEBUG_ARGSCALL);
1593 hold_all_sigs();
1595 if(n < 0 && !ferror(ifile))
1596 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1598 if(n > 0 && nold > 0){
1599 char const *cp;
1600 int i;
1602 i = 0;
1603 cp = &(*linebuf)[nold];
1604 while(spacechar(*cp) && n - i >= nold)
1605 ++cp, ++i;
1606 if(i > 0){
1607 memmove(&(*linebuf)[nold], cp, n - nold - i);
1608 n -= i;
1609 (*linebuf)[n] = '\0';
1614 if(n <= 0)
1615 break;
1617 /* POSIX says:
1618 * An unquoted <backslash> at the end of a command line shall
1619 * be discarded and the next line shall continue the command */
1620 if(!(gif & n_GO_INPUT_NL_ESC) || (*linebuf)[n - 1] != '\\')
1621 break;
1623 /* Definitely outside of quotes, thus the quoting rules are so that an
1624 * uneven number of successive reverse solidus at EOL is a continuation */
1625 if(n > 1){
1626 size_t i, j;
1628 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1629 if((*linebuf)[i] != '\\')
1630 break;
1631 if(!(j & 1))
1632 break;
1634 (*linebuf)[nold = --n] = '\0';
1635 gif |= n_GO_INPUT_NL_FOLLOW;
1638 if(n < 0)
1639 goto jleave;
1640 if(dotty)
1641 n_pstate |= n_PS_READLINE_NL;
1642 (*linebuf)[*linesize = n] = '\0';
1644 jhave_dat:
1645 if(n_poption & n_PO_D_VV)
1646 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1647 jleave:
1648 if (n_pstate & n_PS_PSTATE_PENDMASK)
1649 a_go_update_pstate();
1651 /* TODO We need to special case a_GO_SPLICE, since that is not managed by us
1652 * TODO but only established from the outside and we need to drop this
1653 * TODO overlay context somehow */
1654 if(n < 0 && (a_go_ctx->gc_flags & a_GO_SPLICE))
1655 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS);
1657 if(histok_or_null != NULL && !histok)
1658 *histok_or_null = FAL0;
1660 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1661 rele_all_sigs();
1662 NYD2_LEAVE;
1663 return n;
1666 FL char *
1667 n_go_input_cp(enum n_go_input_flags gif, char const *prompt,
1668 char const *string){
1669 struct n_sigman sm;
1670 bool_t histadd;
1671 size_t linesize;
1672 char *linebuf, * volatile rv;
1673 int n;
1674 NYD2_ENTER;
1676 linesize = 0;
1677 linebuf = NULL;
1678 rv = NULL;
1680 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL){
1681 case 0:
1682 break;
1683 default:
1684 goto jleave;
1687 histadd = TRU1;
1688 n = n_go_input(gif, prompt, &linebuf, &linesize, string, &histadd);
1689 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1690 (gif & n_GO_INPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE) &&
1691 histadd)
1692 n_tty_addhist(rv, ((gif & n_GO_INPUT_HIST_GABBY) != 0));
1694 n_sigman_cleanup_ping(&sm);
1695 jleave:
1696 if(linebuf != NULL)
1697 n_free(linebuf);
1698 NYD2_LEAVE;
1699 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
1700 return rv;
1703 FL bool_t
1704 n_go_load(char const *name){
1705 struct a_go_ctx *gcp;
1706 size_t i;
1707 FILE *fip;
1708 bool_t rv;
1709 NYD_ENTER;
1711 rv = TRU1;
1713 if(name == NULL || *name == '\0')
1714 goto jleave;
1715 else if((fip = Fopen(name, "r")) == NULL){
1716 if(n_poption & n_PO_D_V)
1717 n_err(_("No such file to load: %s\n"), n_shexp_quote_cp(name, FAL0));
1718 goto jleave;
1721 i = strlen(name) +1;
1722 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + i);
1723 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1725 gcp->gc_file = fip;
1726 gcp->gc_flags = a_GO_FREE | a_GO_FILE;
1727 memcpy(gcp->gc_name, name, i);
1729 if(n_poption & n_PO_D_V)
1730 n_err(_("Loading %s\n"), n_shexp_quote_cp(gcp->gc_name, FAL0));
1731 rv = a_go_load(gcp);
1732 jleave:
1733 NYD_LEAVE;
1734 return rv;
1737 FL bool_t
1738 n_go_Xargs(char const **lines, size_t cnt){
1739 static char const name[] = "-X";
1741 union{
1742 bool_t rv;
1743 ui64_t align;
1744 char uf[n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + sizeof(name)];
1745 } b;
1746 char const *srcp, *xsrcp;
1747 char *cp;
1748 size_t imax, i, len;
1749 struct a_go_ctx *gcp;
1750 NYD_ENTER;
1752 gcp = (void*)b.uf;
1753 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1755 gcp->gc_flags = a_GO_MACRO | a_GO_MACRO_X_OPTION |
1756 a_GO_SUPER_MACRO | a_GO_MACRO_FREE_DATA;
1757 memcpy(gcp->gc_name, name, sizeof name);
1759 /* The problem being that we want to support reverse solidus newline
1760 * escaping also within multiline -X, i.e., POSIX says:
1761 * An unquoted <backslash> at the end of a command line shall
1762 * be discarded and the next line shall continue the command
1763 * Therefore instead of "gcp->gc_lines = n_UNCONST(lines)", duplicate the
1764 * entire lines array and set _MACRO_FREE_DATA */
1765 imax = cnt + 1;
1766 gcp->gc_lines = n_alloc(sizeof(*gcp->gc_lines) * imax);
1768 /* For each of the input lines.. */
1769 for(i = len = 0, cp = NULL; cnt > 0;){
1770 bool_t keep;
1771 size_t j;
1773 if((j = strlen(srcp = *lines)) == 0){
1774 ++lines, --cnt;
1775 continue;
1778 /* Separate one line from a possible multiline input string */
1779 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1780 *lines = &xsrcp[1];
1781 j = PTR2SIZE(xsrcp - srcp);
1782 }else
1783 ++lines, --cnt;
1785 /* The (separated) string may itself indicate soft newline escaping */
1786 if((keep = (srcp[j - 1] == '\\'))){
1787 size_t xj, xk;
1789 /* Need an uneven number of reverse solidus */
1790 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1791 if(srcp[xj] != '\\')
1792 break;
1793 if(xk & 1)
1794 --j;
1795 else
1796 keep = FAL0;
1799 /* Strip any leading WS from follow lines, then */
1800 if(cp != NULL)
1801 while(j > 0 && spacechar(*srcp))
1802 ++srcp, --j;
1804 if(j > 0){
1805 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1806 imax += 4;
1807 gcp->gc_lines = n_realloc(gcp->gc_lines, sizeof(*gcp->gc_lines) *
1808 imax);
1810 gcp->gc_lines[i] = cp = n_realloc(cp, len + j +1);
1811 memcpy(&cp[len], srcp, j);
1812 cp[len += j] = '\0';
1814 if(!keep)
1815 ++i;
1817 if(!keep)
1818 cp = NULL, len = 0;
1820 if(cp != NULL){
1821 assert(i + 1 < imax);
1822 gcp->gc_lines[i++] = cp;
1824 gcp->gc_lines[i] = NULL;
1826 b.rv = a_go_load(gcp);
1827 NYD_LEAVE;
1828 return b.rv;
1831 FL int
1832 c_source(void *v){
1833 int rv;
1834 NYD_ENTER;
1836 rv = (a_go_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1837 NYD_LEAVE;
1838 return rv;
1841 FL int
1842 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1843 int rv;
1844 NYD_ENTER;
1846 rv = (a_go_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
1847 NYD_LEAVE;
1848 return rv;
1851 FL bool_t
1852 n_go_macro(enum n_go_input_flags gif, char const *name, char **lines,
1853 void (*on_finalize)(void*), void *finalize_arg){
1854 struct a_go_ctx *gcp;
1855 size_t i;
1856 int rv;
1857 sigset_t osigmask;
1858 NYD_ENTER;
1860 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1862 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1863 (i = strlen(name) +1));
1864 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1866 hold_all_sigs();
1868 gcp->gc_outer = a_go_ctx;
1869 gcp->gc_osigmask = osigmask;
1870 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_FREE_DATA |
1871 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1872 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0) |
1873 ((gif & n_GO_INPUT_NO_XCALL) ? a_GO_XCALL_IS_CALL : 0);
1874 gcp->gc_lines = lines;
1875 gcp->gc_on_finalize = on_finalize;
1876 gcp->gc_finalize_arg = finalize_arg;
1877 memcpy(gcp->gc_name, name, i);
1879 a_go_ctx = gcp;
1880 n_go_data = &gcp->gc_data;
1881 n_pstate |= n_PS_ROBOT;
1882 rv = a_go_event_loop(gcp, gif);
1884 /* Shall this enter a `xcall' stack avoidance optimization (loop)? */
1885 if(a_go_xcall != NULL){
1886 void *vp;
1887 struct n_cmd_arg_ctx *cacp;
1889 if(a_go_xcall == (void*)-1)
1890 a_go_xcall = NULL;
1891 else if(((void const*)(cacp = a_go_xcall)->cac_indat) == gcp){
1892 /* Indicate that "our" (ex-) parent now hosts xcall optimization */
1893 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP;
1894 while(a_go_xcall != NULL){
1895 hold_all_sigs();
1897 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_ERROR;
1899 vp = a_go_xcall;
1900 a_go_xcall = NULL;
1901 cacp = n_cmd_arg_restore_from_heap(vp);
1902 n_free(vp);
1904 rele_all_sigs();
1906 (void)c_call(cacp);
1908 rv = ((a_go_ctx->gc_flags & a_GO_XCALL_LOOP_ERROR) == 0);
1909 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1912 NYD_LEAVE;
1913 return rv;
1916 FL bool_t
1917 n_go_command(enum n_go_input_flags gif, char const *cmd){
1918 struct a_go_ctx *gcp;
1919 bool_t rv;
1920 size_t i, ial;
1921 sigset_t osigmask;
1922 NYD_ENTER;
1924 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1926 i = strlen(cmd) +1;
1927 ial = n_ALIGN(i);
1928 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1929 ial + 2*sizeof(char*));
1930 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1932 hold_all_sigs();
1934 gcp->gc_outer = a_go_ctx;
1935 gcp->gc_osigmask = osigmask;
1936 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_CMD |
1937 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1938 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0);
1939 gcp->gc_lines = (void*)&gcp->gc_name[ial];
1940 memcpy(gcp->gc_lines[0] = &gcp->gc_name[0], cmd, i);
1941 gcp->gc_lines[1] = NULL;
1943 a_go_ctx = gcp;
1944 n_go_data = &gcp->gc_data;
1945 n_pstate |= n_PS_ROBOT;
1946 rv = a_go_event_loop(gcp, gif);
1947 NYD_LEAVE;
1948 return rv;
1951 FL void
1952 n_go_splice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
1953 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
1954 struct a_go_ctx *gcp;
1955 size_t i;
1956 sigset_t osigmask;
1957 NYD_ENTER;
1959 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1961 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1962 (i = strlen(cmd) +1));
1963 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1965 hold_all_sigs();
1967 gcp->gc_outer = a_go_ctx;
1968 gcp->gc_osigmask = osigmask;
1969 gcp->gc_file = new_stdin;
1970 gcp->gc_flags = a_GO_FREE | a_GO_SPLICE | a_GO_DATACTX_INHERITED;
1971 gcp->gc_on_finalize = on_finalize;
1972 gcp->gc_finalize_arg = finalize_arg;
1973 gcp->gc_splice_stdin = n_stdin;
1974 gcp->gc_splice_stdout = n_stdout;
1975 gcp->gc_splice_psonce = n_psonce;
1976 memcpy(gcp->gc_name, cmd, i);
1978 n_stdin = new_stdin;
1979 n_stdout = new_stdout;
1980 n_psonce = new_psonce;
1981 a_go_ctx = gcp;
1982 /* Do NOT touch n_go_data! */
1983 n_pstate |= n_PS_ROBOT;
1985 rele_all_sigs();
1986 NYD_LEAVE;
1989 FL void
1990 n_go_splice_hack_remove_after_jump(void){
1991 a_go_cleanup(a_GO_CLEANUP_TEARDOWN);
1994 FL bool_t
1995 n_go_may_yield_control(void){ /* TODO this is a terrible hack */
1996 struct a_go_ctx *gcp;
1997 bool_t rv;
1998 NYD2_ENTER;
2000 rv = FAL0;
2002 /* Only when startup completed */
2003 if(!(n_psonce & n_PSO_STARTED))
2004 goto jleave;
2005 /* Only interactive or batch mode (assuming that is ok) */
2006 if(!(n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_BATCH_FLAG))
2007 goto jleave;
2009 /* Not when running any hook */
2010 if(n_pstate & n_PS_HOOK_MASK)
2011 goto jleave;
2013 /* Traverse up the stack:
2014 * . not when controlled by a child process
2015 * TODO . not when there are pipes involved, we neither handle job control,
2016 * TODO nor process groups, that is, controlling terminal acceptably
2017 * . not when sourcing a file */
2018 for(gcp = a_go_ctx; gcp != NULL; gcp = gcp->gc_outer){
2019 if(gcp->gc_flags & (a_GO_PIPE | a_GO_FILE | a_GO_SPLICE))
2020 goto jleave;
2023 rv = TRU1;
2024 jleave:
2025 NYD2_LEAVE;
2026 return rv;
2029 FL int
2030 c_eval(void *vp){
2031 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
2032 * TODO ARGV with shell rules, but if that is not possible then simply
2033 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
2034 struct a_go_eval_ctx gec;
2035 struct n_string s_b, *sp;
2036 size_t i, j;
2037 char const **argv, *cp;
2038 NYD_ENTER;
2040 argv = vp;
2042 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
2043 j += strlen(cp);
2045 sp = n_string_creat_auto(&s_b);
2046 sp = n_string_reserve(sp, j);
2048 for(i = 0; (cp = argv[i]) != NULL; ++i){
2049 if(i > 0)
2050 sp = n_string_push_c(sp, ' ');
2051 sp = n_string_push_cp(sp, cp);
2054 memset(&gec, 0, sizeof gec);
2055 gec.gec_line.s = n_string_cp(sp);
2056 gec.gec_line.l = sp->s_len;
2057 if(n_poption & n_PO_D_VV)
2058 n_err(_("EVAL %" PRIuZ " bytes <%s>\n"), gec.gec_line.l, gec.gec_line.s);
2059 (void)/* XXX */a_go_evaluate(&gec);
2060 NYD_LEAVE;
2061 return (a_go_xcall != NULL ? 0 : n_pstate_ex_no);
2064 FL int
2065 c_xcall(void *vp){
2066 int rv;
2067 struct a_go_ctx *gcp;
2068 NYD2_ENTER;
2070 /* The context can only be a macro context, except that possibly a single
2071 * level of `eval' (TODO: yet) was used to double-expand our arguments */
2072 if((gcp = a_go_ctx)->gc_flags & a_GO_MACRO_CMD)
2073 gcp = gcp->gc_outer;
2074 if((gcp->gc_flags & (a_GO_MACRO | a_GO_MACRO_X_OPTION | a_GO_MACRO_CMD)
2075 ) != a_GO_MACRO){
2076 if(n_poption & n_PO_D_V_VV)
2077 n_err(_("`xcall': can only be used inside a macro, using `call'\n"));
2078 rv = c_call(vp);
2079 goto jleave;
2082 /* Try to roll up the stack as much as possible.
2083 * See a_GO_XCALL_LOOP flag description for more */
2084 if(!(gcp->gc_flags & a_GO_XCALL_IS_CALL) && gcp->gc_outer != NULL){
2085 if(gcp->gc_outer->gc_flags & a_GO_XCALL_LOOP)
2086 gcp = gcp->gc_outer;
2087 }else{
2088 /* Otherwise this macro is "invoked from the top level", in which case we
2089 * silently act as if we were `call'... */
2090 rv = c_call(vp);
2091 /* ...which means we must ensure the rest of the macro that was us
2092 * doesn't become evaluated! */
2093 a_go_xcall = (void*)-1;
2094 goto jleave;
2097 /* C99 */{
2098 struct n_cmd_arg_ctx *cacp;
2100 cacp = n_cmd_arg_save_to_heap(vp);
2101 cacp->cac_indat = (char*)gcp;
2102 a_go_xcall = cacp;
2104 rv = 0;
2105 jleave:
2106 NYD2_LEAVE;
2107 return rv;
2110 FL int
2111 c_exit(void *vp){
2112 char const **argv;
2113 NYD_ENTER;
2115 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2116 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2117 ) != n_IDEC_STATE_CONSUMED)
2118 n_exit_status |= n_EXIT_ERR;
2120 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2121 fflush(NULL);
2122 _exit(n_exit_status);
2123 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2124 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2125 n_psonce |= n_PSO_XIT;
2126 NYD_LEAVE;
2127 return 0;
2130 FL int
2131 c_quit(void *vp){
2132 char const **argv;
2133 NYD_ENTER;
2135 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2136 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2137 ) != n_IDEC_STATE_CONSUMED)
2138 n_exit_status |= n_EXIT_ERR;
2140 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2141 fflush(NULL);
2142 _exit(n_exit_status);
2143 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2144 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2145 n_psonce |= n_PSO_QUIT;
2146 NYD_LEAVE;
2147 return 0;
2150 FL int
2151 c_readctl(void *vp){
2152 /* TODO We would need OnForkEvent and then simply remove some internal
2153 * TODO management; we don't have this, therefore we need global
2154 * TODO n_readctl_overlay to be accessible via =NULL, and to make that
2155 * TODO work in turn we need an instance for default STDIN! Sigh. */
2156 static ui8_t a_buf[n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name)+1 +1];
2157 static struct a_go_readctl_ctx *a_stdin;
2159 struct a_go_readctl_ctx *grcp;
2160 char const *emsg;
2161 enum{
2162 a_NONE = 0,
2163 a_ERR = 1u<<0,
2164 a_SET = 1u<<1,
2165 a_CREATE = 1u<<2,
2166 a_REMOVE = 1u<<3
2167 } f;
2168 struct n_cmd_arg *cap;
2169 struct n_cmd_arg_ctx *cacp;
2170 NYD_ENTER;
2172 if(a_stdin == NULL){
2173 a_stdin = (struct a_go_readctl_ctx*)a_buf;
2174 a_stdin->grc_name[0] = '-';
2175 n_readctl_overlay = a_stdin;
2178 n_pstate_err_no = n_ERR_NONE;
2179 cacp = vp;
2180 cap = cacp->cac_arg;
2182 if(cacp->cac_no == 0 || is_asccaseprefix(cap->ca_arg.ca_str.s, "show"))
2183 goto jshow;
2184 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "set"))
2185 f = a_SET;
2186 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "create"))
2187 f = a_CREATE;
2188 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "remove"))
2189 f = a_REMOVE;
2190 else{
2191 emsg = N_("`readctl': invalid subcommand: %s\n");
2192 goto jeinval_quote;
2195 if(cacp->cac_no == 1){ /* TODO better option parser <> subcommand */
2196 n_err(_("`readctl': %s: requires argument\n"), cap->ca_arg.ca_str.s);
2197 goto jeinval;
2199 cap = cap->ca_next;
2201 /* - is special TODO unfortunately also regarding storage */
2202 if(cap->ca_arg.ca_str.l == 1 && *cap->ca_arg.ca_str.s == '-'){
2203 if(f & (a_CREATE | a_REMOVE)){
2204 n_err(_("`readctl': cannot create nor remove -\n"));
2205 goto jeinval;
2207 n_readctl_overlay = a_stdin;
2208 goto jleave;
2211 /* Try to find a yet existing instance */
2212 if((grcp = n_readctl_overlay) != NULL){
2213 for(; grcp != NULL; grcp = grcp->grc_next)
2214 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2215 goto jfound;
2216 for(grcp = n_readctl_overlay; (grcp = grcp->grc_last) != NULL;)
2217 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2218 goto jfound;
2221 if(f & (a_SET | a_REMOVE)){
2222 emsg = N_("`readctl': no such channel: %s\n");
2223 goto jeinval_quote;
2226 jfound:
2227 if(f & a_SET)
2228 n_readctl_overlay = grcp;
2229 else if(f & a_REMOVE){
2230 if(n_readctl_overlay == grcp)
2231 n_readctl_overlay = a_stdin;
2233 if(grcp->grc_last != NULL)
2234 grcp->grc_last->grc_next = grcp->grc_next;
2235 if(grcp->grc_next != NULL)
2236 grcp->grc_next->grc_last = grcp->grc_last;
2237 fclose(grcp->grc_fp);
2238 n_free(grcp);
2239 }else{
2240 FILE *fp;
2241 size_t elen;
2242 si32_t fd;
2244 if(grcp != NULL){
2245 n_err(_("`readctl': channel already exists: %s\n"), /* TODO reopen */
2246 n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2247 n_pstate_err_no = n_ERR_EXIST;
2248 f = a_ERR;
2249 goto jleave;
2252 if((n_idec_si32_cp(&fd, cap->ca_arg.ca_str.s, 0, NULL
2253 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2254 ) != n_IDEC_STATE_CONSUMED){
2255 if((emsg = fexpand(cap->ca_arg.ca_str.s, FEXP_LOCAL | FEXP_NVAR)
2256 ) == NULL){
2257 emsg = N_("`readctl': cannot expand filename %s\n");
2258 goto jeinval_quote;
2260 fd = -1;
2261 elen = strlen(emsg);
2262 fp = safe_fopen(emsg, "r", NULL);
2263 }else if(fd == STDIN_FILENO || fd == STDOUT_FILENO ||
2264 fd == STDERR_FILENO){
2265 n_err(_("`readctl': create: standard descriptors are not allowed\n"));
2266 goto jeinval;
2267 }else{
2268 /* xxx Avoid */
2269 _CLOEXEC_SET(fd);
2270 emsg = NULL;
2271 elen = 0;
2272 fp = fdopen(fd, "r");
2275 if(fp != NULL){
2276 size_t i;
2278 if((i = UIZ_MAX - elen) <= cap->ca_arg.ca_str.l ||
2279 (i -= cap->ca_arg.ca_str.l) <=
2280 n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +2){
2281 n_err(_("`readctl': failed to create storage for %s\n"),
2282 cap->ca_arg.ca_str.s);
2283 n_pstate_err_no = n_ERR_OVERFLOW;
2284 f = a_ERR;
2285 goto jleave;
2288 grcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +
2289 cap->ca_arg.ca_str.l +1 + elen +1);
2290 grcp->grc_last = NULL;
2291 if((grcp->grc_next = n_readctl_overlay) != NULL)
2292 grcp->grc_next->grc_last = grcp;
2293 n_readctl_overlay = grcp;
2294 grcp->grc_fp = fp;
2295 grcp->grc_fd = fd;
2296 memcpy(grcp->grc_name, cap->ca_arg.ca_str.s, cap->ca_arg.ca_str.l +1);
2297 if(elen == 0)
2298 grcp->grc_expand = NULL;
2299 else{
2300 char *cp;
2302 grcp->grc_expand = cp = &grcp->grc_name[cap->ca_arg.ca_str.l +1];
2303 memcpy(cp, emsg, ++elen);
2305 }else{
2306 emsg = N_("`readctl': failed to create file for %s\n");
2307 goto jeinval_quote;
2311 jleave:
2312 NYD_LEAVE;
2313 return (f & a_ERR) ? 1 : 0;
2314 jeinval_quote:
2315 n_err(V_(emsg), n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2316 jeinval:
2317 n_pstate_err_no = n_ERR_INVAL;
2318 f = a_ERR;
2319 goto jleave;
2321 jshow:
2322 if((grcp = n_readctl_overlay) == NULL)
2323 fprintf(n_stdout, _("`readctl': no channels registered\n"));
2324 else{
2325 while(grcp->grc_last != NULL)
2326 grcp = grcp->grc_last;
2328 fprintf(n_stdout, _("`readctl': registered channels:\n"));
2329 for(; grcp != NULL; grcp = grcp->grc_next)
2330 fprintf(n_stdout, _("%c%s %s%s%s%s\n"),
2331 (grcp == n_readctl_overlay ? '*' : ' '),
2332 (grcp->grc_fd != -1 ? _("descriptor") : _("name")),
2333 n_shexp_quote_cp(grcp->grc_name, FAL0),
2334 (grcp->grc_expand != NULL ? " (" : n_empty),
2335 (grcp->grc_expand != NULL ? grcp->grc_expand : n_empty),
2336 (grcp->grc_expand != NULL ? ")" : n_empty));
2338 f = a_NONE;
2339 goto jleave;
2342 /* s-it-mode */