Fix: ask for `write' targets of message/rfc822 attachments (again)
[s-mailx.git] / go.c
blob57c4735463ae0f867b5f2c3e536d6b0c2d619072
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Program input of all sorts, input lexing, event loops, command evaluation.
3 *@ TODO n_PS_ROBOT requires yet n_PS_SOURCING, which REALLY sucks.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 #undef n_FILE
37 #define n_FILE go
39 #ifndef HAVE_AMALGAMATION
40 # include "nail.h"
41 #endif
43 enum a_go_flags{
44 a_GO_NONE,
45 a_GO_FREE = 1u<<0, /* Structure was allocated, n_free() it */
46 a_GO_PIPE = 1u<<1, /* Open on a pipe */
47 a_GO_FILE = 1u<<2, /* Loading or sourcing a file */
48 a_GO_MACRO = 1u<<3, /* Running a macro */
49 a_GO_MACRO_FREE_DATA = 1u<<4, /* Lines are allocated, n_free() once done */
50 /* TODO For simplicity this is yet _MACRO plus specialization overlay
51 * TODO (_X_OPTION, _CMD) -- these should be types on their own! */
52 a_GO_MACRO_X_OPTION = 1u<<5, /* Macro indeed command line -X option */
53 a_GO_MACRO_CMD = 1u<<6, /* Macro indeed single-line: ~:COMMAND */
54 /* TODO a_GO_SPLICE: the right way to support *on-compose-splice(-shell)?*
55 * TODO would be a command_loop object that emits an on_read_line event, and
56 * TODO have a special handler for the compose mode; with that, then,
57 * TODO _event_loop() would not call _evaluate() but CTX->on_read_line,
58 * TODO and _evaluate() would be the standard impl.,
59 * TODO whereas the COMMAND ESCAPE switch in collect.c would be another one.
60 * TODO With this generic accmacvar.c:temporary_compose_mode_hook_call()
61 * TODO could be dropped, and n_go_macro() could become extended,
62 * TODO and/or we would add a n_go_anything(), which would allow special
63 * TODO input handlers, special I/O input and output, special `localopts'
64 * TODO etc., to be glued to the new execution context. And all I/O all
65 * TODO over this software should not use stdin/stdout, but CTX->in/out.
66 * TODO The pstate must be a property of the current execution context, too.
67 * TODO This not today. :( For now we invent a special SPLICE execution
68 * TODO context overlay that at least allows to temporarily modify the
69 * TODO global pstate, and the global stdin and stdout pointers. HACK!
70 * TODO This splice thing is very special and has to go again. HACK!!
71 * TODO a_go_input() will drop it once it sees EOF (HACK!), but care for
72 * TODO jumps must be taken by splice creators. HACK!!! But works. ;} */
73 a_GO_SPLICE = 1u<<7,
74 /* If it is none of those, it must be the outermost, the global one */
75 a_GO_TYPE_MASK = a_GO_PIPE | a_GO_FILE | a_GO_MACRO |
76 /* a_GO_MACRO_X_OPTION | a_GO_MACRO_CMD | */ a_GO_SPLICE,
78 a_GO_FORCE_EOF = 1u<<8, /* go_input() shall return EOF next */
79 a_GO_IS_EOF = 1u<<9,
81 a_GO_SUPER_MACRO = 1u<<16, /* *Not* inheriting n_PS_SOURCING state */
82 /* This context has inherited the memory pool from its parent.
83 * In practice only used for resource file loading and -X args, which enter
84 * a top level n_go_main_loop() and should (re)use the in practice already
85 * allocated memory pool of the global context */
86 a_GO_MEMPOOL_INHERITED = 1u<<17,
88 /* This context has inherited the entire data context from its parent */
89 a_GO_DATACTX_INHERITED = 1u<<18,
91 a_GO_XCALL_IS_CALL = 1u<<24, /* n_GO_INPUT_NO_XCALL */
92 /* `xcall' optimization barrier: n_go_macro() has been finished with
93 * a `xcall' request, and `xcall' set this in the parent a_go_input of the
94 * said n_go_macro() to indicate a barrier: we teardown the a_go_input of
95 * the n_go_macro() away after leaving its _event_loop(), but then,
96 * back in n_go_macro(), that enters a for(;;) loop that directly calls
97 * c_call() -- our `xcall' stack avoidance optimization --, yet this call
98 * will itself end up in a new n_go_macro(), and if that again ends up with
99 * `xcall' this should teardown and leave its own n_go_macro(), unrolling the
100 * stack "up to the barrier level", but which effectively still is the
101 * n_go_macro() that lost its a_go_input and is looping the `xcall'
102 * optimization loop. If no `xcall' is desired that loop is simply left and
103 * the _event_loop() of the outer a_go_ctx will perform a loop tick and
104 * clear this bit again OR become teardown itself */
105 a_GO_XCALL_LOOP = 1u<<25, /* `xcall' optimization barrier level */
106 a_GO_XCALL_LOOP_ERROR = 1u<<26, /* .. state machine error transporter */
107 a_GO_XCALL_LOOP_MASK = a_GO_XCALL_LOOP | a_GO_XCALL_LOOP_ERROR
110 enum a_go_cleanup_mode{
111 a_GO_CLEANUP_UNWIND = 1u<<0, /* Teardown all contexts except outermost */
112 a_GO_CLEANUP_TEARDOWN = 1u<<1, /* Teardown current context */
113 a_GO_CLEANUP_LOOPTICK = 1u<<2, /* Normal looptick cleanup */
114 a_GO_CLEANUP_MODE_MASK = n_BITENUM_MASK(0, 2),
116 a_GO_CLEANUP_ERROR = 1u<<8, /* Error occurred on level */
117 a_GO_CLEANUP_SIGINT = 1u<<9, /* Interrupt signal received */
118 a_GO_CLEANUP_HOLDALLSIGS = 1u<<10 /* hold_all_sigs() active TODO */
121 enum a_go_hist_flags{
122 a_GO_HIST_NONE = 0,
123 a_GO_HIST_ADD = 1u<<0,
124 a_GO_HIST_GABBY = 1u<<1,
125 a_GO_HIST_INIT = 1u<<2
128 struct a_go_eval_ctx{
129 struct str gec_line; /* The terminated data to _evaluate() */
130 ui32_t gec_line_size; /* May be used to store line memory size */
131 bool_t gec_ever_seen; /* Has ever been used (main_loop() only) */
132 ui8_t gec__dummy[2];
133 ui8_t gec_hist_flags; /* enum a_go_hist_flags */
134 char const *gec_hist_cmd; /* If a_GO_HIST_ADD only, cmd and args */
135 char const *gec_hist_args;
138 struct a_go_input_inject{
139 struct a_go_input_inject *gii_next;
140 size_t gii_len;
141 bool_t gii_commit;
142 bool_t gii_no_history;
143 char gii_dat[n_VFIELD_SIZE(6)];
146 struct a_go_ctx{
147 struct a_go_ctx *gc_outer;
148 sigset_t gc_osigmask;
149 ui32_t gc_flags; /* enum a_go_flags */
150 ui32_t gc_loff; /* Pseudo (macro): index in .gc_lines */
151 char **gc_lines; /* Pseudo content, lines unfolded */
152 FILE *gc_file; /* File we were in, if applicable */
153 struct a_go_input_inject *gc_inject; /* To be consumed first */
154 void (*gc_on_finalize)(void *);
155 void *gc_finalize_arg;
156 sigjmp_buf gc_eloop_jmp; /* TODO one day... for _event_loop() */
157 /* SPLICE hacks: saved stdin/stdout, saved pstate */
158 FILE *gc_splice_stdin;
159 FILE *gc_splice_stdout;
160 ui32_t gc_splice_psonce;
161 ui8_t gc_splice__dummy[4];
162 struct n_go_data_ctx gc_data;
163 char gc_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
166 struct a_go_readctl_ctx{ /* TODO localize n_readctl_overlay, use OnForkEvent! */
167 struct a_go_readctl_ctx *grc_last;
168 struct a_go_readctl_ctx *grc_next;
169 char const *grc_expand; /* If filename based, expanded string */
170 FILE *grc_fp;
171 si32_t grc_fd; /* Based upon file-descriptor */
172 char grc_name[n_VFIELD_SIZE(4)]; /* User input for identification purposes */
175 static sighandler_type a_go_oldpipe;
176 /* a_go_cmd_tab[] after fun protos */
178 /* Our current execution context, and the buffer backing the outermost level */
179 static struct a_go_ctx *a_go_ctx;
181 #define a_GO_MAINCTX_NAME "Main event loop"
182 static union{
183 ui64_t align;
184 char uf[n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
185 sizeof(a_GO_MAINCTX_NAME)];
186 } a_go__mainctx_b;
188 /* `xcall' stack-avoidance bypass optimization. This actually is
189 * a n_cmd_arg_save_to_heap() buffer with n_cmd_arg_ctx.cac_indat misused to
190 * point to the a_go_ctx to unroll up to */
191 static void *a_go_xcall;
193 static sigjmp_buf a_go_srbuf; /* TODO GET RID */
195 /* n_PS_STATE_PENDMASK requires some actions */
196 static void a_go_update_pstate(void);
198 /* Evaluate a single command */
199 static bool_t a_go_evaluate(struct a_go_eval_ctx *gecp);
201 /* Branch here on hangup signal and simulate "exit" */
202 static void a_go_hangup(int s);
204 /* The following gets called on receipt of an interrupt */
205 static void a_go_onintr(int s);
207 /* Cleanup current execution context, update the program state.
208 * If _CLEANUP_ERROR is set then we don't alert and error out if the stack
209 * doesn't exist at all, unless _CLEANUP_HOLDALLSIGS we hold_all_sigs() */
210 static void a_go_cleanup(enum a_go_cleanup_mode gcm);
212 /* `source' and `source_if' (if silent_open_error: no pipes allowed, then).
213 * Returns FAL0 if file is somehow not usable (unless silent_open_error) or
214 * upon evaluation error, and TRU1 on success */
215 static bool_t a_go_file(char const *file, bool_t silent_open_error);
217 /* System resource file load()ing or -X command line option array traversal */
218 static bool_t a_go_load(struct a_go_ctx *gcp);
220 /* A simplified command loop for recursed state machines */
221 static bool_t a_go_event_loop(struct a_go_ctx *gcp, enum n_go_input_flags gif);
223 static void
224 a_go_update_pstate(void){
225 bool_t act;
226 NYD_ENTER;
228 act = ((n_pstate & n_PS_SIGWINCH_PEND) != 0);
229 n_pstate &= ~n_PS_PSTATE_PENDMASK;
231 if(act){
232 char buf[32];
234 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
235 ok_vset(COLUMNS, buf);
236 snprintf(buf, sizeof buf, "%d", n_scrnheight);
237 ok_vset(LINES, buf);
239 NYD_LEAVE;
242 static bool_t
243 a_go_evaluate(struct a_go_eval_ctx *gecp){
244 /* xxx old style(9), but also old code */
245 /* TODO a_go_evaluate() should be splitted in multiple subfunctions,
246 * TODO `eval' should be a prefix, etc., a Ctx should be passed along */
247 struct str line;
248 struct n_string s, *sp;
249 struct str const *alias_exp;
250 char _wordbuf[2], **arglist_base/*[n_MAXARGC]*/, **arglist, *cp, *word;
251 char const *alias_name;
252 struct n_cmd_desc const *cdp;
253 si32_t nerrn, nexn; /* TODO n_pstate_ex_no -> si64_t! */
254 int rv, c;
255 enum{
256 a_NONE = 0,
257 a_ALIAS_MASK = n_BITENUM_MASK(0, 2), /* Alias recursion counter bits */
258 a_NOPREFIX = 1u<<4, /* Modifier prefix not allowed right now */
259 a_NOALIAS = 1u<<5, /* "No alias!" expansion modifier */
260 /* New modifier prefixes must be reflected in `commandalias' handling! */
261 a_IGNERR = 1u<<6, /* ignerr modifier prefix */
262 a_WYSH = 1u<<7, /* XXX v15+ drop wysh modifier prefix */
263 a_VPUT = 1u<<8, /* vput modifier prefix */
264 a_MODE_MASK = n_BITENUM_MASK(5, 8),
265 a_NO_ERRNO = 1u<<16 /* Don't set n_pstate_err_no */
266 } flags;
267 NYD_ENTER;
269 n_exit_status = n_EXIT_OK;
271 flags = a_NONE;
272 rv = 1;
273 nerrn = n_ERR_NONE;
274 nexn = n_EXIT_OK;
275 cdp = NULL;
276 alias_name = NULL;
277 n_UNINIT(alias_exp, NULL);
278 arglist =
279 arglist_base = n_autorec_alloc(sizeof(*arglist_base) * n_MAXARGC);
280 line = gecp->gec_line; /* TODO const-ify original (buffer)! */
281 assert(line.s[line.l] == '\0');
283 if(line.l > 0 && spacechar(line.s[0]))
284 gecp->gec_hist_flags = a_GO_HIST_NONE;
285 else if(gecp->gec_hist_flags & a_GO_HIST_ADD)
286 gecp->gec_hist_cmd = gecp->gec_hist_args = NULL;
287 sp = NULL;
289 /* Aliases that refer to shell commands or macro expansion restart */
290 jrestart:
291 if(n_str_trim_ifs(&line, TRU1)->l == 0){
292 line.s[0] = '\0';
293 gecp->gec_hist_flags = a_GO_HIST_NONE;
294 goto jempty;
296 (cp = line.s)[line.l] = '\0';
298 /* No-expansion modifier? */
299 if(!(flags & a_NOPREFIX) && *cp == '\\'){
300 line.s = ++cp;
301 --line.l;
302 flags |= a_NOALIAS;
305 /* Note: adding more special treatments must be reflected in the `help' etc.
306 * output in cmd-tab.c! */
308 /* Ignore null commands (comments) */
309 if(*cp == '#'){
310 gecp->gec_hist_flags = a_GO_HIST_NONE;
311 goto jret0;
314 /* Handle ! differently to get the correct lexical conventions */
315 if(*cp == '!')
316 ++cp;
317 /* Isolate the actual command; since it may not necessarily be
318 * separated from the arguments (as in `p1') we need to duplicate it to
319 * be able to create a NUL terminated version.
320 * We must be aware of several special one letter commands here */
321 else if((cp = n_UNCONST(n_cmd_isolate(cp))) == line.s &&
322 (*cp == '|' || *cp == '?'))
323 ++cp;
324 c = (int)PTR2SIZE(cp - line.s);
325 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : n_autorec_alloc(c +1);
326 memcpy(word, arglist[0] = line.s, c);
327 word[c] = '\0';
328 line.l -= c;
329 line.s = cp;
331 /* It may be a modifier.
332 * Note: adding modifiers must be reflected in commandalias handling code */
333 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
334 flags |= a_NOPREFIX | a_IGNERR;
335 goto jrestart;
336 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
337 flags |= a_NOPREFIX | a_WYSH;
338 goto jrestart;
339 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
340 flags |= a_NOPREFIX | a_VPUT;
341 goto jrestart;
342 }else if(c == sizeof("u") -1 && *word == 'u'){
343 n_err(_("Ignoring yet unused `u' command modifier!"));
344 flags |= a_NOPREFIX;
345 goto jrestart;
348 /* We need to trim for a possible history entry, but do it anyway and insert
349 * a space for argument separation in case of alias expansion. Also, do
350 * terminate again because nothing prevents aliases from introducing WS */
351 n_str_trim_ifs(&line, TRU1);
352 line.s[line.l] = '\0';
354 /* Lengthy history entry setup, possibly even redundant. But having
355 * normalized history entries is a good thing, and this is maybe still
356 * cheaper than parsing a StrList of words per se */
357 if((gecp->gec_hist_flags & (a_GO_HIST_ADD | a_GO_HIST_INIT)
358 ) == a_GO_HIST_ADD){
359 if(line.l > 0){
360 sp = n_string_creat_auto(&s);
361 sp = n_string_assign_buf(sp, line.s, line.l);
362 gecp->gec_hist_args = n_string_cp(sp);
365 sp = n_string_creat_auto(&s);
366 sp = n_string_reserve(sp, 32);
368 if(flags & a_NOALIAS)
369 sp = n_string_push_c(sp, '\\');
370 if(flags & a_IGNERR)
371 sp = n_string_push_buf(sp, "ignerr ", sizeof("ignerr ") -1);
372 if(flags & a_WYSH)
373 sp = n_string_push_buf(sp, "wysh ", sizeof("wysh ") -1);
374 if(flags & a_VPUT)
375 sp = n_string_push_buf(sp, "vput ", sizeof("vput ") -1);
376 gecp->gec_hist_flags = a_GO_HIST_ADD | a_GO_HIST_INIT;
379 /* Look up the command; if not found, bitch.
380 * Normally, a blank command would map to the first command in the
381 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
382 * confusion; act just the same for aliases */
383 if(*word == '\0'){
384 jempty:
385 if((n_pstate & n_PS_ROBOT) || !(n_psonce & n_PSO_INTERACTIVE) ||
386 alias_name != NULL){
387 gecp->gec_hist_flags = a_GO_HIST_NONE;
388 goto jret0;
390 cdp = n_cmd_default();
391 goto jexec;
394 if(!(flags & a_NOALIAS) && (flags & a_ALIAS_MASK) != a_ALIAS_MASK){
395 ui8_t expcnt;
397 expcnt = (flags & a_ALIAS_MASK);
398 ++expcnt;
399 flags = (flags & ~(a_ALIAS_MASK | a_NOPREFIX)) | expcnt;
401 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
402 if(alias_name != NULL && !strcmp(word, alias_name)){
403 if(n_poption & n_PO_D_V)
404 n_err(_("Actively avoiding self-recursion of `commandalias': %s\n"),
405 word);
406 }else if((alias_name = n_commandalias_exists(word, &alias_exp)) != NULL){
407 size_t i;
409 if(sp != NULL){
410 sp = n_string_push_cp(sp, word);
411 gecp->gec_hist_cmd = n_string_cp(sp);
412 sp = NULL;
415 /* And join arguments onto alias expansion */
416 alias_name = word;
417 i = alias_exp->l;
418 cp = line.s;
419 line.s = n_autorec_alloc(i + 1 + line.l +1);
420 memcpy(line.s, alias_exp->s, i);
421 if(line.l > 0){
422 line.s[i++] = ' ';
423 memcpy(&line.s[i], cp, line.l);
425 line.s[i += line.l] = '\0';
426 line.l = i;
427 goto jrestart;
431 if((cdp = n_cmd_firstfit(word)) == NULL){
432 bool_t doskip;
434 if(!(doskip = n_cnd_if_isskip()) || (n_poption & n_PO_D_V))
435 n_err(_("Unknown command%s: `%s'\n"),
436 (doskip ? _(" (ignored due to `if' condition)") : n_empty),
437 prstr(word));
438 gecp->gec_hist_flags = a_GO_HIST_NONE;
439 if(doskip)
440 goto jret0;
441 nerrn = n_ERR_NOSYS;
442 goto jleave;
445 /* See if we should execute the command -- if a conditional we always
446 * execute it, otherwise, check the state of cond */
447 jexec:
448 if(!(cdp->cd_caflags & n_CMD_ARG_F) && n_cnd_if_isskip()){
449 gecp->gec_hist_flags = a_GO_HIST_NONE;
450 goto jret0;
453 if(sp != NULL){
454 sp = n_string_push_cp(sp, cdp->cd_name);
455 gecp->gec_hist_cmd = n_string_cp(sp);
456 sp = NULL;
459 nerrn = n_ERR_INVAL;
461 /* Process the arguments to the command, depending on the type it expects */
462 if((cdp->cd_caflags & n_CMD_ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
463 !(n_poption & n_PO_BATCH_FLAG)){
464 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
465 cdp->cd_name);
466 goto jleave;
468 if(!(cdp->cd_caflags & n_CMD_ARG_M) && (n_psonce & n_PSO_SENDMODE)){
469 n_err(_("May not execute `%s' while sending\n"), cdp->cd_name);
470 goto jleave;
472 if(cdp->cd_caflags & n_CMD_ARG_R){
473 if(n_pstate & n_PS_COMPOSE_MODE){
474 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
475 n_err(_("Cannot invoke `%s' when in compose mode\n"), cdp->cd_name);
476 goto jleave;
478 /* TODO Nothing should prevent n_CMD_ARG_R in conjunction with
479 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
480 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING) && !n_go_may_yield_control()){
481 n_err(_("Cannot invoke `%s' in this program state\n"),
482 cdp->cd_name);
483 goto jleave;
486 if((cdp->cd_caflags & n_CMD_ARG_S) && !(n_psonce & n_PSO_STARTED)){
487 n_err(_("May not execute `%s' during startup\n"), cdp->cd_name);
488 goto jleave;
490 if(!(cdp->cd_caflags & n_CMD_ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
491 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
492 cdp->cd_name);
493 goto jleave;
496 if((cdp->cd_caflags & n_CMD_ARG_A) && mb.mb_type == MB_VOID){
497 n_err(_("Cannot execute `%s' without active mailbox\n"), cdp->cd_name);
498 goto jleave;
500 if((cdp->cd_caflags & n_CMD_ARG_W) && !(mb.mb_perm & MB_DELE)){
501 n_err(_("May not execute `%s' -- message file is read only\n"),
502 cdp->cd_name);
503 goto jleave;
506 if(cdp->cd_caflags & n_CMD_ARG_O)
507 n_OBSOLETE2(_("this command will be removed"), cdp->cd_name);
509 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
510 * TODO doesn't use any of those list commands which strip this mask,
511 * TODO and for now we misuse bits for checking relation to history;
512 * TODO argument state should be property of a per-command carrier instead */
513 n_pstate &= ~n_PS_ARGLIST_MASK;
515 if((flags & a_WYSH) &&
516 (cdp->cd_caflags & n_CMD_ARG_TYPE_MASK) != n_CMD_ARG_TYPE_WYRA){
517 n_err(_("`wysh' prefix does not affect `%s'\n"), cdp->cd_name);
518 flags &= ~a_WYSH;
521 if(flags & a_VPUT){
522 if(cdp->cd_caflags & n_CMD_ARG_V){
523 char const *emsg;
525 emsg = line.s; /* xxx Cannot pass &char* as char const**, so no cp */
526 arglist[0] = n_shexp_parse_token_cp((n_SHEXP_PARSE_TRIM_SPACE |
527 n_SHEXP_PARSE_TRIM_IFSSPACE | n_SHEXP_PARSE_LOG |
528 n_SHEXP_PARSE_META_SEMICOLON | n_SHEXP_PARSE_META_KEEP), &emsg);
529 line.l -= PTR2SIZE(emsg - line.s);
530 line.s = cp = n_UNCONST(emsg);
531 if(cp == NULL)
532 emsg = N_("could not parse input token");
533 else if(!n_shexp_is_valid_varname(arglist[0]))
534 emsg = N_("not a valid variable name");
535 else if(!n_var_is_user_writable(arglist[0]))
536 emsg = N_("either not a user writable, or a boolean variable");
537 else
538 emsg = NULL;
539 if(emsg != NULL){
540 n_err("`%s': vput: %s: %s\n",
541 cdp->cd_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
542 nerrn = n_ERR_NOTSUP;
543 rv = -1;
544 goto jleave;
546 ++arglist;
547 n_pstate |= n_PS_ARGMOD_VPUT; /* TODO YET useless since stripped later
548 * TODO on in getrawlist() etc., i.e., the argument vector producers,
549 * TODO therefore yet needs to be set again based on flags&a_VPUT! */
550 }else{
551 n_err(_("`vput' prefix does not affect `%s'\n"), cdp->cd_name);
552 flags &= ~a_VPUT;
556 switch(cdp->cd_caflags & n_CMD_ARG_TYPE_MASK){
557 case n_CMD_ARG_TYPE_MSGLIST:
558 /* Message list defaulting to nearest forward legal message */
559 if(n_msgvec == NULL)
560 goto jemsglist;
561 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
562 nerrn = n_ERR_NOMSG;
563 flags |= a_NO_ERRNO;
564 break;
566 if(c == 0){
567 if((n_msgvec[0] = first(cdp->cd_msgflag, cdp->cd_msgmask)) != 0)
568 n_msgvec[1] = 0;
570 if(n_msgvec[0] == 0){
571 jemsglist:
572 if(!(n_pstate & n_PS_HOOK_MASK))
573 fprintf(n_stdout, _("No applicable messages\n"));
574 nerrn = n_ERR_NOMSG;
575 flags |= a_NO_ERRNO;
576 break;
578 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
579 n_err_no = 0;
580 rv = (*cdp->cd_func)(n_msgvec);
581 break;
583 case n_CMD_ARG_TYPE_NDMLIST:
584 /* Message list with no defaults, but no error if none exist */
585 if(n_msgvec == NULL)
586 goto jemsglist;
587 if((c = getmsglist(line.s, n_msgvec, cdp->cd_msgflag)) < 0){
588 nerrn = n_ERR_NOMSG;
589 flags |= a_NO_ERRNO;
590 break;
592 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
593 n_err_no = 0;
594 rv = (*cdp->cd_func)(n_msgvec);
595 break;
597 case n_CMD_ARG_TYPE_STRING:
598 /* Just the straight string, old style, with leading blanks removed */
599 for(cp = line.s; spacechar(*cp);)
600 ++cp;
601 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
602 n_err_no = 0;
603 rv = (*cdp->cd_func)(cp);
604 break;
605 case n_CMD_ARG_TYPE_RAWDAT:
606 /* Just the straight string, placed in argv[] */
607 *arglist++ = line.s;
608 *arglist = NULL;
609 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
610 n_err_no = 0;
611 rv = (*cdp->cd_func)(arglist_base);
612 break;
614 case n_CMD_ARG_TYPE_WYSH:
615 c = 1;
616 if(0){
617 /* FALLTHRU */
618 case n_CMD_ARG_TYPE_WYRA:
619 c = (flags & a_WYSH) ? 1 : 0;
620 if(0){
621 case n_CMD_ARG_TYPE_RAWLIST:
622 c = 0;
625 if((c = getrawlist((c != 0), arglist,
626 n_MAXARGC - PTR2SIZE(arglist - arglist_base), line.s, line.l)) < 0){
627 n_err(_("Invalid argument list\n"));
628 flags |= a_NO_ERRNO;
629 break;
632 if(c < cdp->cd_minargs){
633 n_err(_("`%s' requires at least %u arg(s)\n"),
634 cdp->cd_name, (ui32_t)cdp->cd_minargs);
635 flags |= a_NO_ERRNO;
636 break;
638 #undef cd_minargs
639 if(c > cdp->cd_maxargs){
640 n_err(_("`%s' takes no more than %u arg(s)\n"),
641 cdp->cd_name, (ui32_t)cdp->cd_maxargs);
642 flags |= a_NO_ERRNO;
643 break;
645 #undef cd_maxargs
647 if(flags & a_VPUT)
648 n_pstate |= n_PS_ARGMOD_VPUT;
650 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
651 n_err_no = 0;
652 rv = (*cdp->cd_func)(arglist_base);
653 if(a_go_xcall != NULL)
654 goto jret0;
655 break;
657 case n_CMD_ARG_TYPE_ARG:{
658 /* TODO The _ARG_TYPE_ARG is preliminary, in the end we should have a
659 * TODO per command-ctx carrier that also has slots for it arguments,
660 * TODO and that should be passed along all the way. No more arglists
661 * TODO here, etc. */
662 struct n_cmd_arg_ctx cac;
664 cac.cac_desc = cdp->cd_cadp;
665 cac.cac_indat = line.s;
666 cac.cac_inlen = line.l;
667 if(!n_cmd_arg_parse(&cac)){
668 flags |= a_NO_ERRNO;
669 break;
672 if(flags & a_VPUT){
673 cac.cac_vput = *arglist_base;
674 n_pstate |= n_PS_ARGMOD_VPUT;
675 }else
676 cac.cac_vput = NULL;
678 if(!(flags & a_NO_ERRNO) && !(cdp->cd_caflags & n_CMD_ARG_EM)) /* XXX */
679 n_err_no = 0;
680 rv = (*cdp->cd_func)(&cac);
681 if(a_go_xcall != NULL)
682 goto jret0;
683 } break;
685 default:
686 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
687 cdp->cd_caflags & n_CMD_ARG_TYPE_MASK); )
688 nerrn = n_ERR_NOTOBACCO;
689 nexn = 1;
690 goto jret0;
693 if(gecp->gec_hist_flags & a_GO_HIST_ADD){
694 if(cdp->cd_caflags & n_CMD_ARG_H)
695 gecp->gec_hist_flags = a_GO_HIST_NONE;
696 else if((cdp->cd_caflags & n_CMD_ARG_G) ||
697 (n_pstate & n_PS_MSGLIST_GABBY))
698 gecp->gec_hist_flags |= a_GO_HIST_GABBY;
701 if(rv != 0){
702 if(!(flags & a_NO_ERRNO)){
703 if(cdp->cd_caflags & n_CMD_ARG_EM)
704 flags |= a_NO_ERRNO;
705 else if((nerrn = n_err_no) == 0)
706 nerrn = n_ERR_INVAL;
707 }else
708 flags ^= a_NO_ERRNO;
709 }else if(cdp->cd_caflags & n_CMD_ARG_EM)
710 flags |= a_NO_ERRNO;
711 else
712 nerrn = n_ERR_NONE;
713 jleave:
714 nexn = rv;
716 if(flags & a_IGNERR){
717 n_pstate &= ~n_PS_ERR_EXIT_MASK;
718 n_exit_status = n_EXIT_OK;
719 }else if(rv != 0){
720 bool_t bo;
722 if((bo = ok_blook(batch_exit_on_error))){
723 n_OBSOLETE(_("please use *errexit*, not *batch-exit-on-error*"));
724 if(!(n_poption & n_PO_BATCH_FLAG))
725 bo = FAL0;
727 if(ok_blook(errexit) || bo) /* TODO v15: drop bo */
728 n_pstate |= n_PS_ERR_QUIT;
729 else if(ok_blook(posix)){
730 if(n_psonce & n_PSO_STARTED)
731 rv = 0;
732 else if(!(n_psonce & n_PSO_INTERACTIVE))
733 n_pstate |= n_PS_ERR_XIT;
734 }else
735 rv = 0;
737 if(rv != 0){
738 if(n_exit_status == n_EXIT_OK)
739 n_exit_status = n_EXIT_ERR;
740 if((n_poption & n_PO_D_V) &&
741 !(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)))
742 n_alert(_("Non-interactive, bailing out due to errors "
743 "in startup load phase"));
744 goto jret;
748 if(cdp == NULL)
749 goto jret0;
750 if((cdp->cd_caflags & n_CMD_ARG_P) && ok_blook(autoprint))
751 if(visible(dot))
752 n_go_input_inject(n_GO_INPUT_INJECT_COMMIT, "\\type",
753 sizeof("\\type") -1);
755 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
756 !(cdp->cd_caflags & n_CMD_ARG_T))
757 n_pstate |= n_PS_SAW_COMMAND;
758 jret0:
759 rv = 0;
760 jret:
761 if(!(flags & a_NO_ERRNO))
762 n_pstate_err_no = nerrn;
763 n_pstate_ex_no = nexn;
764 NYD_LEAVE;
765 return (rv == 0);
768 static void
769 a_go_hangup(int s){
770 NYD_X; /* Signal handler */
771 n_UNUSED(s);
772 /* nothing to do? */
773 exit(n_EXIT_ERR);
776 #ifdef HAVE_IMAP
777 FL void n_go_onintr_for_imap(void){a_go_onintr(0);}
778 #endif
779 static void
780 a_go_onintr(int s){ /* TODO block signals while acting */
781 NYD_X; /* Signal handler */
782 n_UNUSED(s);
784 safe_signal(SIGINT, a_go_onintr);
786 termios_state_reset();
788 a_go_cleanup(a_GO_CLEANUP_UNWIND | /* XXX FAKE */a_GO_CLEANUP_HOLDALLSIGS);
790 if(interrupts != 1)
791 n_err_sighdl(_("Interrupt\n"));
792 safe_signal(SIGPIPE, a_go_oldpipe);
793 siglongjmp(a_go_srbuf, 0); /* FIXME get rid */
796 static void
797 a_go_cleanup(enum a_go_cleanup_mode gcm){
798 /* Signals blocked */
799 struct a_go_ctx *gcp;
800 NYD_ENTER;
802 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
803 hold_all_sigs();
804 jrestart:
805 gcp = a_go_ctx;
807 /* Free input injections of this level first */
808 if(!(gcm & a_GO_CLEANUP_LOOPTICK)){
809 struct a_go_input_inject **giipp, *giip;
811 for(giipp = &gcp->gc_inject; (giip = *giipp) != NULL;){
812 *giipp = giip->gii_next;
813 n_free(giip);
817 /* Cleanup non-crucial external stuff */
818 n_COLOUR(
819 if(gcp->gc_data.gdc_colour != NULL)
820 n_colour_stack_del(&gcp->gc_data);
823 /* Work the actual context (according to cleanup mode) */
824 if(gcp->gc_outer == NULL){
825 if(gcm & (a_GO_CLEANUP_UNWIND | a_GO_CLEANUP_SIGINT)){
826 if(a_go_xcall != NULL){
827 n_free(a_go_xcall);
828 a_go_xcall = NULL;
830 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
831 n_pstate &= ~n_PS_ERR_EXIT_MASK;
832 close_all_files();
833 }else{
834 if(!(n_pstate & n_PS_SOURCING))
835 close_all_files();
838 n_memory_reset();
840 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
841 assert(a_go_xcall == NULL);
842 assert(!(gcp->gc_flags & a_GO_XCALL_LOOP_MASK));
843 assert(gcp->gc_on_finalize == NULL);
844 assert(gcp->gc_data.gdc_colour == NULL);
845 goto jxleave;
846 }else if(gcm & a_GO_CLEANUP_LOOPTICK){
847 n_memory_reset();
848 goto jxleave;
849 }else if(gcp->gc_flags & a_GO_SPLICE){ /* TODO Temporary hack */
850 n_stdin = gcp->gc_splice_stdin;
851 n_stdout = gcp->gc_splice_stdout;
852 n_psonce = gcp->gc_splice_psonce;
853 goto jstackpop;
856 /* Cleanup crucial external stuff */
857 if(gcp->gc_data.gdc_ifcond != NULL){
858 n_cnd_if_stack_del(&gcp->gc_data);
859 if(!(gcm & (a_GO_CLEANUP_ERROR | a_GO_CLEANUP_SIGINT)) &&
860 !(gcp->gc_flags & a_GO_FORCE_EOF) && a_go_xcall == NULL &&
861 !(n_psonce & n_PSO_EXIT_MASK)){
862 n_err(_("Unmatched `if' at end of %s %s\n"),
863 ((gcp->gc_flags & a_GO_MACRO
864 ? (gcp->gc_flags & a_GO_MACRO_CMD ? _("command") : _("macro"))
865 : _("`source'd file"))),
866 gcp->gc_name);
867 gcm |= a_GO_CLEANUP_ERROR;
871 /* Teardown context */
872 if(gcp->gc_flags & a_GO_MACRO){
873 if(gcp->gc_flags & a_GO_MACRO_FREE_DATA){
874 char **lp;
876 while(*(lp = &gcp->gc_lines[gcp->gc_loff]) != NULL){
877 n_free(*lp);
878 ++gcp->gc_loff;
880 /* Part of gcp's memory chunk, then */
881 if(!(gcp->gc_flags & a_GO_MACRO_CMD))
882 n_free(gcp->gc_lines);
884 }else if(gcp->gc_flags & a_GO_PIPE)
885 /* XXX command manager should -TERM then -KILL instead of hoping
886 * XXX for exit of provider due to n_ERR_PIPE / SIGPIPE */
887 Pclose(gcp->gc_file, TRU1);
888 else if(gcp->gc_flags & a_GO_FILE)
889 Fclose(gcp->gc_file);
891 if(!(gcp->gc_flags & a_GO_MEMPOOL_INHERITED)){
892 if(gcp->gc_data.gdc_mempool != NULL)
893 n_memory_pool_pop(NULL);
894 }else
895 n_memory_reset();
897 jstackpop:
898 /* Update a_go_ctx and n_go_data, n_pstate ... */
899 a_go_ctx = gcp->gc_outer;
900 assert(a_go_ctx != NULL);
901 /* C99 */{
902 struct a_go_ctx *x;
904 for(x = a_go_ctx; x->gc_flags & a_GO_DATACTX_INHERITED;){
905 x = x->gc_outer;
906 assert(x != NULL);
908 n_go_data = &x->gc_data;
911 if((a_go_ctx->gc_flags & (a_GO_MACRO | a_GO_SUPER_MACRO)) ==
912 (a_GO_MACRO | a_GO_SUPER_MACRO)){
913 n_pstate &= ~n_PS_SOURCING;
914 assert(n_pstate & n_PS_ROBOT);
915 }else if(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK))
916 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
917 else
918 assert(n_pstate & n_PS_ROBOT);
920 if(gcp->gc_on_finalize != NULL)
921 (*gcp->gc_on_finalize)(gcp->gc_finalize_arg);
923 if(gcm & a_GO_CLEANUP_ERROR){
924 if(a_go_ctx->gc_flags & a_GO_XCALL_LOOP)
925 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP_ERROR;
926 goto jerr;
928 jleave:
929 if(gcp->gc_flags & a_GO_FREE)
930 n_free(gcp);
932 if(n_UNLIKELY((gcm & a_GO_CLEANUP_UNWIND) && gcp != a_go_ctx))
933 goto jrestart;
935 jxleave:
936 NYD_LEAVE;
937 if(!(gcm & a_GO_CLEANUP_HOLDALLSIGS))
938 rele_all_sigs();
939 return;
941 jerr:
942 /* With *posix* we follow what POSIX says:
943 * Any errors in the start-up file shall either cause mailx to
944 * terminate with a diagnostic message and a non-zero status or to
945 * continue after writing a diagnostic message, ignoring the
946 * remainder of the lines in the start-up file
947 * Print the diagnostic only for the outermost resource unless the user
948 * is debugging or in verbose mode */
949 if((n_poption & n_PO_D_V) ||
950 (!(n_psonce & n_PSO_STARTED) &&
951 !(gcp->gc_flags & (a_GO_SPLICE | a_GO_MACRO)) &&
952 !(gcp->gc_outer->gc_flags & a_GO_TYPE_MASK)))
953 /* I18N: file inclusion, macro etc. evaluation has been stopped */
954 n_alert(_("Stopped %s %s due to errors%s"),
955 (n_psonce & n_PSO_STARTED
956 ? (gcp->gc_flags & a_GO_SPLICE ? _("spliced in program")
957 : (gcp->gc_flags & a_GO_MACRO
958 ? (gcp->gc_flags & a_GO_MACRO_CMD
959 ? _("evaluating command") : _("evaluating macro"))
960 : (gcp->gc_flags & a_GO_PIPE
961 ? _("executing `source'd pipe")
962 : (gcp->gc_flags & a_GO_FILE
963 ? _("loading `source'd file") : _(a_GO_MAINCTX_NAME))))
965 : (gcp->gc_flags & a_GO_MACRO
966 ? (gcp->gc_flags & a_GO_MACRO_X_OPTION
967 ? _("evaluating command line") : _("evaluating macro"))
968 : _("loading initialization resource"))),
969 gcp->gc_name,
970 (n_poption & n_PO_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
971 goto jleave;
974 static bool_t
975 a_go_file(char const *file, bool_t silent_open_error){
976 struct a_go_ctx *gcp;
977 sigset_t osigmask;
978 size_t nlen;
979 char *nbuf;
980 bool_t ispipe;
981 FILE *fip;
982 NYD_ENTER;
984 fip = NULL;
986 /* Being a command argument file is space-trimmed *//* TODO v15 with
987 * TODO WYRALIST this is no longer necessary true, and for that we
988 * TODO don't set _PARSE_TRIM_SPACE because we cannot! -> cmd-tab.h!! */
989 #if 0
990 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
991 file[--nlen] == '|')))
992 #else
993 ispipe = FAL0;
994 if(!silent_open_error){
995 for(nlen = strlen(file); nlen > 0;){
996 char c;
998 c = file[--nlen];
999 if(!spacechar(c)){
1000 if(c == '|'){
1001 nbuf = savestrbuf(file, nlen);
1002 ispipe = TRU1;
1004 break;
1008 #endif
1010 if(ispipe){
1011 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1012 ok_vlook(SHELL), NULL, n_CHILD_FD_NULL)) == NULL)
1013 goto jeopencheck;
1014 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1015 goto jeopencheck;
1016 else if((fip = Fopen(nbuf, "r")) == NULL){
1017 jeopencheck:
1018 if(!silent_open_error || (n_poption & n_PO_D_V))
1019 n_perr(nbuf, 0);
1020 if(silent_open_error)
1021 fip = (FILE*)-1;
1022 goto jleave;
1025 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1027 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1028 (nlen = strlen(nbuf) +1));
1029 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1031 hold_all_sigs();
1033 gcp->gc_outer = a_go_ctx;
1034 gcp->gc_osigmask = osigmask;
1035 gcp->gc_file = fip;
1036 gcp->gc_flags = (ispipe ? a_GO_FREE | a_GO_PIPE : a_GO_FREE | a_GO_FILE) |
1037 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO ? a_GO_SUPER_MACRO : 0);
1038 memcpy(gcp->gc_name, nbuf, nlen);
1040 a_go_ctx = gcp;
1041 n_go_data = &gcp->gc_data;
1042 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1043 if(!a_go_event_loop(gcp, n_GO_INPUT_NONE | n_GO_INPUT_NL_ESC))
1044 fip = NULL;
1045 jleave:
1046 NYD_LEAVE;
1047 return (fip != NULL);
1050 static bool_t
1051 a_go_load(struct a_go_ctx *gcp){
1052 NYD2_ENTER;
1054 assert(!(n_psonce & n_PSO_STARTED));
1055 assert(!(a_go_ctx->gc_flags & a_GO_TYPE_MASK));
1057 gcp->gc_flags |= a_GO_MEMPOOL_INHERITED;
1058 gcp->gc_data.gdc_mempool = n_go_data->gdc_mempool;
1060 hold_all_sigs();
1062 /* POSIX:
1063 * Any errors in the start-up file shall either cause mailx to terminate
1064 * with a diagnostic message and a non-zero status or to continue after
1065 * writing a diagnostic message, ignoring the remainder of the lines in
1066 * the start-up file. */
1067 gcp->gc_outer = a_go_ctx;
1068 a_go_ctx = gcp;
1069 n_go_data = &gcp->gc_data;
1070 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1071 n_pstate |= n_PS_ROBOT |
1072 (gcp->gc_flags & a_GO_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1074 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1076 rele_all_sigs();
1078 n_go_main_loop();
1079 NYD2_LEAVE;
1080 return (((n_psonce & n_PSO_EXIT_MASK) |
1081 (n_pstate & n_PS_ERR_EXIT_MASK)) == 0);
1084 static void
1085 a_go__eloopint(int sig){ /* TODO one day, we don't need it no more */
1086 NYD_X; /* Signal handler */
1087 n_UNUSED(sig);
1088 siglongjmp(a_go_ctx->gc_eloop_jmp, 1);
1091 static bool_t
1092 a_go_event_loop(struct a_go_ctx *gcp, enum n_go_input_flags gif){
1093 sighandler_type soldhdl;
1094 struct a_go_eval_ctx gec;
1095 enum {a_RETOK = TRU1, a_TICKED = 1<<1} volatile f;
1096 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1097 sigset_t osigmask;
1098 NYD2_ENTER;
1100 memset(&gec, 0, sizeof gec);
1101 osigmask = gcp->gc_osigmask;
1102 hadint = FAL0;
1103 f = a_RETOK;
1105 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1106 safe_signal(SIGINT, &a_go__eloopint);
1107 if(sigsetjmp(gcp->gc_eloop_jmp, 1)){
1108 hold_all_sigs();
1109 hadint = TRU1;
1110 f &= ~a_RETOK;
1111 gcp->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1112 goto jjump;
1116 for(;; f |= a_TICKED){
1117 int n;
1119 if(f & a_TICKED)
1120 n_memory_reset();
1122 /* Read a line of commands and handle end of file specially */
1123 gec.gec_line.l = gec.gec_line_size;
1124 rele_all_sigs();
1125 n = n_go_input(gif, NULL, &gec.gec_line.s, &gec.gec_line.l, NULL, NULL);
1126 hold_all_sigs();
1127 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1128 gec.gec_line.l = (ui32_t)n;
1130 if(n < 0)
1131 break;
1133 rele_all_sigs();
1134 assert(gec.gec_hist_flags == a_GO_HIST_NONE);
1135 if(!a_go_evaluate(&gec))
1136 f &= ~a_RETOK;
1137 hold_all_sigs();
1139 if(!(f & a_RETOK) || a_go_xcall != NULL ||
1140 (n_psonce & n_PSO_EXIT_MASK) || (n_pstate & n_PS_ERR_EXIT_MASK))
1141 break;
1144 jjump: /* TODO Should be _CLEANUP_UNWIND not _TEARDOWN on signal if DOABLE! */
1145 a_go_cleanup(a_GO_CLEANUP_TEARDOWN |
1146 (f & a_RETOK ? 0 : a_GO_CLEANUP_ERROR) |
1147 (hadint ? a_GO_CLEANUP_SIGINT : 0) | a_GO_CLEANUP_HOLDALLSIGS);
1149 if(gec.gec_line.s != NULL)
1150 n_free(gec.gec_line.s);
1152 if(soldhdl != SIG_IGN)
1153 safe_signal(SIGINT, soldhdl);
1154 NYD2_LEAVE;
1155 rele_all_sigs();
1156 if(hadint){
1157 sigprocmask(SIG_SETMASK, &osigmask, NULL);
1158 n_raise(SIGINT);
1160 return (f & a_RETOK);
1163 FL void
1164 n_go_init(void){
1165 struct a_go_ctx *gcp;
1166 NYD2_ENTER;
1168 assert(n_stdin != NULL);
1170 gcp = (void*)a_go__mainctx_b.uf;
1171 DBGOR( memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name)),
1172 memset(&gcp->gc_data, 0, sizeof gcp->gc_data) );
1173 gcp->gc_file = n_stdin;
1174 memcpy(gcp->gc_name, a_GO_MAINCTX_NAME, sizeof(a_GO_MAINCTX_NAME));
1175 a_go_ctx = gcp;
1176 n_go_data = &gcp->gc_data;
1178 n_child_manager_start();
1179 NYD2_LEAVE;
1182 FL bool_t
1183 n_go_main_loop(void){ /* FIXME */
1184 struct a_go_eval_ctx gec;
1185 int n, eofcnt;
1186 bool_t volatile rv;
1187 NYD_ENTER;
1189 rv = TRU1;
1191 if (!(n_pstate & n_PS_SOURCING)) {
1192 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1193 safe_signal(SIGINT, &a_go_onintr);
1194 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1195 safe_signal(SIGHUP, &a_go_hangup);
1197 a_go_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1198 safe_signal(SIGPIPE, a_go_oldpipe);
1200 memset(&gec, 0, sizeof gec);
1202 (void)sigsetjmp(a_go_srbuf, 1); /* FIXME get rid */
1203 hold_all_sigs();
1205 for (eofcnt = 0;; gec.gec_ever_seen = TRU1) {
1206 interrupts = 0;
1208 if(gec.gec_ever_seen)
1209 a_go_cleanup(a_GO_CLEANUP_LOOPTICK | a_GO_CLEANUP_HOLDALLSIGS);
1211 if (!(n_pstate & n_PS_SOURCING)) {
1212 char *cp;
1214 /* TODO Note: this buffer may contain a password. We should redefine
1215 * TODO the code flow which has to do that */
1216 if ((cp = termios_state.ts_linebuf) != NULL) {
1217 termios_state.ts_linebuf = NULL;
1218 termios_state.ts_linesize = 0;
1219 n_free(cp); /* TODO pool give-back */
1221 if (gec.gec_line.l > LINESIZE * 3) {
1222 n_free(gec.gec_line.s);
1223 gec.gec_line.s = NULL;
1224 gec.gec_line.l = gec.gec_line_size = 0;
1228 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1229 char *cp;
1231 if ((cp = ok_vlook(newmail)) != NULL) { /* TODO bla */
1232 struct stat st;
1234 if(mb.mb_type == MB_FILE){
1235 if(!stat(mailname, &st) && st.st_size > mailsize) Jnewmail:{
1236 ui32_t odid;
1237 size_t odot;
1239 odot = PTR2SIZE(dot - message);
1240 odid = (n_pstate & n_PS_DID_PRINT_DOT);
1242 rele_all_sigs();
1243 n = setfile(mailname,
1244 (FEDIT_NEWMAIL |
1245 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)));
1246 hold_all_sigs();
1248 if(n < 0) {
1249 n_exit_status |= n_EXIT_ERR;
1250 rv = FAL0;
1251 break;
1253 #ifdef HAVE_IMAP
1254 if(mb.mb_type != MB_IMAP){
1255 #endif
1256 dot = &message[odot];
1257 n_pstate |= odid;
1258 #ifdef HAVE_IMAP
1260 #endif
1262 }else{
1263 n = (cp != NULL && strcmp(cp, "nopoll"));
1265 if(mb.mb_type == MB_MAILDIR){
1266 if(n != 0)
1267 goto Jnewmail;
1269 #ifdef HAVE_IMAP
1270 else if(mb.mb_type == MB_IMAP){
1271 if(!n)
1272 n = (cp != NULL && strcmp(cp, "noimap"));
1274 if(imap_newmail(n) > (cp == NULL))
1275 goto Jnewmail;
1277 #endif
1282 /* Read a line of commands and handle end of file specially */
1283 gec.gec_line.l = gec.gec_line_size;
1284 /* C99 */{
1285 bool_t histadd;
1287 histadd = (!(n_pstate & n_PS_SOURCING) &&
1288 (n_psonce & n_PSO_INTERACTIVE));
1289 rele_all_sigs();
1290 n = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, NULL,
1291 &gec.gec_line.s, &gec.gec_line.l, NULL, &histadd);
1292 hold_all_sigs();
1294 gec.gec_hist_flags = histadd ? a_GO_HIST_ADD : a_GO_HIST_NONE;
1296 gec.gec_line_size = (ui32_t)gec.gec_line.l;
1297 gec.gec_line.l = (ui32_t)n;
1299 if (n < 0) {
1300 if (!(n_pstate & n_PS_ROBOT) &&
1301 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1302 ++eofcnt < 4) {
1303 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1304 n_go_input_clearerr();
1305 continue;
1307 break;
1310 n_pstate &= ~n_PS_HOOK_MASK;
1311 rele_all_sigs();
1312 rv = a_go_evaluate(&gec);
1313 hold_all_sigs();
1315 if(gec.gec_hist_flags & a_GO_HIST_ADD){
1316 char const *cc, *ca;
1318 cc = gec.gec_hist_cmd;
1319 ca = gec.gec_hist_args;
1320 if(cc != NULL && ca != NULL)
1321 cc = savecatsep(cc, ' ', ca);
1322 else if(ca != NULL)
1323 cc = ca;
1324 assert(cc != NULL);
1325 n_tty_addhist(cc, ((gec.gec_hist_flags & a_GO_HIST_GABBY) != 0));
1328 switch(n_pstate & n_PS_ERR_EXIT_MASK){
1329 case n_PS_ERR_XIT: n_psonce |= n_PSO_XIT; break;
1330 case n_PS_ERR_QUIT: n_psonce |= n_PSO_QUIT; break;
1331 default: break;
1333 if(n_psonce & n_PSO_EXIT_MASK)
1334 break;
1336 if(!rv)
1337 break;
1340 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS |
1341 (rv ? 0 : a_GO_CLEANUP_ERROR));
1343 if (gec.gec_line.s != NULL)
1344 n_free(gec.gec_line.s);
1346 rele_all_sigs();
1347 NYD_LEAVE;
1348 return rv;
1351 FL void
1352 n_go_input_clearerr(void){
1353 FILE *fp;
1354 NYD2_ENTER;
1356 fp = NULL;
1358 if(!(a_go_ctx->gc_flags & (a_GO_FORCE_EOF |
1359 a_GO_PIPE | a_GO_MACRO | a_GO_SPLICE)))
1360 fp = a_go_ctx->gc_file;
1362 if(fp != NULL){
1363 a_go_ctx->gc_flags &= ~a_GO_IS_EOF;
1364 clearerr(fp);
1366 NYD2_LEAVE;
1369 FL void
1370 n_go_input_force_eof(void){
1371 NYD2_ENTER;
1372 a_go_ctx->gc_flags |= a_GO_FORCE_EOF;
1373 NYD2_LEAVE;
1376 FL bool_t
1377 n_go_input_is_eof(void){
1378 bool_t rv;
1379 NYD2_ENTER;
1381 rv = ((a_go_ctx->gc_flags & a_GO_IS_EOF) != 0);
1382 NYD2_LEAVE;
1383 return rv;
1386 FL void
1387 n_go_input_inject(enum n_go_input_inject_flags giif, char const *buf,
1388 size_t len){
1389 NYD_ENTER;
1390 if(len == UIZ_MAX)
1391 len = strlen(buf);
1393 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat) -1 > len &&
1394 len > 0){
1395 struct a_go_input_inject *giip, **giipp;
1397 hold_all_sigs();
1399 giip = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_input_inject, gii_dat
1400 ) + 1 + len +1);
1401 giipp = &a_go_ctx->gc_inject;
1402 giip->gii_next = *giipp;
1403 giip->gii_commit = ((giif & n_GO_INPUT_INJECT_COMMIT) != 0);
1404 giip->gii_no_history = ((giif & n_GO_INPUT_INJECT_HISTORY) == 0);
1405 memcpy(&giip->gii_dat[0], buf, len);
1406 giip->gii_dat[giip->gii_len = len] = '\0';
1407 *giipp = giip;
1409 rele_all_sigs();
1411 NYD_LEAVE;
1414 FL int
1415 (n_go_input)(enum n_go_input_flags gif, char const *prompt, char **linebuf,
1416 size_t *linesize, char const *string, bool_t *histok_or_null
1417 n_MEMORY_DEBUG_ARGS){
1418 /* TODO readline: linebuf pool!; n_go_input should return si64_t */
1419 struct n_string xprompt;
1420 FILE *ifile;
1421 bool_t doprompt, dotty;
1422 char const *iftype;
1423 struct a_go_input_inject *giip;
1424 int nold, n;
1425 bool_t histok;
1426 NYD2_ENTER;
1428 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1429 hold_all_sigs();
1431 histok = FAL0;
1433 if(a_go_ctx->gc_flags & a_GO_FORCE_EOF){
1434 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1435 n = -1;
1436 goto jleave;
1439 if(gif & n_GO_INPUT_FORCE_STDIN)
1440 goto jforce_stdin;
1442 /* Special case macro mode: never need to prompt, lines have always been
1443 * unfolded already */
1444 if(a_go_ctx->gc_flags & a_GO_MACRO){
1445 if(*linebuf != NULL)
1446 n_free(*linebuf);
1448 /* Injection in progress? Don't care about the autocommit state here */
1449 if((giip = a_go_ctx->gc_inject) != NULL){
1450 a_go_ctx->gc_inject = giip->gii_next;
1452 /* Simply "reuse" allocation, copy string to front of it */
1453 jinject:
1454 *linesize = giip->gii_len;
1455 *linebuf = (char*)giip;
1456 memmove(*linebuf, giip->gii_dat, giip->gii_len +1);
1457 iftype = "INJECTION";
1458 }else{
1459 if((*linebuf = a_go_ctx->gc_lines[a_go_ctx->gc_loff]) == NULL){
1460 *linesize = 0;
1461 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1462 n = -1;
1463 goto jleave;
1466 ++a_go_ctx->gc_loff;
1467 *linesize = strlen(*linebuf);
1468 if(!(a_go_ctx->gc_flags & a_GO_MACRO_FREE_DATA))
1469 *linebuf = sbufdup(*linebuf, *linesize);
1471 iftype = (a_go_ctx->gc_flags & a_GO_MACRO_X_OPTION)
1472 ? "-X OPTION"
1473 : (a_go_ctx->gc_flags & a_GO_MACRO_CMD) ? "CMD" : "MACRO";
1475 n = (int)*linesize;
1476 n_pstate |= n_PS_READLINE_NL;
1477 goto jhave_dat;
1478 }else{
1479 /* Injection in progress? */
1480 struct a_go_input_inject **giipp;
1482 giipp = &a_go_ctx->gc_inject;
1484 if((giip = *giipp) != NULL){
1485 *giipp = giip->gii_next;
1487 if(giip->gii_commit){
1488 if(*linebuf != NULL)
1489 n_free(*linebuf);
1490 histok = !giip->gii_no_history;
1491 goto jinject; /* (above) */
1492 }else{
1493 string = savestrbuf(giip->gii_dat, giip->gii_len);
1494 n_free(giip);
1499 jforce_stdin:
1500 n_pstate &= ~n_PS_READLINE_NL;
1501 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1502 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1503 histok = (n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1504 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT);
1505 doprompt = !(gif & n_GO_INPUT_FORCE_STDIN) && histok;
1506 dotty = (doprompt && !ok_blook(line_editor_disable));
1507 if(!doprompt)
1508 gif |= n_GO_INPUT_PROMPT_NONE;
1509 else{
1510 if(!dotty)
1511 n_string_creat_auto(&xprompt);
1512 if(prompt == NULL)
1513 gif |= n_GO_INPUT_PROMPT_EVAL;
1516 /* Ensure stdout is flushed first anyway (partial lines, maybe?) */
1517 if(!dotty && (gif & n_GO_INPUT_PROMPT_NONE))
1518 fflush(n_stdout);
1520 if(gif & n_GO_INPUT_FORCE_STDIN){
1521 struct a_go_readctl_ctx *grcp;
1523 grcp = n_readctl_overlay;
1524 ifile = (grcp == NULL || grcp->grc_fp == NULL) ? n_stdin : grcp->grc_fp;
1525 }else
1526 ifile = a_go_ctx->gc_file;
1527 if(ifile == NULL){
1528 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1529 (a_go_ctx->gc_flags & a_GO_MACRO));
1530 ifile = n_stdin;
1533 for(nold = n = 0;;){
1534 if(dotty){
1535 assert(ifile == n_stdin);
1536 if(string != NULL && (n = (int)strlen(string)) > 0){
1537 if(*linesize > 0)
1538 *linesize += n +1;
1539 else
1540 *linesize = (size_t)n + LINESIZE +1;
1541 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1542 memcpy(*linebuf, string, (size_t)n +1);
1544 string = NULL;
1546 rele_all_sigs();
1548 n = (n_tty_readline)(gif, prompt, linebuf, linesize, n, histok_or_null
1549 n_MEMORY_DEBUG_ARGSCALL);
1551 hold_all_sigs();
1553 if(n < 0 && !ferror(ifile)) /* EOF never i guess */
1554 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1555 }else{
1556 if(!(gif & n_GO_INPUT_PROMPT_NONE))
1557 n_tty_create_prompt(&xprompt, prompt, gif);
1559 rele_all_sigs();
1561 if(!(gif & n_GO_INPUT_PROMPT_NONE) && xprompt.s_len > 0){
1562 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1563 fflush(n_stdout);
1566 n = (readline_restart)(ifile, linebuf, linesize, n
1567 n_MEMORY_DEBUG_ARGSCALL);
1569 hold_all_sigs();
1571 if(n < 0 && !ferror(ifile))
1572 a_go_ctx->gc_flags |= a_GO_IS_EOF;
1574 if(n > 0 && nold > 0){
1575 char const *cp;
1576 int i;
1578 i = 0;
1579 cp = &(*linebuf)[nold];
1580 while(spacechar(*cp) && n - i >= nold)
1581 ++cp, ++i;
1582 if(i > 0){
1583 memmove(&(*linebuf)[nold], cp, n - nold - i);
1584 n -= i;
1585 (*linebuf)[n] = '\0';
1590 if(n <= 0)
1591 break;
1593 /* POSIX says:
1594 * An unquoted <backslash> at the end of a command line shall
1595 * be discarded and the next line shall continue the command */
1596 if(!(gif & n_GO_INPUT_NL_ESC) || (*linebuf)[n - 1] != '\\')
1597 break;
1599 /* Definitely outside of quotes, thus the quoting rules are so that an
1600 * uneven number of successive reverse solidus at EOL is a continuation */
1601 if(n > 1){
1602 size_t i, j;
1604 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1605 if((*linebuf)[i] != '\\')
1606 break;
1607 if(!(j & 1))
1608 break;
1610 (*linebuf)[nold = --n] = '\0';
1611 gif |= n_GO_INPUT_NL_FOLLOW;
1614 if(n < 0)
1615 goto jleave;
1616 if(dotty)
1617 n_pstate |= n_PS_READLINE_NL;
1618 (*linebuf)[*linesize = n] = '\0';
1620 jhave_dat:
1621 if(n_poption & n_PO_D_VV)
1622 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1623 jleave:
1624 if (n_pstate & n_PS_PSTATE_PENDMASK)
1625 a_go_update_pstate();
1627 /* TODO We need to special case a_GO_SPLICE, since that is not managed by us
1628 * TODO but only established from the outside and we need to drop this
1629 * TODO overlay context somehow */
1630 if(n < 0 && (a_go_ctx->gc_flags & a_GO_SPLICE))
1631 a_go_cleanup(a_GO_CLEANUP_TEARDOWN | a_GO_CLEANUP_HOLDALLSIGS);
1633 if(histok_or_null != NULL && !histok)
1634 *histok_or_null = FAL0;
1636 if(!(gif & n_GO_INPUT_HOLDALLSIGS))
1637 rele_all_sigs();
1638 NYD2_LEAVE;
1639 return n;
1642 FL char *
1643 n_go_input_cp(enum n_go_input_flags gif, char const *prompt,
1644 char const *string){
1645 struct n_sigman sm;
1646 bool_t histadd;
1647 size_t linesize;
1648 char *linebuf, * volatile rv;
1649 int n;
1650 NYD2_ENTER;
1652 linesize = 0;
1653 linebuf = NULL;
1654 rv = NULL;
1656 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL){
1657 case 0:
1658 break;
1659 default:
1660 goto jleave;
1663 histadd = TRU1;
1664 n = n_go_input(gif, prompt, &linebuf, &linesize, string, &histadd);
1665 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1666 (gif & n_GO_INPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE) &&
1667 histadd)
1668 n_tty_addhist(rv, ((gif & n_GO_INPUT_HIST_GABBY) != 0));
1670 n_sigman_cleanup_ping(&sm);
1671 jleave:
1672 if(linebuf != NULL)
1673 n_free(linebuf);
1674 NYD2_LEAVE;
1675 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
1676 return rv;
1679 FL bool_t
1680 n_go_load(char const *name){
1681 struct a_go_ctx *gcp;
1682 size_t i;
1683 FILE *fip;
1684 bool_t rv;
1685 NYD_ENTER;
1687 rv = TRU1;
1689 if(name == NULL || *name == '\0')
1690 goto jleave;
1691 else if((fip = Fopen(name, "r")) == NULL){
1692 if(n_poption & n_PO_D_V)
1693 n_err(_("No such file to load: %s\n"), n_shexp_quote_cp(name, FAL0));
1694 goto jleave;
1697 i = strlen(name) +1;
1698 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + i);
1699 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1701 gcp->gc_file = fip;
1702 gcp->gc_flags = a_GO_FREE | a_GO_FILE;
1703 memcpy(gcp->gc_name, name, i);
1705 if(n_poption & n_PO_D_V)
1706 n_err(_("Loading %s\n"), n_shexp_quote_cp(gcp->gc_name, FAL0));
1707 rv = a_go_load(gcp);
1708 jleave:
1709 NYD_LEAVE;
1710 return rv;
1713 FL bool_t
1714 n_go_Xargs(char const **lines, size_t cnt){
1715 static char const name[] = "-X";
1717 union{
1718 bool_t rv;
1719 ui64_t align;
1720 char uf[n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) + sizeof(name)];
1721 } b;
1722 char const *srcp, *xsrcp;
1723 char *cp;
1724 size_t imax, i, len;
1725 struct a_go_ctx *gcp;
1726 NYD_ENTER;
1728 gcp = (void*)b.uf;
1729 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1731 gcp->gc_flags = a_GO_MACRO | a_GO_MACRO_X_OPTION |
1732 a_GO_SUPER_MACRO | a_GO_MACRO_FREE_DATA;
1733 memcpy(gcp->gc_name, name, sizeof name);
1735 /* The problem being that we want to support reverse solidus newline
1736 * escaping also within multiline -X, i.e., POSIX says:
1737 * An unquoted <backslash> at the end of a command line shall
1738 * be discarded and the next line shall continue the command
1739 * Therefore instead of "gcp->gc_lines = n_UNCONST(lines)", duplicate the
1740 * entire lines array and set _MACRO_FREE_DATA */
1741 imax = cnt + 1;
1742 gcp->gc_lines = n_alloc(sizeof(*gcp->gc_lines) * imax);
1744 /* For each of the input lines.. */
1745 for(i = len = 0, cp = NULL; cnt > 0;){
1746 bool_t keep;
1747 size_t j;
1749 if((j = strlen(srcp = *lines)) == 0){
1750 ++lines, --cnt;
1751 continue;
1754 /* Separate one line from a possible multiline input string */
1755 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1756 *lines = &xsrcp[1];
1757 j = PTR2SIZE(xsrcp - srcp);
1758 }else
1759 ++lines, --cnt;
1761 /* The (separated) string may itself indicate soft newline escaping */
1762 if((keep = (srcp[j - 1] == '\\'))){
1763 size_t xj, xk;
1765 /* Need an uneven number of reverse solidus */
1766 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1767 if(srcp[xj] != '\\')
1768 break;
1769 if(xk & 1)
1770 --j;
1771 else
1772 keep = FAL0;
1775 /* Strip any leading WS from follow lines, then */
1776 if(cp != NULL)
1777 while(j > 0 && spacechar(*srcp))
1778 ++srcp, --j;
1780 if(j > 0){
1781 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1782 imax += 4;
1783 gcp->gc_lines = n_realloc(gcp->gc_lines, sizeof(*gcp->gc_lines) *
1784 imax);
1786 gcp->gc_lines[i] = cp = n_realloc(cp, len + j +1);
1787 memcpy(&cp[len], srcp, j);
1788 cp[len += j] = '\0';
1790 if(!keep)
1791 ++i;
1793 if(!keep)
1794 cp = NULL, len = 0;
1796 if(cp != NULL){
1797 assert(i + 1 < imax);
1798 gcp->gc_lines[i++] = cp;
1800 gcp->gc_lines[i] = NULL;
1802 b.rv = a_go_load(gcp);
1803 NYD_LEAVE;
1804 return b.rv;
1807 FL int
1808 c_source(void *v){
1809 int rv;
1810 NYD_ENTER;
1812 rv = (a_go_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1813 NYD_LEAVE;
1814 return rv;
1817 FL int
1818 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1819 int rv;
1820 NYD_ENTER;
1822 rv = (a_go_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
1823 NYD_LEAVE;
1824 return rv;
1827 FL bool_t
1828 n_go_macro(enum n_go_input_flags gif, char const *name, char **lines,
1829 void (*on_finalize)(void*), void *finalize_arg){
1830 struct a_go_ctx *gcp;
1831 size_t i;
1832 int rv;
1833 sigset_t osigmask;
1834 NYD_ENTER;
1836 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1838 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1839 (i = strlen(name) +1));
1840 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1842 hold_all_sigs();
1844 gcp->gc_outer = a_go_ctx;
1845 gcp->gc_osigmask = osigmask;
1846 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_FREE_DATA |
1847 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1848 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0) |
1849 ((gif & n_GO_INPUT_NO_XCALL) ? a_GO_XCALL_IS_CALL : 0);
1850 gcp->gc_lines = lines;
1851 gcp->gc_on_finalize = on_finalize;
1852 gcp->gc_finalize_arg = finalize_arg;
1853 memcpy(gcp->gc_name, name, i);
1855 a_go_ctx = gcp;
1856 n_go_data = &gcp->gc_data;
1857 n_pstate |= n_PS_ROBOT;
1858 rv = a_go_event_loop(gcp, gif);
1860 /* Shall this enter a `xcall' stack avoidance optimization (loop)? */
1861 if(a_go_xcall != NULL){
1862 void *vp;
1863 struct n_cmd_arg_ctx *cacp;
1865 if(a_go_xcall == (void*)-1)
1866 a_go_xcall = NULL;
1867 else if(((void const*)(cacp = a_go_xcall)->cac_indat) == gcp){
1868 /* Indicate that "our" (ex-) parent now hosts xcall optimization */
1869 a_go_ctx->gc_flags |= a_GO_XCALL_LOOP;
1870 while(a_go_xcall != NULL){
1871 hold_all_sigs();
1873 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_ERROR;
1875 vp = a_go_xcall;
1876 a_go_xcall = NULL;
1877 cacp = n_cmd_arg_restore_from_heap(vp);
1878 n_free(vp);
1880 rele_all_sigs();
1882 (void)c_call(cacp);
1884 rv = ((a_go_ctx->gc_flags & a_GO_XCALL_LOOP_ERROR) == 0);
1885 a_go_ctx->gc_flags &= ~a_GO_XCALL_LOOP_MASK;
1888 NYD_LEAVE;
1889 return rv;
1892 FL bool_t
1893 n_go_command(enum n_go_input_flags gif, char const *cmd){
1894 struct a_go_ctx *gcp;
1895 bool_t rv;
1896 size_t i, ial;
1897 sigset_t osigmask;
1898 NYD_ENTER;
1900 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1902 i = strlen(cmd) +1;
1903 ial = n_ALIGN(i);
1904 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1905 ial + 2*sizeof(char*));
1906 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1908 hold_all_sigs();
1910 gcp->gc_outer = a_go_ctx;
1911 gcp->gc_osigmask = osigmask;
1912 gcp->gc_flags = a_GO_FREE | a_GO_MACRO | a_GO_MACRO_CMD |
1913 ((!(a_go_ctx->gc_flags & a_GO_TYPE_MASK) ||
1914 (a_go_ctx->gc_flags & a_GO_SUPER_MACRO)) ? a_GO_SUPER_MACRO : 0);
1915 gcp->gc_lines = (void*)&gcp->gc_name[ial];
1916 memcpy(gcp->gc_lines[0] = &gcp->gc_name[0], cmd, i);
1917 gcp->gc_lines[1] = NULL;
1919 a_go_ctx = gcp;
1920 n_go_data = &gcp->gc_data;
1921 n_pstate |= n_PS_ROBOT;
1922 rv = a_go_event_loop(gcp, gif);
1923 NYD_LEAVE;
1924 return rv;
1927 FL void
1928 n_go_splice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
1929 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
1930 struct a_go_ctx *gcp;
1931 size_t i;
1932 sigset_t osigmask;
1933 NYD_ENTER;
1935 sigprocmask(SIG_BLOCK, NULL, &osigmask);
1937 gcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name) +
1938 (i = strlen(cmd) +1));
1939 memset(gcp, 0, n_VSTRUCT_SIZEOF(struct a_go_ctx, gc_name));
1941 hold_all_sigs();
1943 gcp->gc_outer = a_go_ctx;
1944 gcp->gc_osigmask = osigmask;
1945 gcp->gc_file = new_stdin;
1946 gcp->gc_flags = a_GO_FREE | a_GO_SPLICE | a_GO_DATACTX_INHERITED;
1947 gcp->gc_on_finalize = on_finalize;
1948 gcp->gc_finalize_arg = finalize_arg;
1949 gcp->gc_splice_stdin = n_stdin;
1950 gcp->gc_splice_stdout = n_stdout;
1951 gcp->gc_splice_psonce = n_psonce;
1952 memcpy(gcp->gc_name, cmd, i);
1954 n_stdin = new_stdin;
1955 n_stdout = new_stdout;
1956 n_psonce = new_psonce;
1957 a_go_ctx = gcp;
1958 /* Do NOT touch n_go_data! */
1959 n_pstate |= n_PS_ROBOT;
1961 rele_all_sigs();
1962 NYD_LEAVE;
1965 FL void
1966 n_go_splice_hack_remove_after_jump(void){
1967 a_go_cleanup(a_GO_CLEANUP_TEARDOWN);
1970 FL bool_t
1971 n_go_may_yield_control(void){ /* TODO this is a terrible hack */
1972 struct a_go_ctx *gcp;
1973 bool_t rv;
1974 NYD2_ENTER;
1976 rv = FAL0;
1978 /* Only when startup completed */
1979 if(!(n_psonce & n_PSO_STARTED))
1980 goto jleave;
1981 /* Only interactive or batch mode (assuming that is ok) */
1982 if(!(n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_BATCH_FLAG))
1983 goto jleave;
1985 /* Not when running any hook */
1986 if(n_pstate & n_PS_HOOK_MASK)
1987 goto jleave;
1989 /* Traverse up the stack:
1990 * . not when controlled by a child process
1991 * TODO . not when there are pipes involved, we neither handle job control,
1992 * TODO nor process groups, that is, controlling terminal acceptably
1993 * . not when sourcing a file */
1994 for(gcp = a_go_ctx; gcp != NULL; gcp = gcp->gc_outer){
1995 if(gcp->gc_flags & (a_GO_PIPE | a_GO_FILE | a_GO_SPLICE))
1996 goto jleave;
1999 rv = TRU1;
2000 jleave:
2001 NYD2_LEAVE;
2002 return rv;
2005 FL int
2006 c_eval(void *vp){
2007 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
2008 * TODO ARGV with shell rules, but if that is not possible then simply
2009 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
2010 struct a_go_eval_ctx gec;
2011 struct n_string s_b, *sp;
2012 size_t i, j;
2013 char const **argv, *cp;
2014 NYD_ENTER;
2016 argv = vp;
2018 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
2019 j += strlen(cp);
2021 sp = n_string_creat_auto(&s_b);
2022 sp = n_string_reserve(sp, j);
2024 for(i = 0; (cp = argv[i]) != NULL; ++i){
2025 if(i > 0)
2026 sp = n_string_push_c(sp, ' ');
2027 sp = n_string_push_cp(sp, cp);
2030 memset(&gec, 0, sizeof gec);
2031 gec.gec_line.s = n_string_cp(sp);
2032 gec.gec_line.l = sp->s_len;
2033 if(n_poption & n_PO_D_VV)
2034 n_err(_("EVAL %" PRIuZ " bytes <%s>\n"), gec.gec_line.l, gec.gec_line.s);
2035 (void)/* XXX */a_go_evaluate(&gec);
2036 NYD_LEAVE;
2037 return (a_go_xcall != NULL ? 0 : n_pstate_ex_no);
2040 FL int
2041 c_xcall(void *vp){
2042 int rv;
2043 struct a_go_ctx *gcp;
2044 NYD2_ENTER;
2046 /* The context can only be a macro context, except that possibly a single
2047 * level of `eval' (TODO: yet) was used to double-expand our arguments */
2048 if((gcp = a_go_ctx)->gc_flags & a_GO_MACRO_CMD)
2049 gcp = gcp->gc_outer;
2050 if((gcp->gc_flags & (a_GO_MACRO | a_GO_MACRO_X_OPTION | a_GO_MACRO_CMD)
2051 ) != a_GO_MACRO){
2052 if(n_poption & n_PO_D_V_VV)
2053 n_err(_("`xcall': can only be used inside a macro, using `call'\n"));
2054 rv = c_call(vp);
2055 goto jleave;
2058 /* Try to roll up the stack as much as possible.
2059 * See a_GO_XCALL_LOOP flag description for more */
2060 if(!(gcp->gc_flags & a_GO_XCALL_IS_CALL) && gcp->gc_outer != NULL){
2061 if(gcp->gc_outer->gc_flags & a_GO_XCALL_LOOP)
2062 gcp = gcp->gc_outer;
2063 }else{
2064 /* Otherwise this macro is "invoked from the top level", in which case we
2065 * silently act as if we were `call'... */
2066 rv = c_call(vp);
2067 /* ...which means we must ensure the rest of the macro that was us
2068 * doesn't become evaluated! */
2069 a_go_xcall = (void*)-1;
2070 goto jleave;
2073 /* C99 */{
2074 struct n_cmd_arg_ctx *cacp;
2076 cacp = n_cmd_arg_save_to_heap(vp);
2077 cacp->cac_indat = (char*)gcp;
2078 a_go_xcall = cacp;
2080 rv = 0;
2081 jleave:
2082 NYD2_LEAVE;
2083 return rv;
2086 FL int
2087 c_exit(void *vp){
2088 char const **argv;
2089 NYD_ENTER;
2091 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2092 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2093 ) != n_IDEC_STATE_CONSUMED)
2094 n_exit_status |= n_EXIT_ERR;
2096 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2097 fflush(NULL);
2098 _exit(n_exit_status);
2099 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2100 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2101 n_psonce |= n_PSO_XIT;
2102 NYD_LEAVE;
2103 return 0;
2106 FL int
2107 c_quit(void *vp){
2108 char const **argv;
2109 NYD_ENTER;
2111 if(*(argv = vp) != NULL && (n_idec_si32_cp(&n_exit_status, *argv, 0, NULL) &
2112 (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2113 ) != n_IDEC_STATE_CONSUMED)
2114 n_exit_status |= n_EXIT_ERR;
2116 if(n_pstate & n_PS_COMPOSE_FORKHOOK){ /* TODO sic */
2117 fflush(NULL);
2118 _exit(n_exit_status);
2119 }else if(n_pstate & n_PS_COMPOSE_MODE) /* XXX really.. */
2120 n_err(_("`exit' delayed until compose mode is left\n")); /* XXX ..log? */
2121 n_psonce |= n_PSO_QUIT;
2122 NYD_LEAVE;
2123 return 0;
2126 FL int
2127 c_readctl(void *vp){
2128 /* TODO We would need OnForkEvent and then simply remove some internal
2129 * TODO management; we don't have this, therefore we need global
2130 * TODO n_readctl_overlay to be accessible via =NULL, and to make that
2131 * TODO work in turn we need an instance for default STDIN! Sigh. */
2132 static ui8_t a_buf[n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name)+1 +1];
2133 static struct a_go_readctl_ctx *a_stdin;
2135 struct a_go_readctl_ctx *grcp;
2136 char const *emsg;
2137 enum{
2138 a_NONE = 0,
2139 a_ERR = 1u<<0,
2140 a_SET = 1u<<1,
2141 a_CREATE = 1u<<2,
2142 a_REMOVE = 1u<<3
2143 } f;
2144 struct n_cmd_arg *cap;
2145 struct n_cmd_arg_ctx *cacp;
2146 NYD_ENTER;
2148 if(a_stdin == NULL){
2149 a_stdin = (struct a_go_readctl_ctx*)a_buf;
2150 a_stdin->grc_name[0] = '-';
2151 n_readctl_overlay = a_stdin;
2154 n_pstate_err_no = n_ERR_NONE;
2155 cacp = vp;
2156 cap = cacp->cac_arg;
2158 if(cacp->cac_no == 0 || is_asccaseprefix(cap->ca_arg.ca_str.s, "show"))
2159 goto jshow;
2160 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "set"))
2161 f = a_SET;
2162 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "create"))
2163 f = a_CREATE;
2164 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "remove"))
2165 f = a_REMOVE;
2166 else{
2167 emsg = N_("`readctl': invalid subcommand: %s\n");
2168 goto jeinval_quote;
2171 if(cacp->cac_no == 1){ /* TODO better option parser <> subcommand */
2172 n_err(_("`readctl': %s: requires argument\n"), cap->ca_arg.ca_str.s);
2173 goto jeinval;
2175 cap = cap->ca_next;
2177 /* - is special TODO unfortunately also regarding storage */
2178 if(cap->ca_arg.ca_str.l == 1 && *cap->ca_arg.ca_str.s == '-'){
2179 if(f & (a_CREATE | a_REMOVE)){
2180 n_err(_("`readctl': cannot create nor remove -\n"));
2181 goto jeinval;
2183 n_readctl_overlay = a_stdin;
2184 goto jleave;
2187 /* Try to find a yet existing instance */
2188 if((grcp = n_readctl_overlay) != NULL){
2189 for(; grcp != NULL; grcp = grcp->grc_next)
2190 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2191 goto jfound;
2192 for(grcp = n_readctl_overlay; (grcp = grcp->grc_last) != NULL;)
2193 if(!strcmp(grcp->grc_name, cap->ca_arg.ca_str.s))
2194 goto jfound;
2197 if(f & (a_SET | a_REMOVE)){
2198 emsg = N_("`readctl': no such channel: %s\n");
2199 goto jeinval_quote;
2202 jfound:
2203 if(f & a_SET)
2204 n_readctl_overlay = grcp;
2205 else if(f & a_REMOVE){
2206 if(n_readctl_overlay == grcp)
2207 n_readctl_overlay = a_stdin;
2209 if(grcp->grc_last != NULL)
2210 grcp->grc_last->grc_next = grcp->grc_next;
2211 if(grcp->grc_next != NULL)
2212 grcp->grc_next->grc_last = grcp->grc_last;
2213 fclose(grcp->grc_fp);
2214 n_free(grcp);
2215 }else{
2216 FILE *fp;
2217 size_t elen;
2218 si32_t fd;
2220 if(grcp != NULL){
2221 n_err(_("`readctl': channel already exists: %s\n"), /* TODO reopen */
2222 n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2223 n_pstate_err_no = n_ERR_EXIST;
2224 f = a_ERR;
2225 goto jleave;
2228 if((n_idec_si32_cp(&fd, cap->ca_arg.ca_str.s, 0, NULL
2229 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2230 ) != n_IDEC_STATE_CONSUMED){
2231 if((emsg = fexpand(cap->ca_arg.ca_str.s, FEXP_LOCAL | FEXP_NVAR)
2232 ) == NULL){
2233 emsg = N_("`readctl': cannot expand filename %s\n");
2234 goto jeinval_quote;
2236 fd = -1;
2237 elen = strlen(emsg);
2238 fp = safe_fopen(emsg, "r", NULL);
2239 }else if(fd == STDIN_FILENO || fd == STDOUT_FILENO ||
2240 fd == STDERR_FILENO){
2241 n_err(_("`readctl': create: standard descriptors are not allowed\n"));
2242 goto jeinval;
2243 }else{
2244 /* xxx Avoid */
2245 _CLOEXEC_SET(fd);
2246 emsg = NULL;
2247 elen = 0;
2248 fp = fdopen(fd, "r");
2251 if(fp != NULL){
2252 size_t i;
2254 if((i = UIZ_MAX - elen) <= cap->ca_arg.ca_str.l ||
2255 (i -= cap->ca_arg.ca_str.l) <=
2256 n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +2){
2257 n_err(_("`readctl': failed to create storage for %s\n"),
2258 cap->ca_arg.ca_str.s);
2259 n_pstate_err_no = n_ERR_OVERFLOW;
2260 f = a_ERR;
2261 goto jleave;
2264 grcp = n_alloc(n_VSTRUCT_SIZEOF(struct a_go_readctl_ctx, grc_name) +
2265 cap->ca_arg.ca_str.l +1 + elen +1);
2266 grcp->grc_last = NULL;
2267 if((grcp->grc_next = n_readctl_overlay) != NULL)
2268 grcp->grc_next->grc_last = grcp;
2269 n_readctl_overlay = grcp;
2270 grcp->grc_fp = fp;
2271 grcp->grc_fd = fd;
2272 memcpy(grcp->grc_name, cap->ca_arg.ca_str.s, cap->ca_arg.ca_str.l +1);
2273 if(elen == 0)
2274 grcp->grc_expand = NULL;
2275 else{
2276 char *cp;
2278 grcp->grc_expand = cp = &grcp->grc_name[cap->ca_arg.ca_str.l +1];
2279 memcpy(cp, emsg, ++elen);
2281 }else{
2282 emsg = N_("`readctl': failed to create file for %s\n");
2283 goto jeinval_quote;
2287 jleave:
2288 NYD_LEAVE;
2289 return (f & a_ERR) ? 1 : 0;
2290 jeinval_quote:
2291 n_err(V_(emsg), n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
2292 jeinval:
2293 n_pstate_err_no = n_ERR_INVAL;
2294 f = a_ERR;
2295 goto jleave;
2297 jshow:
2298 if((grcp = n_readctl_overlay) == NULL)
2299 fprintf(n_stdout, _("`readctl': no channels registered\n"));
2300 else{
2301 while(grcp->grc_last != NULL)
2302 grcp = grcp->grc_last;
2304 fprintf(n_stdout, _("`readctl': registered channels:\n"));
2305 for(; grcp != NULL; grcp = grcp->grc_next)
2306 fprintf(n_stdout, _("%c%s %s%s%s%s\n"),
2307 (grcp == n_readctl_overlay ? '*' : ' '),
2308 (grcp->grc_fd != -1 ? _("descriptor") : _("name")),
2309 n_shexp_quote_cp(grcp->grc_name, FAL0),
2310 (grcp->grc_expand != NULL ? " (" : n_empty),
2311 (grcp->grc_expand != NULL ? grcp->grc_expand : n_empty),
2312 (grcp->grc_expand != NULL ? ")" : n_empty));
2314 f = a_NONE;
2315 goto jleave;
2318 /* s-it-mode */