make-config.in: install: ignore chown error..
[s-mailx.git] / go.c
blob5ba7d8c83ef4d45822944e4c94b99b0a9a4dabef
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;
344 /* We need to trim for a possible history entry, but do it anyway and insert
345 * a space for argument separation in case of alias expansion. Also, do
346 * terminate again because nothing prevents aliases from introducing WS */
347 n_str_trim_ifs(&line, TRU1);
348 line.s[line.l] = '\0';
350 /* Lengthy history entry setup, possibly even redundant. But having
351 * normalized history entries is a good thing, and this is maybe still
352 * cheaper than parsing a StrList of words per se */
353 if((gecp->gec_hist_flags & (a_GO_HIST_ADD | a_GO_HIST_INIT)
354 ) == a_GO_HIST_ADD){
355 if(line.l > 0){
356 sp = n_string_creat_auto(&s);
357 sp = n_string_assign_buf(sp, line.s, line.l);
358 gecp->gec_hist_args = n_string_cp(sp);
361 sp = n_string_creat_auto(&s);
362 sp = n_string_reserve(sp, 32);
364 if(flags & a_NOALIAS)
365 sp = n_string_push_c(sp, '\\');
366 if(flags & a_IGNERR)
367 sp = n_string_push_buf(sp, "ignerr ", sizeof("ignerr ") -1);
368 if(flags & a_WYSH)
369 sp = n_string_push_buf(sp, "wysh ", sizeof("wysh ") -1);
370 if(flags & a_VPUT)
371 sp = n_string_push_buf(sp, "vput ", sizeof("vput ") -1);
372 gecp->gec_hist_flags = a_GO_HIST_ADD | a_GO_HIST_INIT;
375 /* Look up the command; if not found, bitch.
376 * Normally, a blank command would map to the first command in the
377 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
378 * confusion; act just the same for aliases */
379 if(*word == '\0'){
380 jempty:
381 if((n_pstate & n_PS_ROBOT) || !(n_psonce & n_PSO_INTERACTIVE) ||
382 alias_name != NULL){
383 gecp->gec_hist_flags = a_GO_HIST_NONE;
384 goto jret0;
386 cdp = n_cmd_default();
387 goto jexec;
390 if(!(flags & a_NOALIAS) && (flags & a_ALIAS_MASK) != a_ALIAS_MASK){
391 ui8_t expcnt;
393 expcnt = (flags & a_ALIAS_MASK);
394 ++expcnt;
395 flags = (flags & ~(a_ALIAS_MASK | a_NOPREFIX)) | expcnt;
397 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
398 if(alias_name != NULL && !strcmp(word, alias_name)){
399 if(n_poption & n_PO_D_V)
400 n_err(_("Actively avoiding self-recursion of `commandalias': %s\n"),
401 word);
402 }else if((alias_name = n_commandalias_exists(word, &alias_exp)) != NULL){
403 size_t i;
405 if(sp != NULL){
406 sp = n_string_push_cp(sp, word);
407 gecp->gec_hist_cmd = n_string_cp(sp);
408 sp = NULL;
411 /* And join arguments onto alias expansion */
412 alias_name = word;
413 i = alias_exp->l;
414 cp = line.s;
415 line.s = n_autorec_alloc(i + 1 + line.l +1);
416 memcpy(line.s, alias_exp->s, i);
417 if(line.l > 0){
418 line.s[i++] = ' ';
419 memcpy(&line.s[i], cp, line.l);
421 line.s[i += line.l] = '\0';
422 line.l = i;
423 goto jrestart;
427 if((cdp = n_cmd_firstfit(word)) == NULL){
428 bool_t doskip;
430 if(!(doskip = n_cnd_if_isskip()) || (n_poption & n_PO_D_V))
431 n_err(_("Unknown command%s: `%s'\n"),
432 (doskip ? _(" (ignored due to `if' condition)") : n_empty),
433 prstr(word));
434 gecp->gec_hist_flags = a_GO_HIST_NONE;
435 if(doskip)
436 goto jret0;
437 nerrn = n_ERR_NOSYS;
438 goto jleave;
441 /* See if we should execute the command -- if a conditional we always
442 * execute it, otherwise, check the state of cond */
443 jexec:
444 if(!(cdp->cd_caflags & n_CMD_ARG_F) && n_cnd_if_isskip()){
445 gecp->gec_hist_flags = a_GO_HIST_NONE;
446 goto jret0;
449 if(sp != NULL){
450 sp = n_string_push_cp(sp, cdp->cd_name);
451 gecp->gec_hist_cmd = n_string_cp(sp);
452 sp = NULL;
455 nerrn = n_ERR_INVAL;
457 /* Process the arguments to the command, depending on the type it expects */
458 if((cdp->cd_caflags & n_CMD_ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
459 !(n_poption & n_PO_BATCH_FLAG)){
460 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
461 cdp->cd_name);
462 goto jleave;
464 if(!(cdp->cd_caflags & n_CMD_ARG_M) && (n_psonce & n_PSO_SENDMODE)){
465 n_err(_("May not execute `%s' while sending\n"), cdp->cd_name);
466 goto jleave;
468 if(cdp->cd_caflags & n_CMD_ARG_R){
469 if(n_pstate & n_PS_COMPOSE_MODE){
470 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
471 n_err(_("Cannot invoke `%s' when in compose mode\n"), cdp->cd_name);
472 goto jleave;
474 /* TODO Nothing should prevent n_CMD_ARG_R in conjunction with
475 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
476 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING) && n_go_may_yield_control()){
477 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
478 cdp->cd_name);
479 goto jleave;
482 if((cdp->cd_caflags & n_CMD_ARG_S) && !(n_psonce & n_PSO_STARTED)){
483 n_err(_("May not execute `%s' during startup\n"), cdp->cd_name);
484 goto jleave;
486 if(!(cdp->cd_caflags & n_CMD_ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
487 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
488 cdp->cd_name);
489 goto jleave;
492 if((cdp->cd_caflags & n_CMD_ARG_A) && mb.mb_type == MB_VOID){
493 n_err(_("Cannot execute `%s' without active mailbox\n"), cdp->cd_name);
494 goto jleave;
496 if((cdp->cd_caflags & n_CMD_ARG_W) && !(mb.mb_perm & MB_DELE)){
497 n_err(_("May not execute `%s' -- message file is read only\n"),
498 cdp->cd_name);
499 goto jleave;
502 if(cdp->cd_caflags & n_CMD_ARG_O)
503 n_OBSOLETE2(_("this command will be removed"), cdp->cd_name);
505 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
506 * TODO doesn't use any of those list commands which strip this mask,
507 * TODO and for now we misuse bits for checking relation to history;
508 * TODO argument state should be property of a per-command carrier instead */
509 n_pstate &= ~n_PS_ARGLIST_MASK;
511 if((flags & a_WYSH) &&
512 (cdp->cd_caflags & n_CMD_ARG_TYPE_MASK) != n_CMD_ARG_TYPE_WYRA){
513 n_err(_("`wysh' prefix does not affect `%s'\n"), cdp->cd_name);
514 flags &= ~a_WYSH;
517 if(flags & a_VPUT){
518 if(cdp->cd_caflags & n_CMD_ARG_V){
519 char const *emsg;
521 emsg = line.s; /* xxx Cannot pass &char* as char const**, so no cp */
522 arglist[0] = n_shexp_parse_token_cp((n_SHEXP_PARSE_TRIM_SPACE |
523 n_SHEXP_PARSE_TRIM_IFSSPACE | n_SHEXP_PARSE_LOG |
524 n_SHEXP_PARSE_META_KEEP), &emsg);
525 line.l -= PTR2SIZE(emsg - line.s);
526 line.s = cp = n_UNCONST(emsg);
527 if(cp == NULL)
528 emsg = N_("could not parse input token");
529 else if(!n_shexp_is_valid_varname(arglist[0]))
530 emsg = N_("not a valid variable name");
531 else if(!n_var_is_user_writable(arglist[0]))
532 emsg = N_("either not a user writable, or a boolean variable");
533 else
534 emsg = NULL;
535 if(emsg != NULL){
536 n_err("`%s': vput: %s: %s\n",
537 cdp->cd_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
538 nerrn = n_ERR_NOTSUP;
539 rv = -1;
540 goto jleave;
542 ++arglist;
543 n_pstate |= n_PS_ARGMOD_VPUT; /* TODO YET useless since stripped later
544 * TODO on in getrawlist() etc., i.e., the argument vector producers,
545 * TODO therefore yet needs to be set again based on flags&a_VPUT! */
546 }else{
547 n_err(_("`vput' prefix does not affect `%s'\n"), cdp->cd_name);
548 flags &= ~a_VPUT;
552 switch(cdp->cd_caflags & n_CMD_ARG_TYPE_MASK){
553 case n_CMD_ARG_TYPE_MSGLIST:
554 /* Message list defaulting to nearest forward legal message */
555 if(n_msgvec == NULL)
556 goto jemsglist;
557 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
558 nerrn = n_ERR_NOMSG;
559 flags |= a_NO_ERRNO;
560 break;
562 if(c == 0){
563 if((n_msgvec[0] = first(cdp->cd_msgflag, cdp->cd_msgmask)) != 0)
564 n_msgvec[1] = 0;
566 if(n_msgvec[0] == 0){
567 jemsglist:
568 if(!(n_pstate & n_PS_HOOK_MASK))
569 fprintf(n_stdout, _("No applicable messages\n"));
570 nerrn = n_ERR_NOMSG;
571 flags |= a_NO_ERRNO;
572 break;
574 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
575 n_err_no = 0;
576 rv = (*cdp->cd_func)(n_msgvec);
577 break;
579 case n_CMD_ARG_TYPE_NDMLIST:
580 /* Message list with no defaults, but no error if none exist */
581 if(n_msgvec == NULL)
582 goto jemsglist;
583 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
584 nerrn = n_ERR_NOMSG;
585 flags |= a_NO_ERRNO;
586 break;
588 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
589 n_err_no = 0;
590 rv = (*cdp->cd_func)(n_msgvec);
591 break;
593 case n_CMD_ARG_TYPE_STRING:
594 /* Just the straight string, old style, with leading blanks removed */
595 for(cp = line.s; spacechar(*cp);)
596 ++cp;
597 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
598 n_err_no = 0;
599 rv = (*cdp->cd_func)(cp);
600 break;
601 case n_CMD_ARG_TYPE_RAWDAT:
602 /* Just the straight string, placed in argv[] */
603 *arglist++ = line.s;
604 *arglist = NULL;
605 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
606 n_err_no = 0;
607 rv = (*cdp->cd_func)(arglist_base);
608 break;
610 case n_CMD_ARG_TYPE_WYSH:
611 c = 1;
612 if(0){
613 /* FALLTHRU */
614 case n_CMD_ARG_TYPE_WYRA:
615 c = (flags & a_WYSH) ? 1 : 0;
616 if(0){
617 case n_CMD_ARG_TYPE_RAWLIST:
618 c = 0;
621 if((c = getrawlist((c != 0), arglist,
622 n_MAXARGC - PTR2SIZE(arglist - arglist_base), line.s, line.l)) < 0){
623 n_err(_("Invalid argument list\n"));
624 flags |= a_NO_ERRNO;
625 break;
628 if(c < cdp->cd_minargs){
629 n_err(_("`%s' requires at least %u arg(s)\n"),
630 cdp->cd_name, (ui32_t)cdp->cd_minargs);
631 flags |= a_NO_ERRNO;
632 break;
634 #undef cd_minargs
635 if(c > cdp->cd_maxargs){
636 n_err(_("`%s' takes no more than %u arg(s)\n"),
637 cdp->cd_name, (ui32_t)cdp->cd_maxargs);
638 flags |= a_NO_ERRNO;
639 break;
641 #undef cd_maxargs
643 if(flags & a_VPUT)
644 n_pstate |= n_PS_ARGMOD_VPUT;
646 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
647 n_err_no = 0;
648 rv = (*cdp->cd_func)(arglist_base);
649 if(a_go_xcall != NULL)
650 goto jret0;
651 break;
653 case n_CMD_ARG_TYPE_ARG:{
654 /* TODO The _ARG_TYPE_ARG is preliminary, in the end we should have a
655 * TODO per command-ctx carrier that also has slots for it arguments,
656 * TODO and that should be passed along all the way. No more arglists
657 * TODO here, etc. */
658 struct n_cmd_arg_ctx cac;
660 cac.cac_desc = cdp->cd_cadp;
661 cac.cac_indat = line.s;
662 cac.cac_inlen = line.l;
663 if(!n_cmd_arg_parse(&cac)){
664 flags |= a_NO_ERRNO;
665 break;
668 if(flags & a_VPUT){
669 cac.cac_vput = *arglist_base;
670 n_pstate |= n_PS_ARGMOD_VPUT;
671 }else
672 cac.cac_vput = NULL;
674 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
675 n_err_no = 0;
676 rv = (*cdp->cd_func)(&cac);
677 if(a_go_xcall != NULL)
678 goto jret0;
679 } break;
681 default:
682 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
683 cdp->cd_caflags & n_CMD_ARG_TYPE_MASK); )
684 nerrn = n_ERR_NOTOBACCO;
685 nexn = 1;
686 goto jret0;
689 if(gecp->gec_hist_flags & a_GO_HIST_ADD){
690 if(cdp->cd_caflags & n_CMD_ARG_H)
691 gecp->gec_hist_flags = a_GO_HIST_NONE;
692 else if((cdp->cd_caflags & n_CMD_ARG_G) ||
693 (n_pstate & n_PS_MSGLIST_GABBY))
694 gecp->gec_hist_flags |= a_GO_HIST_GABBY;
697 if(rv != 0){
698 if(!(flags & a_NO_ERRNO)){
699 if(cdp->cd_caflags & n_CMD_ARG_EM)
700 flags |= a_NO_ERRNO;
701 else if((nerrn = n_err_no) == 0)
702 nerrn = n_ERR_INVAL;
703 }else
704 flags ^= a_NO_ERRNO;
705 }else if(cdp->cd_caflags & n_CMD_ARG_EM)
706 flags |= a_NO_ERRNO;
707 else
708 nerrn = n_ERR_NONE;
709 jleave:
710 nexn = rv;
712 if(flags & a_IGNERR){
713 n_pstate &= ~n_PS_ERR_EXIT_MASK;
714 n_exit_status = n_EXIT_OK;
715 }else if(rv != 0){
716 bool_t bo;
718 if((bo = ok_blook(batch_exit_on_error))){
719 n_OBSOLETE(_("please use *errexit*, not *batch-exit-on-error*"));
720 if(!(n_poption & n_PO_BATCH_FLAG))
721 bo = FAL0;
723 if(ok_blook(errexit) || bo) /* TODO v15: drop bo */
724 n_pstate |= n_PS_ERR_QUIT;
725 else if(ok_blook(posix)){
726 if(n_psonce & n_PSO_STARTED)
727 rv = 0;
728 else if(!(n_psonce & n_PSO_INTERACTIVE))
729 n_pstate |= n_PS_ERR_XIT;
730 }else
731 rv = 0;
733 if(rv != 0){
734 if(n_exit_status == n_EXIT_OK)
735 n_exit_status = n_EXIT_ERR;
736 if((n_poption & n_PO_D_V) &&
737 !(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)))
738 n_alert(_("Non-interactive, bailing out due to errors "
739 "in startup load phase"));
740 goto jret;
744 if(cdp == NULL)
745 goto jret0;
746 if((cdp->cd_caflags & n_CMD_ARG_P) && ok_blook(autoprint))
747 if(visible(dot))
748 n_go_input_inject(n_GO_INPUT_INJECT_COMMIT, "\\type",
749 sizeof("\\type") -1);
751 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
752 !(cdp->cd_caflags & n_CMD_ARG_T))
753 n_pstate |= n_PS_SAW_COMMAND;
754 jret0:
755 rv = 0;
756 jret:
757 if(!(flags & a_NO_ERRNO))
758 n_pstate_err_no = nerrn;
759 n_pstate_ex_no = nexn;
760 NYD_LEAVE;
761 return (rv == 0);
764 static void
765 a_go_hangup(int s){
766 NYD_X; /* Signal handler */
767 n_UNUSED(s);
768 /* nothing to do? */
769 exit(n_EXIT_ERR);
772 #ifdef HAVE_IMAP
773 FL void n_go_onintr_for_imap(void){a_go_onintr(0);}
774 #endif
775 static void
776 a_go_onintr(int s){ /* TODO block signals while acting */
777 NYD_X; /* Signal handler */
778 n_UNUSED(s);
780 safe_signal(SIGINT, a_go_onintr);
782 termios_state_reset();
784 a_go_cleanup(a_GO_CLEANUP_UNWIND | /* XXX FAKE */a_GO_CLEANUP_HOLDALLSIGS);
786 if(interrupts != 1)
787 n_err_sighdl(_("Interrupt\n"));
788 safe_signal(SIGPIPE, a_go_oldpipe);
789 siglongjmp(a_go_srbuf, 0); /* FIXME get rid */
792 static void
793 a_go_cleanup(enum a_go_cleanup_mode gcm){
794 /* Signals blocked */
795 struct a_go_ctx *gcp;
796 NYD_ENTER;
798 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
799 hold_all_sigs();
800 jrestart:
801 gcp = a_go_ctx;
803 /* Free input injections of this level first */
804 if(!(gcm & a_GO_CLEANUP_LOOPTICK)){
805 struct a_go_input_inject **giipp, *giip;
807 for(giipp = &gcp->gc_inject; (giip = *giipp) != NULL;){
808 *giipp = giip->gii_next;
809 n_free(giip);
813 /* Cleanup non-crucial external stuff */
814 n_COLOUR(
815 if(gcp->gc_data.gdc_colour != NULL)
816 n_colour_stack_del(&gcp->gc_data);
819 /* Work the actual context (according to cleanup mode) */
820 if(gcp->gc_outer == NULL){
821 if(gcm & (a_GO_CLEANUP_UNWIND | a_GO_CLEANUP_SIGINT)){
822 if(a_go_xcall != NULL){
823 n_free(a_go_xcall);
824 a_go_xcall = NULL;
826 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
827 n_pstate &= ~n_PS_ERR_EXIT_MASK;
828 close_all_files();
829 }else{
830 if(!(n_pstate & n_PS_SOURCING))
831 close_all_files();
834 n_memory_reset();
836 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
837 assert(a_go_xcall == NULL);
838 assert(!(gcp->gc_flags & a_GO_XCALL_LOOP_MASK));
839 assert(gcp->gc_on_finalize == NULL);
840 assert(gcp->gc_data.gdc_colour == NULL);
841 goto jxleave;
842 }else if(gcm & a_GO_CLEANUP_LOOPTICK){
843 n_memory_reset();
844 goto jxleave;
845 }else if(gcp->gc_flags & a_GO_SPLICE){ /* TODO Temporary hack */
846 n_stdin = gcp->gc_splice_stdin;
847 n_stdout = gcp->gc_splice_stdout;
848 n_psonce = gcp->gc_splice_psonce;
849 goto jstackpop;
852 /* Cleanup crucial external stuff */
853 if(gcp->gc_data.gdc_ifcond != NULL){
854 n_cnd_if_stack_del(&gcp->gc_data);
855 if(!(gcm & (a_GO_CLEANUP_ERROR | a_GO_CLEANUP_SIGINT)) &&
856 !(gcp->gc_flags & a_GO_FORCE_EOF) && a_go_xcall == NULL &&
857 !(n_psonce & n_PSO_EXIT_MASK)){
858 n_err(_("Unmatched `if' at end of %s %s\n"),
859 ((gcp->gc_flags & a_GO_MACRO
860 ? (gcp->gc_flags & a_GO_MACRO_CMD ? _("command") : _("macro"))
861 : _("`source'd file"))),
862 gcp->gc_name);
863 gcm |= a_GO_CLEANUP_ERROR;
867 /* Teardown context */
868 if(gcp->gc_flags & a_GO_MACRO){
869 if(gcp->gc_flags & a_GO_MACRO_FREE_DATA){
870 char **lp;
872 while(*(lp = &gcp->gc_lines[gcp->gc_loff]) != NULL){
873 n_free(*lp);
874 ++gcp->gc_loff;
876 /* Part of gcp's memory chunk, then */
877 if(!(gcp->gc_flags & a_GO_MACRO_CMD))
878 n_free(gcp->gc_lines);
880 }else if(gcp->gc_flags & a_GO_PIPE)
881 /* XXX command manager should -TERM then -KILL instead of hoping
882 * XXX for exit of provider due to n_ERR_PIPE / SIGPIPE */
883 Pclose(gcp->gc_file, TRU1);
884 else if(gcp->gc_flags & a_GO_FILE)
885 Fclose(gcp->gc_file);
887 if(!(gcp->gc_flags & a_GO_MEMPOOL_INHERITED)){
888 if(gcp->gc_data.gdc_mempool != NULL)
889 n_memory_pool_pop(NULL);
890 }else
891 n_memory_reset();
893 jstackpop:
894 /* Update a_go_ctx and n_go_data, n_pstate ... */
895 a_go_ctx = gcp->gc_outer;
896 assert(a_go_ctx != NULL);
897 /* C99 */{
898 struct a_go_ctx *x;
900 for(x = a_go_ctx; x->gc_flags & a_GO_DATACTX_INHERITED;){
901 x = x->gc_outer;
902 assert(x != NULL);
904 n_go_data = &x->gc_data;
907 if((a_go_ctx->gc_flags & (a_GO_MACRO | a_GO_SUPER_MACRO)) ==
908 (a_GO_MACRO | a_GO_SUPER_MACRO)){
909 n_pstate &= ~n_PS_SOURCING;
910 assert(n_pstate & n_PS_ROBOT);
911 }else if(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK))
912 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
913 else
914 assert(n_pstate & n_PS_ROBOT);
916 if(gcp->gc_on_finalize != NULL)
917 (*gcp->gc_on_finalize)(gcp->gc_finalize_arg);
919 if(gcm & a_GO_CLEANUP_ERROR){
920 if(a_go_ctx->gc_flags & a_GO_XCALL_LOOP)
921 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP_ERROR;
922 goto jerr;
924 jleave:
925 if(gcp->gc_flags & a_GO_FREE)
926 n_free(gcp);
928 if(n_UNLIKELY((gcm & a_GO_CLEANUP_UNWIND) && gcp != a_go_ctx))
929 goto jrestart;
931 jxleave:
932 NYD_LEAVE;
933 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
934 rele_all_sigs();
935 return;
937 jerr:
938 /* With *posix* we follow what POSIX says:
939 * Any errors in the start-up file shall either cause mailx to
940 * terminate with a diagnostic message and a non-zero status or to
941 * continue after writing a diagnostic message, ignoring the
942 * remainder of the lines in the start-up file
943 * Print the diagnostic only for the outermost resource unless the user
944 * is debugging or in verbose mode */
945 if((n_poption & n_PO_D_V) ||
946 (!(n_psonce & n_PSO_STARTED) &&
947 !(gcp->gc_flags & (a_GO_SPLICE | a_GO_MACRO)) &&
948 !(gcp->gc_outer->gc_flags & a_GO_TYPE_MASK)))
949 /* I18N: file inclusion, macro etc. evaluation has been stopped */
950 n_alert(_("Stopped %s %s due to errors%s"),
951 (n_psonce & n_PSO_STARTED
952 ? (gcp->gc_flags & a_GO_SPLICE ? _("spliced in program")
953 : (gcp->gc_flags & a_GO_MACRO
954 ? (gcp->gc_flags & a_GO_MACRO_CMD
955 ? _("evaluating command") : _("evaluating macro"))
956 : (gcp->gc_flags & a_GO_PIPE
957 ? _("executing `source'd pipe")
958 : (gcp->gc_flags & a_GO_FILE
959 ? _("loading `source'd file") : _(a_GO_MAINCTX_NAME))))
961 : (gcp->gc_flags & a_GO_MACRO
962 ? (gcp->gc_flags & a_GO_MACRO_X_OPTION
963 ? _("evaluating command line") : _("evaluating macro"))
964 : _("loading initialization resource"))),
965 gcp->gc_name,
966 (n_poption & n_PO_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
967 goto jleave;
970 static bool_t
971 a_go_file(char const *file, bool_t silent_open_error){
972 struct a_go_ctx *gcp;
973 sigset_t osigmask;
974 size_t nlen;
975 char *nbuf;
976 bool_t ispipe;
977 FILE *fip;
978 NYD_ENTER;
980 fip = NULL;
982 /* Being a command argument file is space-trimmed *//* TODO v15 with
983 * TODO WYRALIST this is no longer necessary true, and for that we
984 * TODO don't set _PARSE_TRIM_SPACE because we cannot! -> cmd-tab.h!! */
985 #if 0
986 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
987 file[--nlen] == '|')))
988 #else
989 ispipe = FAL0;
990 if(!silent_open_error){
991 for(nlen = strlen(file); nlen > 0;){
992 char c;
994 c = file[--nlen];
995 if(!spacechar(c)){
996 if(c == '|'){
997 nbuf = savestrbuf(file, nlen);
998 ispipe = TRU1;
1000 break;
1004 #endif
1006 if(ispipe){
1007 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1008 ok_vlook(SHELL), NULL, n_CHILD_FD_NULL)) == NULL)
1009 goto jeopencheck;
1010 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1011 goto jeopencheck;
1012 else if((fip = Fopen(nbuf, "r")) == NULL){
1013 jeopencheck:
1014 if(!silent_open_error || (n_poption & n_PO_D_V))
1015 n_perr(nbuf, 0);
1016 if(silent_open_error)
1017 fip = (FILE*)-1;
1018 goto jleave;
1021 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1023 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1024 (nlen = strlen(nbuf) +1));
1025 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1027 hold_all_sigs();
1029 gcp->gc_outer = a_go_ctx;
1030 gcp->gc_osigmask = osigmask;
1031 gcp->gc_file = fip;
1032 gcp->gc_flags = (ispipe ? a_GO_FREE | a_GO_PIPE : a_GO_FREE | a_GO_FILE) |
1033 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO ? a_GO_SUPER_MACRO : 0);
1034 memcpy(gcp->gc_name, nbuf, nlen);
1036 a_go_ctx = gcp;
1037 n_go_data = &gcp->gc_data;
1038 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1039 if(!a_go_event_loop(gcp, n_GO_INPUT_NONE | n_GO_INPUT_NL_ESC))
1040 fip = NULL;
1041 jleave:
1042 NYD_LEAVE;
1043 return (fip != NULL);
1046 static bool_t
1047 a_go_load(struct a_go_ctx *gcp){
1048 NYD2_ENTER;
1050 assert(!(n_psonce & n_PSO_STARTED));
1051 assert(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK));
1053 gcp->gc_flags |= a_GO_MEMPOOL_INHERITED;
1054 gcp->gc_data.gdc_mempool = n_go_data->gdc_mempool;
1056 hold_all_sigs();
1058 /* POSIX:
1059 * Any errors in the start-up file shall either cause mailx to terminate
1060 * with a diagnostic message and a non-zero status or to continue after
1061 * writing a diagnostic message, ignoring the remainder of the lines in
1062 * the start-up file. */
1063 gcp->gc_outer = a_go_ctx;
1064 a_go_ctx = gcp;
1065 n_go_data = &gcp->gc_data;
1066 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1067 n_pstate |= n_PS_ROBOT |
1068 (gcp->gc_flags & a_GO_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1070 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1072 rele_all_sigs();
1074 n_go_main_loop();
1075 NYD2_LEAVE;
1076 return (((n_psonce & n_PSO_EXIT_MASK) |
1077 (n_pstate & n_PS_ERR_EXIT_MASK)) == 0);
1080 static void
1081 a_go__eloopint(int sig){ /* TODO one day, we don't need it no more */
1082 NYD_X; /* Signal handler */
1083 n_UNUSED(sig);
1084 siglongjmp(a_go_ctx->gc_eloop_jmp, 1);
1087 static bool_t
1088 a_go_event_loop(struct a_go_ctx *gcp, enum n_go_input_flags gif){
1089 sighandler_type soldhdl;
1090 struct a_go_eval_ctx gec;
1091 enum {a_RETOK = TRU1, a_TICKED = 1<<1} volatile f;
1092 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1093 sigset_t osigmask;
1094 NYD2_ENTER;
1096 memset(&gec, 0, sizeof gec);
1097 osigmask = gcp->gc_osigmask;
1098 hadint = FAL0;
1099 f = a_RETOK;
1101 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1102 safe_signal(SIGINT, &a_go__eloopint);
1103 if(sigsetjmp(gcp->gc_eloop_jmp, 1)){
1104 hold_all_sigs();
1105 hadint = TRU1;
1106 f &= ~a_RETOK;
1107 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1108 goto jjump;
1112 for(;; f |= a_TICKED){
1113 int n;
1115 if(f & a_TICKED)
1116 n_memory_reset();
1118 /* Read a line of commands and handle end of file specially */
1119 gec.gec_line.l = gec.gec_line_size;
1120 rele_all_sigs();
1121 n = n_go_input(gif, NULL, &gec.gec_line.s, &gec.gec_line.l, NULL, NULL);
1122 hold_all_sigs();
1123 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1124 gec.gec_line.l = (ui32_t)n;
1126 if(n < 0)
1127 break;
1129 rele_all_sigs();
1130 assert(gec.gec_hist_flags == a_GO_HIST_NONE);
1131 if(!a_go_evaluate(&gec))
1132 f &= ~a_RETOK;
1133 hold_all_sigs();
1135 if(!(f & a_RETOK) || a_go_xcall != NULL ||
1136 (n_psonce & n_PSO_EXIT_MASK) || (n_pstate & n_PS_ERR_EXIT_MASK))
1137 break;
1140 jjump: /* TODO Should be _CLEANUP_UNWIND not _TEARDOWN on signal if DOABLE! */
1141 a_go_cleanup(a_GO_CLEANUP_TEARDOWN |
1142 (f & a_RETOK ? 0 : a_GO_CLEANUP_ERROR) |
1143 (hadint ? a_GO_CLEANUP_SIGINT : 0) | a_GO_CLEANUP_HOLDALLSIGS);
1145 if(gec.gec_line.s != NULL)
1146 n_free(gec.gec_line.s);
1148 if(soldhdl != SIG_IGN)
1149 safe_signal(SIGINT, soldhdl);
1150 NYD2_LEAVE;
1151 rele_all_sigs();
1152 if(hadint){
1153 sigprocmask(SIG_SETMASK, &osigmask, NULL);
1154 n_raise(SIGINT);
1156 return (f & a_RETOK);
1159 FL void
1160 n_go_init(void){
1161 struct a_go_ctx *gcp;
1162 NYD2_ENTER;
1164 assert(n_stdin != NULL);
1166 gcp = (void*)a_go__mainctx_b.uf;
1167 DBGOR( memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name)),
1168 memset(&gcp->gc_data, 0, sizeof gcp->gc_data) );
1169 gcp->gc_file = n_stdin;
1170 memcpy(gcp->gc_name, a_GO_MAINCTX_NAME, sizeof(a_GO_MAINCTX_NAME));
1171 a_go_ctx = gcp;
1172 n_go_data = &gcp->gc_data;
1174 n_child_manager_start();
1175 NYD2_LEAVE;
1178 FL bool_t
1179 n_go_main_loop(void){ /* FIXME */
1180 struct a_go_eval_ctx gec;
1181 int n, eofcnt;
1182 bool_t volatile rv;
1183 NYD_ENTER;
1185 rv = TRU1;
1187 if (!(n_pstate & n_PS_SOURCING)) {
1188 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1189 safe_signal(SIGINT, &a_go_onintr);
1190 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1191 safe_signal(SIGHUP, &a_go_hangup);
1193 a_go_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1194 safe_signal(SIGPIPE, a_go_oldpipe);
1196 memset(&gec, 0, sizeof gec);
1198 (void)sigsetjmp(a_go_srbuf, 1); /* FIXME get rid */
1199 hold_all_sigs();
1201 for (eofcnt = 0;; gec.gec_ever_seen = TRU1) {
1202 interrupts = 0;
1204 if(gec.gec_ever_seen)
1205 a_go_cleanup(a_GO_CLEANUP_LOOPTICK | a_GO_CLEANUP_HOLDALLSIGS);
1207 if (!(n_pstate & n_PS_SOURCING)) {
1208 char *cp;
1210 /* TODO Note: this buffer may contain a password. We should redefine
1211 * TODO the code flow which has to do that */
1212 if ((cp = termios_state.ts_linebuf) != NULL) {
1213 termios_state.ts_linebuf = NULL;
1214 termios_state.ts_linesize = 0;
1215 n_free(cp); /* TODO pool give-back */
1217 if (gec.gec_line.l > LINESIZE * 3) {
1218 n_free(gec.gec_line.s);
1219 gec.gec_line.s = NULL;
1220 gec.gec_line.l = gec.gec_line_size = 0;
1224 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1225 char *cp;
1227 if ((cp = ok_vlook(newmail)) != NULL) { /* TODO bla */
1228 struct stat st;
1230 if(mb.mb_type == MB_FILE){
1231 if(!stat(mailname, &st) && st.st_size > mailsize) Jnewmail:{
1232 ui32_t odid;
1233 size_t odot;
1235 odot = PTR2SIZE(dot - message);
1236 odid = (n_pstate & n_PS_DID_PRINT_DOT);
1238 rele_all_sigs();
1239 n = setfile(mailname,
1240 (FEDIT_NEWMAIL |
1241 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)));
1242 hold_all_sigs();
1244 if(n < 0) {
1245 n_exit_status |= n_EXIT_ERR;
1246 rv = FAL0;
1247 break;
1249 #ifdef HAVE_IMAP
1250 if(mb.mb_type != MB_IMAP){
1251 #endif
1252 dot = &message[odot];
1253 n_pstate |= odid;
1254 #ifdef HAVE_IMAP
1256 #endif
1258 }else{
1259 n = (cp != NULL && strcmp(cp, "nopoll"));
1261 if(mb.mb_type == MB_MAILDIR){
1262 if(n != 0)
1263 goto Jnewmail;
1265 #ifdef HAVE_IMAP
1266 else if(mb.mb_type == MB_IMAP){
1267 if(!n)
1268 n = (cp != NULL && strcmp(cp, "noimap"));
1270 if(imap_newmail(n) > (cp == NULL))
1271 goto Jnewmail;
1273 #endif
1278 /* Read a line of commands and handle end of file specially */
1279 gec.gec_line.l = gec.gec_line_size;
1280 /* C99 */{
1281 bool_t histadd;
1283 histadd = (!(n_pstate & n_PS_SOURCING) &&
1284 (n_psonce & n_PSO_INTERACTIVE));
1285 rele_all_sigs();
1286 n = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, NULL,
1287 &gec.gec_line.s, &gec.gec_line.l, NULL, &histadd);
1288 hold_all_sigs();
1290 gec.gec_hist_flags = histadd ? a_GO_HIST_ADD : a_GO_HIST_NONE;
1292 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1293 gec.gec_line.l = (ui32_t)n;
1295 if (n < 0) {
1296 if (!(n_pstate & n_PS_ROBOT) &&
1297 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1298 ++eofcnt < 4) {
1299 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1300 n_go_input_clearerr();
1301 continue;
1303 break;
1306 n_pstate &= ~n_PS_HOOK_MASK;
1307 rele_all_sigs();
1308 rv = a_go_evaluate(&gec);
1309 hold_all_sigs();
1311 if(gec.gec_hist_flags & a_GO_HIST_ADD){
1312 char const *cc, *ca;
1314 cc = gec.gec_hist_cmd;
1315 ca = gec.gec_hist_args;
1316 if(cc != NULL && ca != NULL)
1317 cc = savecatsep(cc, ' ', ca);
1318 else if(ca != NULL)
1319 cc = ca;
1320 assert(cc != NULL);
1321 n_tty_addhist(cc, ((gec.gec_hist_flags & a_GO_HIST_GABBY) != 0));
1324 switch(n_pstate & n_PS_ERR_EXIT_MASK){
1325 case n_PS_ERR_XIT: n_psonce |= n_PSO_XIT; break;
1326 case n_PS_ERR_QUIT: n_psonce |= n_PSO_QUIT; break;
1327 default: break;
1329 if(n_psonce & n_PSO_EXIT_MASK)
1330 break;
1332 if(!rv)
1333 break;
1336 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS |
1337 (rv ? 0 : a_GO_CLEANUP_ERROR));
1339 if (gec.gec_line.s != NULL)
1340 n_free(gec.gec_line.s);
1342 rele_all_sigs();
1343 NYD_LEAVE;
1344 return rv;
1347 FL void
1348 n_go_input_clearerr(void){
1349 FILE *fp;
1350 NYD2_ENTER;
1352 fp = NULL;
1354 if(!(a_go_ctx->gc_flags & (a_GO_FORCE_EOF |
1355 a_GO_PIPE | a_GO_MACRO | a_GO_SPLICE)))
1356 fp = a_go_ctx->gc_file;
1358 if(fp != NULL){
1359 a_go_ctx->gc_flags &= ~a_GO_IS_EOF;
1360 clearerr(fp);
1362 NYD2_LEAVE;
1365 FL void
1366 n_go_input_force_eof(void){
1367 NYD2_ENTER;
1368 a_go_ctx->gc_flags |= a_GO_FORCE_EOF;
1369 NYD2_LEAVE;
1372 FL bool_t
1373 n_go_input_is_eof(void){
1374 bool_t rv;
1375 NYD2_ENTER;
1377 rv = ((a_go_ctx->gc_flags & a_GO_IS_EOF) != 0);
1378 NYD2_LEAVE;
1379 return rv;
1382 FL void
1383 n_go_input_inject(enum n_go_input_inject_flags giif, char const *buf,
1384 size_t len){
1385 NYD_ENTER;
1386 if(len == UIZ_MAX)
1387 len = strlen(buf);
1389 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat) -1 > len &&
1390 len > 0){
1391 struct a_go_input_inject *giip, **giipp;
1393 hold_all_sigs();
1395 giip = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat
1396 ) + 1 + len +1);
1397 giipp = &a_go_ctx->gc_inject;
1398 giip->gii_next = *giipp;
1399 giip->gii_commit = ((giif & n_GO_INPUT_INJECT_COMMIT) != 0);
1400 giip->gii_no_history = ((giif & n_GO_INPUT_INJECT_HISTORY) == 0);
1401 memcpy(&giip->gii_dat[0], buf, len);
1402 giip->gii_dat[giip->gii_len = len] = '\0';
1403 *giipp = giip;
1405 rele_all_sigs();
1407 NYD_LEAVE;
1410 FL int
1411 (n_go_input)(enum n_go_input_flags gif, char const *prompt, char **linebuf,
1412 size_t *linesize, char const *string, bool_t *histok_or_null
1413 n_MEMORY_DEBUG_ARGS){
1414 /* TODO readline: linebuf pool!; n_go_input should return si64_t */
1415 struct n_string xprompt;
1416 FILE *ifile;
1417 bool_t doprompt, dotty;
1418 char const *iftype;
1419 struct a_go_input_inject *giip;
1420 int nold, n;
1421 bool_t histok;
1422 NYD2_ENTER;
1424 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1425 hold_all_sigs();
1427 histok = FAL0;
1429 if(a_go_ctx->gc_flags & a_GO_FORCE_EOF){
1430 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1431 n = -1;
1432 goto jleave;
1435 if(gif & n_GO_INPUT_FORCE_STDIN)
1436 goto jforce_stdin;
1438 /* Special case macro mode: never need to prompt, lines have always been
1439 * unfolded already */
1440 if(a_go_ctx->gc_flags & a_GO_MACRO){
1441 if(*linebuf != NULL)
1442 n_free(*linebuf);
1444 /* Injection in progress? Don't care about the autocommit state here */
1445 if((giip = a_go_ctx->gc_inject) != NULL){
1446 a_go_ctx->gc_inject = giip->gii_next;
1448 /* Simply "reuse" allocation, copy string to front of it */
1449 jinject:
1450 *linesize = giip->gii_len;
1451 *linebuf = (char*)giip;
1452 memmove(*linebuf, giip->gii_dat, giip->gii_len +1);
1453 iftype = "INJECTION";
1454 }else{
1455 if((*linebuf = a_go_ctx->gc_lines[a_go_ctx->gc_loff]) == NULL){
1456 *linesize = 0;
1457 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1458 n = -1;
1459 goto jleave;
1462 ++a_go_ctx->gc_loff;
1463 *linesize = strlen(*linebuf);
1464 if(!(a_go_ctx->gc_flags & a_GO_MACRO_FREE_DATA))
1465 *linebuf = sbufdup(*linebuf, *linesize);
1467 iftype = (a_go_ctx->gc_flags & a_GO_MACRO_X_OPTION)
1468 ? "-X OPTION"
1469 : (a_go_ctx->gc_flags & a_GO_MACRO_CMD) ? "CMD" : "MACRO";
1471 n = (int)*linesize;
1472 n_pstate |= n_PS_READLINE_NL;
1473 goto jhave_dat;
1474 }else{
1475 /* Injection in progress? */
1476 struct a_go_input_inject **giipp;
1478 giipp = &a_go_ctx->gc_inject;
1480 if((giip = *giipp) != NULL){
1481 *giipp = giip->gii_next;
1483 if(giip->gii_commit){
1484 if(*linebuf != NULL)
1485 n_free(*linebuf);
1486 histok = !giip->gii_no_history;
1487 goto jinject; /* (above) */
1488 }else{
1489 string = savestrbuf(giip->gii_dat, giip->gii_len);
1490 n_free(giip);
1495 jforce_stdin:
1496 n_pstate &= ~n_PS_READLINE_NL;
1497 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1498 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1499 histok = (n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1500 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT);
1501 doprompt = !(gif & n_GO_INPUT_FORCE_STDIN) && histok;
1502 dotty = (doprompt && !ok_blook(line_editor_disable));
1503 if(!doprompt)
1504 gif |= n_GO_INPUT_PROMPT_NONE;
1505 else{
1506 if(!dotty)
1507 n_string_creat_auto(&xprompt);
1508 if(prompt == NULL)
1509 gif |= n_GO_INPUT_PROMPT_EVAL;
1512 /* Ensure stdout is flushed first anyway (partial lines, maybe?) */
1513 if(!dotty && (gif & n_GO_INPUT_PROMPT_NONE))
1514 fflush(n_stdout);
1516 if(gif & n_GO_INPUT_FORCE_STDIN){
1517 struct a_go_readctl_ctx *grcp;
1519 grcp = n_readctl_overlay;
1520 ifile = (grcp == NULL || grcp->grc_fp == NULL) ? n_stdin : grcp->grc_fp;
1521 }else
1522 ifile = a_go_ctx->gc_file;
1523 if(ifile == NULL){
1524 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1525 (a_go_ctx->gc_flags & a_GO_MACRO));
1526 ifile = n_stdin;
1529 for(nold = n = 0;;){
1530 if(dotty){
1531 assert(ifile == n_stdin);
1532 if(string != NULL && (n = (int)strlen(string)) > 0){
1533 if(*linesize > 0)
1534 *linesize += n +1;
1535 else
1536 *linesize = (size_t)n + LINESIZE +1;
1537 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1538 memcpy(*linebuf, string, (size_t)n +1);
1540 string = NULL;
1542 rele_all_sigs();
1544 n = (n_tty_readline)(gif, prompt, linebuf, linesize, n, histok_or_null
1545 n_MEMORY_DEBUG_ARGSCALL);
1547 hold_all_sigs();
1548 }else{
1549 if(!(gif & n_GO_INPUT_PROMPT_NONE))
1550 n_tty_create_prompt(&xprompt, prompt, gif);
1552 rele_all_sigs();
1554 if(!(gif & n_GO_INPUT_PROMPT_NONE) && xprompt.s_len > 0){
1555 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1556 fflush(n_stdout);
1559 n = (readline_restart)(ifile, linebuf, linesize, n
1560 n_MEMORY_DEBUG_ARGSCALL);
1562 hold_all_sigs();
1564 if(n < 0 && feof(ifile))
1565 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1567 if(n > 0 && nold > 0){
1568 char const *cp;
1569 int i;
1571 i = 0;
1572 cp = &(*linebuf)[nold];
1573 while(spacechar(*cp) && n - i >= nold)
1574 ++cp, ++i;
1575 if(i > 0){
1576 memmove(&(*linebuf)[nold], cp, n - nold - i);
1577 n -= i;
1578 (*linebuf)[n] = '\0';
1583 if(n <= 0)
1584 break;
1586 /* POSIX says:
1587 * An unquoted <backslash> at the end of a command line shall
1588 * be discarded and the next line shall continue the command */
1589 if(!(gif & n_GO_INPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1590 if(dotty)
1591 n_pstate |= n_PS_READLINE_NL;
1592 break;
1594 /* Definitely outside of quotes, thus the quoting rules are so that an
1595 * uneven number of successive reverse solidus at EOL is a continuation */
1596 if(n > 1){
1597 size_t i, j;
1599 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1600 if((*linebuf)[i] != '\\')
1601 break;
1602 if(!(j & 1))
1603 break;
1605 (*linebuf)[nold = --n] = '\0';
1606 gif |= n_GO_INPUT_NL_FOLLOW;
1609 if(n < 0)
1610 goto jleave;
1611 (*linebuf)[*linesize = n] = '\0';
1613 jhave_dat:
1614 if(n_poption & n_PO_D_VV)
1615 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1616 jleave:
1617 if (n_pstate & n_PS_PSTATE_PENDMASK)
1618 a_go_update_pstate();
1620 /* TODO We need to special case a_GO_SPLICE, since that is not managed by us
1621 * TODO but only established from the outside and we need to drop this
1622 * TODO overlay context somehow */
1623 if(n < 0 && (a_go_ctx->gc_flags & a_GO_SPLICE))
1624 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS);
1626 if(histok_or_null != NULL && !histok)
1627 *histok_or_null = FAL0;
1629 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1630 rele_all_sigs();
1631 NYD2_LEAVE;
1632 return n;
1635 FL char *
1636 n_go_input_cp(enum n_go_input_flags gif, char const *prompt,
1637 char const *string){
1638 struct n_sigman sm;
1639 bool_t histadd;
1640 size_t linesize;
1641 char *linebuf, * volatile rv;
1642 int n;
1643 NYD2_ENTER;
1645 linesize = 0;
1646 linebuf = NULL;
1647 rv = NULL;
1649 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL){
1650 case 0:
1651 break;
1652 default:
1653 goto jleave;
1656 histadd = TRU1;
1657 n = n_go_input(gif, prompt, &linebuf, &linesize, string, &histadd);
1658 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1659 (gif & n_GO_INPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE) &&
1660 histadd)
1661 n_tty_addhist(rv, ((gif & n_GO_INPUT_HIST_GABBY) != 0));
1663 n_sigman_cleanup_ping(&sm);
1664 jleave:
1665 if(linebuf != NULL)
1666 n_free(linebuf);
1667 NYD2_LEAVE;
1668 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
1669 return rv;
1672 FL bool_t
1673 n_go_load(char const *name){
1674 struct a_go_ctx *gcp;
1675 size_t i;
1676 FILE *fip;
1677 bool_t rv;
1678 NYD_ENTER;
1680 rv = TRU1;
1682 if(name == NULL || *name == '\0')
1683 goto jleave;
1684 else if((fip = Fopen(name, "r")) == NULL){
1685 if(n_poption & n_PO_D_V)
1686 n_err(_("No such file to load: %s\n"), n_shexp_quote_cp(name, FAL0));
1687 goto jleave;
1690 i = strlen(name) +1;
1691 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + i);
1692 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1694 gcp->gc_file = fip;
1695 gcp->gc_flags = a_GO_FREE | a_GO_FILE;
1696 memcpy(gcp->gc_name, name, i);
1698 if(n_poption & n_PO_D_V)
1699 n_err(_("Loading %s\n"), n_shexp_quote_cp(gcp->gc_name, FAL0));
1700 rv = a_go_load(gcp);
1701 jleave:
1702 NYD_LEAVE;
1703 return rv;
1706 FL bool_t
1707 n_go_Xargs(char const **lines, size_t cnt){
1708 static char const name[] = "-X";
1710 union{
1711 bool_t rv;
1712 ui64_t align;
1713 char uf[n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + sizeof(name)];
1714 } b;
1715 char const *srcp, *xsrcp;
1716 char *cp;
1717 size_t imax, i, len;
1718 struct a_go_ctx *gcp;
1719 NYD_ENTER;
1721 gcp = (void*)b.uf;
1722 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1724 gcp->gc_flags = a_GO_MACRO | a_GO_MACRO_X_OPTION |
1725 a_GO_SUPER_MACRO | a_GO_MACRO_FREE_DATA;
1726 memcpy(gcp->gc_name, name, sizeof name);
1728 /* The problem being that we want to support reverse solidus newline
1729 * escaping also within multiline -X, i.e., POSIX says:
1730 * An unquoted <backslash> at the end of a command line shall
1731 * be discarded and the next line shall continue the command
1732 * Therefore instead of "gcp->gc_lines = n_UNCONST(lines)", duplicate the
1733 * entire lines array and set _MACRO_FREE_DATA */
1734 imax = cnt + 1;
1735 gcp->gc_lines = n_alloc(sizeof(*gcp->gc_lines) * imax);
1737 /* For each of the input lines.. */
1738 for(i = len = 0, cp = NULL; cnt > 0;){
1739 bool_t keep;
1740 size_t j;
1742 if((j = strlen(srcp = *lines)) == 0){
1743 ++lines, --cnt;
1744 continue;
1747 /* Separate one line from a possible multiline input string */
1748 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1749 *lines = &xsrcp[1];
1750 j = PTR2SIZE(xsrcp - srcp);
1751 }else
1752 ++lines, --cnt;
1754 /* The (separated) string may itself indicate soft newline escaping */
1755 if((keep = (srcp[j - 1] == '\\'))){
1756 size_t xj, xk;
1758 /* Need an uneven number of reverse solidus */
1759 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1760 if(srcp[xj] != '\\')
1761 break;
1762 if(xk & 1)
1763 --j;
1764 else
1765 keep = FAL0;
1768 /* Strip any leading WS from follow lines, then */
1769 if(cp != NULL)
1770 while(j > 0 && spacechar(*srcp))
1771 ++srcp, --j;
1773 if(j > 0){
1774 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1775 imax += 4;
1776 gcp->gc_lines = n_realloc(gcp->gc_lines, sizeof(*gcp->gc_lines) *
1777 imax);
1779 gcp->gc_lines[i] = cp = n_realloc(cp, len + j +1);
1780 memcpy(&cp[len], srcp, j);
1781 cp[len += j] = '\0';
1783 if(!keep)
1784 ++i;
1786 if(!keep)
1787 cp = NULL, len = 0;
1789 if(cp != NULL){
1790 assert(i + 1 < imax);
1791 gcp->gc_lines[i++] = cp;
1793 gcp->gc_lines[i] = NULL;
1795 b.rv = a_go_load(gcp);
1796 NYD_LEAVE;
1797 return b.rv;
1800 FL int
1801 c_source(void *v){
1802 int rv;
1803 NYD_ENTER;
1805 rv = (a_go_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1806 NYD_LEAVE;
1807 return rv;
1810 FL int
1811 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1812 int rv;
1813 NYD_ENTER;
1815 rv = (a_go_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
1816 NYD_LEAVE;
1817 return rv;
1820 FL bool_t
1821 n_go_macro(enum n_go_input_flags gif, char const *name, char **lines,
1822 void (*on_finalize)(void*), void *finalize_arg){
1823 struct a_go_ctx *gcp;
1824 size_t i;
1825 int rv;
1826 sigset_t osigmask;
1827 NYD_ENTER;
1829 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1831 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1832 (i = strlen(name) +1));
1833 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1835 hold_all_sigs();
1837 gcp->gc_outer = a_go_ctx;
1838 gcp->gc_osigmask = osigmask;
1839 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_FREE_DATA |
1840 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1841 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0) |
1842 ((gif & n_GO_INPUT_NO_XCALL) ? a_GO_XCALL_IS_CALL : 0);
1843 gcp->gc_lines = lines;
1844 gcp->gc_on_finalize = on_finalize;
1845 gcp->gc_finalize_arg = finalize_arg;
1846 memcpy(gcp->gc_name, name, i);
1848 a_go_ctx = gcp;
1849 n_go_data = &gcp->gc_data;
1850 n_pstate |= n_PS_ROBOT;
1851 rv = a_go_event_loop(gcp, gif);
1853 /* Shall this enter a `xcall' stack avoidance optimization (loop)? */
1854 if(a_go_xcall != NULL){
1855 void *vp;
1856 struct n_cmd_arg_ctx *cacp;
1858 if(a_go_xcall == (void*)-1)
1859 a_go_xcall = NULL;
1860 else if(((void const*)(cacp = a_go_xcall)->cac_indat) == gcp){
1861 /* Indicate that "our" (ex-) parent now hosts xcall optimization */
1862 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP;
1863 while(a_go_xcall != NULL){
1864 hold_all_sigs();
1866 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_ERROR;
1868 vp = a_go_xcall;
1869 a_go_xcall = NULL;
1870 cacp = n_cmd_arg_restore_from_heap(vp);
1871 n_free(vp);
1873 rele_all_sigs();
1875 (void)c_call(cacp);
1877 rv = ((a_go_ctx->gc_flags & a_GO_XCALL_LOOP_ERROR) == 0);
1878 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1881 NYD_LEAVE;
1882 return rv;
1885 FL bool_t
1886 n_go_command(enum n_go_input_flags gif, char const *cmd){
1887 struct a_go_ctx *gcp;
1888 bool_t rv;
1889 size_t i, ial;
1890 sigset_t osigmask;
1891 NYD_ENTER;
1893 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1895 i = strlen(cmd) +1;
1896 ial = n_ALIGN(i);
1897 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1898 ial + 2*sizeof(char*));
1899 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1901 hold_all_sigs();
1903 gcp->gc_outer = a_go_ctx;
1904 gcp->gc_osigmask = osigmask;
1905 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_CMD |
1906 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1907 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0);
1908 gcp->gc_lines = (void*)&gcp->gc_name[ial];
1909 memcpy(gcp->gc_lines[0] = &gcp->gc_name[0], cmd, i);
1910 gcp->gc_lines[1] = NULL;
1912 a_go_ctx = gcp;
1913 n_go_data = &gcp->gc_data;
1914 n_pstate |= n_PS_ROBOT;
1915 rv = a_go_event_loop(gcp, gif);
1916 NYD_LEAVE;
1917 return rv;
1920 FL void
1921 n_go_splice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
1922 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
1923 struct a_go_ctx *gcp;
1924 size_t i;
1925 sigset_t osigmask;
1926 NYD_ENTER;
1928 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1930 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1931 (i = strlen(cmd) +1));
1932 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1934 hold_all_sigs();
1936 gcp->gc_outer = a_go_ctx;
1937 gcp->gc_osigmask = osigmask;
1938 gcp->gc_file = new_stdin;
1939 gcp->gc_flags = a_GO_FREE | a_GO_SPLICE | a_GO_DATACTX_INHERITED;
1940 gcp->gc_on_finalize = on_finalize;
1941 gcp->gc_finalize_arg = finalize_arg;
1942 gcp->gc_splice_stdin = n_stdin;
1943 gcp->gc_splice_stdout = n_stdout;
1944 gcp->gc_splice_psonce = n_psonce;
1945 memcpy(gcp->gc_name, cmd, i);
1947 n_stdin = new_stdin;
1948 n_stdout = new_stdout;
1949 n_psonce = new_psonce;
1950 a_go_ctx = gcp;
1951 /* Do NOT touch n_go_data! */
1952 n_pstate |= n_PS_ROBOT;
1954 rele_all_sigs();
1955 NYD_LEAVE;
1958 FL void
1959 n_go_splice_hack_remove_after_jump(void){
1960 a_go_cleanup(a_GO_CLEANUP_TEARDOWN);
1963 FL bool_t
1964 n_go_may_yield_control(void){ /* TODO this is a terrible hack */
1965 struct a_go_ctx *gcp;
1966 bool_t rv;
1967 NYD2_ENTER;
1969 rv = FAL0;
1971 /* Only when startup completed */
1972 if(!(n_psonce & n_PSO_STARTED))
1973 goto jleave;
1974 /* Only interactive or batch mode (assuming that is ok) */
1975 if(!(n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_BATCH_FLAG))
1976 goto jleave;
1978 /* Not when running any hook */
1979 if(n_pstate & n_PS_HOOK_MASK)
1980 goto jleave;
1982 /* Traverse up the stack:
1983 * . not when controlled by a child process
1984 * TODO . not when there are pipes involved, we neither handle job control,
1985 * TODO nor process groups, that is, controlling terminal acceptably
1986 * . not when sourcing a file */
1987 for(gcp = a_go_ctx; gcp != NULL; gcp = gcp->gc_outer){
1988 if(gcp->gc_flags & (a_GO_PIPE | a_GO_FILE | a_GO_SPLICE))
1989 goto jleave;
1992 rv = TRU1;
1993 jleave:
1994 NYD2_LEAVE;
1995 return rv;
1998 FL int
1999 c_eval(void *vp){
2000 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
2001 * TODO ARGV with shell rules, but if that is not possible then simply
2002 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
2003 struct a_go_eval_ctx gec;
2004 struct n_string s_b, *sp;
2005 size_t i, j;
2006 char const **argv, *cp;
2007 NYD_ENTER;
2009 argv = vp;
2011 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
2012 j += strlen(cp);
2014 sp = n_string_creat_auto(&s_b);
2015 sp = n_string_reserve(sp, j);
2017 for(i = 0; (cp = argv[i]) != NULL; ++i){
2018 if(i > 0)
2019 sp = n_string_push_c(sp, ' ');
2020 sp = n_string_push_cp(sp, cp);
2023 memset(&gec, 0, sizeof gec);
2024 gec.gec_line.s = n_string_cp(sp);
2025 gec.gec_line.l = sp->s_len;
2026 if(n_poption & n_PO_D_VV)
2027 n_err(_("EVAL %" PRIuZ " bytes <%s>\n"), gec.gec_line.l, gec.gec_line.s);
2028 (void)/* XXX */a_go_evaluate(&gec);
2029 NYD_LEAVE;
2030 return (a_go_xcall != NULL ? 0 : n_pstate_ex_no);
2033 FL int
2034 c_xcall(void *vp){
2035 int rv;
2036 struct a_go_ctx *gcp;
2037 NYD2_ENTER;
2039 /* The context can only be a macro context, except that possibly a single
2040 * level of `eval' (TODO: yet) was used to double-expand our arguments */
2041 if((gcp = a_go_ctx)->gc_flags & a_GO_MACRO_CMD)
2042 gcp = gcp->gc_outer;
2043 if((gcp->gc_flags & (a_GO_MACRO | a_GO_MACRO_X_OPTION | a_GO_MACRO_CMD)
2044 ) != a_GO_MACRO){
2045 if(n_poption & n_PO_D_V_VV)
2046 n_err(_("`xcall': can only be used inside a macro, using `call'\n"));
2047 rv = c_call(vp);
2048 goto jleave;
2051 /* Try to roll up the stack as much as possible.
2052 * See a_GO_XCALL_LOOP flag description for more */
2053 if(!(gcp->gc_flags & a_GO_XCALL_IS_CALL) && gcp->gc_outer != NULL){
2054 if(gcp->gc_outer->gc_flags & a_GO_XCALL_LOOP)
2055 gcp = gcp->gc_outer;
2056 }else{
2057 /* Otherwise this macro is "invoked from the top level", in which case we
2058 * silently act as if we were `call'... */
2059 rv = c_call(vp);
2060 /* ...which means we must ensure the rest of the macro that was us
2061 * doesn't become evaluated! */
2062 a_go_xcall = (void*)-1;
2063 goto jleave;
2066 /* C99 */{
2067 struct n_cmd_arg_ctx *cacp;
2069 cacp = n_cmd_arg_save_to_heap(vp);
2070 cacp->cac_indat = (char*)gcp;
2071 a_go_xcall = cacp;
2073 rv = 0;
2074 jleave:
2075 NYD2_LEAVE;
2076 return rv;
2079 FL int
2080 c_exit(void *vp){
2081 char const **argv;
2082 NYD_ENTER;
2084 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2085 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2086 ) != n_IDEC_STATE_CONSUMED)
2087 n_exit_status |= n_EXIT_ERR;
2089 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2090 fflush(NULL);
2091 _exit(n_exit_status);
2092 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2093 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2094 n_psonce |= n_PSO_XIT;
2095 NYD_LEAVE;
2096 return 0;
2099 FL int
2100 c_quit(void *vp){
2101 char const **argv;
2102 NYD_ENTER;
2104 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2105 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2106 ) != n_IDEC_STATE_CONSUMED)
2107 n_exit_status |= n_EXIT_ERR;
2109 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2110 fflush(NULL);
2111 _exit(n_exit_status);
2112 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2113 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2114 n_psonce |= n_PSO_QUIT;
2115 NYD_LEAVE;
2116 return 0;
2119 FL int
2120 c_readctl(void *vp){
2121 /* TODO We would need OnForkEvent and then simply remove some internal
2122 * TODO management; we don't have this, therefore we need global
2123 * TODO n_readctl_overlay to be accessible via =NULL, and to make that
2124 * TODO work in turn we need an instance for default STDIN! Sigh. */
2125 static ui8_t a_buf[n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name)+1 +1];
2126 static struct a_go_readctl_ctx *a_stdin;
2128 struct a_go_readctl_ctx *grcp;
2129 char const *emsg;
2130 enum{
2131 a_NONE = 0,
2132 a_ERR = 1u<<0,
2133 a_SET = 1u<<1,
2134 a_CREATE = 1u<<2,
2135 a_REMOVE = 1u<<3
2136 } f;
2137 struct n_cmd_arg *cap;
2138 struct n_cmd_arg_ctx *cacp;
2139 NYD_ENTER;
2141 if(a_stdin == NULL){
2142 a_stdin = (struct a_go_readctl_ctx*)a_buf;
2143 a_stdin->grc_name[0] = '-';
2144 n_readctl_overlay = a_stdin;
2147 n_pstate_err_no = n_ERR_NONE;
2148 cacp = vp;
2149 cap = cacp->cac_arg;
2151 if(cacp->cac_no == 0 || is_asccaseprefix(cap->ca_arg.ca_str.s, "show"))
2152 goto jshow;
2153 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "set"))
2154 f = a_SET;
2155 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "create"))
2156 f = a_CREATE;
2157 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "remove"))
2158 f = a_REMOVE;
2159 else{
2160 emsg = N_("`readctl': invalid subcommand: %s\n");
2161 goto jeinval_quote;
2164 if(cacp->cac_no == 1){ /* TODO better option parser <> subcommand */
2165 n_err(_("`readctl': %s: requires argument\n"), cap->ca_arg.ca_str.s);
2166 goto jeinval;
2168 cap = cap->ca_next;
2170 /* - is special TODO unfortunately also regarding storage */
2171 if(cap->ca_arg.ca_str.l == 1 && *cap->ca_arg.ca_str.s == '-'){
2172 if(f & (a_CREATE | a_REMOVE)){
2173 n_err(_("`readctl': cannot create nor remove -\n"));
2174 goto jeinval;
2176 n_readctl_overlay = a_stdin;
2177 goto jleave;
2180 /* Try to find a yet existing instance */
2181 if((grcp = n_readctl_overlay) != NULL){
2182 for(; grcp != NULL; grcp = grcp->grc_next)
2183 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2184 goto jfound;
2185 for(grcp = n_readctl_overlay; (grcp = grcp->grc_last) != NULL;)
2186 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2187 goto jfound;
2190 if(f & (a_SET | a_REMOVE)){
2191 emsg = N_("`readctl': no such channel: %s\n");
2192 goto jeinval_quote;
2195 jfound:
2196 if(f & a_SET)
2197 n_readctl_overlay = grcp;
2198 else if(f & a_REMOVE){
2199 if(n_readctl_overlay == grcp)
2200 n_readctl_overlay = a_stdin;
2202 if(grcp->grc_last != NULL)
2203 grcp->grc_last->grc_next = grcp->grc_next;
2204 if(grcp->grc_next != NULL)
2205 grcp->grc_next->grc_last = grcp->grc_last;
2206 fclose(grcp->grc_fp);
2207 n_free(grcp);
2208 }else{
2209 FILE *fp;
2210 size_t elen;
2211 si32_t fd;
2213 if(grcp != NULL){
2214 n_err(_("`readctl': channel already exists: %s\n"), /* TODO reopen */
2215 n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2216 n_pstate_err_no = n_ERR_EXIST;
2217 f = a_ERR;
2218 goto jleave;
2221 if((n_idec_si32_cp(&fd, cap->ca_arg.ca_str.s, 0, NULL
2222 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2223 ) != n_IDEC_STATE_CONSUMED){
2224 if((emsg = fexpand(cap->ca_arg.ca_str.s, FEXP_LOCAL | FEXP_NVAR)
2225 ) == NULL){
2226 emsg = N_("`readctl': cannot expand filename %s\n");
2227 goto jeinval_quote;
2229 fd = -1;
2230 elen = strlen(emsg);
2231 fp = safe_fopen(emsg, "r", NULL);
2232 }else if(fd == STDIN_FILENO || fd == STDOUT_FILENO ||
2233 fd == STDERR_FILENO){
2234 n_err(_("`readctl': create: standard descriptors are not allowed"));
2235 goto jeinval;
2236 }else{
2237 /* xxx Avoid */
2238 _CLOEXEC_SET(fd);
2239 emsg = NULL;
2240 elen = 0;
2241 fp = fdopen(fd, "r");
2244 if(fp != NULL){
2245 size_t i;
2247 if((i = UIZ_MAX - elen) <= cap->ca_arg.ca_str.l ||
2248 (i -= cap->ca_arg.ca_str.l) <=
2249 n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +2){
2250 n_err(_("`readctl': failed to create storage for %s\n"),
2251 cap->ca_arg.ca_str.s);
2252 n_pstate_err_no = n_ERR_OVERFLOW;
2253 f = a_ERR;
2254 goto jleave;
2257 grcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +
2258 cap->ca_arg.ca_str.l +1 + elen +1);
2259 grcp->grc_last = NULL;
2260 if((grcp->grc_next = n_readctl_overlay) != NULL)
2261 grcp->grc_next->grc_last = grcp;
2262 n_readctl_overlay = grcp;
2263 grcp->grc_fp = fp;
2264 grcp->grc_fd = fd;
2265 memcpy(grcp->grc_name, cap->ca_arg.ca_str.s, cap->ca_arg.ca_str.l +1);
2266 if(elen == 0)
2267 grcp->grc_expand = NULL;
2268 else{
2269 char *cp;
2271 grcp->grc_expand = cp = &grcp->grc_name[cap->ca_arg.ca_str.l +1];
2272 memcpy(cp, emsg, ++elen);
2274 }else{
2275 emsg = N_("`readctl': failed to create file for %s\n");
2276 goto jeinval_quote;
2280 jleave:
2281 NYD_LEAVE;
2282 return (f & a_ERR) ? 1 : 0;
2283 jeinval_quote:
2284 n_err(V_(emsg), n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2285 jeinval:
2286 n_pstate_err_no = n_ERR_INVAL;
2287 f = a_ERR;
2288 goto jleave;
2290 jshow:
2291 if((grcp = n_readctl_overlay) == NULL)
2292 fprintf(n_stdout, _("`readctl': no channels registered\n"));
2293 else{
2294 while(grcp->grc_last != NULL)
2295 grcp = grcp->grc_last;
2297 fprintf(n_stdout, _("`readctl': registered channels:\n"));
2298 for(; grcp != NULL; grcp = grcp->grc_next)
2299 fprintf(n_stdout, _("%c%s %s%s%s%s\n"),
2300 (grcp == n_readctl_overlay ? '*' : ' '),
2301 (grcp->grc_fd != -1 ? _("descriptor") : _("name")),
2302 n_shexp_quote_cp(grcp->grc_name, FAL0),
2303 (grcp->grc_expand != NULL ? " (" : n_empty),
2304 (grcp->grc_expand != NULL ? grcp->grc_expand : n_empty),
2305 (grcp->grc_expand != NULL ? ")" : n_empty));
2307 f = a_NONE;
2308 goto jleave;
2311 /* s-it-mode */