Implement `xcall' stack-avoidance optimization
[s-mailx.git] / accmacvar.c
blob121922a4bd7781afc4371cbabb1af2dd3c687458
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Account, macro and variable handling.
3 *@ HOWTO add a new non-dynamic boolean or value option:
4 *@ - add an entry to nail.h:enum okeys
5 *@ - run mk-okey-map.pl
6 *@ - update the manual!
7 *@ TODO . should be recursive environment based.
8 *@ TODO Otherwise, the `localopts' should be an attribute of the lex-input.c
9 *@ TODO command context, so that it belongs to the execution context
10 *@ TODO we are running in, instead of being global data. See, e.g.,
11 *@ TODO the a_LEX_SPLICE comment in lex-input.c.
12 *@ TODO . once we can have non-fatal !0 returns for commands, we should
13 *@ TODO return error if "(environ)? unset" goes for non-existent.
15 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
16 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
19 * Copyright (c) 1980, 1993
20 * The Regents of the University of California. All rights reserved.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. Neither the name of the University nor the names of its contributors
31 * may be used to endorse or promote products derived from this software
32 * without specific prior written permission.
34 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44 * SUCH DAMAGE.
46 #undef n_FILE
47 #define n_FILE accmacvar
49 #ifndef HAVE_AMALGAMATION
50 # include "nail.h"
51 #endif
53 #if !defined HAVE_SETENV && !defined HAVE_PUTENV
54 # error Exactly one of HAVE_SETENV and HAVE_PUTENV
55 #endif
57 /* Special "pseudo macro" that stabs you from the back */
58 #define a_AMV_MACKY_MACK ((struct a_amv_mac*)-1)
60 /* Note: changing the hash function must be reflected in mk-okey-map.pl */
61 #define a_AMV_PRIME HSHSIZE
62 #define a_AMV_NAME2HASH(N) torek_hash(N)
63 #define a_AMV_HASH2PRIME(H) ((H) % a_AMV_PRIME)
65 enum a_amv_mac_flags{
66 a_AMV_MF_NONE = 0,
67 a_AMV_MF_ACCOUNT = 1<<0, /* This macro is an `account' */
68 a_AMV_MF_TYPE_MASK = a_AMV_MF_ACCOUNT,
69 a_AMV_MF_UNDEF = 1<<1, /* Unlink after lookup */
70 a_AMV_MF_DELETE = 1<<7, /* Delete in progress, free once refcnt==0 */
71 a_AMV_MF__MAX = 0xFF
74 /* mk-okey-map.pl ensures that _VIRT implies _RDONLY and _NODEL, and that
75 * _IMPORT implies _ENV; it doesn't verify anything... */
76 enum a_amv_var_flags{
77 a_AMV_VF_NONE = 0,
78 a_AMV_VF_BOOL = 1<<0, /* ok_b_* */
79 a_AMV_VF_VIRT = 1<<1, /* "Stateless" automatic variable */
80 a_AMV_VF_NOLOPTS = 1<<2, /* May not be tracked by `localopts' */
81 a_AMV_VF_RDONLY = 1<<3, /* May not be set by user */
82 a_AMV_VF_NODEL = 1<<4, /* May not be deleted */
83 a_AMV_VF_NOTEMPTY = 1<<5, /* May not be assigned an empty value */
84 a_AMV_VF_NOCNTRLS = 1<<6, /* Value may not contain control characters */
85 a_AMV_VF_NUM = 1<<7, /* Value must be a 32-bit number */
86 a_AMV_VF_POSNUM = 1<<8, /* Value must be positive 32-bit number */
87 a_AMV_VF_LOWER = 1<<9, /* Values will be stored in a lowercase version */
88 a_AMV_VF_VIP = 1<<10, /* Wants _var_check_vips() evaluation */
89 a_AMV_VF_IMPORT = 1<<11, /* Import ONLY from environ (pre n_PSO_STARTED) */
90 a_AMV_VF_ENV = 1<<12, /* Update environment on change */
91 a_AMV_VF_I3VAL = 1<<13, /* Has an initial value */
92 a_AMV_VF_DEFVAL = 1<<14, /* Has a default value */
93 a_AMV_VF_LINKED = 1<<15, /* `environ' linked */
94 a_AMV_VF__MASK = (1<<(15+1)) - 1
97 /* We support some special parameter names for one-letter variable names;
98 * note these have counterparts in the code that manages shell expansion!
99 * Macro-local variables are solely backed by n_var_vlook(), and besides there
100 * is only a_amv_var_revlookup() which knows about them.
101 * The ARGV $[1-9][0-9]* variables are also special, but they are special ;] */
102 enum a_amv_var_special_category{
103 a_AMV_VSC_NONE, /* Normal variable, no special treatment */
104 a_AMV_VSC_GLOBAL, /* ${[?!]} are specially mapped, but global */
105 a_AMV_VSC_MULTIPLEX, /* ${^.*} circumflex accent multiplexer */
106 a_AMV_VSC_MAC, /* ${[*@#]} macro argument access */
107 a_AMV_VSC_MAC_ARGV /* ${[1-9][0-9]*} macro ARGV access */
110 enum a_amv_var_special_type{
111 /* _VSC_GLOBAL */
112 a_AMV_VST_QM, /* ? */
113 a_AMV_VST_EM, /* ! */
114 /* _VSC_MULTIPLEX */
115 /* This is special in that it is a multiplex indicator, the ^ is followed by
116 * a normal variable */
117 a_AMV_VST_CACC, /* ^ (circumflex accent) */
118 /* _VSC_MAC */
119 a_AMV_VST_STAR, /* * */
120 a_AMV_VST_AT, /* @ */
121 a_AMV_VST_NOSIGN /* # */
124 enum a_amv_var_vip_mode{
125 a_AMV_VIP_SET_PRE,
126 a_AMV_VIP_SET_POST,
127 a_AMV_VIP_CLEAR
130 struct a_amv_mac{
131 struct a_amv_mac *am_next;
132 ui32_t am_maxlen; /* of any line in .am_line_dat */
133 ui32_t am_line_cnt; /* of *.am_line_dat (but NULL terminated) */
134 struct a_amv_mac_line **am_line_dat; /* TODO use deque? */
135 struct a_amv_var *am_lopts; /* `localopts' unroll list */
136 ui32_t am_refcnt; /* 0-based for `un{account,define}' purposes */
137 ui8_t am_flags; /* enum a_amv_mac_flags */
138 char am_name[n_VFIELD_SIZE(3)]; /* of this macro */
140 n_CTA(a_AMV_MF__MAX <= UI8_MAX, "Enumeration excesses storage datatype");
142 struct a_amv_mac_line{
143 ui32_t aml_len;
144 ui32_t aml_prespc; /* Number of leading SPC, for display purposes */
145 char aml_dat[n_VFIELD_SIZE(0)];
148 struct a_amv_mac_call_args{
149 char const *amca_name; /* For MACKY_MACK, this is *0*! */
150 struct a_amv_mac *amca_amp; /* "const", but for am_refcnt */
151 struct a_amv_var **amca_unroller;
152 void (*amca_hook_pre)(void *);
153 void *amca_hook_arg;
154 bool_t amca_lopts_on;
155 bool_t amca_ps_hook_mask;
156 ui8_t amca__pad[4];
157 ui16_t amca_argc; /* Max is SI16_MAX */
158 char const **amca_argv;
161 struct a_amv_lostack{
162 struct a_amv_lostack *as_global_saved; /* Saved global XXX due to jump */
163 struct a_amv_mac_call_args *as_amcap;
164 struct a_amv_lostack *as_up; /* Outer context */
165 struct a_amv_var *as_lopts;
166 bool_t as_unroll; /* Unrolling enabled? */
167 ui8_t avs__pad[7];
170 struct a_amv_var{
171 struct a_amv_var *av_link;
172 char *av_value;
173 #ifdef HAVE_PUTENV
174 char *av_env; /* Actively managed putenv(3) memory */
175 #endif
176 ui16_t av_flags; /* enum a_amv_var_flags */
177 char av_name[n_VFIELD_SIZE(6)];
179 n_CTA(a_AMV_VF__MASK <= UI16_MAX, "Enumeration excesses storage datatype");
181 struct a_amv_var_map{
182 ui32_t avm_hash;
183 ui16_t avm_keyoff;
184 ui16_t avm_flags; /* enum a_amv_var_flags */
186 n_CTA(a_AMV_VF__MASK <= UI16_MAX, "Enumeration excesses storage datatype");
188 struct a_amv_var_virt{
189 ui32_t avv_okey;
190 ui8_t avv__dummy[4];
191 struct a_amv_var const *avv_var;
194 struct a_amv_var_defval{
195 ui32_t avdv_okey;
196 ui8_t avdv__pad[4];
197 char const *avdv_value; /* Only for !BOOL (otherwise plain existence) */
200 struct a_amv_var_carrier{
201 char const *avc_name;
202 ui32_t avc_hash;
203 ui32_t avc_prime;
204 struct a_amv_var *avc_var;
205 struct a_amv_var_map const *avc_map;
206 enum okeys avc_okey;
207 ui8_t avc__pad[1];
208 ui8_t avc_special_cat;
209 /* Numerical parameter name if .avc_special_cat=a_AMV_VSC_MAC_ARGV,
210 * otherwise a enum a_amv_var_special_type */
211 ui16_t avc_special_prop;
214 /* Include the constant mk-okey-map.pl output, and the generated version data */
215 #include "gen-version.h"
216 #include "gen-okeys.h"
218 /* The currently active account */
219 static struct a_amv_mac *a_amv_acc_curr;
221 static struct a_amv_mac *a_amv_macs[a_AMV_PRIME]; /* TODO dynamically spaced */
223 /* Unroll list of currently running macro stack */
224 static struct a_amv_lostack *a_amv_lopts;
226 static struct a_amv_var *a_amv_vars[a_AMV_PRIME]; /* TODO dynamically spaced */
228 /* TODO We really deserve localopts support for *folder-hook*s, so hack it in
229 * TODO today via a static lostack, it should be a field in mailbox, once that
230 * TODO is a real multi-instance object */
231 static struct a_amv_var *a_amv_folder_hook_lopts;
233 /* TODO Rather ditto (except for storage -> cmd_ctx), compose hooks */
234 static struct a_amv_var *a_amv_compose_lopts;
236 /* Lookup for macros/accounts: if newamp is not NULL it will be linked in the
237 * map, if _MF_UNDEF is set a possibly existing entry will be removed (first).
238 * Returns NULL if a lookup failed, or if newamp was set, the found entry in
239 * plain lookup cases or when _UNDEF was performed on a currently active entry
240 * (the entry will have been unlinked, and the _MF_DELETE will be honoured once
241 * the reference count reaches 0), and (*)-1 if an _UNDEF was performed */
242 static struct a_amv_mac *a_amv_mac_lookup(char const *name,
243 struct a_amv_mac *newamp, enum a_amv_mac_flags amf);
245 /* `call', `call_if' */
246 static int a_amv_mac_call(void *v, bool_t silent_nexist);
248 /* Execute a macro; amcap must reside in LOFI memory */
249 static bool_t a_amv_mac_exec(struct a_amv_mac_call_args *amcap);
251 static void a_amv_mac__finalize(void *vp);
253 /* User display helpers */
254 static bool_t a_amv_mac_show(enum a_amv_mac_flags amf);
256 /* _def() returns error for faulty definitions and already existing * names,
257 * _undef() returns error if a named thing doesn't exist */
258 static bool_t a_amv_mac_def(char const *name, enum a_amv_mac_flags amf);
259 static bool_t a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf);
261 /* */
262 static void a_amv_mac_free(struct a_amv_mac *amp);
264 /* Update replay-log */
265 static void a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
266 struct a_amv_var *oavp);
267 static void a_amv_lopts_unroll(struct a_amv_var **avpp);
269 /* Special cased value string allocation */
270 static char *a_amv_var_copy(char const *str);
271 static void a_amv_var_free(char *cp);
273 /* Check for special housekeeping. _VIP_SET_POST and _VIP_CLEAR do not fail
274 * (or propagate errors), _VIP_SET_PRE may and should case abortion */
275 static bool_t a_amv_var_check_vips(enum a_amv_var_vip_mode avvm,
276 enum okeys okey, char const *val);
278 /* _VF_NOCNTRLS, _VF_NUM / _VF_POSNUM */
279 static bool_t a_amv_var_check_nocntrls(char const *val);
280 static bool_t a_amv_var_check_num(char const *val, bool_t posnum);
282 /* If a variable name begins with a lowercase-character and contains at
283 * least one '@', it is converted to all-lowercase. This is necessary
284 * for lookups of names based on email addresses.
285 * Following the standard, only the part following the last '@' should
286 * be lower-cased, but practice has established otherwise here */
287 static char const *a_amv_var_canonify(char const *vn);
289 /* Try to reverse lookup an option name to an enum okeys mapping.
290 * Updates .avc_name and .avc_hash; .avc_map is NULL if none found */
291 static bool_t a_amv_var_revlookup(struct a_amv_var_carrier *avcp,
292 char const *name);
294 /* Lookup a variable from .avc_(map|name|hash), return whether it was found.
295 * Sets .avc_prime; .avc_var is NULL if not found.
296 * Here it is where we care for _I3VAL and _DEFVAL, too.
297 * An _I3VAL will be "consumed" as necessary anyway, but it won't be used to
298 * create a new variable if i3val_nonew is true; if i3val_nonew is TRUM1 then
299 * we set .avc_var to -1 and return true if that was the case, otherwise we'll
300 * return FAL0, then! */
301 static bool_t a_amv_var_lookup(struct a_amv_var_carrier *avcp,
302 bool_t i3val_nonew);
304 /* Lookup functions for special category variables, _mac drives all macro etc.
305 * local special categories */
306 static char const *a_amv_var_vsc_global(struct a_amv_var_carrier *avcp);
307 static char const *a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp);
308 static char const *a_amv_var_vsc_mac(struct a_amv_var_carrier *avcp);
310 /* Set var from .avc_(map|name|hash), return success */
311 static bool_t a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
312 bool_t force_env);
314 static bool_t a_amv_var__putenv(struct a_amv_var_carrier *avcp,
315 struct a_amv_var *avp);
317 /* Clear var from .avc_(map|name|hash); sets .avc_var=NULL, return success */
318 static bool_t a_amv_var_clear(struct a_amv_var_carrier *avcp, bool_t force_env);
320 static bool_t a_amv_var__clearenv(char const *name, char *value);
322 /* List all variables */
323 static void a_amv_var_show_all(void);
325 static int a_amv_var__show_cmp(void const *s1, void const *s2);
327 /* Actually do print one, return number of lines written */
328 static size_t a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp);
330 /* Shared c_set() and c_environ():set impl, return success */
331 static bool_t a_amv_var_c_set(char **ap, bool_t issetenv);
333 static struct a_amv_mac *
334 a_amv_mac_lookup(char const *name, struct a_amv_mac *newamp,
335 enum a_amv_mac_flags amf){
336 struct a_amv_mac *amp, **ampp;
337 ui32_t h;
338 enum a_amv_mac_flags save_amf;
339 NYD2_ENTER;
341 save_amf = amf;
342 amf &= a_AMV_MF_TYPE_MASK;
343 h = a_AMV_NAME2HASH(name);
344 h = a_AMV_HASH2PRIME(h);
345 ampp = &a_amv_macs[h];
347 for(amp = *ampp; amp != NULL; ampp = &(*ampp)->am_next, amp = amp->am_next){
348 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf &&
349 !strcmp(amp->am_name, name)){
350 if(n_LIKELY((save_amf & a_AMV_MF_UNDEF) == 0))
351 goto jleave;
353 *ampp = amp->am_next;
355 if(amp->am_refcnt > 0){
356 amp->am_flags |= a_AMV_MF_DELETE;
357 if(n_poption & n_PO_D_V)
358 n_err(_("Delayed deletion of currently active %s: %s\n"),
359 (amp->am_flags & a_AMV_MF_ACCOUNT ? "account" : "define"),
360 name);
361 }else{
362 a_amv_mac_free(amp);
363 amp = (struct a_amv_mac*)-1;
365 break;
369 if(newamp != NULL){
370 ampp = &a_amv_macs[h];
371 newamp->am_next = *ampp;
372 *ampp = newamp;
373 amp = NULL;
375 jleave:
376 NYD2_LEAVE;
377 return amp;
380 static int
381 a_amv_mac_call(void *v, bool_t silent_nexist){
382 int rv;
383 struct a_amv_mac *amp;
384 char const *name;
385 NYD_ENTER;
387 name = *(char const**)v;
389 if((amp = a_amv_mac_lookup(name, NULL, a_AMV_MF_NONE)) != NULL){
390 struct a_amv_mac_call_args *amcap;
392 amcap = n_lofi_alloc(sizeof *amcap);
393 memset(amcap, 0, sizeof *amcap);
394 amcap->amca_name = name;
395 amcap->amca_amp = amp;
396 /* C99 */{
397 char const **argv;
398 ui32_t argc;
400 for(argc = 0, argv = v; *++argv != NULL; ++argc)
402 if(argc > 0){
403 amcap->amca_argc = argc;
404 amcap->amca_argv = &(argv = v)[1];
407 rv = (a_amv_mac_exec(amcap) == FAL0);
408 }else if((rv = (silent_nexist == FAL0)))
409 n_err(_("Undefined macro `call'ed: %s\n"), n_shexp_quote_cp(name, FAL0));
410 NYD_LEAVE;
411 return rv;
414 static bool_t
415 a_amv_mac_exec(struct a_amv_mac_call_args *amcap){
416 struct a_amv_lostack *losp;
417 struct a_amv_mac_line **amlp;
418 char **args_base, **args;
419 struct a_amv_mac *amp;
420 bool_t rv;
421 NYD2_ENTER;
423 amp = amcap->amca_amp;
424 assert(amp != NULL && amp != a_AMV_MACKY_MACK);
425 ++amp->am_refcnt;
426 /* XXX Unfortunately we yet need to dup the macro lines! :( */
427 args_base = args = smalloc(sizeof(*args) * (amp->am_line_cnt +1));
428 for(amlp = amp->am_line_dat; *amlp != NULL; ++amlp)
429 *(args++) = sbufdup((*amlp)->aml_dat, (*amlp)->aml_len);
430 *args = NULL;
432 losp = n_lofi_alloc(sizeof *losp);
433 losp->as_global_saved = a_amv_lopts;
434 if((losp->as_amcap = amcap)->amca_unroller == NULL){
435 losp->as_up = losp->as_global_saved;
436 losp->as_lopts = NULL;
437 }else{
438 losp->as_up = NULL;
439 losp->as_lopts = *amcap->amca_unroller;
441 losp->as_unroll = amcap->amca_lopts_on;
443 a_amv_lopts = losp;
444 if(amcap->amca_hook_pre != NULL)
445 n_PS_ROOT_BLOCK((*amcap->amca_hook_pre)(amcap->amca_hook_arg));
446 rv = n_source_macro(n_LEXINPUT_NONE, amp->am_name, args_base,
447 &a_amv_mac__finalize, losp);
448 NYD2_LEAVE;
449 return rv;
452 static void
453 a_amv_mac__finalize(void *vp){
454 struct a_amv_mac *amp;
455 struct a_amv_mac_call_args *amcap;
456 struct a_amv_lostack *losp;
457 NYD2_ENTER;
459 losp = vp;
460 a_amv_lopts = losp->as_global_saved;
462 if((amcap = losp->as_amcap)->amca_unroller == NULL){
463 if(losp->as_lopts != NULL)
464 a_amv_lopts_unroll(&losp->as_lopts);
465 }else
466 *amcap->amca_unroller = losp->as_lopts;
468 if(amcap->amca_ps_hook_mask)
469 n_pstate &= ~n_PS_HOOK_MASK;
471 if((amp = amcap->amca_amp) != a_AMV_MACKY_MACK && amp != NULL &&
472 --amp->am_refcnt == 0 && (amp->am_flags & a_AMV_MF_DELETE))
473 a_amv_mac_free(amp);
475 n_lofi_free(losp);
476 n_lofi_free(amcap);
477 NYD2_LEAVE;
480 static bool_t
481 a_amv_mac_show(enum a_amv_mac_flags amf){
482 size_t lc, mc, ti, i;
483 char const *typestr;
484 FILE *fp;
485 bool_t rv;
486 NYD2_ENTER;
488 rv = FAL0;
490 if((fp = Ftmp(NULL, "deflist", OF_RDWR | OF_UNLINK | OF_REGISTER)) ==
491 NULL){
492 n_perr(_("Can't create temporary file for `define' or `account' listing"),
494 goto jleave;
497 amf &= a_AMV_MF_TYPE_MASK;
498 typestr = (amf & a_AMV_MF_ACCOUNT) ? "account" : "define";
500 for(lc = mc = ti = 0; ti < a_AMV_PRIME; ++ti){
501 struct a_amv_mac *amp;
503 for(amp = a_amv_macs[ti]; amp != NULL; amp = amp->am_next){
504 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
505 struct a_amv_mac_line **amlpp;
507 if(++mc > 1){
508 putc('\n', fp);
509 ++lc;
511 ++lc;
512 fprintf(fp, "%s %s {\n", typestr, amp->am_name);
513 for(amlpp = amp->am_line_dat; *amlpp != NULL; ++lc, ++amlpp){
514 for(i = (*amlpp)->aml_prespc; i > 0; --i)
515 putc(' ', fp);
516 fputs((*amlpp)->aml_dat, fp);
517 putc('\n', fp);
519 fputs("}\n", fp);
520 ++lc;
524 if(mc > 0)
525 page_or_print(fp, lc);
527 rv = (ferror(fp) == 0);
528 Fclose(fp);
529 jleave:
530 NYD2_LEAVE;
531 return rv;
534 static bool_t
535 a_amv_mac_def(char const *name, enum a_amv_mac_flags amf){
536 struct str line;
537 ui32_t line_cnt, maxlen;
538 struct linelist{
539 struct linelist *ll_next;
540 struct a_amv_mac_line *ll_amlp;
541 } *llp, *ll_head, *ll_tail;
542 union {size_t s; int i; ui32_t ui; size_t l;} n;
543 struct a_amv_mac *amp;
544 bool_t rv;
545 NYD2_ENTER;
547 memset(&line, 0, sizeof line);
548 rv = FAL0;
549 amp = NULL;
551 /* TODO We should have our input state machine which emits Line events,
552 * TODO and hook different consumers dependent on our content, as stated
553 * TODO in i think lex_input; */
554 /* Read in the lines which form the macro content */
555 for(ll_tail = ll_head = NULL, line_cnt = maxlen = 0;;){
556 ui32_t leaspc;
557 char *cp;
559 n.i = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, n_empty,
560 &line.s, &line.l, NULL);
561 if(n.ui == 0)
562 continue;
563 if(n.i < 0){
564 n_err(_("Unterminated %s definition: %s\n"),
565 (amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
566 goto jerr;
569 /* Trim WS, remember amount of leading spaces for display purposes */
570 for(cp = line.s, leaspc = 0; n.ui > 0; ++cp, --n.ui)
571 if(*cp == '\t')
572 leaspc = (leaspc + 8u) & ~7u;
573 else if(*cp == ' ')
574 ++leaspc;
575 else
576 break;
577 for(; n.ui > 0 && spacechar(cp[n.ui - 1]); --n.ui)
579 if(n.ui == 0)
580 continue;
582 maxlen = n_MAX(maxlen, n.ui);
583 cp[n.ui++] = '\0';
585 /* Is is the closing brace? */
586 if(*cp == '}')
587 break;
589 if(n_LIKELY(++line_cnt < UI32_MAX)){
590 struct a_amv_mac_line *amlp;
592 llp = salloc(sizeof *llp);
593 if(ll_head == NULL)
594 ll_head = llp;
595 else
596 ll_tail->ll_next = llp;
597 ll_tail = llp;
598 llp->ll_next = NULL;
599 llp->ll_amlp = amlp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_mac_line,
600 aml_dat) + n.ui);
601 amlp->aml_len = n.ui -1;
602 amlp->aml_prespc = leaspc;
603 memcpy(amlp->aml_dat, cp, n.ui);
604 }else{
605 n_err(_("Too much content in %s definition: %s\n"),
606 (amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
607 goto jerr;
611 /* Create the new macro */
612 n.s = strlen(name) +1;
613 amp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_mac, am_name) + n.s);
614 amp->am_next = NULL;
615 amp->am_maxlen = maxlen;
616 amp->am_line_cnt = line_cnt;
617 amp->am_refcnt = 0;
618 amp->am_flags = amf;
619 amp->am_lopts = NULL;
620 memcpy(amp->am_name, name, n.s);
621 /* C99 */{
622 struct a_amv_mac_line **amlpp;
624 amp->am_line_dat = amlpp = smalloc(sizeof(*amlpp) * ++line_cnt);
625 for(llp = ll_head; llp != NULL; llp = llp->ll_next)
626 *amlpp++ = llp->ll_amlp;
627 *amlpp = NULL;
630 /* Create entry, replace a yet existing one as necessary */
631 a_amv_mac_lookup(name, amp, amf | a_AMV_MF_UNDEF);
632 rv = TRU1;
633 jleave:
634 if(line.s != NULL)
635 free(line.s);
636 NYD2_LEAVE;
637 return rv;
639 jerr:
640 for(llp = ll_head; llp != NULL; llp = llp->ll_next)
641 free(llp->ll_amlp);
642 if(amp != NULL){
643 free(amp->am_line_dat);
644 free(amp);
646 goto jleave;
649 static bool_t
650 a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf){
651 struct a_amv_mac *amp;
652 bool_t rv;
653 NYD2_ENTER;
655 rv = TRU1;
657 if(n_LIKELY(name[0] != '*' || name[1] != '\0')){
658 if((amp = a_amv_mac_lookup(name, NULL, amf | a_AMV_MF_UNDEF)) == NULL){
659 n_err(_("%s not defined: %s\n"),
660 (amf & a_AMV_MF_ACCOUNT ? "Account" : "Macro"), name);
661 rv = FAL0;
663 }else{
664 struct a_amv_mac **ampp, *lamp;
666 for(ampp = a_amv_macs; PTRCMP(ampp, <, &a_amv_macs[n_NELEM(a_amv_macs)]);
667 ++ampp)
668 for(lamp = NULL, amp = *ampp; amp != NULL;){
669 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
670 /* xxx Expensive but rare: be simple */
671 a_amv_mac_lookup(amp->am_name, NULL, amf | a_AMV_MF_UNDEF);
672 amp = (lamp == NULL) ? *ampp : lamp->am_next;
673 }else{
674 lamp = amp;
675 amp = amp->am_next;
679 NYD2_LEAVE;
680 return rv;
683 static void
684 a_amv_mac_free(struct a_amv_mac *amp){
685 struct a_amv_mac_line **amlpp;
686 NYD2_ENTER;
688 for(amlpp = amp->am_line_dat; *amlpp != NULL; ++amlpp)
689 free(*amlpp);
690 free(amp->am_line_dat);
691 free(amp);
692 NYD2_LEAVE;
695 static void
696 a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
697 struct a_amv_var *oavp){
698 struct a_amv_var *avp;
699 size_t nl, vl;
700 NYD2_ENTER;
702 /* Propagate unrolling up the stack, as necessary */
703 assert(alp != NULL);
704 for(;;){
705 if(alp->as_unroll)
706 break;
707 if((alp = alp->as_up) == NULL)
708 goto jleave;
711 /* Check whether this variable is handled yet */
712 for(avp = alp->as_lopts; avp != NULL; avp = avp->av_link)
713 if(!strcmp(avp->av_name, name))
714 goto jleave;
716 nl = strlen(name) +1;
717 vl = (oavp != NULL) ? strlen(oavp->av_value) +1 : 0;
718 avp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + nl + vl);
719 avp->av_link = alp->as_lopts;
720 alp->as_lopts = avp;
721 memcpy(avp->av_name, name, nl);
722 if(vl == 0){
723 avp->av_value = NULL;
724 avp->av_flags = 0;
725 #ifdef HAVE_PUTENV
726 avp->av_env = NULL;
727 #endif
728 }else{
729 avp->av_value = &avp->av_name[nl];
730 avp->av_flags = oavp->av_flags;
731 memcpy(avp->av_value, oavp->av_value, vl);
732 #ifdef HAVE_PUTENV
733 avp->av_env = (oavp->av_env == NULL) ? NULL : sstrdup(oavp->av_env);
734 #endif
736 jleave:
737 NYD2_LEAVE;
740 static void
741 a_amv_lopts_unroll(struct a_amv_var **avpp){
742 struct a_amv_lostack *save_alp;
743 struct a_amv_var *x, *avp;
744 NYD2_ENTER;
746 avp = *avpp;
747 *avpp = NULL;
749 save_alp = a_amv_lopts;
750 a_amv_lopts = NULL;
751 while(avp != NULL){
752 x = avp;
753 avp = avp->av_link;
754 n_PS_ROOT_BLOCK(n_var_vset(x->av_name, (uintptr_t)x->av_value));
755 free(x);
757 a_amv_lopts = save_alp;
758 NYD2_LEAVE;
761 static char *
762 a_amv_var_copy(char const *str){
763 char *news;
764 size_t len;
765 NYD2_ENTER;
767 if(*str == '\0')
768 news = n_UNCONST(n_empty);
769 else if(str[1] == '\0'){
770 if(str[0] == '1')
771 news = n_UNCONST(n_1);
772 else if(str[0] == '0')
773 news = n_UNCONST(n_0);
774 else
775 goto jheap;
776 }else if(str[2] == '\0' && str[0] == '-' && str[1] == '1')
777 news = n_UNCONST(n_m1);
778 else{
779 jheap:
780 len = strlen(str) +1;
781 news = smalloc(len);
782 memcpy(news, str, len);
784 NYD2_LEAVE;
785 return news;
788 static void
789 a_amv_var_free(char *cp){
790 NYD2_ENTER;
791 if(cp[0] != '\0' && cp != n_0 && cp != n_1 && cp != n_m1)
792 free(cp);
793 NYD2_LEAVE;
796 static bool_t
797 a_amv_var_check_vips(enum a_amv_var_vip_mode avvm, enum okeys okey,
798 char const *val){
799 bool_t ok;
800 NYD2_ENTER;
802 ok = TRU1;
804 if(avvm == a_AMV_VIP_SET_PRE){
805 switch(okey){
806 default:
807 break;
808 case ok_v_HOME:
809 /* Note this gets called from main.c during initialization, and they
810 * simply set this to pw_dir as a fallback: don't verify _that_ call.
811 * See main.c! */
812 if(!(n_pstate & n_PS_ROOT) && !n_is_dir(val, TRU1)){
813 n_err(_("$HOME is not a directory or not accessible: %s\n"),
814 n_shexp_quote_cp(val, FAL0));
815 ok = FAL0;
816 break;
818 case ok_v_TMPDIR:
819 if(!n_is_dir(val, TRU1)){
820 n_err(_("$TMPDIR is not a directory or not accessible: %s\n"),
821 n_shexp_quote_cp(val, FAL0));
822 ok = FAL0;
824 break;
825 case ok_v_umask:
826 if(*val != '\0'){
827 ui64_t uib;
829 n_idec_ui64_cp(&uib, val, 0, NULL);
830 if(uib & ~0777u){ /* (is valid _VF_POSNUM) */
831 n_err(_("Invalid *umask* setting: %s\n"), val);
832 ok = FAL0;
835 break;
837 }else if(avvm == a_AMV_VIP_SET_POST){
838 switch(okey){
839 default:
840 break;
841 case ok_b_debug:
842 n_poption |= n_PO_DEBUG;
843 break;
844 case ok_v_HOME:
845 /* Invalidate any resolved folder then, too
846 * FALLTHRU */
847 case ok_v_folder:
848 n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
849 break;
850 case ok_b_memdebug:
851 n_poption |= n_PO_MEMDEBUG;
852 break;
853 case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
854 if(!(n_pstate & n_PS_ROOT))
855 n_PS_ROOT_BLOCK(ok_bset(posix));
856 break;
857 case ok_b_posix: /* <-> $POSIXLY_CORRECT */
858 if(!(n_pstate & n_PS_ROOT))
859 n_PS_ROOT_BLOCK(ok_bset(POSIXLY_CORRECT));
860 break;
861 case ok_b_skipemptybody:
862 n_poption |= n_PO_E_FLAG;
863 break;
864 case ok_b_typescript_mode:
865 ok_bset(colour_disable);
866 ok_bset(line_editor_disable);
867 if(!(n_psonce & n_PSO_STARTED))
868 ok_bset(termcap_disable);
869 case ok_v_umask:
870 if(*val != '\0'){
871 ui64_t uib;
873 n_idec_ui64_cp(&uib, val, 0, NULL);
874 umask((mode_t)uib);
876 break;
877 case ok_b_verbose:
878 n_poption |= (n_poption & n_PO_VERB) ? n_PO_VERBVERB : n_PO_VERB;
879 break;
881 }else{
882 switch(okey){
883 default:
884 break;
885 case ok_b_debug:
886 n_poption &= ~n_PO_DEBUG;
887 break;
888 case ok_v_HOME:
889 /* Invalidate any resolved folder then, too
890 * FALLTHRU */
891 case ok_v_folder:
892 n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
893 break;
894 case ok_b_memdebug:
895 n_poption &= ~n_PO_MEMDEBUG;
896 break;
897 case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
898 if(!(n_pstate & n_PS_ROOT))
899 n_PS_ROOT_BLOCK(ok_bclear(posix));
900 break;
901 case ok_b_posix: /* <-> $POSIXLY_CORRECT */
902 if(!(n_pstate & n_PS_ROOT))
903 n_PS_ROOT_BLOCK(ok_bclear(POSIXLY_CORRECT));
904 break;
905 case ok_b_skipemptybody:
906 n_poption &= ~n_PO_E_FLAG;
907 break;
908 case ok_b_verbose:
909 n_poption &= ~(n_PO_VERB | n_PO_VERBVERB);
910 break;
913 NYD2_LEAVE;
914 return ok;
917 static bool_t
918 a_amv_var_check_nocntrls(char const *val){
919 char c;
920 NYD2_ENTER;
922 while((c = *val++) != '\0')
923 if(cntrlchar(c))
924 break;
925 NYD2_LEAVE;
926 return (c == '\0');
929 static bool_t
930 a_amv_var_check_num(char const *val, bool_t posnum){
931 /* TODO The internal/environment variables which are num= or posnum= should
932 * TODO gain special lookup functions, or the return should be void* and
933 * TODO castable to integer; i.e. no more strtoX() should be needed.
934 * TODO I.e., the result of this function should instead be stored */
935 bool_t rv;
936 NYD2_ENTER;
938 rv = TRU1;
940 if(*val != '\0'){ /* Would be _VF_NOTEMPTY if not allowed */
941 ui64_t uib;
942 enum n_idec_state ids;
944 ids = n_idec_cp(&uib, val, 0,
945 (posnum ? n_IDEC_MODE_SIGNED_TYPE : n_IDEC_MODE_NONE), NULL);
946 if((ids & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
947 ) != n_IDEC_STATE_CONSUMED)
948 rv = FAL0;
949 /* TODO Unless we store integers we need to look and forbid, because
950 * TODO callee may not be able to swallow, e.g., "-1" */
951 if(posnum && (ids & n_IDEC_STATE_SEEN_MINUS))
952 rv = FAL0;
954 NYD2_LEAVE;
955 return rv;
958 static char const *
959 a_amv_var_canonify(char const *vn){
960 NYD2_ENTER;
961 if(!upperchar(*vn)){
962 char const *vp;
964 for(vp = vn; *vp != '\0' && *vp != '@'; ++vp)
966 vn = (*vp == '@') ? i_strdup(vn) : vn;
968 NYD2_LEAVE;
969 return vn;
972 static bool_t
973 a_amv_var_revlookup(struct a_amv_var_carrier *avcp, char const *name){
974 ui32_t hash, i, j;
975 struct a_amv_var_map const *avmp;
976 char c;
977 NYD2_ENTER;
979 /* It may be a special a.k.a. macro-local or one-letter parameter */
980 c = name[0];
981 if(n_UNLIKELY(digitchar(c))){
982 /* (Inline dec. atoi, ugh) */
983 for(j = (ui8_t)c - '0', i = 1;; ++i){
984 c = name[i];
985 if(c == '\0')
986 break;
987 if(!digitchar(c))
988 goto jno_special_param;
989 j = j * 10 + (ui8_t)c - '0';
991 if(j <= SI16_MAX){
992 avcp->avc_special_cat = a_AMV_VSC_MAC_ARGV;
993 goto jspecial_param;
995 }else if(n_UNLIKELY(name[1] == '\0')){
996 switch(c){
997 case '?':
998 case '!':
999 avcp->avc_special_cat = a_AMV_VSC_GLOBAL;
1000 j = (c == '?') ? a_AMV_VST_QM : a_AMV_VST_EM;
1001 goto jspecial_param;
1002 case '^':
1003 goto jmultiplex;
1004 case '*':
1005 avcp->avc_special_cat = a_AMV_VSC_MAC;
1006 j = a_AMV_VST_STAR;
1007 goto jspecial_param;
1008 case '@':
1009 avcp->avc_special_cat = a_AMV_VSC_MAC;
1010 j = a_AMV_VST_AT;
1011 goto jspecial_param;
1012 case '#':
1013 avcp->avc_special_cat = a_AMV_VSC_MAC;
1014 j = a_AMV_VST_NOSIGN;
1015 goto jspecial_param;
1016 default:
1017 break;
1019 }else if(c == '^'){
1020 jmultiplex:
1021 avcp->avc_special_cat = a_AMV_VSC_MULTIPLEX;
1022 j = a_AMV_VST_CACC;
1023 goto jspecial_param;
1026 /* Normal reverse lookup, walk over the hashtable */
1027 jno_special_param:
1028 avcp->avc_special_cat = a_AMV_VSC_NONE;
1029 avcp->avc_name = name = a_amv_var_canonify(name);
1030 avcp->avc_hash = hash = a_AMV_NAME2HASH(name);
1032 for(i = hash % a_AMV_VAR_REV_PRIME, j = 0; j <= a_AMV_VAR_REV_LONGEST; ++j){
1033 ui32_t x;
1035 if((x = a_amv_var_revmap[i]) == a_AMV_VAR_REV_ILL)
1036 break;
1038 avmp = &a_amv_var_map[x];
1039 if(avmp->avm_hash == hash &&
1040 !strcmp(&a_amv_var_names[avmp->avm_keyoff], name)){
1041 avcp->avc_map = avmp;
1042 avcp->avc_okey = (enum okeys)x;
1043 goto jleave;
1046 if(++i == a_AMV_VAR_REV_PRIME){
1047 #ifdef a_AMV_VAR_REV_WRAPAROUND
1048 i = 0;
1049 #else
1050 break;
1051 #endif
1054 avcp->avc_map = NULL;
1055 avcp = NULL;
1056 jleave:
1057 NYD2_LEAVE;
1058 return (avcp != NULL);
1060 /* All these are mapped to *--special-param* */
1061 jspecial_param:
1062 avcp->avc_name = name;
1063 avcp->avc_special_prop = (ui16_t)j;
1064 avmp = &a_amv_var_map[a_AMV_VAR__SPECIAL_PARAM_MAP_IDX];
1065 avcp->avc_hash = avmp->avm_hash;
1066 avcp->avc_map = avmp;
1067 avcp->avc_okey = ok_v___special_param;
1068 goto jleave;
1071 static bool_t
1072 a_amv_var_lookup(struct a_amv_var_carrier *avcp, bool_t i3val_nonew){
1073 size_t i;
1074 char const *cp;
1075 struct a_amv_var_map const *avmp;
1076 struct a_amv_var *avp;
1077 NYD2_ENTER;
1079 /* C99 */{
1080 struct a_amv_var **avpp, *lavp;
1082 avpp = &a_amv_vars[avcp->avc_prime = a_AMV_HASH2PRIME(avcp->avc_hash)];
1084 for(lavp = NULL, avp = *avpp; avp != NULL; lavp = avp, avp = avp->av_link)
1085 if(!strcmp(avp->av_name, avcp->avc_name)){
1086 /* Relink as head, hope it "sorts on usage" over time.
1087 * _clear() relies on this behaviour */
1088 if(lavp != NULL){
1089 lavp->av_link = avp->av_link;
1090 avp->av_link = *avpp;
1091 *avpp = avp;
1093 goto jleave;
1097 /* If this is not an assembled variable we need to consider some special
1098 * initialization cases and eventually create the variable anew */
1099 if(n_LIKELY((avmp = avcp->avc_map) != NULL)){
1100 /* Does it have an import-from-environment flag? */
1101 if(n_UNLIKELY((avmp->avm_flags & (a_AMV_VF_IMPORT | a_AMV_VF_ENV)) != 0)){
1102 if(n_LIKELY((cp = getenv(avcp->avc_name)) != NULL)){
1103 /* May be better not to use that one, though? */
1104 bool_t isempty, isbltin;
1106 isempty = (*cp == '\0' &&
1107 (avmp->avm_flags & a_AMV_VF_NOTEMPTY) != 0);
1108 isbltin = ((avmp->avm_flags & (a_AMV_VF_I3VAL | a_AMV_VF_DEFVAL)
1109 ) != 0);
1111 if(n_UNLIKELY(isempty)){
1112 if(!isbltin)
1113 goto jerr;
1114 }else if(n_LIKELY(*cp != '\0')){
1115 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NOCNTRLS) &&
1116 !a_amv_var_check_nocntrls(cp))){
1117 n_err(_("Ignoring environment, control characters "
1118 "invalid in variable: %s\n"), avcp->avc_name);
1119 goto jerr;
1121 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NUM) &&
1122 !a_amv_var_check_num(cp, FAL0))){
1123 n_err(_("Environment variable value not a number "
1124 "or out of range: %s\n"), avcp->avc_name);
1125 goto jerr;
1127 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_POSNUM) &&
1128 !a_amv_var_check_num(cp, TRU1))){
1129 n_err(_("Environment variable value not a number, "
1130 "negative or out of range: %s\n"), avcp->avc_name);
1131 goto jerr;
1133 goto jnewval;
1134 }else
1135 goto jnewval;
1139 /* A first-time init switch is to be handled now and here */
1140 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_I3VAL) != 0)){
1141 static struct a_amv_var_defval const **arr,
1142 *arr_base[a_AMV_VAR_I3VALS_CNT +1];
1144 if(arr == NULL){
1145 arr = &arr_base[0];
1146 arr[i = a_AMV_VAR_I3VALS_CNT] = NULL;
1147 while(i-- > 0)
1148 arr[i] = &a_amv_var_i3vals[i];
1151 for(i = 0; arr[i] != NULL; ++i)
1152 if(arr[i]->avdv_okey == avcp->avc_okey){
1153 cp = (avmp->avm_flags & a_AMV_VF_BOOL) ? n_empty
1154 : arr[i]->avdv_value;
1155 /* Remove this entry, hope entire block becomes no-op asap */
1157 arr[i] = arr[i + 1];
1158 while(arr[i++] != NULL);
1160 if(!i3val_nonew)
1161 goto jnewval;
1162 if(i3val_nonew == TRUM1)
1163 avp = (struct a_amv_var*)-1;
1164 goto jleave;
1168 /* The virtual variables */
1169 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIRT) != 0)){
1170 for(i = 0; i < a_AMV_VAR_VIRTS_CNT; ++i)
1171 if(a_amv_var_virts[i].avv_okey == avcp->avc_okey){
1172 avp = n_UNCONST(a_amv_var_virts[i].avv_var);
1173 goto jleave;
1175 /* Not reached */
1178 /* Place this last because once it is set first the variable will never
1179 * be removed again and thus match in the first block above */
1180 jdefval:
1181 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_DEFVAL) != 0){
1182 for(i = 0; i < a_AMV_VAR_DEFVALS_CNT; ++i)
1183 if(a_amv_var_defvals[i].avdv_okey == avcp->avc_okey){
1184 cp = (avmp->avm_flags & a_AMV_VF_BOOL) ? n_empty
1185 : a_amv_var_defvals[i].avdv_value;
1186 goto jnewval;
1191 jerr:
1192 avp = NULL;
1193 jleave:
1194 avcp->avc_var = avp;
1195 NYD2_LEAVE;
1196 return (avp != NULL);
1198 jnewval:
1199 /* E.g., $TMPDIR may be set to non-existent, so we need to be able to catch
1200 * that and redirect to a possible default value */
1201 if((avmp->avm_flags & a_AMV_VF_VIP) &&
1202 !a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, cp)){
1203 #ifdef HAVE_SETENV
1204 if(avmp->avm_flags & (a_AMV_VF_IMPORT | a_AMV_VF_ENV))
1205 unsetenv(avcp->avc_name);
1206 #endif
1207 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_DEFVAL) != 0)
1208 goto jdefval;
1209 goto jerr;
1210 }else{
1211 struct a_amv_var **avpp;
1212 size_t l;
1214 l = strlen(avcp->avc_name) +1;
1215 avcp->avc_var =
1216 avp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
1217 avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
1218 *avpp = avp;
1219 memcpy(avp->av_name, avcp->avc_name, l);
1220 #ifdef HAVE_PUTENV
1221 avp->av_env = NULL;
1222 #endif
1223 avp->av_flags = avmp->avm_flags;
1224 avp->av_value = a_amv_var_copy(cp);
1226 if(avp->av_flags & a_AMV_VF_ENV)
1227 a_amv_var__putenv(avcp, avp);
1228 if(avmp->avm_flags & a_AMV_VF_VIP)
1229 a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, cp);
1230 goto jleave;
1234 static char const *
1235 a_amv_var_vsc_global(struct a_amv_var_carrier *avcp){
1236 char itoabuf[32];
1237 char const *rv;
1238 si32_t *ep;
1239 struct a_amv_var_map const *avmp;
1240 NYD2_ENTER;
1242 /* Not function local, TODO but lazy evaluted for now */
1243 if(avcp->avc_special_prop == a_AMV_VST_QM){
1244 avmp = &a_amv_var_map[a_AMV_VAR__QM_MAP_IDX];
1245 avcp->avc_okey = ok_v___qm;
1246 ep = &n_pstate_ex_no;
1247 }else{
1248 avmp = &a_amv_var_map[a_AMV_VAR__EM_MAP_IDX];
1249 avcp->avc_okey = ok_v___em;
1250 ep = &n_pstate_err_no;
1253 /* XXX Oh heaven, we are responsible to ensure that $?/! is up-to-date
1254 * XXX and represents n_pstate_err_no; TODO unfortunately
1255 * TODO we could num=1 ok_v___[qe]m, but the thing is still a string
1256 * TODO and thus conversion takes places over and over again; also
1257 * TODO for now that would have to occur before we set _that_ value
1258 * TODO so let's special treat it until we store ints as such */
1259 if(*ep >= 0){
1260 switch(*ep){
1261 case 0: rv = n_0; break;
1262 case 1: rv = n_1; break;
1263 default:
1264 snprintf(itoabuf, sizeof itoabuf, "%d", *ep);
1265 rv = itoabuf;
1266 break;
1268 n_PS_ROOT_BLOCK(n_var_okset(avcp->avc_okey, (uintptr_t)rv));
1270 avcp->avc_hash = avmp->avm_hash;
1271 avcp->avc_map = avmp;
1273 rv = a_amv_var_lookup(avcp, TRU1) ? avcp->avc_var->av_value : NULL;
1274 NYD2_LEAVE;
1275 return rv;
1278 static char const *
1279 a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp){
1280 char itoabuf[32];
1281 si32_t e;
1282 size_t i;
1283 char const *rv;
1284 NYD2_ENTER;
1286 i = strlen(rv = &avcp->avc_name[1]);
1288 /* ERR, ERRDOC, ERRNAME, plus *-NAME variants */
1289 if(rv[0] == 'E' && i >= 3 && rv[1] == 'R' && rv[2] == 'R'){
1290 if(i == 3){
1291 e = n_pstate_err_no;
1292 goto jeno;
1293 }else if(rv[3] == '-'){
1294 e = n_err_from_name(&rv[4]);
1295 jeno:
1296 switch(e){
1297 case 0: rv = n_0; break;
1298 case 1: rv = n_1; break;
1299 default:
1300 snprintf(itoabuf, sizeof itoabuf, "%d", e);
1301 rv = savestr(itoabuf); /* XXX yet, cannot do numbers */
1302 break;
1304 goto jleave;
1305 }else if(i >= 6){
1306 if(!memcmp(&rv[3], "DOC", 3)){
1307 rv += 6;
1308 switch(*rv){
1309 case '\0': e = n_pstate_err_no; break;
1310 case '-': e = n_err_from_name(&rv[1]); break;
1311 default: goto jerr;
1313 rv = n_err_to_doc(e);
1314 goto jleave;
1315 }else if(i >= 7 && !memcmp(&rv[3], "NAME", 4)){
1316 rv += 7;
1317 switch(*rv){
1318 case '\0': e = n_pstate_err_no; break;
1319 case '-': e = n_err_from_name(&rv[1]); break;
1320 default: goto jerr;
1322 rv = n_err_to_name(e);
1323 goto jleave;
1328 jerr:
1329 rv = NULL;
1330 jleave:
1331 NYD2_LEAVE;
1332 return rv;
1335 static char const *
1336 a_amv_var_vsc_mac(struct a_amv_var_carrier *avcp){
1337 bool_t ismacky;
1338 struct a_amv_mac_call_args *amcap;
1339 char const *rv;
1340 NYD2_ENTER;
1342 rv = NULL;
1344 /* These may occur only in a macro.. */
1345 if(n_UNLIKELY(a_amv_lopts == NULL))
1346 goto jmaylog;
1348 amcap = a_amv_lopts->as_amcap;
1350 /* ..in a `call'ed macro only, to be exact. Or in a_AMV_MACKY_MACK */
1351 if(!(ismacky = (amcap->amca_amp == a_AMV_MACKY_MACK)) &&
1352 (amcap->amca_ps_hook_mask ||
1353 (assert(amcap->amca_amp != NULL),
1354 (amcap->amca_amp->am_flags & a_AMV_MF_TYPE_MASK
1355 ) == a_AMV_MF_ACCOUNT)))
1356 goto jleave;
1358 if(avcp->avc_special_cat == a_AMV_VSC_MAC_ARGV){
1359 if(avcp->avc_special_prop > 0){
1360 if(amcap->amca_argc >= avcp->avc_special_prop)
1361 rv = amcap->amca_argv[avcp->avc_special_prop - 1];
1362 }else if(ismacky)
1363 rv = amcap->amca_name;
1364 else
1365 rv = (a_amv_lopts->as_up != NULL
1366 ? a_amv_lopts->as_up->as_amcap->amca_name : n_empty);
1367 goto jleave;
1370 /* MACKY_MACK doesn't know about [*@#] */
1371 if(ismacky)
1372 goto jmaylog;
1374 switch(avcp->avc_special_prop){
1375 case a_AMV_VST_STAR:
1376 case a_AMV_VST_AT:{
1377 ui32_t i, l;
1379 for(i = l = 0; i < amcap->amca_argc; ++i)
1380 l += strlen(amcap->amca_argv[i]) + 1;
1381 if(l == 0)
1382 rv = n_empty;
1383 else{
1384 char *cp;
1386 rv = cp = salloc(l);
1387 for(i = l = 0; i < amcap->amca_argc; ++i){
1388 l = strlen(amcap->amca_argv[i]);
1389 memcpy(cp, amcap->amca_argv[i], l);
1390 cp += l;
1391 *cp++ = ' ';
1393 *--cp = '\0';
1395 } break;
1396 case a_AMV_VST_NOSIGN:{
1397 char *cp;
1399 rv = cp = salloc(sizeof("65535"));
1400 snprintf(cp, sizeof("65535"), "%hu", amcap->amca_argc);
1401 } break;
1402 default:
1403 rv = n_empty;
1404 break;
1407 jleave:
1408 NYD2_LEAVE;
1409 return rv;
1410 jmaylog:
1411 if(n_poption & n_PO_D_V)
1412 n_err(_("Cannot use macro local variable in this context: %s\n"),
1413 n_shexp_quote_cp(avcp->avc_name, FAL0));
1414 goto jleave;
1417 static bool_t
1418 a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
1419 bool_t force_env){
1420 struct a_amv_var *avp;
1421 char *oval;
1422 struct a_amv_var_map const *avmp;
1423 bool_t rv;
1424 NYD2_ENTER;
1426 if(value == NULL){
1427 rv = a_amv_var_clear(avcp, force_env);
1428 goto jleave;
1431 if((avmp = avcp->avc_map) != NULL){
1432 rv = FAL0;
1434 /* Validity checks */
1435 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_RDONLY) != 0 &&
1436 !(n_pstate & n_PS_ROOT))){
1437 value = N_("Variable is read-only: %s\n");
1438 goto jeavmp;
1440 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NOTEMPTY) && *value == '\0')){
1441 value = N_("Variable must not be empty: %s\n");
1442 goto jeavmp;
1444 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NOCNTRLS) != 0 &&
1445 !a_amv_var_check_nocntrls(value))){
1446 value = N_("Variable forbids control characters: %s\n");
1447 goto jeavmp;
1449 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NUM) &&
1450 !a_amv_var_check_num(value, FAL0))){
1451 value = N_("Variable value not a number or out of range: %s\n");
1452 goto jeavmp;
1454 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_POSNUM) &&
1455 !a_amv_var_check_num(value, TRU1))){
1456 value = _("Variable value not a number, negative, "
1457 "or out of range: %s\n");
1458 goto jeavmp;
1460 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_IMPORT) != 0 &&
1461 !(n_psonce & n_PSO_STARTED) && !(n_pstate & n_PS_ROOT))){
1462 value = N_("Variable cannot be set in a resource file: %s\n");
1463 goto jeavmp;
1466 /* Any more complicated inter-dependency? */
1467 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIP) != 0 &&
1468 !a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, value))){
1469 value = N_("Assignment of variable aborted: %s\n");
1470 jeavmp:
1471 n_err(V_(value), avcp->avc_name);
1472 goto jleave;
1475 /* Transformations */
1476 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_LOWER)){
1477 char c;
1479 oval = savestr(value);
1480 value = oval;
1481 for(; (c = *oval) != '\0'; ++oval)
1482 *oval = lowerconv(c);
1486 rv = TRU1;
1487 a_amv_var_lookup(avcp, TRU1);
1489 /* Don't care what happens later on, store this in the unroll list */
1490 if(a_amv_lopts != NULL &&
1491 (avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
1492 a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
1494 if((avp = avcp->avc_var) == NULL){
1495 struct a_amv_var **avpp;
1496 size_t l;
1498 l = strlen(avcp->avc_name) +1;
1499 avcp->avc_var = avp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_var, av_name
1500 ) + l);
1501 avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
1502 *avpp = avp;
1503 #ifdef HAVE_PUTENV
1504 avp->av_env = NULL;
1505 #endif
1506 memcpy(avp->av_name, avcp->avc_name, l);
1507 avp->av_flags = (avmp != NULL) ? avmp->avm_flags : 0;
1508 oval = n_UNCONST(n_empty);
1509 }else
1510 oval = avp->av_value;
1512 if(avmp == NULL)
1513 avp->av_value = a_amv_var_copy(value);
1514 else{
1515 /* Via `set' etc. the user may give even boolean options non-boolean
1516 * values, ignore that and force boolean */
1517 if(avp->av_flags & a_AMV_VF_BOOL){
1518 if(!(n_pstate & n_PS_ROOT) && (n_poption & n_PO_D_VV) &&
1519 *value != '\0')
1520 n_err(_("Ignoring value of boolean variable: %s: %s\n"),
1521 avcp->avc_name, value);
1522 avp->av_value = n_UNCONST(n_1);
1523 }else
1524 avp->av_value = a_amv_var_copy(value);
1527 if(force_env && !(avp->av_flags & a_AMV_VF_ENV))
1528 avp->av_flags |= a_AMV_VF_LINKED;
1529 if(avp->av_flags & (a_AMV_VF_ENV | a_AMV_VF_LINKED))
1530 rv = a_amv_var__putenv(avcp, avp);
1531 if(avp->av_flags & a_AMV_VF_VIP)
1532 a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, value);
1533 a_amv_var_free(oval);
1534 jleave:
1535 NYD2_LEAVE;
1536 return rv;
1539 static bool_t
1540 a_amv_var__putenv(struct a_amv_var_carrier *avcp, struct a_amv_var *avp){
1541 #ifndef HAVE_SETENV
1542 char *cp;
1543 #endif
1544 bool_t rv;
1545 NYD2_ENTER;
1547 #ifdef HAVE_SETENV
1548 rv = (setenv(avcp->avc_name, avp->av_value, 1) == 0);
1549 #else
1550 cp = sstrdup(savecatsep(avcp->avc_name, '=', avp->av_value));
1552 if((rv = (putenv(cp) == 0))){
1553 char *ocp;
1555 if((ocp = avp->av_env) != NULL)
1556 free(ocp);
1557 avp->av_env = cp;
1558 }else
1559 free(cp);
1560 #endif
1561 NYD2_LEAVE;
1562 return rv;
1565 static bool_t
1566 a_amv_var_clear(struct a_amv_var_carrier *avcp, bool_t force_env){
1567 struct a_amv_var **avpp, *avp;
1568 struct a_amv_var_map const *avmp;
1569 bool_t rv;
1570 NYD2_ENTER;
1572 rv = FAL0;
1574 if(n_LIKELY((avmp = avcp->avc_map) != NULL)){
1575 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NODEL) != 0 &&
1576 !(n_pstate & n_PS_ROOT))){
1577 n_err(_("Variable may not be unset: %s\n"), avcp->avc_name);
1578 goto jleave;
1580 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIP) != 0 &&
1581 !a_amv_var_check_vips(a_AMV_VIP_CLEAR, avcp->avc_okey, NULL))){
1582 n_err(_("Clearance of variable aborted: %s\n"), avcp->avc_name);
1583 goto jleave;
1587 rv = TRU1;
1589 if(n_UNLIKELY(!a_amv_var_lookup(avcp, TRUM1))){
1590 if(force_env){
1591 jforce_env:
1592 rv = a_amv_var__clearenv(avcp->avc_name, NULL);
1593 }else if(!(n_pstate & (n_PS_ROOT | n_PS_ROBOT)) && (n_poption & n_PO_D_V))
1594 n_err(_("Can't unset undefined variable: %s\n"), avcp->avc_name);
1595 goto jleave;
1596 }else if(avcp->avc_var == (struct a_amv_var*)-1){
1597 avcp->avc_var = NULL;
1598 if(force_env)
1599 goto jforce_env;
1600 goto jleave;
1603 if(a_amv_lopts != NULL &&
1604 (avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
1605 a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
1607 avp = avcp->avc_var;
1608 avcp->avc_var = NULL;
1609 avpp = &a_amv_vars[avcp->avc_prime];
1610 assert(*avpp == avp); /* (always listhead after lookup()) */
1611 *avpp = (*avpp)->av_link;
1613 /* C99 */{
1614 char *envval;
1616 #ifdef HAVE_SETENV
1617 envval = NULL;
1618 #else
1619 envval = avp->av_env;
1620 #endif
1621 if((avp->av_flags & (a_AMV_VF_ENV | a_AMV_VF_LINKED)) || envval != NULL)
1622 rv = a_amv_var__clearenv(avp->av_name, envval);
1624 a_amv_var_free(avp->av_value);
1625 free(avp);
1627 /* XXX Fun part, extremely simple-minded for now: if this variable has
1628 * XXX a default value, immediately reinstantiate it! TODO Heh? */
1629 if(n_UNLIKELY(avmp != NULL && (avmp->avm_flags & a_AMV_VF_DEFVAL) != 0))
1630 a_amv_var_lookup(avcp, TRU1);
1631 jleave:
1632 NYD2_LEAVE;
1633 return rv;
1636 static bool_t
1637 a_amv_var__clearenv(char const *name, char *value){
1638 #ifndef HAVE_SETENV
1639 extern char **environ;
1640 char **ecpp;
1641 #endif
1642 bool_t rv;
1643 NYD2_ENTER;
1644 n_UNUSED(value);
1646 #ifdef HAVE_SETENV
1647 unsetenv(name);
1648 rv = TRU1;
1649 #else
1650 if(value != NULL)
1651 for(ecpp = environ; *ecpp != NULL; ++ecpp)
1652 if(*ecpp == value){
1653 free(value);
1655 ecpp[0] = ecpp[1];
1656 while(*ecpp++ != NULL);
1657 break;
1659 rv = TRU1;
1660 #endif
1661 NYD2_LEAVE;
1662 return rv;
1665 static void
1666 a_amv_var_show_all(void){
1667 struct n_string msg, *msgp;
1668 FILE *fp;
1669 size_t no, i;
1670 struct a_amv_var *avp;
1671 char const **vacp, **cap;
1672 NYD2_ENTER;
1674 if((fp = Ftmp(NULL, "setlist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
1675 n_perr(_("Can't create temporary file for `set' listing"), 0);
1676 goto jleave;
1679 /* We need to instantiate first-time-inits and default values here, so that
1680 * they will be regular members of our _vars[] table */
1681 for(i = a_AMV_VAR_I3VALS_CNT; i-- > 0;)
1682 n_var_oklook(a_amv_var_i3vals[i].avdv_okey);
1683 for(i = a_AMV_VAR_DEFVALS_CNT; i-- > 0;)
1684 n_var_oklook(a_amv_var_defvals[i].avdv_okey);
1686 for(no = i = 0; i < a_AMV_PRIME; ++i)
1687 for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
1688 ++no;
1689 no += a_AMV_VAR_VIRTS_CNT;
1691 vacp = salloc(no * sizeof(*vacp));
1693 for(cap = vacp, i = 0; i < a_AMV_PRIME; ++i)
1694 for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
1695 *cap++ = avp->av_name;
1696 for(i = a_AMV_VAR_VIRTS_CNT; i-- > 0;)
1697 *cap++ = a_amv_var_virts[i].avv_var->av_name;
1699 if(no > 1)
1700 qsort(vacp, no, sizeof *vacp, &a_amv_var__show_cmp);
1702 msgp = &msg;
1703 msgp = n_string_reserve(n_string_creat(msgp), 80);
1704 for(i = 0, cap = vacp; no != 0; ++cap, --no)
1705 i += a_amv_var_show(*cap, fp, msgp);
1706 n_string_gut(&msg);
1708 page_or_print(fp, i);
1709 Fclose(fp);
1710 jleave:
1711 NYD2_LEAVE;
1714 static int
1715 a_amv_var__show_cmp(void const *s1, void const *s2){
1716 int rv;
1717 NYD2_ENTER;
1719 rv = strcmp(*(char**)n_UNCONST(s1), *(char**)n_UNCONST(s2));
1720 NYD2_LEAVE;
1721 return rv;
1724 static size_t
1725 a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp){
1726 struct a_amv_var_carrier avc;
1727 char const *quote;
1728 bool_t isset;
1729 size_t i;
1730 NYD2_ENTER;
1732 msgp = n_string_trunc(msgp, 0);
1733 i = 0;
1735 a_amv_var_revlookup(&avc, name);
1736 isset = a_amv_var_lookup(&avc, FAL0);
1738 if(n_poption & n_PO_D_V){
1739 if(avc.avc_map == NULL){
1740 msgp = n_string_push_cp(msgp, "#assembled variable with value");
1741 i = 1;
1742 }else{
1743 struct{
1744 ui16_t flag;
1745 char msg[22];
1746 } const tbase[] = {
1747 {a_AMV_VF_VIRT, "virtual"},
1748 {a_AMV_VF_RDONLY, "read-only"},
1749 {a_AMV_VF_NODEL, "nodelete"},
1750 {a_AMV_VF_NOTEMPTY, "notempty"},
1751 {a_AMV_VF_NOCNTRLS, "no-control-chars"},
1752 {a_AMV_VF_NUM, "number"},
1753 {a_AMV_VF_POSNUM, "positive-number"},
1754 {a_AMV_VF_IMPORT, "import-environ-first\0"},
1755 {a_AMV_VF_ENV, "sync-environ"},
1756 {a_AMV_VF_I3VAL, "initial-value"},
1757 {a_AMV_VF_DEFVAL, "default-value"},
1758 {a_AMV_VF_LINKED, "`environ' link"}
1759 }, *tp;
1761 for(tp = tbase; PTRCMP(tp, <, &tbase[n_NELEM(tbase)]); ++tp)
1762 if(isset ? (avc.avc_var->av_flags & tp->flag)
1763 : (avc.avc_map->avm_flags & tp->flag)){
1764 msgp = n_string_push_c(msgp, (i++ == 0 ? '#' : ','));
1765 msgp = n_string_push_cp(msgp, tp->msg);
1768 if(i > 0)
1769 msgp = n_string_push_cp(msgp, "\n ");
1772 if(!isset || (avc.avc_var->av_flags & a_AMV_VF_RDONLY)){
1773 msgp = n_string_push_cp(msgp, "#");
1774 if(!isset){
1775 if(avc.avc_map != NULL && (avc.avc_map->avm_flags & a_AMV_VF_BOOL))
1776 msgp = n_string_push_cp(msgp, "boolean; ");
1777 msgp = n_string_push_cp(msgp, "variable not set: ");
1778 msgp = n_string_push_cp(msgp, n_shexp_quote_cp(name, FAL0));
1779 goto jleave;
1783 n_UNINIT(quote, NULL);
1784 if(!(avc.avc_var->av_flags & a_AMV_VF_BOOL)){
1785 quote = n_shexp_quote_cp(avc.avc_var->av_value, TRU1);
1786 if(strcmp(quote, avc.avc_var->av_value))
1787 msgp = n_string_push_cp(msgp, "wysh ");
1788 }else if(n_poption & n_PO_D_V)
1789 msgp = n_string_push_cp(msgp, "wysh ");
1790 if(avc.avc_var->av_flags & a_AMV_VF_LINKED)
1791 msgp = n_string_push_cp(msgp, "environ ");
1792 msgp = n_string_push_cp(msgp, "set ");
1793 msgp = n_string_push_cp(msgp, name);
1794 if(!(avc.avc_var->av_flags & a_AMV_VF_BOOL)){
1795 msgp = n_string_push_c(msgp, '=');
1796 msgp = n_string_push_cp(msgp, quote);
1797 }else if(n_poption & n_PO_D_V)
1798 msgp = n_string_push_cp(msgp, " #boolean");
1800 jleave:
1801 msgp = n_string_push_c(msgp, '\n');
1802 fputs(n_string_cp(msgp), fp);
1803 NYD2_ENTER;
1804 return (i > 0 ? 2 : 1);
1807 static bool_t
1808 a_amv_var_c_set(char **ap, bool_t issetenv){
1809 char *cp, *cp2, *varbuf, c;
1810 size_t errs;
1811 NYD2_ENTER;
1813 errs = 0;
1814 jouter:
1815 while((cp = *ap++) != NULL){
1816 /* Isolate key */
1817 cp2 = varbuf = salloc(strlen(cp) +1);
1819 for(; (c = *cp) != '=' && c != '\0'; ++cp){
1820 if(cntrlchar(c) || spacechar(c)){
1821 n_err(_("Variable name with control character ignored: %s\n"),
1822 ap[-1]);
1823 ++errs;
1824 goto jouter;
1826 *cp2++ = c;
1828 *cp2 = '\0';
1829 if(c == '\0')
1830 cp = n_UNCONST(n_empty);
1831 else
1832 ++cp;
1834 if(varbuf == cp2){
1835 n_err(_("Empty variable name ignored\n"));
1836 ++errs;
1837 }else{
1838 struct a_amv_var_carrier avc;
1839 bool_t isunset;
1841 if((isunset = (varbuf[0] == 'n' && varbuf[1] == 'o')))
1842 varbuf = &varbuf[2];
1844 a_amv_var_revlookup(&avc, varbuf);
1846 if(isunset)
1847 errs += !a_amv_var_clear(&avc, issetenv);
1848 else
1849 errs += !a_amv_var_set(&avc, cp, issetenv);
1852 NYD2_LEAVE;
1853 return (errs == 0);
1856 FL int
1857 c_define(void *v){
1858 int rv;
1859 char **args;
1860 NYD_ENTER;
1862 rv = 1;
1864 if((args = v)[0] == NULL){
1865 rv = (a_amv_mac_show(a_AMV_MF_NONE) == FAL0);
1866 goto jleave;
1869 if(args[1] == NULL || args[1][0] != '{' || args[1][1] != '\0' ||
1870 args[2] != NULL){
1871 n_err(_("Synopsis: define: <name> {\n"));
1872 goto jleave;
1875 rv = (a_amv_mac_def(args[0], a_AMV_MF_NONE) == FAL0);
1876 jleave:
1877 NYD_LEAVE;
1878 return rv;
1881 FL int
1882 c_undefine(void *v){
1883 int rv;
1884 char **args;
1885 NYD_ENTER;
1887 rv = 0;
1888 args = v;
1890 rv |= !a_amv_mac_undef(*args, a_AMV_MF_NONE);
1891 while(*++args != NULL);
1892 NYD_LEAVE;
1893 return rv;
1896 FL int
1897 c_call(void *v){
1898 int rv;
1899 NYD_ENTER;
1901 rv = a_amv_mac_call(v, FAL0);
1902 NYD_LEAVE;
1903 return rv;
1906 FL int
1907 c_call_if(void *v){
1908 int rv;
1909 NYD_ENTER;
1911 rv = a_amv_mac_call(v, TRU1);
1912 NYD_LEAVE;
1913 return rv;
1916 FL int
1917 c_account(void *v){
1918 struct a_amv_mac_call_args *amcap;
1919 struct a_amv_mac *amp;
1920 char **args;
1921 int rv, i, oqf, nqf;
1922 NYD_ENTER;
1924 rv = 1;
1926 if((args = v)[0] == NULL){
1927 rv = (a_amv_mac_show(a_AMV_MF_ACCOUNT) == FAL0);
1928 goto jleave;
1931 if(args[1] && args[1][0] == '{' && args[1][1] == '\0'){
1932 if(args[2] != NULL){
1933 n_err(_("Synopsis: account: <name> {\n"));
1934 goto jleave;
1936 if(!asccasecmp(args[0], ACCOUNT_NULL)){
1937 n_err(_("`account': cannot use reserved name: %s\n"),
1938 ACCOUNT_NULL);
1939 goto jleave;
1941 rv = (a_amv_mac_def(args[0], a_AMV_MF_ACCOUNT) == FAL0);
1942 goto jleave;
1945 if(n_pstate & n_PS_HOOK_MASK){
1946 n_err(_("`account': can't change account from within a hook\n"));
1947 goto jleave;
1950 save_mbox_for_possible_quitstuff();
1952 amp = NULL;
1953 if(asccasecmp(args[0], ACCOUNT_NULL) != 0 &&
1954 (amp = a_amv_mac_lookup(args[0], NULL, a_AMV_MF_ACCOUNT)) == NULL){
1955 n_err(_("`account': account does not exist: %s\n"), args[0]);
1956 goto jleave;
1959 oqf = savequitflags();
1961 if(a_amv_acc_curr != NULL){
1962 if(a_amv_acc_curr->am_lopts != NULL)
1963 a_amv_lopts_unroll(&a_amv_acc_curr->am_lopts);
1964 /* For accounts this lingers */
1965 --a_amv_acc_curr->am_refcnt;
1966 if(a_amv_acc_curr->am_flags & a_AMV_MF_DELETE)
1967 a_amv_mac_free(a_amv_acc_curr);
1970 a_amv_acc_curr = amp;
1972 if(amp != NULL){
1973 bool_t ok;
1974 assert(amp->am_lopts == NULL);
1975 amcap = n_lofi_alloc(sizeof *amcap);
1976 memset(amcap, 0, sizeof *amcap);
1977 amcap->amca_name = amp->am_name;
1978 amcap->amca_amp = amp;
1979 amcap->amca_unroller = &amp->am_lopts;
1980 amcap->amca_lopts_on = TRU1;
1981 ++amp->am_refcnt; /* We may not run 0 to avoid being deleted! */
1982 ok = a_amv_mac_exec(amcap);
1983 if(!ok){
1984 /* XXX account switch incomplete, unroll? */
1985 n_err(_("`account': failed to switch to account: %s\n"), amp->am_name);
1986 goto jleave;
1990 n_PS_ROOT_BLOCK((amp != NULL ? ok_vset(account, amp->am_name)
1991 : ok_vclear(account)));
1993 if((n_psonce & n_PSO_STARTED) && !(n_pstate & n_PS_HOOK_MASK)){
1994 nqf = savequitflags(); /* TODO obsolete (leave -> void -> new box!) */
1995 restorequitflags(oqf);
1996 if((i = setfile("%", 0)) < 0)
1997 goto jleave;
1998 temporary_folder_hook_check(FAL0);
1999 if(i > 0 && !ok_blook(emptystart))
2000 goto jleave;
2001 announce(ok_blook(bsdcompat) || ok_blook(bsdannounce));
2002 restorequitflags(nqf);
2004 rv = 0;
2005 jleave:
2006 NYD_LEAVE;
2007 return rv;
2010 FL int
2011 c_unaccount(void *v){
2012 int rv;
2013 char **args;
2014 NYD_ENTER;
2016 rv = 0;
2017 args = v;
2019 rv |= !a_amv_mac_undef(*args, a_AMV_MF_ACCOUNT);
2020 while(*++args != NULL);
2021 NYD_LEAVE;
2022 return rv;
2025 FL int
2026 c_localopts(void *v){
2027 char **argv;
2028 int rv;
2029 NYD_ENTER;
2031 rv = 1;
2033 if(a_amv_lopts == NULL){
2034 n_err(_("Cannot use `localopts' in this context "
2035 "(not in `define' or `account', nor special hook)\n"));
2036 goto jleave;
2039 rv = 0;
2041 if(n_pstate & (n_PS_HOOK | n_PS_COMPOSE_MODE)){
2042 if(n_poption & n_PO_D_V)
2043 n_err(_("Cannot turn off `localopts' for compose-mode hooks\n"));
2044 goto jleave;
2047 a_amv_lopts->as_unroll = (boolify(*(argv = v), UIZ_MAX, FAL0) > 0);
2048 jleave:
2049 NYD_LEAVE;
2050 return rv;
2053 FL int
2054 c_shift(void *v){
2055 int rv;
2056 NYD_ENTER;
2058 rv = 1;
2060 if(a_amv_lopts != NULL){
2061 ui16_t i, j;
2062 struct a_amv_mac const *amp;
2063 struct a_amv_mac_call_args *amcap;
2065 amp = (amcap = a_amv_lopts->as_amcap)->amca_amp;
2066 if(amp == NULL || amcap->amca_ps_hook_mask ||
2067 (amp->am_flags & a_AMV_MF_TYPE_MASK) == a_AMV_MF_ACCOUNT)
2068 goto jerr;
2070 v = *(char**)v;
2071 if(v == NULL)
2072 i = 1;
2073 else{
2074 si16_t sib;
2076 if((n_idec_si16_cp(&sib, v, 10, NULL
2077 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2078 ) != n_IDEC_STATE_CONSUMED || sib < 0){
2079 n_err(_("`shift': invalid argument: %s\n"), v);
2080 goto jleave;
2082 i = (ui16_t)sib;
2085 if(i > (j = amcap->amca_argc)){
2086 n_err(_("`shift': cannot shift %hu of %hu parameters\n"), i, j);
2087 goto jleave;
2088 }else{
2089 rv = 0;
2090 if(j > 0){
2091 j -= i;
2092 amcap->amca_argc = j;
2093 amcap->amca_argv += i;
2096 }else
2097 jerr:
2098 n_err(_("Can only use `shift' in a `call'ed macro\n"));
2099 jleave:
2100 NYD_LEAVE;
2101 return rv;
2104 FL int
2105 c_return(void *v){
2106 int rv;
2107 NYD_ENTER;
2109 rv = 1;
2111 if(a_amv_lopts != NULL){
2112 char const **argv;
2114 n_source_force_eof();
2116 if((argv = v)[0] != NULL){
2117 si32_t i;
2119 if((n_idec_si32_cp(&i, argv[0], 10, NULL
2120 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2121 ) == n_IDEC_STATE_CONSUMED && i >= 0)
2122 n_pstate_var__em = argv[0];
2123 else
2124 n_err(_("`return': argument one is invalid: %s\n"), argv[0]);
2126 if(argv[1] != NULL){
2127 if((n_idec_si32_cp(&i, argv[1], 10, NULL
2128 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2129 ) == n_IDEC_STATE_CONSUMED && i >= 0)
2130 rv = (int)i;
2131 else{
2132 n_err(_("`return': argument two is invalid: %s\n"), argv[1]);
2133 n_pstate_var__em = n_1;
2135 }else
2136 rv = 0;
2137 }else{
2138 rv = 0;
2139 n_pstate_var__em = n_0;
2141 }else
2142 n_err(_("Can only use `return' in a macro\n"));
2143 NYD_LEAVE;
2144 return rv;
2147 FL bool_t
2148 temporary_folder_hook_check(bool_t nmail){ /* TODO temporary, v15: drop */
2149 struct a_amv_mac_call_args *amcap;
2150 struct a_amv_mac *amp;
2151 size_t len;
2152 char const *cp;
2153 char *var;
2154 bool_t rv;
2155 NYD_ENTER;
2157 rv = TRU1;
2158 var = salloc(len = strlen(mailname) + sizeof("folder-hook-") -1 +1);
2160 /* First try the fully resolved path */
2161 snprintf(var, len, "folder-hook-%s", mailname);
2162 if((cp = n_var_vlook(var, FAL0)) != NULL)
2163 goto jmac;
2165 /* If we are under *folder*, try the usual +NAME syntax, too */
2166 if(displayname[0] == '+'){
2167 char *x;
2169 for(x = &mailname[len]; x != mailname; --x)
2170 if(x[-1] == '/'){
2171 snprintf(var, len, "folder-hook-+%s", x);
2172 if((cp = n_var_vlook(var, FAL0)) != NULL)
2173 goto jmac;
2174 break;
2178 /* Plain *folder-hook* is our last try */
2179 if((cp = ok_vlook(folder_hook)) == NULL)
2180 goto jleave;
2182 jmac:
2183 if((amp = a_amv_mac_lookup(cp, NULL, a_AMV_MF_NONE)) == NULL){
2184 n_err(_("Cannot call *folder-hook* for %s: macro does not exist: %s\n"),
2185 n_shexp_quote_cp(displayname, FAL0), cp);
2186 rv = FAL0;
2187 goto jleave;
2190 amcap = n_lofi_alloc(sizeof *amcap);
2191 memset(amcap, 0, sizeof *amcap);
2192 amcap->amca_name = cp;
2193 amcap->amca_amp = amp;
2194 n_pstate &= ~n_PS_HOOK_MASK;
2195 if(nmail){
2196 amcap->amca_unroller = NULL;
2197 n_pstate |= n_PS_HOOK_NEWMAIL;
2198 }else{
2199 amcap->amca_unroller = &a_amv_folder_hook_lopts;
2200 n_pstate |= n_PS_HOOK;
2202 amcap->amca_lopts_on = TRU1;
2203 amcap->amca_ps_hook_mask = TRU1;
2204 rv = a_amv_mac_exec(amcap);
2205 n_pstate &= ~n_PS_HOOK_MASK;
2207 jleave:
2208 NYD_LEAVE;
2209 return rv;
2212 FL void
2213 temporary_folder_hook_unroll(void){ /* XXX intermediate hack */
2214 NYD_ENTER;
2215 if(a_amv_folder_hook_lopts != NULL){
2216 void *save = a_amv_lopts;
2218 a_amv_lopts = NULL;
2219 a_amv_lopts_unroll(&a_amv_folder_hook_lopts);
2220 a_amv_folder_hook_lopts = NULL;
2221 a_amv_lopts = save;
2223 NYD_LEAVE;
2226 FL void
2227 temporary_compose_mode_hook_call(char const *macname,
2228 void (*hook_pre)(void *), void *hook_arg){
2229 /* TODO compose_mode_hook_call() temporary, v15: generalize; see a_LEX_SPLICE
2230 * TODO comment in lex-input.c for the right way of doing things! */
2231 static struct a_amv_lostack *cmh_losp;
2232 struct a_amv_mac_call_args *amcap;
2233 struct a_amv_mac *amp;
2234 NYD_ENTER;
2236 amp = NULL;
2238 if(macname == (char*)-1){
2239 a_amv_mac__finalize(cmh_losp);
2240 cmh_losp = NULL;
2241 }else if(macname != NULL &&
2242 (amp = a_amv_mac_lookup(macname, NULL, a_AMV_MF_NONE)) == NULL)
2243 n_err(_("Cannot call *on-compose-**: macro does not exist: %s\n"),
2244 macname);
2245 else{
2246 amcap = n_lofi_alloc(sizeof *amcap);
2247 memset(amcap, 0, sizeof *amcap);
2248 amcap->amca_name = (macname != NULL) ? macname
2249 : "on-compose-splice-shell";
2250 amcap->amca_amp = amp;
2251 amcap->amca_unroller = &a_amv_compose_lopts;
2252 amcap->amca_hook_pre = hook_pre;
2253 amcap->amca_hook_arg = hook_arg;
2254 amcap->amca_lopts_on = TRU1;
2255 amcap->amca_ps_hook_mask = TRU1;
2256 n_pstate &= ~n_PS_HOOK_MASK;
2257 n_pstate |= n_PS_HOOK;
2258 if(macname != NULL)
2259 a_amv_mac_exec(amcap);
2260 else{
2261 cmh_losp = n_lofi_alloc(sizeof *cmh_losp);
2262 cmh_losp->as_global_saved = a_amv_lopts;
2263 cmh_losp->as_up = NULL;
2264 cmh_losp->as_lopts = *(cmh_losp->as_amcap = amcap)->amca_unroller;
2265 cmh_losp->as_unroll = TRU1;
2266 a_amv_lopts = cmh_losp;
2269 NYD_LEAVE;
2272 FL void
2273 temporary_compose_mode_hook_unroll(void){ /* XXX intermediate hack */
2274 NYD_ENTER;
2275 if(a_amv_compose_lopts != NULL){
2276 void *save = a_amv_lopts;
2278 a_amv_lopts = NULL;
2279 a_amv_lopts_unroll(&a_amv_compose_lopts);
2280 a_amv_compose_lopts = NULL;
2281 a_amv_lopts = save;
2283 NYD_LEAVE;
2286 FL bool_t
2287 n_var_is_user_writable(char const *name){
2288 struct a_amv_var_carrier avc;
2289 struct a_amv_var_map const *avmp;
2290 bool_t rv;
2291 NYD_ENTER;
2293 a_amv_var_revlookup(&avc, name);
2294 if((avmp = avc.avc_map) == NULL)
2295 rv = TRU1;
2296 else
2297 rv = ((avmp->avm_flags & (a_AMV_VF_BOOL | a_AMV_VF_RDONLY)) == 0);
2298 NYD_LEAVE;
2299 return rv;
2302 FL char *
2303 n_var_oklook(enum okeys okey){
2304 struct a_amv_var_carrier avc;
2305 char *rv;
2306 struct a_amv_var_map const *avmp;
2307 NYD_ENTER;
2309 avc.avc_map = avmp = &a_amv_var_map[okey];
2310 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2311 avc.avc_hash = avmp->avm_hash;
2312 avc.avc_okey = okey;
2314 if(a_amv_var_lookup(&avc, FAL0))
2315 rv = avc.avc_var->av_value;
2316 else
2317 rv = NULL;
2318 NYD_LEAVE;
2319 return rv;
2322 FL bool_t
2323 n_var_okset(enum okeys okey, uintptr_t val){
2324 struct a_amv_var_carrier avc;
2325 bool_t ok;
2326 struct a_amv_var_map const *avmp;
2327 NYD_ENTER;
2329 avc.avc_map = avmp = &a_amv_var_map[okey];
2330 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2331 avc.avc_hash = avmp->avm_hash;
2332 avc.avc_okey = okey;
2334 ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val), FAL0);
2335 NYD_LEAVE;
2336 return ok;
2339 FL bool_t
2340 n_var_okclear(enum okeys okey){
2341 struct a_amv_var_carrier avc;
2342 bool_t rv;
2343 struct a_amv_var_map const *avmp;
2344 NYD_ENTER;
2346 avc.avc_map = avmp = &a_amv_var_map[okey];
2347 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2348 avc.avc_hash = avmp->avm_hash;
2349 avc.avc_okey = okey;
2351 rv = a_amv_var_clear(&avc, FAL0);
2352 NYD_LEAVE;
2353 return rv;
2356 FL char const *
2357 n_var_vlook(char const *vokey, bool_t try_getenv){
2358 struct a_amv_var_carrier avc;
2359 char const *rv;
2360 NYD_ENTER;
2362 a_amv_var_revlookup(&avc, vokey);
2364 switch((enum a_amv_var_special_category)avc.avc_special_cat){
2365 default: /* silence CC */
2366 case a_AMV_VSC_NONE:
2367 if(a_amv_var_lookup(&avc, FAL0))
2368 rv = avc.avc_var->av_value;
2369 /* Only check the environment for something that is otherwise unknown */
2370 else if(try_getenv && avc.avc_map == NULL)
2371 rv = getenv(vokey);
2372 else
2373 rv = NULL;
2374 break;
2375 case a_AMV_VSC_GLOBAL:
2376 rv = a_amv_var_vsc_global(&avc);
2377 break;
2378 case a_AMV_VSC_MULTIPLEX:
2379 rv = a_amv_var_vsc_multiplex(&avc);
2380 break;
2381 case a_AMV_VSC_MAC:
2382 case a_AMV_VSC_MAC_ARGV:
2383 rv = a_amv_var_vsc_mac(&avc);
2384 break;
2386 NYD_LEAVE;
2387 return rv;
2390 FL bool_t
2391 n_var_vexplode(void const **cookie){
2392 NYD_ENTER;
2393 /* These may occur only in a macro.. */
2394 *cookie = (a_amv_lopts != NULL) ? a_amv_lopts->as_amcap->amca_argv : NULL;
2395 NYD_LEAVE;
2396 return (*cookie != NULL);
2399 FL bool_t
2400 n_var_vset(char const *vokey, uintptr_t val){
2401 struct a_amv_var_carrier avc;
2402 bool_t ok;
2403 NYD_ENTER;
2405 a_amv_var_revlookup(&avc, vokey);
2407 ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val), FAL0);
2408 NYD_LEAVE;
2409 return ok;
2412 FL bool_t
2413 n_var_vclear(char const *vokey){
2414 struct a_amv_var_carrier avc;
2415 bool_t ok;
2416 NYD_ENTER;
2418 a_amv_var_revlookup(&avc, vokey);
2420 ok = a_amv_var_clear(&avc, FAL0);
2421 NYD_LEAVE;
2422 return ok;
2425 #ifdef HAVE_SOCKETS
2426 FL char *
2427 n_var_xoklook(enum okeys okey, struct url const *urlp,
2428 enum okey_xlook_mode oxm){
2429 struct a_amv_var_carrier avc;
2430 struct str const *us;
2431 size_t nlen;
2432 char *nbuf, *rv;
2433 struct a_amv_var_map const *avmp;
2434 NYD_ENTER;
2436 assert(oxm & (OXM_PLAIN | OXM_H_P | OXM_U_H_P));
2438 /* For simplicity: allow this case too */
2439 if(!(oxm & (OXM_H_P | OXM_U_H_P))){
2440 nbuf = NULL;
2441 goto jplain;
2444 avc.avc_map = avmp = &a_amv_var_map[okey];
2445 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2446 avc.avc_okey = okey;
2448 us = (oxm & OXM_U_H_P) ? &urlp->url_u_h_p : &urlp->url_h_p;
2449 nlen = strlen(avc.avc_name);
2450 nbuf = n_lofi_alloc(nlen + 1 + us->l +1);
2451 memcpy(nbuf, avc.avc_name, nlen);
2452 nbuf[nlen++] = '-';
2454 /* One of .url_u_h_p and .url_h_p we test in here */
2455 memcpy(nbuf + nlen, us->s, us->l +1);
2456 avc.avc_name = a_amv_var_canonify(nbuf);
2457 avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
2458 if(a_amv_var_lookup(&avc, FAL0))
2459 goto jvar;
2461 /* The second */
2462 if(oxm & OXM_H_P){
2463 us = &urlp->url_h_p;
2464 memcpy(nbuf + nlen, us->s, us->l +1);
2465 avc.avc_name = a_amv_var_canonify(nbuf);
2466 avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
2467 if(a_amv_var_lookup(&avc, FAL0)){
2468 jvar:
2469 rv = avc.avc_var->av_value;
2470 goto jleave;
2474 jplain:
2475 rv = (oxm & OXM_PLAIN) ? n_var_oklook(okey) : NULL;
2476 jleave:
2477 if(nbuf != NULL)
2478 n_lofi_free(nbuf);
2479 NYD_LEAVE;
2480 return rv;
2482 #endif /* HAVE_SOCKETS */
2484 FL int
2485 c_set(void *v){
2486 char **ap;
2487 int err;
2488 NYD_ENTER;
2490 if(*(ap = v) == NULL){
2491 a_amv_var_show_all();
2492 err = 0;
2493 }else
2494 err = !a_amv_var_c_set(ap, FAL0);
2495 NYD_LEAVE;
2496 return err;
2499 FL int
2500 c_unset(void *v){
2501 char **ap;
2502 int err;
2503 NYD_ENTER;
2505 for(err = 0, ap = v; *ap != NULL; ++ap)
2506 err |= !n_var_vclear(*ap);
2507 NYD_LEAVE;
2508 return err;
2511 FL int
2512 c_varshow(void *v){
2513 char **ap;
2514 NYD_ENTER;
2516 if(*(ap = v) == NULL)
2517 v = NULL;
2518 else{
2519 struct n_string msg, *msgp = &msg;
2521 msgp = n_string_creat(msgp);
2522 for(; *ap != NULL; ++ap)
2523 a_amv_var_show(*ap, n_stdout, msgp);
2524 n_string_gut(msgp);
2526 NYD_LEAVE;
2527 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
2530 FL int
2531 c_varedit(void *v){
2532 struct a_amv_var_carrier avc;
2533 FILE *of, *nf;
2534 char *val, **argv;
2535 int err;
2536 sighandler_type sigint;
2537 NYD_ENTER;
2539 sigint = safe_signal(SIGINT, SIG_IGN);
2541 for(err = 0, argv = v; *argv != NULL; ++argv){
2542 memset(&avc, 0, sizeof avc);
2544 a_amv_var_revlookup(&avc, *argv);
2546 if(avc.avc_map != NULL){
2547 if(avc.avc_map->avm_flags & a_AMV_VF_BOOL){
2548 n_err(_("`varedit': cannot edit boolean variable: %s\n"),
2549 avc.avc_name);
2550 continue;
2552 if(avc.avc_map->avm_flags & a_AMV_VF_RDONLY){
2553 n_err(_("`varedit': cannot edit read-only variable: %s\n"),
2554 avc.avc_name);
2555 continue;
2559 a_amv_var_lookup(&avc, FAL0);
2561 if((of = Ftmp(NULL, "varedit", OF_RDWR | OF_UNLINK | OF_REGISTER)) ==
2562 NULL){
2563 n_perr(_("`varedit': can't create temporary file, bailing out"), 0);
2564 err = 1;
2565 break;
2566 }else if(avc.avc_var != NULL && *(val = avc.avc_var->av_value) != '\0' &&
2567 sizeof *val != fwrite(val, strlen(val), sizeof *val, of)){
2568 n_perr(_("`varedit' failed to write old value to temporary file"), 0);
2569 Fclose(of);
2570 err = 1;
2571 continue;
2574 fflush_rewind(of);
2575 nf = run_editor(of, (off_t)-1, 'e', FAL0, NULL, NULL, SEND_MBOX, sigint);
2576 Fclose(of);
2578 if(nf != NULL){
2579 int c;
2580 char *base;
2581 off_t l;
2583 l = fsize(nf);
2584 assert(l >= 0);
2585 base = salloc((size_t)l +1);
2587 for(l = 0, val = base; (c = getc(nf)) != EOF; ++val)
2588 if(c == '\n' || c == '\r'){
2589 *val = ' ';
2590 ++l;
2591 }else{
2592 *val = (char)(uc_i)c;
2593 l = 0;
2595 val -= l;
2596 *val = '\0';
2598 if(!a_amv_var_set(&avc, base, FAL0))
2599 err = 1;
2601 Fclose(nf);
2602 }else{
2603 n_err(_("`varedit': can't start $EDITOR, bailing out\n"));
2604 err = 1;
2605 break;
2609 safe_signal(SIGINT, sigint);
2610 NYD_LEAVE;
2611 return err;
2614 FL int
2615 c_environ(void *v){
2616 struct a_amv_var_carrier avc;
2617 int err;
2618 char **ap;
2619 bool_t islnk;
2620 NYD_ENTER;
2622 if((islnk = is_asccaseprefix(*(ap = v), "link")) ||
2623 is_asccaseprefix(*ap, "unlink")){
2624 for(err = 0; *++ap != NULL;){
2625 a_amv_var_revlookup(&avc, *ap);
2627 if(a_amv_var_lookup(&avc, FAL0) && (islnk ||
2628 (avc.avc_var->av_flags & a_AMV_VF_LINKED))){
2629 if(!islnk){
2630 avc.avc_var->av_flags &= ~a_AMV_VF_LINKED;
2631 continue;
2632 }else if(avc.avc_var->av_flags & (a_AMV_VF_ENV | a_AMV_VF_LINKED)){
2633 if(n_poption & n_PO_D_V)
2634 n_err(_("`environ': link: already established: %s\n"), *ap);
2635 continue;
2637 avc.avc_var->av_flags |= a_AMV_VF_LINKED;
2638 if(!(avc.avc_var->av_flags & a_AMV_VF_ENV))
2639 a_amv_var__putenv(&avc, avc.avc_var);
2640 }else if(!islnk){
2641 n_err(_("`environ': unlink: no link established: %s\n"), *ap);
2642 err = 1;
2643 }else{
2644 char const *evp = getenv(*ap);
2646 if(evp != NULL)
2647 err |= !a_amv_var_set(&avc, evp, TRU1);
2648 else{
2649 n_err(_("`environ': link: cannot link to non-existent: %s\n"),
2650 *ap);
2651 err = 1;
2655 }else if(is_asccaseprefix(*ap, "set"))
2656 err = !a_amv_var_c_set(++ap, TRU1);
2657 else if(is_asccaseprefix(*ap, "unset")){
2658 for(err = 0; *++ap != NULL;){
2659 a_amv_var_revlookup(&avc, *ap);
2661 if(!a_amv_var_clear(&avc, TRU1))
2662 err = 1;
2664 }else{
2665 n_err(_("Synopsis: environ: <link|set|unset> <variable>...\n"));
2666 err = 1;
2668 NYD_LEAVE;
2669 return err;
2672 FL int
2673 c_vexpr(void *v){ /* TODO POSIX expr(1) comp. exit status; overly complicat. */
2674 /* This needs to be here because we need to apply MACKY_MACK for
2675 * search+replace regular expression support :( */
2676 size_t i;
2677 enum n_idec_state ids;
2678 si64_t lhv, rhv;
2679 char op, varbuf[64 + 64 / 8 +1];
2680 char const **argv, *varname, *varres, *cp;
2681 enum{
2682 a_ERR = 1<<0,
2683 a_SOFTERR = 1<<1,
2684 a_ISNUM = 1<<2,
2685 a_ISDECIMAL = 1<<3, /* Print only decimal result */
2686 a_SATURATED = 1<<4,
2687 a_ICASE = 1<<5,
2688 a_UNSIGNED = 1<<6, /* Unsigned right shift (share bit ok) */
2689 a_TMP = 1<<30
2690 } f;
2691 NYD_ENTER;
2693 f = a_ERR;
2694 argv = v;
2695 varname = (n_pstate & n_PS_ARGMOD_VPUT) ? *argv++ : NULL;
2696 n_UNINIT(varres, n_empty);
2698 if((cp = argv[0])[0] == '\0')
2699 goto jesubcmd;
2701 if(cp[1] == '\0'){
2702 op = cp[0];
2703 jnumop:
2704 f |= a_ISNUM;
2705 switch(op){
2706 case '=':
2707 case '~':
2708 if(argv[1] == NULL || argv[2] != NULL)
2709 goto jesynopsis;
2711 if(*(cp = *++argv) == '\0')
2712 lhv = 0;
2713 else if(((ids = n_idec_si64_cp(&lhv, cp, 0, NULL)
2714 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2715 ) != n_IDEC_STATE_CONSUMED){
2716 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
2717 goto jenum_range;
2718 f |= a_SOFTERR;
2719 break;
2721 if(op == '~')
2722 lhv = ~lhv;
2723 break;
2725 case '+':
2726 case '-':
2727 case '*':
2728 case '/':
2729 case '%':
2730 case '|':
2731 case '&':
2732 case '^':
2733 case '<':
2734 case '>':
2735 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
2736 goto jesynopsis;
2737 else{
2738 char xop;
2740 if(*(cp = *++argv) == '\0')
2741 lhv = 0;
2742 else if(((ids = n_idec_si64_cp(&lhv, cp, 0, NULL)
2743 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2744 ) != n_IDEC_STATE_CONSUMED){
2745 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
2746 goto jenum_range;
2747 f |= a_SOFTERR;
2748 break;
2751 if(*(cp = *++argv) == '\0')
2752 rhv = 0;
2753 else if(((ids = n_idec_si64_cp(&rhv, cp, 0, NULL)
2754 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2755 ) != n_IDEC_STATE_CONSUMED){
2756 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
2757 goto jenum_range;
2758 f |= a_SOFTERR;
2759 lhv = rhv;
2760 break;
2763 xop = op;
2764 jnumop_again:
2765 switch(xop){
2766 case '+':
2767 if(rhv < 0){
2768 if(rhv != SI64_MIN){
2769 rhv = -rhv;
2770 xop = '-';
2771 goto jnumop_again;
2772 }else if(lhv < 0)
2773 goto jeplusminus;
2774 else if(lhv == 0){
2775 lhv = rhv;
2776 break;
2779 if(SI64_MAX - rhv < lhv)
2780 goto jeplusminus;
2781 lhv += rhv;
2782 break;
2783 case '-':
2784 if(rhv < 0){
2785 if(rhv != SI64_MIN){
2786 rhv = -rhv;
2787 xop = '+';
2788 goto jnumop_again;
2789 }else if(lhv > 0)
2790 goto jeplusminus;
2791 else if(lhv == 0){
2792 lhv = rhv;
2793 break;
2796 if(SI64_MIN + rhv > lhv){
2797 jeplusminus:
2798 if(!(f & a_SATURATED))
2799 goto jenum_overflow;
2800 f |= a_SOFTERR;
2801 lhv = (lhv < 0 || xop == '-') ? SI64_MIN : SI64_MAX;
2802 }else
2803 lhv -= rhv;
2804 break;
2805 case '*':
2806 /* Will the result be positive? */
2807 if((lhv < 0) == (rhv < 0)){
2808 if(lhv > 0){
2809 lhv = -lhv;
2810 rhv = -rhv;
2812 if(rhv != 0 && lhv != 0 && SI64_MAX / rhv > lhv){
2813 if(!(f & a_SATURATED))
2814 goto jenum_overflow;
2815 f |= a_SOFTERR;
2816 lhv = SI64_MAX;
2817 }else
2818 lhv *= rhv;
2819 }else{
2820 if(rhv > 0){
2821 if(lhv != 0 && SI64_MIN / lhv < rhv){
2822 if(!(f & a_SATURATED))
2823 goto jenum_overflow;
2824 f |= a_SOFTERR;
2825 lhv = SI64_MIN;
2826 }else
2827 lhv *= rhv;
2828 }else{
2829 if(rhv != 0 && lhv != 0 && SI64_MIN / rhv < lhv){
2830 if(!(f & a_SATURATED))
2831 goto jenum_overflow;
2832 f |= a_SOFTERR;
2833 lhv = SI64_MIN;
2834 }else
2835 lhv *= rhv;
2838 break;
2839 case '/':
2840 if(rhv == 0){
2841 if(!(f & a_SATURATED))
2842 goto jenum_range;
2843 f |= a_SOFTERR;
2844 lhv = SI64_MAX;
2845 }else
2846 lhv /= rhv;
2847 break;
2848 case '%':
2849 if(rhv == 0){
2850 if(!(f & a_SATURATED))
2851 goto jenum_range;
2852 f |= a_SOFTERR;
2853 lhv = SI64_MAX;
2854 }else
2855 lhv %= rhv;
2856 break;
2857 case '|':
2858 lhv |= rhv;
2859 break;
2860 case '&':
2861 lhv &= rhv;
2862 break;
2863 case '^':
2864 lhv ^= rhv;
2865 break;
2866 case '<':
2867 case '>':
2868 if(!(f & a_TMP))
2869 goto jesubcmd;
2870 if(rhv > 63){ /* xxx 63? */
2871 if(!(f & a_SATURATED))
2872 goto jenum_overflow;
2873 rhv = 63;
2875 if(op == '<')
2876 lhv <<= (ui8_t)rhv;
2877 else if(f & a_UNSIGNED)
2878 lhv = (ui64_t)lhv >> (ui8_t)rhv;
2879 else
2880 lhv >>= (ui8_t)rhv;
2881 break;
2884 break;
2885 default:
2886 goto jesubcmd;
2888 }else if(cp[2] == '\0' && cp[1] == '@'){
2889 f |= a_SATURATED;
2890 op = cp[0];
2891 goto jnumop;
2892 }else if(cp[0] == '<'){
2893 if(*++cp != '<')
2894 goto jesubcmd;
2895 if(*++cp == '@'){
2896 f |= a_SATURATED;
2897 ++cp;
2899 if(*cp != '\0')
2900 goto jesubcmd;
2901 f |= a_TMP;
2902 op = '<';
2903 goto jnumop;
2904 }else if(cp[0] == '>'){
2905 if(*++cp != '>')
2906 goto jesubcmd;
2907 if(*++cp == '>'){
2908 f |= a_UNSIGNED;
2909 ++cp;
2911 if(*cp == '@'){
2912 f |= a_SATURATED;
2913 ++cp;
2915 if(*cp != '\0')
2916 goto jesubcmd;
2917 f |= a_TMP;
2918 op = '>';
2919 goto jnumop;
2920 }else if(is_asccaseprefix(cp, "length")){
2921 f |= a_ISNUM | a_ISDECIMAL;
2922 if(argv[1] == NULL || argv[2] != NULL)
2923 goto jesynopsis;
2925 i = strlen(*++argv);
2926 if(UICMP(64, i, >, SI64_MAX))
2927 goto jestr_overflow;
2928 lhv = (si64_t)i;
2929 }else if(is_asccaseprefix(cp, "hash")){
2930 f |= a_ISNUM | a_ISDECIMAL;
2931 if(argv[1] == NULL || argv[2] != NULL)
2932 goto jesynopsis;
2934 i = torek_hash(*++argv);
2935 lhv = (si64_t)i;
2936 }else if(is_asccaseprefix(cp, "file-expand")){
2937 if(argv[1] == NULL || argv[2] != NULL)
2938 goto jesynopsis;
2940 if((varres = fexpand(argv[1], FEXP_NVAR | FEXP_NOPROTO)) == NULL)
2941 goto jsofterr;
2942 }else if(is_asccaseprefix(cp, "random")){
2943 if(argv[1] == NULL || argv[2] != NULL)
2944 goto jesynopsis;
2946 if((n_idec_si64_cp(&lhv, argv[1], 0, NULL
2947 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2948 ) != n_IDEC_STATE_CONSUMED || lhv < 0 || lhv > PATH_MAX)
2949 goto jenum_range;
2950 if(lhv == 0)
2951 lhv = NAME_MAX;
2952 varres = getrandstring((size_t)lhv);
2953 }else if(is_asccaseprefix(cp, "find")){
2954 f |= a_ISNUM | a_ISDECIMAL;
2955 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
2956 goto jesynopsis;
2958 if((cp = strstr(argv[1], argv[2])) == NULL)
2959 goto jsofterr;
2960 i = PTR2SIZE(cp - argv[1]);
2961 if(UICMP(64, i, >, SI64_MAX))
2962 goto jestr_overflow;
2963 lhv = (si64_t)i;
2964 }else if(is_asccaseprefix(cp, "ifind")){
2965 f |= a_ISNUM | a_ISDECIMAL;
2966 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
2967 goto jesynopsis;
2969 if((cp = asccasestr(argv[1], argv[2])) == NULL)
2970 goto jsofterr;
2971 i = PTR2SIZE(cp - argv[1]);
2972 if(UICMP(64, i, >, SI64_MAX))
2973 goto jestr_overflow;
2974 lhv = (si64_t)i;
2975 }else if(is_asccaseprefix(cp, "substring")){
2976 if(argv[1] == NULL || argv[2] == NULL)
2977 goto jesynopsis;
2978 if(argv[3] != NULL && argv[4] != NULL)
2979 goto jesynopsis;
2981 i = strlen(varres = *++argv);
2983 if(*(cp = *++argv) == '\0')
2984 lhv = 0;
2985 else if((n_idec_si64_cp(&lhv, cp, 0, NULL
2986 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2987 ) != n_IDEC_STATE_CONSUMED)
2988 goto jenum_range;
2989 if(UICMP(64, i, >=, lhv)){
2990 i -= lhv;
2991 varres += lhv;
2992 }else{
2993 if(n_poption & n_PO_D_V)
2994 n_err(_("`vexpr': substring: offset argument too large: %s\n"),
2995 n_shexp_quote_cp(argv[-1], FAL0));
2996 f |= a_SOFTERR;
2999 if(argv[1] != NULL){
3000 if(*(cp = *++argv) == '\0')
3001 lhv = 0;
3002 else if((n_idec_si64_cp(&lhv, cp, 0, NULL
3003 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3004 ) != n_IDEC_STATE_CONSUMED)
3005 goto jenum_range;
3006 if(UICMP(64, i, >=, lhv)){
3007 if(UICMP(64, i, !=, lhv))
3008 varres = savestrbuf(varres, (size_t)lhv);
3009 }else{
3010 if(n_poption & n_PO_D_V)
3011 n_err(_("`vexpr': substring: length argument too large: %s\n"),
3012 n_shexp_quote_cp(argv[-2], FAL0));
3013 f |= a_SOFTERR;
3016 #ifdef HAVE_REGEX
3017 }else if(is_asccaseprefix(cp, "regex")) Jregex:{
3018 regmatch_t rema[1 + n_VEXPR_REGEX_MAX];
3019 regex_t re;
3020 int reflrv;
3022 f |= a_ISNUM | a_ISDECIMAL;
3023 if(argv[1] == NULL || argv[2] == NULL ||
3024 (argv[3] != NULL && argv[4] != NULL))
3025 goto jesynopsis;
3027 reflrv = REG_EXTENDED;
3028 if(f & a_ICASE)
3029 reflrv |= REG_ICASE;
3030 if((reflrv = regcomp(&re, argv[2], reflrv))){
3031 n_err(_("`vexpr': invalid regular expression: %s: %s\n"),
3032 n_shexp_quote_cp(argv[2], FAL0), n_regex_err_to_doc(&re, reflrv));
3033 assert(f & a_ERR);
3034 goto jerr;
3036 reflrv = regexec(&re, argv[1], n_NELEM(rema), rema, 0);
3037 regfree(&re);
3038 if(reflrv == REG_NOMATCH)
3039 goto jsofterr;
3041 /* Search only? Else replace, which is a bit */
3042 if(argv[3] == NULL){
3043 if(UICMP(64, rema[0].rm_so, >, SI64_MAX))
3044 goto jestr_overflow;
3045 lhv = (si64_t)rema[0].rm_so;
3046 }else{
3047 /* We need to setup some kind of pseudo macro environment for this */
3048 struct a_amv_lostack los;
3049 struct a_amv_mac_call_args amca;
3050 char const **reargv;
3052 memset(&amca, 0, sizeof amca);
3053 amca.amca_name = savestrbuf(&argv[1][rema[0].rm_so],
3054 rema[0].rm_eo - rema[0].rm_so);
3055 amca.amca_amp = a_AMV_MACKY_MACK;
3056 for(i = 1; rema[i].rm_so != -1 && i < n_NELEM(rema); ++i)
3058 amca.amca_argc = (ui32_t)i - 1;
3059 amca.amca_argv =
3060 reargv = salloc(sizeof(char*) * i);
3061 for(i = 1; rema[i].rm_so != -1 && i < n_NELEM(rema); ++i)
3062 *reargv++ = savestrbuf(&argv[1][rema[i].rm_so],
3063 rema[i].rm_eo - rema[i].rm_so);
3064 *reargv = NULL;
3066 hold_all_sigs(); /* TODO DISLIKE! */
3067 los.as_global_saved = a_amv_lopts;
3068 los.as_amcap = &amca;
3069 los.as_up = los.as_global_saved;
3070 los.as_lopts = NULL;
3071 los.as_unroll = FAL0;
3072 a_amv_lopts = &los;
3074 /* C99 */{
3075 struct str templ;
3076 struct n_string s_b;
3077 enum n_shexp_state shs;
3079 templ.s = n_UNCONST(argv[3]);
3080 templ.l = UIZ_MAX;
3081 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
3082 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
3083 n_SHEXP_PARSE_QUOTE_AUTO_DSQ),
3084 n_string_creat_auto(&s_b), &templ, NULL);
3085 if((shs & (n_SHEXP_STATE_ERR_MASK | n_SHEXP_STATE_STOP)
3086 ) == n_SHEXP_STATE_STOP){
3087 varres = n_string_cp(&s_b);
3088 n_string_drop_ownership(&s_b);
3089 }else
3090 varres = NULL;
3093 a_amv_lopts = los.as_global_saved;
3094 rele_all_sigs(); /* TODO DISLIKE! */
3096 if(varres == NULL)
3097 goto jsofterr;
3098 f &= ~(a_ISNUM | a_ISDECIMAL);
3100 }else if(is_asccaseprefix(argv[0], "iregex")){
3101 f |= a_ICASE;
3102 goto Jregex;
3103 #endif /* HAVE_REGEX */
3104 }else
3105 goto jesubcmd;
3107 f &= ~a_ERR;
3109 /* Generate the variable value content for numerics.
3110 * Anticipate in our handling below! (Don't do needless work) */
3111 jleave:
3112 if((f & a_ISNUM) && ((f & a_ISDECIMAL) || varname != NULL)){
3113 snprintf(varbuf, sizeof varbuf, "%" PRId64 , lhv);
3114 varres = varbuf;
3117 if(varname == NULL){
3118 /* If there was no error and we are printing a numeric result, print some
3119 * more bases for the fun of it */
3120 if((f & (a_ERR | a_ISNUM | a_ISDECIMAL)) == a_ISNUM){
3121 size_t j;
3123 for(j = 1, i = 0; i < 64; ++i){
3124 varbuf[63 + 64 / 8 -j - i] = (lhv & ((ui64_t)1 << i)) ? '1' : '0';
3125 if((i & 7) == 7 && i != 63){
3126 ++j;
3127 varbuf[63 + 64 / 8 -j - i] = ' ';
3130 varbuf[64 + 64 / 8 -1] = '\0';
3131 fprintf(n_stdout, "%s\n0%" PRIo64 " | 0x%" PRIX64 " | %" PRId64 "\n",
3132 varbuf, lhv, lhv, lhv);
3133 }else
3134 fprintf(n_stdout, "%s\n", varres);
3135 }else if(!n_var_vset(varname, (uintptr_t)varres))
3136 f |= a_ERR | a_SOFTERR;
3137 else if(!(f & a_SOFTERR))
3138 n_pstate_var__em = n_0;
3139 NYD_LEAVE;
3140 return (f & a_ERR) ? 1 : 0;
3142 jsofterr:
3143 f &= ~a_ERR;
3144 jerr:
3145 f &= ~(a_ISNUM | a_ISDECIMAL);
3146 f |= a_SOFTERR | a_ISNUM;
3147 lhv = -1;
3148 goto jleave;
3149 jesubcmd:
3150 assert(f & a_ERR);
3151 n_err(_("`vexpr': invalid subcommand: %s\n"),
3152 n_shexp_quote_cp(*argv, FAL0));
3153 goto jerr;
3154 jesynopsis:
3155 assert(f & a_ERR);
3156 n_err(_("Synopsis: vexpr: <target-variable> <operator> <:argument:>\n"));
3157 goto jerr;
3158 jenum_range:
3159 assert(f & a_ERR);
3160 n_err(_("`vexpr': numeric argument invalid or out of range: %s\n"),
3161 n_shexp_quote_cp(*argv, FAL0));
3162 goto jsofterr;
3163 jenum_overflow:
3164 assert(f & a_ERR);
3165 n_err(_("`vexpr': expression overflows datatype: %" PRId64 " %c %" PRId64
3166 "\n"), lhv, op, rhv);
3167 goto jsofterr;
3168 jestr_overflow:
3169 assert(f & a_ERR);
3170 n_err(_("`vexpr': string length or offset overflows datatype\n"));
3171 goto jsofterr;
3174 /* s-it-mode */