cc-test.sh: add t_behave_quote_a_cmd_escapes() (Andrew Gee)
[s-mailx.git] / accmacvar.c
blob9c325ca6d05ceb647361bb96f76bc7c1e481ca18
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 make-okey-map.pl
6 *@ - update the manual!
7 *@ TODO . Improve support for chains so that we can apply the property checks
8 *@ TODO of the base variable to -HOST and -USER@HOST variants! Add some!!
9 *@ TODO Now with `local' modifier we need to be able to catch that, as well
10 *@ TODO as linked environment variables: both of which are not catched and
11 *@ TODO can be shadowed, which is documented for `set' - change on change!!
12 *@ TODO . `localopts' should act like an automatic permanent `scope' command
13 *@ TODO modifier! We need an OnScopeLeaveEvent, then.
14 *@ TODO Also see the a_GO_SPLICE comment in go.c.
15 *@ TODO . Optimize: with the dynamic hashmaps, and the object based approach
16 *@ TODO it should become possible to strip down the implementation again.
17 *@ TODO E.g., FREEZE is much too complicated: use an overlay object ptr,
18 *@ TODO UNLIKELY() it, and add a OnProgramStartupCompletedEvent to
19 *@ TODO incorporate what it tracks, then drop it. Etc.
20 *@ TODO Global -> Scope -> Local, all "overlay" objects.
22 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
23 * Copyright (c) 2012 - 2018 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
26 * Copyright (c) 1980, 1993
27 * The Regents of the University of California. All rights reserved.
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that the following conditions
31 * are met:
32 * 1. Redistributions of source code must retain the above copyright
33 * notice, this list of conditions and the following disclaimer.
34 * 2. Redistributions in binary form must reproduce the above copyright
35 * notice, this list of conditions and the following disclaimer in the
36 * documentation and/or other materials provided with the distribution.
37 * 3. Neither the name of the University nor the names of its contributors
38 * may be used to endorse or promote products derived from this software
39 * without specific prior written permission.
41 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
53 #undef n_FILE
54 #define n_FILE accmacvar
56 #ifndef HAVE_AMALGAMATION
57 # include "nail.h"
58 #endif
60 #if !defined HAVE_SETENV && !defined HAVE_PUTENV
61 # error Exactly one of HAVE_SETENV and HAVE_PUTENV
62 #endif
64 /* Positional parameter maximum (macro arguments, `vexpr' "splitifs") */
65 #define a_AMV_POSPAR_MAX SI16_MAX
67 /* Special "pseudo macro" that stabs you from the back */
68 #define a_AMV_MACKY_MACK ((struct a_amv_mac*)-1)
70 /* Note: changing the hash function must be reflected in `vexpr' "hash",
71 * because that is used by the hashtable creator scripts! */
72 #define a_AMV_PRIME HSHSIZE
73 #define a_AMV_NAME2HASH(N) n_torek_hash(N)
74 #define a_AMV_HASH2PRIME(H) ((H) % a_AMV_PRIME)
76 enum a_amv_mac_flags{
77 a_AMV_MF_NONE = 0,
78 a_AMV_MF_ACCOUNT = 1u<<0, /* This macro is an `account' */
79 a_AMV_MF_TYPE_MASK = a_AMV_MF_ACCOUNT,
80 a_AMV_MF_UNDEF = 1u<<1, /* Unlink after lookup */
81 a_AMV_MF_DELETE = 1u<<7, /* Delete in progress, free once refcnt==0 */
82 a_AMV_MF__MAX = 0xFFu
85 enum a_amv_loflags{
86 a_AMV_LF_NONE = 0,
87 a_AMV_LF_SCOPE = 1u<<0, /* Current scope `localopts' on */
88 a_AMV_LF_SCOPE_FIXATE = 1u<<1, /* Ditto, but fixated */
89 a_AMV_LF_SCOPE_MASK = a_AMV_LF_SCOPE | a_AMV_LF_SCOPE_FIXATE,
90 a_AMV_LF_CALL = 1u<<2, /* `localopts' on for `call'ed scopes */
91 a_AMV_LF_CALL_FIXATE = 1u<<3, /* Ditto, but fixated */
92 a_AMV_LF_CALL_MASK = a_AMV_LF_CALL | a_AMV_LF_CALL_FIXATE,
93 a_AMV_LF_CALL_TO_SCOPE_SHIFT = 2
96 /* make-okey-map.pl ensures that _VIRT implies _RDONLY and _NODEL, and that
97 * _IMPORT implies _ENV; it doesn't verify anything...
98 * More description at nail.h:enum okeys */
99 enum a_amv_var_flags{
100 a_AMV_VF_NONE = 0,
102 /* The basic set of flags, also present in struct a_amv_var_map.avm_flags */
103 a_AMV_VF_BOOL = 1u<<0, /* ok_b_* */
104 a_AMV_VF_CHAIN = 1u<<1, /* Is variable chain (-USER{,@HOST} variants) */
105 a_AMV_VF_VIRT = 1u<<2, /* "Stateless" automatic variable */
106 a_AMV_VF_VIP = 1u<<3, /* Wants _var_check_vips() evaluation */
107 a_AMV_VF_RDONLY = 1u<<4, /* May not be set by user */
108 a_AMV_VF_NODEL = 1u<<5, /* May not be deleted */
109 a_AMV_VF_I3VAL = 1u<<6, /* Has an initial value */
110 a_AMV_VF_DEFVAL = 1u<<7, /* Has a default value */
111 a_AMV_VF_IMPORT = 1u<<8, /* Import ONLY from env (pre n_PSO_STARTED) */
112 a_AMV_VF_ENV = 1u<<9, /* Update environment on change */
113 a_AMV_VF_NOLOPTS = 1u<<10, /* May not be tracked by `localopts' */
114 a_AMV_VF_NOTEMPTY = 1u<<11, /* May not be assigned an empty value */
115 /* TODO _VF_NUM, _VF_POSNUM: we also need 64-bit limit numbers! */
116 a_AMV_VF_NUM = 1u<<12, /* Value must be a 32-bit number */
117 a_AMV_VF_POSNUM = 1u<<13, /* Value must be positive 32-bit number */
118 a_AMV_VF_LOWER = 1u<<14, /* Values will be stored in lowercase version */
119 a_AMV_VF_OBSOLETE = 1u<<15, /* Is obsolete? */
120 a_AMV_VF__MASK = (1u<<(15+1)) - 1,
122 /* Extended flags, not part of struct a_amv_var_map.avm_flags */
123 a_AMV_VF_EXT_LOCAL = 1u<<23, /* `local' */
124 a_AMV_VF_EXT_LINKED = 1u<<24, /* `environ' link'ed */
125 a_AMV_VF_EXT_FROZEN = 1u<<25, /* Has been set by -S,.. */
126 a_AMV_VF_EXT_FROZEN_UNSET = 1u<<26, /* ..and was used to unset a variable */
127 a_AMV_VF_EXT__FROZEN_MASK = a_AMV_VF_EXT_FROZEN | a_AMV_VF_EXT_FROZEN_UNSET,
128 a_AMV_VF_EXT__MASK = (1u<<(26+1)) - 1
131 enum a_amv_var_lookup_flags{
132 a_AMV_VLOOK_NONE = 0,
133 a_AMV_VLOOK_LOCAL = 1u<<0, /* Query `local' layer first */
134 a_AMV_VLOOK_LOCAL_ONLY = 1u<<1, /* MUST be a `local' variable */
135 /* Do not allocate new var for _I3VAL, see _var_lookup() for more */
136 a_AMV_VLOOK_I3VAL_NONEW = 1u<<2,
137 a_AMV_VLOOK_I3VAL_NONEW_REPORT = 1u<<3
140 enum a_amv_var_setclr_flags{
141 a_AMV_VSETCLR_NONE = 0,
142 a_AMV_VSETCLR_LOCAL = 1u<<0, /* Use `local' variables only */
143 a_AMV_VSETCLR_ENV = 1u<<1 /* `environ' or otherwise environ */
146 /* We support some special parameter names for one(+)-letter variable names;
147 * note these have counterparts in the code that manages shell expansion!
148 * All these special variables are solely backed by n_var_vlook(), and besides
149 * there is only a_amv_var_revlookup() which knows about them */
150 enum a_amv_var_special_category{
151 a_AMV_VSC_NONE, /* Normal variable, no special treatment */
152 a_AMV_VSC_GLOBAL, /* ${[?!]} are specially mapped, but global */
153 a_AMV_VSC_MULTIPLEX, /* ${^.*} circumflex accent multiplexer */
154 a_AMV_VSC_POSPAR, /* ${[1-9][0-9]*} positional parameters */
155 a_AMV_VSC_POSPAR_ENV /* ${[*@#]} positional parameter support variables */
158 enum a_amv_var_special_type{
159 /* _VSC_GLOBAL */
160 a_AMV_VST_QM, /* ? */
161 a_AMV_VST_EM, /* ! */
162 /* _VSC_MULTIPLEX */
163 /* This is special in that it is a multiplex indicator, the ^ is followed by
164 * a normal variable */
165 a_AMV_VST_CACC, /* ^ (circumflex accent) */
166 /* _VSC_POSPAR_ENV */
167 a_AMV_VST_STAR, /* * */
168 a_AMV_VST_AT, /* @ */
169 a_AMV_VST_NOSIGN /* # */
172 enum a_amv_var_vip_mode{
173 a_AMV_VIP_SET_PRE,
174 a_AMV_VIP_SET_POST,
175 a_AMV_VIP_CLEAR
178 struct a_amv_pospar{
179 ui16_t app_maxcount; /* == slots in .app_dat */
180 ui16_t app_count; /* Maximum a_AMV_POSPAR_MAX */
181 ui16_t app_idx; /* `shift' moves this one, decs .app_count */
182 bool_t app_not_heap; /* .app_dat stuff not dynamically allocated */
183 ui8_t app__dummy[1];
184 char const **app_dat; /* NULL terminated (for "$@" explosion support) */
186 n_CTA(a_AMV_POSPAR_MAX <= SI16_MAX, "Limit exceeds datatype capabilities");
188 struct a_amv_mac{
189 struct a_amv_mac *am_next;
190 ui32_t am_maxlen; /* of any line in .am_line_dat */
191 ui32_t am_line_cnt; /* of *.am_line_dat (but NULL terminated) */
192 struct a_amv_mac_line **am_line_dat; /* TODO use deque? */
193 struct a_amv_var *am_lopts; /* `localopts' unroll list */
194 ui32_t am_refcnt; /* 0-based for `un{account,define}' purposes */
195 ui8_t am_flags; /* enum a_amv_mac_flags */
196 char am_name[n_VFIELD_SIZE(3)]; /* of this macro */
198 n_CTA(a_AMV_MF__MAX <= UI8_MAX, "Enumeration excesses storage datatype");
200 struct a_amv_mac_line{
201 ui32_t aml_len;
202 ui32_t aml_prespc; /* Number of leading SPACEs, for display purposes */
203 char aml_dat[n_VFIELD_SIZE(0)];
206 struct a_amv_mac_call_args{
207 char const *amca_name; /* For MACKY_MACK, this is *0*! */
208 struct a_amv_mac *amca_amp; /* "const", but for am_refcnt */
209 struct a_amv_var **amca_unroller;
210 void (*amca_hook_pre)(void *);
211 void *amca_hook_arg;
212 ui8_t amca_loflags;
213 bool_t amca_ps_hook_mask;
214 bool_t amca_no_xcall; /* We want n_GO_INPUT_NO_XCALL for this */
215 ui8_t amca__pad[5];
216 struct a_amv_var *(*amca_local_vars)[a_AMV_PRIME]; /* `local's, or NULL */
217 struct a_amv_pospar amca_pospar;
220 struct a_amv_lostack{
221 struct a_amv_lostack *as_global_saved; /* Saved global XXX due to jump */
222 struct a_amv_mac_call_args *as_amcap;
223 struct a_amv_lostack *as_up; /* Outer context */
224 struct a_amv_var *as_lopts;
225 ui8_t as_loflags; /* enum a_amv_mac_loflags */
226 ui8_t avs__pad[7];
229 struct a_amv_var{
230 struct a_amv_var *av_link;
231 char *av_value;
232 #ifdef HAVE_PUTENV
233 char *av_env; /* Actively managed putenv(3) memory, or NULL */
234 #endif
235 ui32_t av_flags; /* enum a_amv_var_flags inclusive extended bits */
236 char av_name[n_VFIELD_SIZE(4)];
238 n_CTA(a_AMV_VF_EXT__MASK <= UI32_MAX, "Enumeration excesses storage datatype");
240 struct a_amv_var_map{
241 ui32_t avm_hash;
242 ui16_t avm_keyoff;
243 ui16_t avm_flags; /* enum a_amv_var_flags without extended bits */
245 n_CTA(a_AMV_VF__MASK <= UI16_MAX, "Enumeration excesses storage datatype");
247 struct a_amv_var_virt{
248 ui32_t avv_okey;
249 ui8_t avv__dummy[4];
250 struct a_amv_var const *avv_var;
253 struct a_amv_var_defval{
254 ui32_t avdv_okey;
255 ui8_t avdv__pad[4];
256 char const *avdv_value; /* Only for !BOOL (otherwise plain existence) */
259 struct a_amv_var_carrier{
260 char const *avc_name;
261 ui32_t avc_hash;
262 ui32_t avc_prime;
263 struct a_amv_var *avc_var;
264 struct a_amv_var_map const *avc_map;
265 enum okeys avc_okey;
266 ui8_t avc__pad[1];
267 ui8_t avc_special_cat;
268 /* Numerical parameter name if .avc_special_cat=a_AMV_VSC_POSPAR,
269 * otherwise a enum a_amv_var_special_type */
270 ui16_t avc_special_prop;
273 /* Include constant make-okey-map.pl output, and the generated version data */
274 #include <gen-version.h>
275 #include <gen-okeys.h>
277 /* The currently active account */
278 static struct a_amv_mac *a_amv_acc_curr;
280 static struct a_amv_mac *a_amv_macs[a_AMV_PRIME]; /* TODO dynamically spaced */
282 /* Unroll list of currently running macro stack */
283 static struct a_amv_lostack *a_amv_lopts;
285 static struct a_amv_var *a_amv_vars[a_AMV_PRIME]; /* TODO dynamically spaced */
287 /* Global (i.e., non-local) a_AMV_VSC_POSPAR stack */
288 static struct a_amv_pospar a_amv_pospar;
290 /* TODO We really deserve localopts support for *folder-hook*s, so hack it in
291 * TODO today via a static lostack, it should be a field in mailbox, once that
292 * TODO is a real multi-instance object */
293 static struct a_amv_var *a_amv_folder_hook_lopts;
295 /* TODO Rather ditto (except for storage -> cmd_ctx), compose hooks */
296 static struct a_amv_var *a_amv_compose_lopts;
298 /* Lookup for macros/accounts: if newamp is not NULL it will be linked in the
299 * map, if _MF_UNDEF is set a possibly existing entry will be removed (first).
300 * Returns NULL if a lookup failed, or if newamp was set, the found entry in
301 * plain lookup cases or when _UNDEF was performed on a currently active entry
302 * (the entry will have been unlinked, and the _MF_DELETE will be honoured once
303 * the reference count reaches 0), and (*)-1 if an _UNDEF was performed */
304 static struct a_amv_mac *a_amv_mac_lookup(char const *name,
305 struct a_amv_mac *newamp, enum a_amv_mac_flags amf);
307 /* `call', `call_if' (and `xcall' via go.c -> c_call()) */
308 static int a_amv_mac_call(void *v, bool_t silent_nexist);
310 /* Execute a macro; amcap must reside in LOFI memory */
311 static bool_t a_amv_mac_exec(struct a_amv_mac_call_args *amcap);
313 static void a_amv_mac__finalize(void *vp);
315 /* User display helpers */
316 static bool_t a_amv_mac_show(enum a_amv_mac_flags amf);
318 /* _def() returns error for faulty definitions and already existing * names,
319 * _undef() returns error if a named thing doesn't exist */
320 static bool_t a_amv_mac_def(char const *name, enum a_amv_mac_flags amf);
321 static bool_t a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf);
323 /* */
324 static void a_amv_mac_free(struct a_amv_mac *amp);
326 /* Update replay-log */
327 static void a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
328 struct a_amv_var *oavp);
329 static void a_amv_lopts_unroll(struct a_amv_var **avpp);
331 /* Special cased value string allocation */
332 static char *a_amv_var_copy(char const *str);
333 static void a_amv_var_free(char *cp);
335 /* Check for special housekeeping. _VIP_SET_POST and _VIP_CLEAR do not fail
336 * (or propagate errors), _VIP_SET_PRE may and should case abortion */
337 static bool_t a_amv_var_check_vips(enum a_amv_var_vip_mode avvm,
338 enum okeys okey, char const **val);
340 /* _VF_NUM / _VF_POSNUM */
341 static bool_t a_amv_var_check_num(char const *val, bool_t posnum);
343 /* If a variable name begins with a lowercase-character and contains at
344 * least one '@', it is converted to all-lowercase. This is necessary
345 * for lookups of names based on email addresses.
346 * Following the standard, only the part following the last '@' should
347 * be lower-cased, but practice has established otherwise here */
348 static char const *a_amv_var_canonify(char const *vn);
350 /* Try to reverse lookup an option name to an enum okeys mapping.
351 * Updates .avc_name and .avc_hash; .avc_map is NULL if none found */
352 static bool_t a_amv_var_revlookup(struct a_amv_var_carrier *avcp,
353 char const *name);
355 /* Lookup a variable from .avc_(map|name|hash), return whether it was found.
356 * Sets .avc_prime; .avc_var is NULL if not found.
357 * Here it is where we care for _I3VAL and _DEFVAL.
358 * An _I3VAL will be "consumed" as necessary anyway, but it won't be used to
359 * create a new variable if _VLOOK_I3VAL_NONEW is set; if
360 * _VLOOK_I3VAL_NONEW_REPORT is set then we set .avc_var to -1 and return true
361 * if that was the case, otherwise we'll return FAL0, then! */
362 static bool_t a_amv_var_lookup(struct a_amv_var_carrier *avcp,
363 enum a_amv_var_lookup_flags avlf);
365 /* Lookup functions for special category variables, _pospar drives all
366 * positional parameter etc. special categories */
367 static char const *a_amv_var_vsc_global(struct a_amv_var_carrier *avcp);
368 static char const *a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp);
369 static char const *a_amv_var_vsc_pospar(struct a_amv_var_carrier *avcp);
371 /* Set var from .avc_(map|name|hash), return success */
372 static bool_t a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
373 enum a_amv_var_setclr_flags avscf);
375 static bool_t a_amv_var__putenv(struct a_amv_var_carrier *avcp,
376 struct a_amv_var *avp);
378 /* Clear var from .avc_(map|name|hash); sets .avc_var=NULL, return success */
379 static bool_t a_amv_var_clear(struct a_amv_var_carrier *avcp,
380 enum a_amv_var_setclr_flags avscf);
382 static bool_t a_amv_var__clearenv(char const *name, struct a_amv_var *avp);
384 /* List all variables */
385 static void a_amv_var_show_all(void);
387 static int a_amv_var__show_cmp(void const *s1, void const *s2);
389 /* Actually do print one, return number of lines written */
390 static size_t a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp);
392 /* Shared c_set() and c_environ():set impl, return success */
393 static bool_t a_amv_var_c_set(char **ap, enum a_amv_var_setclr_flags avscf);
395 static struct a_amv_mac *
396 a_amv_mac_lookup(char const *name, struct a_amv_mac *newamp,
397 enum a_amv_mac_flags amf){
398 struct a_amv_mac *amp, **ampp;
399 ui32_t h;
400 enum a_amv_mac_flags save_amf;
401 NYD2_ENTER;
403 save_amf = amf;
404 amf &= a_AMV_MF_TYPE_MASK;
405 h = a_AMV_NAME2HASH(name);
406 h = a_AMV_HASH2PRIME(h);
407 ampp = &a_amv_macs[h];
409 for(amp = *ampp; amp != NULL; ampp = &(*ampp)->am_next, amp = amp->am_next){
410 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf &&
411 !strcmp(amp->am_name, name)){
412 if(n_LIKELY((save_amf & a_AMV_MF_UNDEF) == 0))
413 goto jleave;
415 *ampp = amp->am_next;
417 if(amp->am_refcnt > 0){
418 amp->am_flags |= a_AMV_MF_DELETE;
419 if(n_poption & n_PO_D_V)
420 n_err(_("Delayed deletion of currently active %s: %s\n"),
421 (amp->am_flags & a_AMV_MF_ACCOUNT ? "account" : "define"),
422 name);
423 }else{
424 a_amv_mac_free(amp);
425 amp = (struct a_amv_mac*)-1;
427 break;
431 if(newamp != NULL){
432 ampp = &a_amv_macs[h];
433 newamp->am_next = *ampp;
434 *ampp = newamp;
435 amp = NULL;
437 jleave:
438 NYD2_LEAVE;
439 return amp;
442 static int
443 a_amv_mac_call(void *v, bool_t silent_nexist){
444 struct a_amv_mac *amp;
445 int rv;
446 char const *name;
447 struct n_cmd_arg_ctx *cacp;
448 NYD_ENTER;
450 cacp = v;
452 if(cacp->cac_no == 0){
453 n_err(_("Synopsis: call(_if)?: name [:<arguments>:]\n"));
454 n_pstate_err_no = n_ERR_INVAL;
455 rv = 1;
456 goto jleave;
459 name = cacp->cac_arg->ca_arg.ca_str.s;
461 if(n_UNLIKELY(cacp->cac_no > a_AMV_POSPAR_MAX)){
462 n_err(_("Too many arguments to macro `call': %s\n"), name);
463 n_pstate_err_no = n_ERR_OVERFLOW;
464 rv = 1;
465 }else if(n_UNLIKELY((amp = a_amv_mac_lookup(name, NULL, a_AMV_MF_NONE)
466 ) == NULL)){
467 if(!silent_nexist)
468 n_err(_("Undefined macro called: %s\n"), n_shexp_quote_cp(name, FAL0));
469 n_pstate_err_no = n_ERR_NOENT;
470 rv = 1;
471 }else{
472 char const **argv;
473 struct a_amv_mac_call_args *amcap;
474 size_t argc;
476 argc = cacp->cac_no + 1;
477 amcap = n_lofi_alloc(sizeof *amcap + (argc * sizeof *argv));
478 argv = (void*)&amcap[1];
480 for(argc = 0; (cacp->cac_arg = cacp->cac_arg->ca_next) != NULL; ++argc)
481 argv[argc] = cacp->cac_arg->ca_arg.ca_str.s;
482 argv[argc] = NULL;
484 memset(amcap, 0, sizeof *amcap);
485 amcap->amca_name = name;
486 amcap->amca_amp = amp;
487 if(a_amv_lopts != NULL)
488 amcap->amca_loflags = (a_amv_lopts->as_loflags & a_AMV_LF_CALL_MASK
489 ) >> a_AMV_LF_CALL_TO_SCOPE_SHIFT;
490 if(argc > 0){
491 amcap->amca_pospar.app_count = (ui16_t)argc;
492 amcap->amca_pospar.app_not_heap = TRU1;
493 amcap->amca_pospar.app_dat = argv;
496 (void)a_amv_mac_exec(amcap);
497 rv = n_pstate_ex_no;
499 jleave:
500 NYD_LEAVE;
501 return rv;
504 static bool_t
505 a_amv_mac_exec(struct a_amv_mac_call_args *amcap){
506 struct a_amv_lostack *losp;
507 struct a_amv_mac_line **amlp;
508 char **args_base, **args;
509 struct a_amv_mac *amp;
510 bool_t rv;
511 NYD2_ENTER;
513 amp = amcap->amca_amp;
514 assert(amp != NULL && amp != a_AMV_MACKY_MACK);
515 ++amp->am_refcnt;
516 /* XXX Unfortunately we yet need to dup the macro lines! :( */
517 args_base = args = n_alloc(sizeof(*args) * (amp->am_line_cnt +1));
518 for(amlp = amp->am_line_dat; *amlp != NULL; ++amlp)
519 *(args++) = sbufdup((*amlp)->aml_dat, (*amlp)->aml_len);
520 *args = NULL;
522 losp = n_lofi_alloc(sizeof *losp);
523 losp->as_global_saved = a_amv_lopts;
524 if((losp->as_amcap = amcap)->amca_unroller == NULL){
525 losp->as_up = losp->as_global_saved;
526 losp->as_lopts = NULL;
527 }else{
528 losp->as_up = NULL;
529 losp->as_lopts = *amcap->amca_unroller;
531 losp->as_loflags = amcap->amca_loflags;
533 a_amv_lopts = losp;
534 if(amcap->amca_hook_pre != NULL)
535 n_PS_ROOT_BLOCK((*amcap->amca_hook_pre)(amcap->amca_hook_arg));
536 rv = n_go_macro((n_GO_INPUT_NONE |
537 (amcap->amca_no_xcall ? n_GO_INPUT_NO_XCALL : 0)),
538 amp->am_name, args_base, &a_amv_mac__finalize, losp);
539 NYD2_LEAVE;
540 return rv;
543 static void
544 a_amv_mac__finalize(void *vp){
545 struct a_amv_mac *amp;
546 struct a_amv_mac_call_args *amcap;
547 struct a_amv_lostack *losp;
548 NYD2_ENTER;
550 losp = vp;
551 a_amv_lopts = losp->as_global_saved;
553 amcap = losp->as_amcap;
555 /* Delete positional parameter stack */
556 if(!amcap->amca_pospar.app_not_heap && amcap->amca_pospar.app_maxcount > 0){
557 ui16_t i;
559 for(i = amcap->amca_pospar.app_maxcount; i-- != 0;)
560 n_free(n_UNCONST(amcap->amca_pospar.app_dat[i]));
561 n_free(amcap->amca_pospar.app_dat);
564 /* `local' variable hashmap. These have no environment map, never */
565 if(amcap->amca_local_vars != NULL){
566 struct a_amv_var **avpp_base, **avpp, *avp;
568 for(avpp_base = *amcap->amca_local_vars, avpp = &avpp_base[a_AMV_PRIME];
569 avpp-- != avpp_base;)
570 while((avp = *avpp)){
571 assert((avp->av_flags & (a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL)) ==
572 (a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL));
573 assert(!(avp->av_flags &
574 ((a_AMV_VF__MASK | a_AMV_VF_EXT__MASK) &
575 ~(a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL))));
576 *avpp = avp->av_link;
577 a_amv_var_free(avp->av_value);
578 n_free(avp);
580 n_free(avpp_base);
583 /* Unroll `localopts', if applicable */
584 if(amcap->amca_unroller == NULL){
585 if(losp->as_lopts != NULL)
586 a_amv_lopts_unroll(&losp->as_lopts);
587 }else
588 *amcap->amca_unroller = losp->as_lopts;
590 if(amcap->amca_ps_hook_mask)
591 n_pstate &= ~n_PS_HOOK_MASK;
593 if((amp = amcap->amca_amp) != a_AMV_MACKY_MACK && amp != NULL &&
594 --amp->am_refcnt == 0 && (amp->am_flags & a_AMV_MF_DELETE))
595 a_amv_mac_free(amp);
597 n_lofi_free(losp);
598 n_lofi_free(amcap);
599 NYD2_LEAVE;
602 static bool_t
603 a_amv_mac_show(enum a_amv_mac_flags amf){
604 size_t lc, mc, ti, i;
605 char const *typestr;
606 FILE *fp;
607 bool_t rv;
608 NYD2_ENTER;
610 rv = FAL0;
612 if((fp = Ftmp(NULL, "deflist", OF_RDWR | OF_UNLINK | OF_REGISTER)) ==
613 NULL){
614 n_perr(_("`define' or `account' list: cannot create temporary file"), 0);
615 goto jleave;
618 amf &= a_AMV_MF_TYPE_MASK;
619 typestr = (amf & a_AMV_MF_ACCOUNT) ? "account" : "define";
621 for(lc = mc = ti = 0; ti < a_AMV_PRIME; ++ti){
622 struct a_amv_mac *amp;
624 for(amp = a_amv_macs[ti]; amp != NULL; amp = amp->am_next){
625 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
626 struct a_amv_mac_line **amlpp;
628 if(++mc > 1){
629 putc('\n', fp);
630 ++lc;
632 ++lc;
633 fprintf(fp, "%s %s {\n", typestr, amp->am_name);
634 for(amlpp = amp->am_line_dat; *amlpp != NULL; ++lc, ++amlpp){
635 for(i = (*amlpp)->aml_prespc; i > 0; --i)
636 putc(' ', fp);
637 fputs((*amlpp)->aml_dat, fp);
638 putc('\n', fp);
640 fputs("}\n", fp);
641 ++lc;
645 if(mc > 0)
646 page_or_print(fp, lc);
648 rv = (ferror(fp) == 0);
649 Fclose(fp);
650 jleave:
651 NYD2_LEAVE;
652 return rv;
655 static bool_t
656 a_amv_mac_def(char const *name, enum a_amv_mac_flags amf){
657 struct str line;
658 ui32_t line_cnt, maxlen;
659 struct linelist{
660 struct linelist *ll_next;
661 struct a_amv_mac_line *ll_amlp;
662 } *llp, *ll_head, *ll_tail;
663 union {size_t s; int i; ui32_t ui; size_t l;} n;
664 struct a_amv_mac *amp;
665 bool_t rv;
666 NYD2_ENTER;
668 memset(&line, 0, sizeof line);
669 rv = FAL0;
670 amp = NULL;
672 /* TODO We should have our input state machine which emits Line events,
673 * TODO and hook different consumers dependent on our content, as stated
674 * TODO in i think lex_input: like this local macros etc. would become
675 * TODO possible from the input side */
676 /* Read in the lines which form the macro content */
677 for(ll_tail = ll_head = NULL, line_cnt = maxlen = 0;;){
678 ui32_t leaspc;
679 char *cp;
681 n.i = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, n_empty,
682 &line.s, &line.l, NULL, NULL);
683 if(n.ui == 0)
684 continue;
685 if(n.i < 0){
686 n_err(_("Unterminated %s definition: %s\n"),
687 (amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
688 goto jerr;
691 /* Trim WS, remember amount of leading spaces for display purposes */
692 for(cp = line.s, leaspc = 0; n.ui > 0; ++cp, --n.ui)
693 if(*cp == '\t')
694 leaspc = (leaspc + 8u) & ~7u;
695 else if(*cp == ' ')
696 ++leaspc;
697 else
698 break;
699 for(; n.ui > 0 && spacechar(cp[n.ui - 1]); --n.ui)
701 if(n.ui == 0)
702 continue;
704 maxlen = n_MAX(maxlen, n.ui);
705 cp[n.ui++] = '\0';
707 /* Is is the closing brace? */
708 if(*cp == '}')
709 break;
711 if(n_LIKELY(++line_cnt < UI32_MAX)){
712 struct a_amv_mac_line *amlp;
714 llp = n_autorec_alloc(sizeof *llp);
715 if(ll_head == NULL)
716 ll_head = llp;
717 else
718 ll_tail->ll_next = llp;
719 ll_tail = llp;
720 llp->ll_next = NULL;
721 llp->ll_amlp = amlp = n_alloc(n_VSTRUCT_SIZEOF(struct a_amv_mac_line,
722 aml_dat) + n.ui);
723 amlp->aml_len = n.ui -1;
724 amlp->aml_prespc = leaspc;
725 memcpy(amlp->aml_dat, cp, n.ui);
726 }else{
727 n_err(_("Too much content in %s definition: %s\n"),
728 (amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
729 goto jerr;
733 /* Create the new macro */
734 n.s = strlen(name) +1;
735 amp = n_alloc(n_VSTRUCT_SIZEOF(struct a_amv_mac, am_name) + n.s);
736 memset(amp, 0, n_VSTRUCT_SIZEOF(struct a_amv_mac, am_name));
737 amp->am_maxlen = maxlen;
738 amp->am_line_cnt = line_cnt;
739 amp->am_flags = amf;
740 memcpy(amp->am_name, name, n.s);
741 /* C99 */{
742 struct a_amv_mac_line **amlpp;
744 amp->am_line_dat = amlpp = n_alloc(sizeof(*amlpp) * ++line_cnt);
745 for(llp = ll_head; llp != NULL; llp = llp->ll_next)
746 *amlpp++ = llp->ll_amlp;
747 *amlpp = NULL;
750 /* Create entry, replace a yet existing one as necessary */
751 a_amv_mac_lookup(name, amp, amf | a_AMV_MF_UNDEF);
752 rv = TRU1;
753 jleave:
754 if(line.s != NULL)
755 n_free(line.s);
756 NYD2_LEAVE;
757 return rv;
759 jerr:
760 for(llp = ll_head; llp != NULL; llp = llp->ll_next)
761 n_free(llp->ll_amlp);
763 * if(amp != NULL){
764 * n_free(amp->am_line_dat);
765 * n_free(amp);
766 *}*/
767 goto jleave;
770 static bool_t
771 a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf){
772 struct a_amv_mac *amp;
773 bool_t rv;
774 NYD2_ENTER;
776 rv = TRU1;
778 if(n_LIKELY(name[0] != '*' || name[1] != '\0')){
779 if((amp = a_amv_mac_lookup(name, NULL, amf | a_AMV_MF_UNDEF)) == NULL){
780 n_err(_("%s not defined: %s\n"),
781 (amf & a_AMV_MF_ACCOUNT ? "Account" : "Macro"), name);
782 rv = FAL0;
784 }else{
785 struct a_amv_mac **ampp, *lamp;
787 for(ampp = a_amv_macs; PTRCMP(ampp, <, &a_amv_macs[n_NELEM(a_amv_macs)]);
788 ++ampp)
789 for(lamp = NULL, amp = *ampp; amp != NULL;){
790 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
791 /* xxx Expensive but rare: be simple */
792 a_amv_mac_lookup(amp->am_name, NULL, amf | a_AMV_MF_UNDEF);
793 amp = (lamp == NULL) ? *ampp : lamp->am_next;
794 }else{
795 lamp = amp;
796 amp = amp->am_next;
800 NYD2_LEAVE;
801 return rv;
804 static void
805 a_amv_mac_free(struct a_amv_mac *amp){
806 struct a_amv_mac_line **amlpp;
807 NYD2_ENTER;
809 for(amlpp = amp->am_line_dat; *amlpp != NULL; ++amlpp)
810 n_free(*amlpp);
811 n_free(amp->am_line_dat);
812 n_free(amp);
813 NYD2_LEAVE;
816 static void
817 a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
818 struct a_amv_var *oavp){
819 struct a_amv_var *avp;
820 size_t nl, vl;
821 NYD2_ENTER;
823 /* Propagate unrolling up the stack, as necessary */
824 assert(alp != NULL);
825 for(;;){
826 if(alp->as_loflags & a_AMV_LF_SCOPE_MASK)
827 break;
828 if((alp = alp->as_up) == NULL)
829 goto jleave;
832 /* Check whether this variable is handled yet XXX Boost: ID check etc.!! */
833 for(avp = alp->as_lopts; avp != NULL; avp = avp->av_link)
834 if(!strcmp(avp->av_name, name))
835 goto jleave;
837 nl = strlen(name) +1;
838 vl = (oavp != NULL) ? strlen(oavp->av_value) +1 : 0;
839 avp = n_calloc(1, n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + nl + vl);
840 avp->av_link = alp->as_lopts;
841 alp->as_lopts = avp;
842 if(vl != 0){
843 avp->av_value = &avp->av_name[nl];
844 avp->av_flags = oavp->av_flags;
845 memcpy(avp->av_value, oavp->av_value, vl);
847 memcpy(avp->av_name, name, nl);
848 jleave:
849 NYD2_LEAVE;
852 static void
853 a_amv_lopts_unroll(struct a_amv_var **avpp){
854 struct a_amv_lostack *save_alp;
855 struct a_amv_var *x, *avp;
856 NYD2_ENTER;
858 avp = *avpp;
859 *avpp = NULL;
861 save_alp = a_amv_lopts;
862 a_amv_lopts = NULL;
863 while(avp != NULL){
864 x = avp;
865 avp = avp->av_link;
866 n_PS_ROOT_BLOCK(n_var_vset(x->av_name, (uintptr_t)x->av_value));
867 n_free(x);
869 a_amv_lopts = save_alp;
870 NYD2_LEAVE;
873 static char *
874 a_amv_var_copy(char const *str){
875 char *news;
876 size_t len;
877 NYD2_ENTER;
879 if(*str == '\0')
880 news = n_UNCONST(n_empty);
881 else if(str[1] == '\0'){
882 if(str[0] == '1')
883 news = n_UNCONST(n_1);
884 else if(str[0] == '0')
885 news = n_UNCONST(n_0);
886 else
887 goto jheap;
888 }else if(str[2] == '\0' && str[0] == '-' && str[1] == '1')
889 news = n_UNCONST(n_m1);
890 else{
891 jheap:
892 len = strlen(str) +1;
893 news = n_alloc(len);
894 memcpy(news, str, len);
896 NYD2_LEAVE;
897 return news;
900 static void
901 a_amv_var_free(char *cp){
902 NYD2_ENTER;
903 if(cp[0] != '\0' && cp != n_0 && cp != n_1 && cp != n_m1)
904 n_free(cp);
905 NYD2_LEAVE;
908 static bool_t
909 a_amv_var_check_vips(enum a_amv_var_vip_mode avvm, enum okeys okey,
910 char const **val){
911 char const *emsg;
912 bool_t ok;
913 NYD2_ENTER;
915 ok = TRU1;
917 if(avvm == a_AMV_VIP_SET_PRE){
918 switch(okey){
919 default:
920 break;
921 case ok_v_charset_7bit:
922 case ok_v_charset_8bit:
923 case ok_v_charset_unknown_8bit:
924 case ok_v_ttycharset:
925 if((*val = n_iconv_normalize_name(*val)) == NULL)
926 ok = FAL0;
927 break;
928 case ok_v_customhdr:{
929 char const *vp;
930 char *buf;
931 struct n_header_field *hflp, **hflpp, *hfp;
932 NYD_ENTER;
934 buf = savestr(*val);
935 hflp = NULL;
936 hflpp = &hflp;
938 while((vp = n_strsep_esc(&buf, ',', TRU1)) != NULL){
939 if(!n_header_add_custom(hflpp, vp, TRU1)){
940 emsg = N_("Invalid *customhdr* entry: %s\n");
941 ok = FAL0;
942 break;
944 hflpp = &(*hflpp)->hf_next;
947 hflpp = ok ? &n_customhdr_list : &hflp;
948 while((hfp = *hflpp) != NULL){
949 *hflpp = hfp->hf_next;
950 n_free(hfp);
952 if(!ok)
953 goto jerr;
954 n_customhdr_list = hflp;
955 } break;
956 case ok_v_from:
957 case ok_v_sender:{
958 struct name *np;
960 if((np = lextract(*val, GEXTRA | GFULL)) == NULL){
961 jefrom:
962 emsg = N_("*from* / *sender*: invalid address(es): %s\n");
963 goto jerr;
964 }else if(okey == ok_v_sender && np->n_flink != NULL){
965 emsg = N_("*sender*: may not contain multiple addresses: %s\n");
966 goto jerr;
967 }else for(; np != NULL; np = np->n_flink)
968 if(is_addr_invalid(np, EACM_STRICT | EACM_NOLOG | EACM_NONAME))
969 goto jefrom;
970 } break;
971 case ok_v_HOME:
972 /* Note this gets called from main.c during initialization, and they
973 * simply set this to pw_dir as a fallback: don't verify _that_ call.
974 * See main.c! */
975 if(!(n_pstate & n_PS_ROOT) && !n_is_dir(*val, TRUM1)){
976 emsg = N_("$HOME is not a directory or not accessible: %s\n");
977 goto jerr;
979 break;
980 case ok_v_hostname:
981 case ok_v_smtp_hostname:
982 #ifdef HAVE_IDNA
983 if(**val != '\0'){
984 struct n_string cnv;
986 n_string_creat_auto(&cnv);
987 if(!n_idna_to_ascii(&cnv, *val, UIZ_MAX)){
988 /*n_string_gut(&res);*/
989 emsg = N_("*hostname*/*smtp_hostname*: "
990 "IDNA encoding failed: %s\n");
991 goto jerr;
993 *val = n_string_cp(&cnv);
994 /*n_string_drop_ownership(&cnv);*/
996 #endif
997 break;
998 case ok_v_quote_chars:{
999 char c;
1000 char const *cp;
1002 for(cp = *val; (c = *cp++) != '\0';)
1003 if(!asciichar(c) || blankspacechar(c)){
1004 ok = FAL0;
1005 break;
1007 } break;
1008 case ok_v_sendcharsets:{
1009 struct n_string s, *sp = &s;
1010 char *csv, *cp;
1012 sp = n_string_creat_auto(sp);
1013 csv = savestr(*val);
1015 while((cp = n_strsep(&csv, ',', TRU1)) != NULL){
1016 if((cp = n_iconv_normalize_name(cp)) == NULL){
1017 ok = FAL0;
1018 break;
1020 if(sp->s_len > 0)
1021 sp = n_string_push_c(sp, ',');
1022 sp = n_string_push_cp(sp, cp);
1025 *val = n_string_cp(sp);
1026 /* n_string_drop_ownership(sp); */
1027 } break;
1028 case ok_v_TMPDIR:
1029 if(!n_is_dir(*val, TRU1)){
1030 emsg = N_("$TMPDIR is not a directory or not accessible: %s\n");
1031 goto jerr;
1033 break;
1034 case ok_v_umask:
1035 if(**val != '\0'){
1036 ui64_t uib;
1038 n_idec_ui64_cp(&uib, *val, 0, NULL);
1039 if(uib & ~0777u){ /* (is valid _VF_POSNUM) */
1040 emsg = N_("Invalid *umask* setting: %s\n");
1041 goto jerr;
1044 break;
1046 }else if(avvm == a_AMV_VIP_SET_POST){
1047 switch(okey){
1048 default:
1049 break;
1050 case ok_b_ask:
1051 ok_bset(asksub);
1052 break;
1053 case ok_b_debug:
1054 n_poption |= n_PO_DEBUG;
1055 break;
1056 case ok_v_HOME:
1057 /* Invalidate any resolved folder then, too
1058 * FALLTHRU */
1059 case ok_v_folder:
1060 n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
1061 break;
1062 case ok_v_ifs:{
1063 char *x_b, *x, c;
1064 char const *cp;
1066 cp = *val;
1067 x_b = x = n_autorec_alloc(strlen(cp) +1);
1068 while((c = *cp++) != '\0')
1069 if(spacechar(c))
1070 *x++ = c;
1071 *x = '\0';
1072 n_PS_ROOT_BLOCK(ok_vset(ifs_ws, x_b));
1073 } break;
1074 #ifdef HAVE_SETLOCALE
1075 case ok_v_LANG:
1076 case ok_v_LC_ALL:
1077 case ok_v_LC_CTYPE:
1078 n_locale_init();
1079 break;
1080 #endif
1081 case ok_b_memdebug:
1082 n_poption |= n_PO_MEMDEBUG;
1083 break;
1084 case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
1085 if(!(n_pstate & n_PS_ROOT))
1086 n_PS_ROOT_BLOCK(ok_bset(posix));
1087 break;
1088 case ok_b_posix: /* <-> $POSIXLY_CORRECT */
1089 if(!(n_pstate & n_PS_ROOT))
1090 n_PS_ROOT_BLOCK(ok_bset(POSIXLY_CORRECT));
1091 break;
1092 case ok_b_skipemptybody:
1093 n_poption |= n_PO_E_FLAG;
1094 break;
1095 case ok_b_typescript_mode:
1096 ok_bset(colour_disable);
1097 ok_bset(line_editor_disable);
1098 if(!(n_psonce & n_PSO_STARTED))
1099 ok_bset(termcap_disable);
1100 break;
1101 case ok_v_umask:
1102 if(**val != '\0'){
1103 ui64_t uib;
1105 n_idec_ui64_cp(&uib, *val, 0, NULL);
1106 umask((mode_t)uib);
1108 break;
1109 case ok_b_verbose:
1110 n_poption |= (n_poption & n_PO_VERB) ? n_PO_VERBVERB : n_PO_VERB;
1111 break;
1113 }else{
1114 switch(okey){
1115 default:
1116 break;
1117 case ok_b_ask:
1118 ok_bclear(asksub);
1119 break;
1120 case ok_b_debug:
1121 n_poption &= ~n_PO_DEBUG;
1122 break;
1123 case ok_v_customhdr:{
1124 struct n_header_field *hfp;
1126 while((hfp = n_customhdr_list) != NULL){
1127 n_customhdr_list = hfp->hf_next;
1128 n_free(hfp);
1130 } break;
1131 case ok_v_HOME:
1132 /* Invalidate any resolved folder then, too
1133 * FALLTHRU */
1134 case ok_v_folder:
1135 n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
1136 break;
1137 case ok_b_memdebug:
1138 n_poption &= ~n_PO_MEMDEBUG;
1139 break;
1140 case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
1141 if(!(n_pstate & n_PS_ROOT))
1142 n_PS_ROOT_BLOCK(ok_bclear(posix));
1143 break;
1144 case ok_b_posix: /* <-> $POSIXLY_CORRECT */
1145 if(!(n_pstate & n_PS_ROOT))
1146 n_PS_ROOT_BLOCK(ok_bclear(POSIXLY_CORRECT));
1147 break;
1148 case ok_b_skipemptybody:
1149 n_poption &= ~n_PO_E_FLAG;
1150 break;
1151 case ok_b_verbose:
1152 n_poption &= ~(n_PO_VERB | n_PO_VERBVERB);
1153 break;
1157 jleave:
1158 NYD2_LEAVE;
1159 return ok;
1160 jerr:
1161 n_err(V_(emsg), n_shexp_quote_cp(*val, FAL0));
1162 ok = FAL0;
1163 goto jleave;
1166 static bool_t
1167 a_amv_var_check_num(char const *val, bool_t posnum){
1168 /* TODO The internal/environment variables which are num= or posnum= should
1169 * TODO gain special lookup functions, or the return should be void* and
1170 * TODO castable to integer; i.e. no more strtoX() should be needed.
1171 * TODO I.e., the result of this function should instead be stored */
1172 bool_t rv;
1173 NYD2_ENTER;
1175 rv = TRU1;
1177 if(*val != '\0'){ /* Would be _VF_NOTEMPTY if not allowed */
1178 ui64_t uib;
1179 enum n_idec_state ids;
1181 ids = n_idec_cp(&uib, val, 0,
1182 (n_IDEC_MODE_LIMIT_32BIT |
1183 (posnum ? n_IDEC_MODE_SIGNED_TYPE : n_IDEC_MODE_NONE)), NULL);
1184 if((ids & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1185 ) != n_IDEC_STATE_CONSUMED)
1186 rv = FAL0;
1187 /* TODO Unless we store integers we need to look and forbid, because
1188 * TODO callee may not be able to swallow, e.g., "-1" */
1189 if(posnum && (ids & n_IDEC_STATE_SEEN_MINUS))
1190 rv = FAL0;
1192 NYD2_LEAVE;
1193 return rv;
1196 static char const *
1197 a_amv_var_canonify(char const *vn){
1198 NYD2_ENTER;
1199 if(!upperchar(*vn)){
1200 char const *vp;
1202 for(vp = vn; *vp != '\0' && *vp != '@'; ++vp)
1204 vn = (*vp == '@') ? i_strdup(vn) : vn;
1206 NYD2_LEAVE;
1207 return vn;
1210 static bool_t
1211 a_amv_var_revlookup(struct a_amv_var_carrier *avcp, char const *name){
1212 ui32_t hash, i, j;
1213 struct a_amv_var_map const *avmp;
1214 char c;
1215 NYD2_ENTER;
1217 /* It may be a special a.k.a. macro-local or one-letter parameter */
1218 c = name[0];
1219 if(n_UNLIKELY(digitchar(c))){
1220 /* (Inline dec. atoi, ugh) */
1221 for(j = (ui8_t)c - '0', i = 1;; ++i){
1222 c = name[i];
1223 if(c == '\0')
1224 break;
1225 if(!digitchar(c))
1226 goto jno_special_param;
1227 j = j * 10 + (ui8_t)c - '0';
1229 if(j <= a_AMV_POSPAR_MAX){
1230 avcp->avc_special_cat = a_AMV_VSC_POSPAR;
1231 goto jspecial_param;
1233 }else if(n_UNLIKELY(name[1] == '\0')){
1234 switch(c){
1235 case '?':
1236 case '!':
1237 avcp->avc_special_cat = a_AMV_VSC_GLOBAL;
1238 j = (c == '?') ? a_AMV_VST_QM : a_AMV_VST_EM;
1239 goto jspecial_param;
1240 case '^':
1241 goto jmultiplex;
1242 case '*':
1243 avcp->avc_special_cat = a_AMV_VSC_POSPAR_ENV;
1244 j = a_AMV_VST_STAR;
1245 goto jspecial_param;
1246 case '@':
1247 avcp->avc_special_cat = a_AMV_VSC_POSPAR_ENV;
1248 j = a_AMV_VST_AT;
1249 goto jspecial_param;
1250 case '#':
1251 avcp->avc_special_cat = a_AMV_VSC_POSPAR_ENV;
1252 j = a_AMV_VST_NOSIGN;
1253 goto jspecial_param;
1254 default:
1255 break;
1257 }else if(c == '^'){
1258 jmultiplex:
1259 avcp->avc_special_cat = a_AMV_VSC_MULTIPLEX;
1260 j = a_AMV_VST_CACC;
1261 goto jspecial_param;
1264 /* Normal reverse lookup, walk over the hashtable */
1265 jno_special_param:
1266 avcp->avc_special_cat = a_AMV_VSC_NONE;
1267 avcp->avc_name = name = a_amv_var_canonify(name);
1268 avcp->avc_hash = hash = a_AMV_NAME2HASH(name);
1270 for(i = hash % a_AMV_VAR_REV_PRIME, j = 0; j <= a_AMV_VAR_REV_LONGEST; ++j){
1271 ui32_t x;
1273 if((x = a_amv_var_revmap[i]) == a_AMV_VAR_REV_ILL)
1274 break;
1276 avmp = &a_amv_var_map[x];
1277 if(avmp->avm_hash == hash &&
1278 !strcmp(&a_amv_var_names[avmp->avm_keyoff], name)){
1279 avcp->avc_map = avmp;
1280 avcp->avc_okey = (enum okeys)x;
1281 goto jleave;
1284 if(++i == a_AMV_VAR_REV_PRIME){
1285 #ifdef a_AMV_VAR_REV_WRAPAROUND
1286 i = 0;
1287 #else
1288 break;
1289 #endif
1293 avcp->avc_map = NULL;
1294 avcp = NULL;
1295 jleave:
1296 assert(avcp == NULL || avcp->avc_map != NULL ||
1297 avcp->avc_special_cat == a_AMV_VSC_NONE);
1298 NYD2_LEAVE;
1299 return (avcp != NULL);
1301 /* All these are mapped to *--special-param* */
1302 jspecial_param:
1303 avcp->avc_name = name;
1304 avcp->avc_special_prop = (ui16_t)j;
1305 avmp = &a_amv_var_map[a_AMV_VAR__SPECIAL_PARAM_MAP_IDX];
1306 avcp->avc_hash = avmp->avm_hash;
1307 avcp->avc_map = avmp;
1308 avcp->avc_okey = ok_v___special_param;
1309 goto jleave;
1312 static bool_t
1313 a_amv_var_lookup(struct a_amv_var_carrier *avcp,
1314 enum a_amv_var_lookup_flags avlf){
1315 size_t i;
1316 char const *cp;
1317 struct a_amv_var_map const *avmp;
1318 struct a_amv_var *avp;
1319 NYD2_ENTER;
1321 assert(!(avlf & a_AMV_VLOOK_LOCAL_ONLY) || (avlf & a_AMV_VLOOK_LOCAL));
1322 assert(!(avlf & a_AMV_VLOOK_I3VAL_NONEW_REPORT) ||
1323 (avlf & a_AMV_VLOOK_I3VAL_NONEW));
1325 /* C99 */{
1326 struct a_amv_var **avpp, *lavp;
1328 avcp->avc_prime = a_AMV_HASH2PRIME(avcp->avc_hash);
1330 /* Optionally macro-`local' variables first */
1331 if(avlf & a_AMV_VLOOK_LOCAL){
1332 if(a_amv_lopts != NULL &&
1333 (avpp = *a_amv_lopts->as_amcap->amca_local_vars) != NULL){
1334 avpp += avcp->avc_prime;
1336 for(lavp = NULL, avp = *avpp; avp != NULL;
1337 lavp = avp, avp = avp->av_link)
1338 if(!strcmp(avp->av_name, avcp->avc_name)){
1339 /* Relink as head, hope it "sorts on usage" over time.
1340 * The code relies on this behaviour! */
1341 if(lavp != NULL){
1342 lavp->av_link = avp->av_link;
1343 avp->av_link = *avpp;
1344 *avpp = avp;
1346 goto jleave;
1350 if(avlf & a_AMV_VLOOK_LOCAL_ONLY)
1351 goto jerr;
1354 /* Global variable map */
1355 avpp = &a_amv_vars[avcp->avc_prime];
1357 for(lavp = NULL, avp = *avpp; avp != NULL; lavp = avp, avp = avp->av_link)
1358 if(!strcmp(avp->av_name, avcp->avc_name)){
1359 /* Relink as head, hope it "sorts on usage" over time.
1360 * The code relies on this behaviour! */
1361 if(lavp != NULL){
1362 lavp->av_link = avp->av_link;
1363 avp->av_link = *avpp;
1364 *avpp = avp;
1367 /* If this setting has been established via -S and we still have
1368 * not reached the _STARTED_CONFIG program state, it may have been
1369 * an explicit "clearance" that is to be treated as unset.
1370 * Because that is a special condition that (has been hacked in
1371 * later and) needs to be encapsulated in lower levels, but not
1372 * of interest if _set() or _clear() called us */
1373 switch(avp->av_flags & a_AMV_VF_EXT__FROZEN_MASK){
1374 case a_AMV_VF_EXT_FROZEN | a_AMV_VF_EXT_FROZEN_UNSET:
1375 if(!(avlf & a_AMV_VLOOK_I3VAL_NONEW)){
1376 avcp->avc_var = avp;
1377 avp = NULL;
1378 goto j_leave;
1380 /* FALLTHRU */
1381 default:
1382 break;
1384 goto jleave;
1388 /* If this is not an assembled variable we need to consider some special
1389 * initialization cases and eventually create the variable anew */
1390 if(n_LIKELY((avmp = avcp->avc_map) != NULL)){
1391 /* Does it have an import-from-environment flag? */
1392 if(n_UNLIKELY((avmp->avm_flags & (a_AMV_VF_IMPORT | a_AMV_VF_ENV)) != 0)){
1393 if(n_LIKELY((cp = getenv(avcp->avc_name)) != NULL)){
1394 /* May be better not to use that one, though? */
1395 /* TODO Outsource the tests into a _shared_ test function! */
1396 bool_t isempty, isbltin;
1398 isempty = (*cp == '\0' &&
1399 (avmp->avm_flags & a_AMV_VF_NOTEMPTY) != 0);
1400 isbltin = ((avmp->avm_flags & (a_AMV_VF_I3VAL | a_AMV_VF_DEFVAL)
1401 ) != 0);
1403 if(n_UNLIKELY(isempty)){
1404 n_err(_("Environment variable must not be empty: %s\n"),
1405 avcp->avc_name);
1406 if(!isbltin)
1407 goto jerr;
1408 }else if(n_LIKELY(*cp != '\0')){
1409 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NUM) &&
1410 !a_amv_var_check_num(cp, FAL0))){
1411 n_err(_("Environment variable value not a number "
1412 "or out of range: %s\n"), avcp->avc_name);
1413 goto jerr;
1415 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_POSNUM) &&
1416 !a_amv_var_check_num(cp, TRU1))){
1417 n_err(_("Environment variable value not a number, "
1418 "negative or out of range: %s\n"), avcp->avc_name);
1419 goto jerr;
1421 goto jnewval;
1422 }else
1423 goto jnewval;
1427 /* A first-time init switch is to be handled now and here */
1428 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_I3VAL) != 0)){
1429 static struct a_amv_var_defval const **arr,
1430 *arr_base[a_AMV_VAR_I3VALS_CNT +1];
1432 if(arr == NULL){
1433 arr = &arr_base[0];
1434 arr[i = a_AMV_VAR_I3VALS_CNT] = NULL;
1435 while(i-- > 0)
1436 arr[i] = &a_amv_var_i3vals[i];
1439 for(i = 0; arr[i] != NULL; ++i)
1440 if(arr[i]->avdv_okey == avcp->avc_okey){
1441 cp = (avmp->avm_flags & a_AMV_VF_BOOL) ? n_1
1442 : arr[i]->avdv_value;
1443 /* Remove this entry, hope entire block becomes no-op asap */
1445 arr[i] = arr[i + 1];
1446 while(arr[i++] != NULL);
1448 if(!(avlf & a_AMV_VLOOK_I3VAL_NONEW))
1449 goto jnewval;
1450 if(avlf & a_AMV_VLOOK_I3VAL_NONEW_REPORT)
1451 avp = (struct a_amv_var*)-1;
1452 goto jleave;
1456 /* */
1457 jdefval:
1458 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_DEFVAL) != 0){
1459 for(i = 0; i < a_AMV_VAR_DEFVALS_CNT; ++i)
1460 if(a_amv_var_defvals[i].avdv_okey == avcp->avc_okey){
1461 cp = (avmp->avm_flags & a_AMV_VF_BOOL) ? n_1
1462 : a_amv_var_defvals[i].avdv_value;
1463 goto jnewval;
1467 /* The virtual variables */
1468 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIRT) != 0)){
1469 for(i = 0; i < a_AMV_VAR_VIRTS_CNT; ++i)
1470 if(a_amv_var_virts[i].avv_okey == avcp->avc_okey){
1471 avp = n_UNCONST(a_amv_var_virts[i].avv_var);
1472 goto jleave;
1474 /* Not reached */
1478 jerr:
1479 avp = NULL;
1480 jleave:
1481 avcp->avc_var = avp;
1482 j_leave:
1483 NYD2_LEAVE;
1484 return (avp != NULL);
1486 jnewval:
1487 /* E.g., $TMPDIR may be set to non-existent, so we need to be able to catch
1488 * that and redirect to a possible default value */
1489 if((avmp->avm_flags & a_AMV_VF_VIP) &&
1490 !a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, &cp)){
1491 #ifdef HAVE_SETENV
1492 if(avmp->avm_flags & (a_AMV_VF_IMPORT | a_AMV_VF_ENV))
1493 unsetenv(avcp->avc_name);
1494 #endif
1495 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_DEFVAL) != 0)
1496 goto jdefval;
1497 goto jerr;
1498 }else{
1499 struct a_amv_var **avpp;
1500 size_t l;
1502 l = strlen(avcp->avc_name) +1;
1503 avcp->avc_var =
1504 avp = n_calloc(1, n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
1505 avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
1506 *avpp = avp;
1507 avp->av_flags = avmp->avm_flags;
1508 avp->av_value = a_amv_var_copy(cp);
1509 memcpy(avp->av_name, avcp->avc_name, l);
1511 if(avp->av_flags & a_AMV_VF_ENV)
1512 a_amv_var__putenv(avcp, avp);
1513 if(avmp->avm_flags & a_AMV_VF_VIP)
1514 a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, &cp);
1515 goto jleave;
1519 static char const *
1520 a_amv_var_vsc_global(struct a_amv_var_carrier *avcp){
1521 char itoabuf[32];
1522 char const *rv;
1523 si32_t *ep;
1524 struct a_amv_var_map const *avmp;
1525 NYD2_ENTER;
1527 /* Not function local, TODO but lazy evaluted for now */
1528 if(avcp->avc_special_prop == a_AMV_VST_QM){
1529 avmp = &a_amv_var_map[a_AMV_VAR__QM_MAP_IDX];
1530 avcp->avc_okey = ok_v___qm;
1531 ep = &n_pstate_ex_no;
1532 }else{
1533 avmp = &a_amv_var_map[a_AMV_VAR__EM_MAP_IDX];
1534 avcp->avc_okey = ok_v___em;
1535 ep = &n_pstate_err_no;
1538 /* XXX Oh heaven, we are responsible to ensure that $?/! is up-to-date
1539 * TODO we could num=1 ok_v___[qe]m, but the thing is still a string
1540 * TODO and thus conversion takes places over and over again; also
1541 * TODO for now that would have to occur before we set _that_ value
1542 * TODO so let's special treat it until we store ints as such */
1543 switch(*ep){
1544 case 0: rv = n_0; break;
1545 case 1: rv = n_1; break;
1546 default:
1547 snprintf(itoabuf, sizeof itoabuf, "%d", *ep);
1548 rv = itoabuf;
1549 break;
1551 n_PS_ROOT_BLOCK(n_var_okset(avcp->avc_okey, (uintptr_t)rv));
1553 avcp->avc_hash = avmp->avm_hash;
1554 avcp->avc_map = avmp;
1555 rv = a_amv_var_lookup(avcp, a_AMV_VLOOK_NONE)
1556 ? avcp->avc_var->av_value : NULL;
1557 NYD2_LEAVE;
1558 return rv;
1561 static char const *
1562 a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp){
1563 char itoabuf[32];
1564 si32_t e;
1565 size_t i;
1566 char const *rv;
1567 NYD2_ENTER;
1569 i = strlen(rv = &avcp->avc_name[1]);
1571 /* ERR, ERRDOC, ERRNAME, plus *-NAME variants */
1572 if(rv[0] == 'E' && i >= 3 && rv[1] == 'R' && rv[2] == 'R'){
1573 if(i == 3){
1574 e = n_pstate_err_no;
1575 goto jeno;
1576 }else if(rv[3] == '-'){
1577 e = n_err_from_name(&rv[4]);
1578 jeno:
1579 switch(e){
1580 case 0: rv = n_0; break;
1581 case 1: rv = n_1; break;
1582 default:
1583 snprintf(itoabuf, sizeof itoabuf, "%d", e);
1584 rv = savestr(itoabuf); /* XXX yet, cannot do numbers */
1585 break;
1587 goto jleave;
1588 }else if(i >= 6){
1589 if(!memcmp(&rv[3], "DOC", 3)){
1590 rv += 6;
1591 switch(*rv){
1592 case '\0': e = n_pstate_err_no; break;
1593 case '-': e = n_err_from_name(&rv[1]); break;
1594 default: goto jerr;
1596 rv = n_err_to_doc(e);
1597 goto jleave;
1598 }else if(i >= 7 && !memcmp(&rv[3], "NAME", 4)){
1599 rv += 7;
1600 switch(*rv){
1601 case '\0': e = n_pstate_err_no; break;
1602 case '-': e = n_err_from_name(&rv[1]); break;
1603 default: goto jerr;
1605 rv = n_err_to_name(e);
1606 goto jleave;
1611 jerr:
1612 rv = NULL;
1613 jleave:
1614 NYD2_LEAVE;
1615 return rv;
1618 static char const *
1619 a_amv_var_vsc_pospar(struct a_amv_var_carrier *avcp){
1620 size_t i, j;
1621 ui16_t argc;
1622 char const *rv, **argv;
1623 NYD2_ENTER;
1625 rv = NULL;
1627 /* If in a macro/xy.. */
1628 if(a_amv_lopts != NULL){
1629 bool_t ismacky;
1630 struct a_amv_mac_call_args *amcap;
1632 amcap = a_amv_lopts->as_amcap;
1633 argc = amcap->amca_pospar.app_count;
1634 argv = amcap->amca_pospar.app_dat;
1635 argv += amcap->amca_pospar.app_idx;
1637 /* ..in a `call'ed macro only, to be exact. Or in a_AMV_MACKY_MACK */
1638 if(!(ismacky = (amcap->amca_amp == a_AMV_MACKY_MACK)) &&
1639 (amcap->amca_ps_hook_mask ||
1640 (assert(amcap->amca_amp != NULL),
1641 (amcap->amca_amp->am_flags & a_AMV_MF_TYPE_MASK
1642 ) == a_AMV_MF_ACCOUNT)))
1643 goto jleave;
1645 if(avcp->avc_special_cat == a_AMV_VSC_POSPAR){
1646 if(avcp->avc_special_prop > 0){
1647 if(argc >= avcp->avc_special_prop)
1648 rv = argv[avcp->avc_special_prop - 1];
1649 }else if(ismacky)
1650 rv = amcap->amca_name;
1651 else
1652 rv = (a_amv_lopts->as_up != NULL
1653 ? a_amv_lopts->as_up->as_amcap->amca_name : n_empty);
1654 goto jleave;
1656 /* MACKY_MACK doesn't know about [*@#] */
1657 /*else*/ if(ismacky){
1658 if(n_poption & n_PO_D_V)
1659 n_err(_("Cannot use $*/$@/$# in this context: %s\n"),
1660 n_shexp_quote_cp(avcp->avc_name, FAL0));
1661 goto jleave;
1663 }else{
1664 argc = a_amv_pospar.app_count;
1665 argv = a_amv_pospar.app_dat;
1666 argv += a_amv_pospar.app_idx;
1668 if(avcp->avc_special_cat == a_AMV_VSC_POSPAR){
1669 if(avcp->avc_special_prop > 0){
1670 if(argc >= avcp->avc_special_prop)
1671 rv = argv[avcp->avc_special_prop - 1];
1672 }else
1673 rv = n_progname;
1674 goto jleave;
1678 switch(avcp->avc_special_prop){ /* XXX OPTIMIZE */
1679 case a_AMV_VST_STAR:{
1680 char sep;
1682 sep = *ok_vlook(ifs);
1683 if(0){
1684 case a_AMV_VST_AT:
1685 sep = ' ';
1687 for(i = j = 0; i < argc; ++i)
1688 j += strlen(argv[i]) + 1;
1689 if(j == 0)
1690 rv = n_empty;
1691 else{
1692 char *cp;
1694 rv = cp = n_autorec_alloc(j);
1695 for(i = j = 0; i < argc; ++i){
1696 j = strlen(argv[i]);
1697 memcpy(cp, argv[i], j);
1698 cp += j;
1699 if(sep != '\0')
1700 *cp++ = sep;
1702 if(sep != '\0')
1703 --cp;
1704 *cp = '\0';
1706 }break;
1707 case a_AMV_VST_NOSIGN:{
1708 char *cp;
1710 rv = cp = n_autorec_alloc(sizeof("65535"));
1711 snprintf(cp, sizeof("65535"), "%hu", argc);
1712 }break;
1713 default:
1714 rv = n_empty;
1715 break;
1717 jleave:
1718 NYD2_LEAVE;
1719 return rv;
1722 static bool_t
1723 a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
1724 enum a_amv_var_setclr_flags avscf){
1725 struct a_amv_var *avp;
1726 char *oval;
1727 struct a_amv_var_map const *avmp;
1728 bool_t rv;
1729 NYD2_ENTER;
1731 if(value == NULL){
1732 rv = a_amv_var_clear(avcp, avscf);
1733 goto jleave;
1736 if((avmp = avcp->avc_map) != NULL){
1737 rv = FAL0;
1739 /* Validity checks */
1740 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_RDONLY) != 0 &&
1741 !(n_pstate & n_PS_ROOT))){
1742 value = N_("Variable is read-only: %s\n");
1743 goto jeavmp;
1745 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NOTEMPTY) && *value == '\0')){
1746 value = N_("Variable must not be empty: %s\n");
1747 goto jeavmp;
1749 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NUM) &&
1750 !a_amv_var_check_num(value, FAL0))){
1751 value = N_("Variable value not a number or out of range: %s\n");
1752 goto jeavmp;
1754 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_POSNUM) &&
1755 !a_amv_var_check_num(value, TRU1))){
1756 value = _("Variable value not a number, negative, "
1757 "or out of range: %s\n");
1758 goto jeavmp;
1761 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_IMPORT) != 0 &&
1762 !(n_psonce & n_PSO_STARTED) && !(n_pstate & n_PS_ROOT))){
1763 value = N_("Variable cannot be set in a resource file: %s\n");
1764 goto jeavmp;
1767 /* Any more complicated inter-dependency? */
1768 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIP) != 0 &&
1769 !a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, &value))){
1770 value = N_("Assignment of variable aborted: %s\n");
1771 jeavmp:
1772 n_err(V_(value), avcp->avc_name);
1773 goto jleave;
1776 /* Transformations */
1777 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_LOWER)){
1778 char c;
1780 oval = savestr(value);
1781 value = oval;
1782 for(; (c = *oval) != '\0'; ++oval)
1783 *oval = lowerconv(c);
1786 /* Obsoletion warning */
1787 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_OBSOLETE) != 0))
1788 n_OBSOLETE2(_("obsoleted variable"), avcp->avc_name);
1791 /* Lookup possibly existing var. For */
1793 rv = TRU1;
1794 a_amv_var_lookup(avcp, (a_AMV_VLOOK_I3VAL_NONEW |
1795 ((avscf & a_AMV_VSETCLR_LOCAL)
1796 ? (a_AMV_VLOOK_LOCAL | a_AMV_VLOOK_LOCAL_ONLY) : 0)));
1797 avp = avcp->avc_var;
1799 /* A `local' setting is never covered by `localopts' nor frozen */
1800 if(avscf & a_AMV_VSETCLR_LOCAL)
1801 goto jislocal;
1803 /* If this setting had been established via -S and we still have not reached
1804 * the _STARTED_CONFIG program state, silently ignore request! */
1805 if(n_UNLIKELY(avp != NULL) &&
1806 n_UNLIKELY((avp->av_flags & a_AMV_VF_EXT__FROZEN_MASK) != 0)){
1807 if(!(n_psonce & n_PSO_STARTED_CONFIG)){
1808 if((n_pstate & n_PS_ROOT) ||
1809 (!(n_psonce & n_PSO_STARTED_GETOPT) &&
1810 (n_poption & n_PO_S_FLAG_TEMPORARY)))
1811 goto joval_and_go;
1812 if(n_poption & n_PO_D_VV)
1813 n_err(_("Temporarily frozen by -S, not `set'ing: %s\n"),
1814 avcp->avc_name);
1815 goto jleave;
1818 /* Otherwise, if -S freezing was an `unset' request, be very simple and
1819 * avoid tampering with that very special case we are not really prepared
1820 * for just one more line of code: throw the old thing away! */
1821 if(!(avp->av_flags & a_AMV_VF_EXT_FROZEN_UNSET))
1822 avp->av_flags &= ~a_AMV_VF_EXT__FROZEN_MASK;
1823 else{
1824 assert(avp->av_value == n_empty);
1825 a_amv_vars[avcp->avc_prime] = avp->av_link;
1826 n_free(avp);
1827 avcp->avc_var = avp = NULL;
1831 /* Optionally cover by `localopts' */
1832 if(n_UNLIKELY(a_amv_lopts != NULL) &&
1833 (avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
1834 a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
1836 jislocal:
1837 if(avp != NULL)
1838 joval_and_go:
1839 oval = avp->av_value;
1840 else{
1841 size_t l;
1842 struct a_amv_var **avpp;
1844 if(avscf & a_AMV_VSETCLR_LOCAL){
1845 if((avpp = *a_amv_lopts->as_amcap->amca_local_vars) == NULL)
1846 avpp = *(a_amv_lopts->as_amcap->amca_local_vars =
1847 n_calloc(1, sizeof(*a_amv_lopts->as_amcap->amca_local_vars)));
1848 avpp += avcp->avc_prime;
1849 }else
1850 avpp = &a_amv_vars[avcp->avc_prime];
1852 l = strlen(avcp->avc_name) +1;
1853 avcp->avc_var = avp = n_calloc(1,
1854 n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
1855 avp->av_link = *avpp;
1856 *avpp = avp;
1857 avp->av_flags = (avscf & a_AMV_VSETCLR_LOCAL)
1858 ? a_AMV_VF_NOLOPTS | a_AMV_VF_EXT_LOCAL
1859 : (avmp != NULL) ? avmp->avm_flags : 0;
1860 memcpy(avp->av_name, avcp->avc_name, l);
1861 oval = n_UNCONST(n_empty);
1864 if(avmp == NULL)
1865 avp->av_value = a_amv_var_copy(value);
1866 else{
1867 assert(!(avscf & a_AMV_VSETCLR_LOCAL));
1868 /* Via `set' etc. the user may give even boolean options non-boolean
1869 * values, ignore that and force boolean */
1870 if(!(avp->av_flags & a_AMV_VF_BOOL))
1871 avp->av_value = a_amv_var_copy(value);
1872 else{
1873 if(!(n_pstate & n_PS_ROOT) && (n_poption & n_PO_D_V) &&
1874 *value != '\0')
1875 n_err(_("Ignoring value of boolean variable: %s: %s\n"),
1876 avcp->avc_name, value);
1877 avp->av_value = n_UNCONST(n_1);
1881 /* A `local' setting can skip all the crude special things */
1882 if(!(avscf & a_AMV_VSETCLR_LOCAL)){
1883 if((avscf & a_AMV_VSETCLR_ENV) && !(avp->av_flags & a_AMV_VF_ENV))
1884 avp->av_flags |= a_AMV_VF_EXT_LINKED;
1885 if(avp->av_flags & (a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED))
1886 rv = a_amv_var__putenv(avcp, avp);
1887 if(avp->av_flags & a_AMV_VF_VIP)
1888 a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, &value);
1890 avp->av_flags &= ~a_AMV_VF_EXT__FROZEN_MASK;
1891 if(!(n_psonce & n_PSO_STARTED_GETOPT) &&
1892 (n_poption & n_PO_S_FLAG_TEMPORARY) != 0)
1893 avp->av_flags |= a_AMV_VF_EXT_FROZEN;
1896 a_amv_var_free(oval);
1897 jleave:
1898 NYD2_LEAVE;
1899 return rv;
1902 static bool_t
1903 a_amv_var__putenv(struct a_amv_var_carrier *avcp, struct a_amv_var *avp){
1904 #ifndef HAVE_SETENV
1905 char *cp;
1906 #endif
1907 bool_t rv;
1908 NYD2_ENTER;
1910 #ifdef HAVE_SETENV
1911 rv = (setenv(avcp->avc_name, avp->av_value, 1) == 0);
1912 #else
1913 cp = sstrdup(savecatsep(avcp->avc_name, '=', avp->av_value));
1915 if((rv = (putenv(cp) == 0))){
1916 char *ocp;
1918 ocp = avp->av_env;
1919 avp->av_env = cp;
1920 cp = ocp;
1923 if(cp != NULL)
1924 n_free(cp);
1925 #endif
1926 NYD2_LEAVE;
1927 return rv;
1930 static bool_t
1931 a_amv_var_clear(struct a_amv_var_carrier *avcp,
1932 enum a_amv_var_setclr_flags avscf){
1933 struct a_amv_var **avpp, *avp;
1934 struct a_amv_var_map const *avmp;
1935 bool_t rv;
1936 NYD2_ENTER;
1938 rv = FAL0;
1940 if(n_LIKELY((avmp = avcp->avc_map) != NULL)){
1941 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NODEL) != 0 &&
1942 !(n_pstate & n_PS_ROOT))){
1943 n_err(_("Variable may not be unset: %s\n"), avcp->avc_name);
1944 goto jleave;
1946 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIP) != 0 &&
1947 !a_amv_var_check_vips(a_AMV_VIP_CLEAR, avcp->avc_okey, NULL))){
1948 n_err(_("Clearance of variable aborted: %s\n"), avcp->avc_name);
1949 goto jleave;
1953 rv = TRU1;
1955 if(n_UNLIKELY(!a_amv_var_lookup(avcp,
1956 (((avscf & a_AMV_VSETCLR_LOCAL)
1957 ? (a_AMV_VLOOK_LOCAL | a_AMV_VLOOK_LOCAL_ONLY) : 0) |
1958 a_AMV_VLOOK_I3VAL_NONEW | a_AMV_VLOOK_I3VAL_NONEW_REPORT)))){
1959 assert(avcp->avc_var == NULL);
1960 /* This may be a clearance request from the command line, via -S, and we
1961 * need to keep track of that! Unfortunately we are not prepared for
1962 * this, really, so we need to create a fake entry that is known and
1963 * handled correctly by the lowermost variable layer!
1964 * However, all this cannot happen for plain unset of `local' variables */
1965 if(avscf & a_AMV_VSETCLR_LOCAL)
1966 goto jleave;
1967 if(n_UNLIKELY(!(n_psonce & n_PSO_STARTED_GETOPT)) &&
1968 (n_poption & n_PO_S_FLAG_TEMPORARY)) Jfreeze:{
1969 size_t l;
1971 l = strlen(avcp->avc_name) +1;
1972 avp = n_calloc(1, n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
1973 avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
1974 *avpp = avp;
1975 avp->av_value = n_UNCONST(n_empty); /* Sth. covered by _var_free()! */
1976 avp->av_flags = (avmp != NULL ? avmp->avm_flags : 0) |
1977 a_AMV_VF_EXT_FROZEN | a_AMV_VF_EXT_FROZEN_UNSET;
1978 memcpy(avp->av_name, avcp->avc_name, l);
1980 if((avscf & a_AMV_VSETCLR_ENV) ||
1981 (avmp != NULL && (avmp->avm_flags & a_AMV_VF_ENV)))
1982 a_amv_var__clearenv(avcp->avc_name, NULL);
1983 }else if(avscf & a_AMV_VSETCLR_ENV){
1984 jforce_env:
1985 if(!(rv = a_amv_var__clearenv(avcp->avc_name, NULL)))
1986 goto jerr_env_unset;
1987 }else{
1988 /* TODO "cannot unset undefined variable" not echoed in "ROBOT" state,
1989 * TODO should only be like that with "ignerr"! */
1990 jerr_env_unset:
1991 if(!(n_pstate & (n_PS_ROOT | n_PS_ROBOT)) && (n_poption & n_PO_D_V))
1992 n_err(_("Cannot unset undefined variable: %s\n"), avcp->avc_name);
1994 goto jleave;
1995 }else if((avp = avcp->avc_var) == (struct a_amv_var*)-1){
1996 /* Clearance request from command line, via -S? As above.. */
1997 if(n_UNLIKELY(!(n_psonce & n_PSO_STARTED_GETOPT) &&
1998 (n_poption & n_PO_S_FLAG_TEMPORARY) != 0))
1999 goto Jfreeze;
2000 avcp->avc_var = NULL;
2001 if(avscf & a_AMV_VSETCLR_ENV)
2002 goto jforce_env;
2003 goto jleave;
2005 assert(avcp->avc_var != NULL);
2007 /* `local' variables bypass "frozen" checks and `localopts' coverage etc. */
2008 if(avp->av_flags & a_AMV_VF_EXT_LOCAL)
2009 goto jdefault_path;
2011 /* If this setting has been established via -S and we still have not reached
2012 * the _STARTED_CONFIG program state, silently ignore request!
2013 * XXX All this is very complicated for the tenth of a second */
2014 /*else*/ if(n_UNLIKELY((avp->av_flags & a_AMV_VF_EXT__FROZEN_MASK) != 0)){
2015 if(!(n_psonce & n_PSO_STARTED_CONFIG)){
2016 if((n_pstate & n_PS_ROOT) ||
2017 (!(n_psonce & n_PSO_STARTED_GETOPT) &&
2018 (n_poption & n_PO_S_FLAG_TEMPORARY))){
2019 /* Be aware this may turn a set into an unset! */
2020 if(!(avp->av_flags & a_AMV_VF_EXT_FROZEN_UNSET)){
2021 if(avp->av_flags & a_AMV_VF_DEFVAL)
2022 goto jdefault_path;
2023 a_amv_var_free(avp->av_value);
2024 avp->av_flags |= a_AMV_VF_EXT_FROZEN_UNSET;
2025 avp->av_value = n_UNCONST(n_empty); /* _var_free() covered */
2026 if(avp->av_flags & (a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED))
2027 goto jforce_env;
2029 goto jleave;
2031 if(n_poption & n_PO_D_VV)
2032 n_err(_("Temporarily frozen by -S, not `unset'ting: %s\n"),
2033 avcp->avc_name);
2034 goto jleave;
2036 avp->av_flags &= ~a_AMV_VF_EXT__FROZEN_MASK;
2039 if(n_UNLIKELY(a_amv_lopts != NULL) &&
2040 (avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
2041 a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
2043 jdefault_path:
2044 assert(avp == avcp->avc_var);
2045 avcp->avc_var = NULL;
2046 avpp = &((avp->av_flags & a_AMV_VF_EXT_LOCAL)
2047 ? *a_amv_lopts->as_amcap->amca_local_vars : a_amv_vars
2048 )[avcp->avc_prime];
2049 assert(*avpp == avp); /* (always listhead after lookup()) */
2050 *avpp = (*avpp)->av_link;
2052 if(avp->av_flags & (a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED))
2053 rv = a_amv_var__clearenv(avp->av_name, avp);
2054 a_amv_var_free(avp->av_value);
2055 n_free(avp);
2057 /* XXX Fun part, extremely simple-minded for now: if this variable has
2058 * XXX a default value, immediately reinstantiate it! TODO Heh? */
2059 if(n_UNLIKELY(avmp != NULL && (avmp->avm_flags & a_AMV_VF_DEFVAL) != 0)){
2060 a_amv_var_lookup(avcp, a_AMV_VLOOK_I3VAL_NONEW);
2061 if(n_UNLIKELY(!(n_psonce & n_PSO_STARTED_GETOPT)) &&
2062 (n_poption & n_PO_S_FLAG_TEMPORARY))
2063 avcp->avc_var->av_flags |= a_AMV_VF_EXT_FROZEN;
2065 jleave:
2066 NYD2_LEAVE;
2067 return rv;
2070 static bool_t
2071 a_amv_var__clearenv(char const *name, struct a_amv_var *avp){
2072 extern char **environ;
2073 char **ecpp;
2074 bool_t rv;
2075 NYD2_ENTER;
2076 n_UNUSED(avp);
2078 rv = FAL0;
2079 ecpp = environ;
2081 #ifndef HAVE_SETENV
2082 if(avp != NULL && avp->av_env != NULL){
2083 for(; *ecpp != NULL; ++ecpp)
2084 if(*ecpp == avp->av_env){
2086 ecpp[0] = ecpp[1];
2087 while(*ecpp++ != NULL);
2088 n_free(avp->av_env);
2089 avp->av_env = NULL;
2090 rv = TRU1;
2091 break;
2093 }else
2094 #endif
2096 size_t l;
2098 if((l = strlen(name)) > 0){
2099 for(; *ecpp != NULL; ++ecpp)
2100 if(!strncmp(*ecpp, name, l) && (*ecpp)[l] == '='){
2101 #ifdef HAVE_SETENV
2102 unsetenv(name);
2103 #else
2105 ecpp[0] = ecpp[1];
2106 while(*ecpp++ != NULL);
2107 #endif
2108 rv = TRU1;
2109 break;
2113 NYD2_LEAVE;
2114 return rv;
2117 static void
2118 a_amv_var_show_all(void){
2119 struct n_string msg, *msgp;
2120 FILE *fp;
2121 size_t no, i;
2122 struct a_amv_var *avp;
2123 char const **vacp, **cap;
2124 NYD2_ENTER;
2126 if((fp = Ftmp(NULL, "setlist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
2127 n_perr(_("`set' list: cannot create temporary file"), 0);
2128 goto jleave;
2131 /* We need to instantiate first-time-inits and default values here, so that
2132 * they will be regular members of our _vars[] table */
2133 for(i = a_AMV_VAR_I3VALS_CNT; i-- > 0;)
2134 n_var_oklook(a_amv_var_i3vals[i].avdv_okey);
2135 for(i = a_AMV_VAR_DEFVALS_CNT; i-- > 0;)
2136 n_var_oklook(a_amv_var_defvals[i].avdv_okey);
2138 for(no = i = 0; i < a_AMV_PRIME; ++i)
2139 for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
2140 ++no;
2141 no += a_AMV_VAR_VIRTS_CNT;
2143 vacp = n_autorec_alloc(no * sizeof(*vacp));
2145 for(cap = vacp, i = 0; i < a_AMV_PRIME; ++i)
2146 for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
2147 *cap++ = avp->av_name;
2148 for(i = a_AMV_VAR_VIRTS_CNT; i-- > 0;)
2149 *cap++ = a_amv_var_virts[i].avv_var->av_name;
2151 if(no > 1)
2152 qsort(vacp, no, sizeof *vacp, &a_amv_var__show_cmp);
2154 msgp = &msg;
2155 msgp = n_string_reserve(n_string_creat(msgp), 80);
2156 for(i = 0, cap = vacp; no != 0; ++cap, --no)
2157 i += a_amv_var_show(*cap, fp, msgp);
2158 n_string_gut(&msg);
2160 page_or_print(fp, i);
2161 Fclose(fp);
2162 jleave:
2163 NYD2_LEAVE;
2166 static int
2167 a_amv_var__show_cmp(void const *s1, void const *s2){
2168 int rv;
2169 NYD2_ENTER;
2171 rv = strcmp(*(char**)n_UNCONST(s1), *(char**)n_UNCONST(s2));
2172 NYD2_LEAVE;
2173 return rv;
2176 static size_t
2177 a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp){
2178 struct a_amv_var_carrier avc;
2179 char const *quote;
2180 struct a_amv_var *avp;
2181 bool_t isset;
2182 size_t i;
2183 NYD2_ENTER;
2185 msgp = n_string_trunc(msgp, 0);
2186 i = 0;
2188 a_amv_var_revlookup(&avc, name);
2189 isset = a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE);
2190 avp = avc.avc_var;
2192 if(n_poption & n_PO_D_V){
2193 if(avc.avc_map == NULL){
2194 msgp = n_string_push_cp(msgp, "#assembled variable with value");
2195 i = 1;
2196 }else{
2197 struct{
2198 ui16_t flag;
2199 char msg[22];
2200 } const tbase[] = {
2201 {a_AMV_VF_CHAIN, "variable chain"},
2202 {a_AMV_VF_VIRT, "virtual"},
2203 {a_AMV_VF_RDONLY, "read-only"},
2204 {a_AMV_VF_NODEL, "nodelete"},
2205 {a_AMV_VF_I3VAL, "initial-value"},
2206 {a_AMV_VF_DEFVAL, "default-value"},
2207 {a_AMV_VF_IMPORT, "import-environ-first\0"}, /* assert NUL in max */
2208 {a_AMV_VF_ENV, "sync-environ"},
2209 {a_AMV_VF_NOLOPTS, "no-localopts"},
2210 {a_AMV_VF_NOTEMPTY, "notempty"},
2211 {a_AMV_VF_NUM, "number"},
2212 {a_AMV_VF_POSNUM, "positive-number"},
2213 {a_AMV_VF_OBSOLETE, "obsoleted"},
2214 }, *tp;
2216 for(tp = tbase; PTRCMP(tp, <, &tbase[n_NELEM(tbase)]); ++tp)
2217 if(isset ? (avp->av_flags & tp->flag)
2218 : (avc.avc_map->avm_flags & tp->flag)){
2219 msgp = n_string_push_c(msgp, (i++ == 0 ? '#' : ','));
2220 msgp = n_string_push_cp(msgp, tp->msg);
2224 if(isset && (avp->av_flags & a_AMV_VF_EXT_FROZEN)){
2225 msgp = n_string_push_c(msgp, (i++ == 0 ? '#' : ','));
2226 msgp = n_string_push_cp(msgp, "(un)?set via -S");
2229 if(i > 0)
2230 msgp = n_string_push_cp(msgp, "\n ");
2233 /* (Read-only variables are generally shown via comments..) */
2234 if(!isset || (avp->av_flags & a_AMV_VF_RDONLY)){
2235 msgp = n_string_push_c(msgp, n_ns[0]);
2236 if(!isset){
2237 if(avc.avc_map != NULL && (avc.avc_map->avm_flags & a_AMV_VF_BOOL))
2238 msgp = n_string_push_cp(msgp, "boolean; ");
2239 msgp = n_string_push_cp(msgp, "variable not set: ");
2240 msgp = n_string_push_cp(msgp, n_shexp_quote_cp(name, FAL0));
2241 goto jleave;
2245 n_UNINIT(quote, NULL);
2246 if(!(avp->av_flags & a_AMV_VF_BOOL)){
2247 quote = n_shexp_quote_cp(avp->av_value, TRU1);
2248 if(strcmp(quote, avp->av_value))
2249 msgp = n_string_push_cp(msgp, "wysh ");
2250 }else if(n_poption & n_PO_D_V)
2251 msgp = n_string_push_cp(msgp, "wysh "); /* (for shell-style comment) */
2253 if(avp->av_flags & a_AMV_VF_EXT_LINKED)
2254 msgp = n_string_push_cp(msgp, "environ ");
2255 msgp = n_string_push_cp(msgp, "set ");
2256 msgp = n_string_push_cp(msgp, name);
2258 if(!(avp->av_flags & a_AMV_VF_BOOL)){
2259 msgp = n_string_push_c(msgp, '=');
2260 msgp = n_string_push_cp(msgp, quote);
2261 }else if(n_poption & n_PO_D_V)
2262 msgp = n_string_push_cp(msgp, " #boolean");
2264 jleave:
2265 msgp = n_string_push_c(msgp, '\n');
2266 fputs(n_string_cp(msgp), fp);
2267 NYD2_ENTER;
2268 return (i > 0 ? 2 : 1);
2271 static bool_t
2272 a_amv_var_c_set(char **ap, enum a_amv_var_setclr_flags avscf){
2273 char *cp, *cp2, *varbuf, c;
2274 size_t errs;
2275 NYD2_ENTER;
2277 errs = 0;
2278 jouter:
2279 while((cp = *ap++) != NULL){
2280 /* Isolate key */
2281 cp2 = varbuf = n_autorec_alloc(strlen(cp) +1);
2283 for(; (c = *cp) != '=' && c != '\0'; ++cp){
2284 if(cntrlchar(c) || spacechar(c)){
2285 n_err(_("Variable name with control or space character ignored: "
2286 "%s\n"), ap[-1]);
2287 ++errs;
2288 goto jouter;
2290 *cp2++ = c;
2292 *cp2 = '\0';
2293 if(c == '\0')
2294 cp = n_UNCONST(n_empty);
2295 else
2296 ++cp;
2298 if(varbuf == cp2){
2299 n_err(_("Empty variable name ignored\n"));
2300 ++errs;
2301 }else{
2302 struct a_amv_var_carrier avc;
2303 bool_t isunset;
2305 if((isunset = (varbuf[0] == 'n' && varbuf[1] == 'o')))
2306 varbuf = &varbuf[2];
2308 a_amv_var_revlookup(&avc, varbuf);
2310 if((avscf & a_AMV_VSETCLR_LOCAL) && avc.avc_map != NULL){
2311 if(n_poption & n_PO_D_V)
2312 n_err(_("Builtin variable not overwritten by `local': %s\n"),
2313 varbuf);
2314 ++errs;
2315 }else if(isunset)
2316 errs += !a_amv_var_clear(&avc, avscf);
2317 else
2318 errs += !a_amv_var_set(&avc, cp, avscf);
2321 NYD2_LEAVE;
2322 return (errs == 0);
2325 FL int
2326 c_define(void *v){
2327 int rv;
2328 char **args;
2329 NYD_ENTER;
2331 rv = 1;
2333 if((args = v)[0] == NULL){
2334 rv = (a_amv_mac_show(a_AMV_MF_NONE) == FAL0);
2335 goto jleave;
2338 if(args[1] == NULL || args[1][0] != '{' || args[1][1] != '\0' ||
2339 args[2] != NULL){
2340 n_err(_("Synopsis: define: <name> {\n"));
2341 goto jleave;
2344 rv = (a_amv_mac_def(args[0], a_AMV_MF_NONE) == FAL0);
2345 jleave:
2346 NYD_LEAVE;
2347 return rv;
2350 FL int
2351 c_undefine(void *v){
2352 int rv;
2353 char **args;
2354 NYD_ENTER;
2356 rv = 0;
2357 args = v;
2359 rv |= !a_amv_mac_undef(*args, a_AMV_MF_NONE);
2360 while(*++args != NULL);
2361 NYD_LEAVE;
2362 return rv;
2365 FL int
2366 c_call(void *vp){
2367 int rv;
2368 NYD_ENTER;
2370 rv = a_amv_mac_call(vp, FAL0);
2371 NYD_LEAVE;
2372 return rv;
2375 FL int
2376 c_call_if(void *vp){
2377 int rv;
2378 NYD_ENTER;
2380 rv = a_amv_mac_call(vp, TRU1);
2381 NYD_LEAVE;
2382 return rv;
2385 FL int
2386 c_account(void *v){
2387 struct a_amv_mac_call_args *amcap;
2388 struct a_amv_mac *amp;
2389 char **args;
2390 int rv, i, oqf, nqf;
2391 NYD_ENTER;
2393 rv = 1;
2395 if((args = v)[0] == NULL){
2396 rv = (a_amv_mac_show(a_AMV_MF_ACCOUNT) == FAL0);
2397 goto jleave;
2400 if(args[1] && args[1][0] == '{' && args[1][1] == '\0'){
2401 if(args[2] != NULL){
2402 n_err(_("Synopsis: account: <name> {\n"));
2403 goto jleave;
2405 if(!asccasecmp(args[0], ACCOUNT_NULL)){
2406 n_err(_("`account': cannot use reserved name: %s\n"),
2407 ACCOUNT_NULL);
2408 goto jleave;
2410 rv = (a_amv_mac_def(args[0], a_AMV_MF_ACCOUNT) == FAL0);
2411 goto jleave;
2414 if(n_pstate & n_PS_HOOK_MASK){
2415 n_err(_("`account': cannot change account from within a hook\n"));
2416 goto jleave;
2419 save_mbox_for_possible_quitstuff();
2421 amp = NULL;
2422 if(asccasecmp(args[0], ACCOUNT_NULL) != 0 &&
2423 (amp = a_amv_mac_lookup(args[0], NULL, a_AMV_MF_ACCOUNT)) == NULL){
2424 n_err(_("`account': account does not exist: %s\n"), args[0]);
2425 goto jleave;
2428 oqf = savequitflags();
2430 /* Shutdown the active account */
2431 if(a_amv_acc_curr != NULL){
2432 char const *cp;
2433 char *var;
2435 /* Is there a cleanup hook? */
2436 var = savecat("on-account-cleanup-", a_amv_acc_curr->am_name);
2437 if((cp = n_var_vlook(var, FAL0)) != NULL ||
2438 (cp = ok_vlook(on_account_cleanup)) != NULL){
2439 struct a_amv_mac *amphook;
2441 if((amphook = a_amv_mac_lookup(cp, NULL, a_AMV_MF_NONE)) != NULL){
2442 amcap = n_lofi_alloc(sizeof *amcap);
2443 memset(amcap, 0, sizeof *amcap);
2444 amcap->amca_name = cp;
2445 amcap->amca_amp = amphook;
2446 amcap->amca_unroller = &a_amv_acc_curr->am_lopts;
2447 amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
2448 amcap->amca_no_xcall = TRU1;
2449 n_pstate |= n_PS_HOOK;
2450 rv = a_amv_mac_exec(amcap);
2451 n_pstate &= ~n_PS_HOOK_MASK;
2452 }else
2453 n_err(_("*on-account-leave* hook %s does not exist\n"),
2454 n_shexp_quote_cp(cp, FAL0));
2457 /* `localopts'? */
2458 if(a_amv_acc_curr->am_lopts != NULL)
2459 a_amv_lopts_unroll(&a_amv_acc_curr->am_lopts);
2461 /* For accounts this lingers */
2462 --a_amv_acc_curr->am_refcnt;
2463 if(a_amv_acc_curr->am_flags & a_AMV_MF_DELETE)
2464 a_amv_mac_free(a_amv_acc_curr);
2467 a_amv_acc_curr = amp;
2469 /* And switch to any non-"null" account */
2470 if(amp != NULL){
2471 assert(amp->am_lopts == NULL);
2472 amcap = n_lofi_alloc(sizeof *amcap);
2473 memset(amcap, 0, sizeof *amcap);
2474 amcap->amca_name = amp->am_name;
2475 amcap->amca_amp = amp;
2476 amcap->amca_unroller = &amp->am_lopts;
2477 amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
2478 amcap->amca_no_xcall = TRU1;
2479 ++amp->am_refcnt; /* We may not run 0 to avoid being deleted! */
2480 if(!a_amv_mac_exec(amcap)){
2481 /* XXX account switch incomplete, unroll? */
2482 n_err(_("`account': failed to switch to account: %s\n"), amp->am_name);
2483 goto jleave;
2487 n_PS_ROOT_BLOCK((amp != NULL ? ok_vset(account, amp->am_name)
2488 : ok_vclear(account)));
2490 if(n_psonce & n_PSO_STARTED){
2491 assert(!(n_pstate & n_PS_HOOK_MASK));
2492 nqf = savequitflags(); /* TODO obsolete (leave -> void -> new box!) */
2493 restorequitflags(oqf);
2494 if((i = setfile("%", 0)) < 0)
2495 goto jleave;
2496 temporary_folder_hook_check(FAL0);
2497 if(i > 0 && !ok_blook(emptystart))
2498 goto jleave;
2499 n_folder_announce(n_ANNOUNCE_CHANGE);
2500 restorequitflags(nqf);
2502 rv = 0;
2503 jleave:
2504 NYD_LEAVE;
2505 return rv;
2508 FL int
2509 c_unaccount(void *v){
2510 int rv;
2511 char **args;
2512 NYD_ENTER;
2514 rv = 0;
2515 args = v;
2517 rv |= !a_amv_mac_undef(*args, a_AMV_MF_ACCOUNT);
2518 while(*++args != NULL);
2519 NYD_LEAVE;
2520 return rv;
2523 FL int
2524 c_localopts(void *vp){
2525 enum a_amv_loflags alf, alm;
2526 char const **argv;
2527 int rv;
2528 NYD_ENTER;
2530 rv = 1;
2532 if(a_amv_lopts == NULL){
2533 n_err(_("Cannot use `localopts' in this context\n"));
2534 goto jleave;
2537 if((argv = vp)[1] == NULL || is_asccaseprefix((++argv)[-1], "scope"))
2538 alf = alm = a_AMV_LF_SCOPE;
2539 else if(is_asccaseprefix(argv[-1], "call"))
2540 alf = a_AMV_LF_CALL, alm = a_AMV_LF_CALL_MASK;
2541 else if(is_asccaseprefix(argv[-1], "call-fixate"))
2542 alf = a_AMV_LF_CALL_FIXATE, alm = a_AMV_LF_CALL_MASK;
2543 else{
2544 jesynopsis:
2545 n_err(_("Synopsis: localopts: [<scope|call|call-fixate>] <boolean>\n"));
2546 goto jleave;
2549 if(alf == a_AMV_LF_SCOPE &&
2550 (a_amv_lopts->as_loflags & a_AMV_LF_SCOPE_FIXATE)){
2551 if(n_poption & n_PO_D_V)
2552 n_err(_("Cannot turn off `localopts', setting is fixated\n"));
2553 goto jleave;
2556 if((rv = n_boolify(*argv, UIZ_MAX, FAL0)) < FAL0)
2557 goto jesynopsis;
2558 a_amv_lopts->as_loflags &= ~alm;
2559 if(rv > FAL0)
2560 a_amv_lopts->as_loflags |= alf;
2561 rv = 0;
2562 jleave:
2563 NYD_LEAVE;
2564 return rv;
2567 FL int
2568 c_shift(void *vp){ /* xxx move to bottom, not in macro part! */
2569 struct a_amv_pospar *appp;
2570 ui16_t i;
2571 int rv;
2572 NYD_ENTER;
2574 rv = 1;
2576 if((vp = *(char**)vp) == NULL)
2577 i = 1;
2578 else{
2579 si16_t sib;
2581 if((n_idec_si16_cp(&sib, vp, 10, NULL
2582 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2583 ) != n_IDEC_STATE_CONSUMED || sib < 0){
2584 n_err(_("`shift': invalid argument: %s\n"), vp);
2585 goto jleave;
2587 i = (ui16_t)sib;
2590 /* If in in a macro/xy */
2591 if(a_amv_lopts != NULL){
2592 struct a_amv_mac const *amp;
2593 struct a_amv_mac_call_args *amcap;
2595 /* Explicitly do allow `vpospar' created things! */
2596 amp = (amcap = a_amv_lopts->as_amcap)->amca_amp;
2597 if((amp == NULL || amcap->amca_ps_hook_mask ||
2598 (amp->am_flags & a_AMV_MF_TYPE_MASK) == a_AMV_MF_ACCOUNT) &&
2599 amcap->amca_pospar.app_not_heap){
2600 n_err(_("Cannot use `shift' in `account's or hook macros etc.\n"));
2601 goto jleave;
2603 appp = &amcap->amca_pospar;
2604 }else
2605 appp = &a_amv_pospar;
2607 if(i > appp->app_count){
2608 n_err(_("`shift': cannot shift %hu of %hu parameters\n"),
2609 i, appp->app_count);
2610 goto jleave;
2611 }else{
2612 appp->app_idx += i;
2613 appp->app_count -= i;
2614 rv = 0;
2616 jleave:
2617 NYD_LEAVE;
2618 return rv;
2621 FL int
2622 c_return(void *vp){ /* TODO the exit status should be m_si64! */
2623 int rv;
2624 NYD_ENTER;
2626 if(a_amv_lopts != NULL){
2627 char const **argv;
2629 n_go_input_force_eof();
2630 n_pstate_err_no = n_ERR_NONE;
2631 rv = 0;
2633 if((argv = vp)[0] != NULL){
2634 si32_t i;
2636 if((n_idec_si32_cp(&i, argv[0], 10, NULL
2637 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2638 ) == n_IDEC_STATE_CONSUMED && i >= 0)
2639 rv = (int)i;
2640 else{
2641 n_err(_("`return': return value argument is invalid: %s\n"),
2642 argv[0]);
2643 n_pstate_err_no = n_ERR_INVAL;
2644 rv = 1;
2647 if(argv[1] != NULL){
2648 if((n_idec_si32_cp(&i, argv[1], 10, NULL
2649 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2650 ) == n_IDEC_STATE_CONSUMED && i >= 0)
2651 n_pstate_err_no = i;
2652 else{
2653 n_err(_("`return': error number argument is invalid: %s\n"),
2654 argv[1]);
2655 n_pstate_err_no = n_ERR_INVAL;
2656 rv = 1;
2660 }else{
2661 n_err(_("Can only use `return' in a macro\n"));
2662 n_pstate_err_no = n_ERR_OPNOTSUPP;
2663 rv = 1;
2665 NYD_LEAVE;
2666 return rv;
2669 FL bool_t
2670 temporary_folder_hook_check(bool_t nmail){ /* TODO temporary, v15: drop */
2671 struct a_amv_mac_call_args *amcap;
2672 struct a_amv_mac *amp;
2673 size_t len;
2674 char const *cp;
2675 char *var;
2676 bool_t rv;
2677 NYD_ENTER;
2679 rv = TRU1;
2680 var = n_autorec_alloc(len = strlen(mailname) + sizeof("folder-hook-") -1 +1);
2682 /* First try the fully resolved path */
2683 snprintf(var, len, "folder-hook-%s", mailname);
2684 if((cp = n_var_vlook(var, FAL0)) != NULL)
2685 goto jmac;
2687 /* If we are under *folder*, try the usual +NAME syntax, too */
2688 if(displayname[0] == '+'){
2689 char *x;
2691 for(x = &mailname[len]; x != mailname; --x)
2692 if(x[-1] == '/'){
2693 snprintf(var, len, "folder-hook-+%s", x);
2694 if((cp = n_var_vlook(var, FAL0)) != NULL)
2695 goto jmac;
2696 break;
2700 /* Plain *folder-hook* is our last try */
2701 if((cp = ok_vlook(folder_hook)) == NULL)
2702 goto jleave;
2704 jmac:
2705 if((amp = a_amv_mac_lookup(cp, NULL, a_AMV_MF_NONE)) == NULL){
2706 n_err(_("Cannot call *folder-hook* for %s: macro does not exist: %s\n"),
2707 n_shexp_quote_cp(displayname, FAL0), cp);
2708 rv = FAL0;
2709 goto jleave;
2712 amcap = n_lofi_alloc(sizeof *amcap);
2713 memset(amcap, 0, sizeof *amcap);
2714 amcap->amca_name = cp;
2715 amcap->amca_amp = amp;
2716 n_pstate &= ~n_PS_HOOK_MASK;
2717 if(nmail){
2718 amcap->amca_unroller = NULL;
2719 n_pstate |= n_PS_HOOK_NEWMAIL;
2720 }else{
2721 amcap->amca_unroller = &a_amv_folder_hook_lopts;
2722 n_pstate |= n_PS_HOOK;
2724 amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
2725 amcap->amca_ps_hook_mask = TRU1;
2726 amcap->amca_no_xcall = TRU1;
2727 rv = a_amv_mac_exec(amcap);
2728 n_pstate &= ~n_PS_HOOK_MASK;
2730 jleave:
2731 NYD_LEAVE;
2732 return rv;
2735 FL void
2736 temporary_folder_hook_unroll(void){ /* XXX intermediate hack */
2737 NYD_ENTER;
2738 if(a_amv_folder_hook_lopts != NULL){
2739 void *save = a_amv_lopts;
2741 a_amv_lopts = NULL;
2742 a_amv_lopts_unroll(&a_amv_folder_hook_lopts);
2743 assert(a_amv_folder_hook_lopts == NULL);
2744 a_amv_lopts = save;
2746 NYD_LEAVE;
2749 FL void
2750 temporary_compose_mode_hook_call(char const *macname,
2751 void (*hook_pre)(void *), void *hook_arg){
2752 /* TODO compose_mode_hook_call() temporary, v15: generalize; see a_GO_SPLICE
2753 * TODO comment in go.c for the right way of doing things! */
2754 static struct a_amv_lostack *cmh_losp;
2755 struct a_amv_mac_call_args *amcap;
2756 struct a_amv_mac *amp;
2757 NYD_ENTER;
2759 amp = NULL;
2761 if(macname == (char*)-1){
2762 a_amv_mac__finalize(cmh_losp);
2763 cmh_losp = NULL;
2764 }else if(macname != NULL &&
2765 (amp = a_amv_mac_lookup(macname, NULL, a_AMV_MF_NONE)) == NULL)
2766 n_err(_("Cannot call *on-compose-**: macro does not exist: %s\n"),
2767 macname);
2768 else{
2769 amcap = n_lofi_alloc(sizeof *amcap);
2770 memset(amcap, 0, sizeof *amcap);
2771 amcap->amca_name = (macname != NULL) ? macname
2772 : "*on-compose-splice(-shell)?*";
2773 amcap->amca_amp = amp;
2774 amcap->amca_unroller = &a_amv_compose_lopts;
2775 amcap->amca_hook_pre = hook_pre;
2776 amcap->amca_hook_arg = hook_arg;
2777 amcap->amca_loflags = a_AMV_LF_SCOPE_FIXATE;
2778 amcap->amca_ps_hook_mask = TRU1;
2779 amcap->amca_no_xcall = TRU1;
2780 n_pstate &= ~n_PS_HOOK_MASK;
2781 n_pstate |= n_PS_HOOK;
2782 if(macname != NULL)
2783 a_amv_mac_exec(amcap);
2784 else{
2785 cmh_losp = n_lofi_alloc(sizeof *cmh_losp);
2786 memset(cmh_losp, 0, sizeof *cmh_losp);
2787 cmh_losp->as_global_saved = a_amv_lopts;
2788 cmh_losp->as_lopts = *(cmh_losp->as_amcap = amcap)->amca_unroller;
2789 cmh_losp->as_loflags = a_AMV_LF_SCOPE_FIXATE;
2790 a_amv_lopts = cmh_losp;
2793 NYD_LEAVE;
2796 FL void
2797 temporary_compose_mode_hook_unroll(void){ /* XXX intermediate hack */
2798 NYD_ENTER;
2799 if(a_amv_compose_lopts != NULL){
2800 void *save = a_amv_lopts;
2802 a_amv_lopts = NULL;
2803 a_amv_lopts_unroll(&a_amv_compose_lopts);
2804 assert(a_amv_compose_lopts == NULL);
2805 a_amv_lopts = save;
2807 NYD_LEAVE;
2810 FL bool_t
2811 n_var_is_user_writable(char const *name){
2812 struct a_amv_var_carrier avc;
2813 struct a_amv_var_map const *avmp;
2814 bool_t rv;
2815 NYD_ENTER;
2817 a_amv_var_revlookup(&avc, name);
2818 if((avmp = avc.avc_map) == NULL)
2819 rv = TRU1;
2820 else
2821 rv = ((avmp->avm_flags & (a_AMV_VF_BOOL | a_AMV_VF_RDONLY)) == 0);
2822 NYD_LEAVE;
2823 return rv;
2826 FL char *
2827 n_var_oklook(enum okeys okey){
2828 struct a_amv_var_carrier avc;
2829 char *rv;
2830 struct a_amv_var_map const *avmp;
2831 NYD_ENTER;
2833 avc.avc_map = avmp = &a_amv_var_map[okey];
2834 avc.avc_name = &a_amv_var_names[avmp->avm_keyoff];
2835 avc.avc_hash = avmp->avm_hash;
2836 avc.avc_okey = okey;
2838 if(a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE))
2839 rv = avc.avc_var->av_value;
2840 else
2841 rv = NULL;
2842 NYD_LEAVE;
2843 return rv;
2846 FL bool_t
2847 n_var_okset(enum okeys okey, uintptr_t val){
2848 struct a_amv_var_carrier avc;
2849 bool_t ok;
2850 struct a_amv_var_map const *avmp;
2851 NYD_ENTER;
2853 avc.avc_map = avmp = &a_amv_var_map[okey];
2854 avc.avc_name = &a_amv_var_names[avmp->avm_keyoff];
2855 avc.avc_hash = avmp->avm_hash;
2856 avc.avc_okey = okey;
2858 ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val),
2859 a_AMV_VSETCLR_NONE);
2860 NYD_LEAVE;
2861 return ok;
2864 FL bool_t
2865 n_var_okclear(enum okeys okey){
2866 struct a_amv_var_carrier avc;
2867 bool_t rv;
2868 struct a_amv_var_map const *avmp;
2869 NYD_ENTER;
2871 avc.avc_map = avmp = &a_amv_var_map[okey];
2872 avc.avc_name = &a_amv_var_names[avmp->avm_keyoff];
2873 avc.avc_hash = avmp->avm_hash;
2874 avc.avc_okey = okey;
2876 rv = a_amv_var_clear(&avc, a_AMV_VSETCLR_NONE);
2877 NYD_LEAVE;
2878 return rv;
2881 FL char const *
2882 n_var_vlook(char const *vokey, bool_t try_getenv){
2883 struct a_amv_var_carrier avc;
2884 char const *rv;
2885 NYD_ENTER;
2887 a_amv_var_revlookup(&avc, vokey);
2889 switch((enum a_amv_var_special_category)avc.avc_special_cat){
2890 default: /* silence CC */
2891 case a_AMV_VSC_NONE:
2892 if(a_amv_var_lookup(&avc, a_AMV_VLOOK_LOCAL))
2893 rv = avc.avc_var->av_value;
2894 /* Only check the environment for something that is otherwise unknown */
2895 else if(try_getenv && avc.avc_map == NULL)
2896 rv = getenv(vokey);
2897 else
2898 rv = NULL;
2899 break;
2900 case a_AMV_VSC_GLOBAL:
2901 rv = a_amv_var_vsc_global(&avc);
2902 break;
2903 case a_AMV_VSC_MULTIPLEX:
2904 rv = a_amv_var_vsc_multiplex(&avc);
2905 break;
2906 case a_AMV_VSC_POSPAR:
2907 case a_AMV_VSC_POSPAR_ENV:
2908 rv = a_amv_var_vsc_pospar(&avc);
2909 break;
2911 NYD_LEAVE;
2912 return rv;
2915 FL bool_t
2916 n_var_vexplode(void const **cookie){
2917 struct a_amv_pospar *appp;
2918 NYD_ENTER;
2920 appp = (a_amv_lopts != NULL) ? &a_amv_lopts->as_amcap->amca_pospar
2921 : &a_amv_pospar;
2922 *cookie = (appp->app_count > 0) ? &appp->app_dat[appp->app_idx] : NULL;
2923 NYD_LEAVE;
2924 return (*cookie != NULL);
2927 FL bool_t
2928 n_var_vset(char const *vokey, uintptr_t val){
2929 struct a_amv_var_carrier avc;
2930 bool_t ok;
2931 NYD_ENTER;
2933 a_amv_var_revlookup(&avc, vokey);
2935 ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val),
2936 a_AMV_VSETCLR_NONE);
2937 NYD_LEAVE;
2938 return ok;
2941 FL bool_t
2942 n_var_vclear(char const *vokey){
2943 struct a_amv_var_carrier avc;
2944 bool_t ok;
2945 NYD_ENTER;
2947 a_amv_var_revlookup(&avc, vokey);
2949 ok = a_amv_var_clear(&avc, a_AMV_VSETCLR_NONE);
2950 NYD_LEAVE;
2951 return ok;
2954 #ifdef HAVE_SOCKETS
2955 FL char *
2956 n_var_xoklook(enum okeys okey, struct url const *urlp,
2957 enum okey_xlook_mode oxm){
2958 struct a_amv_var_carrier avc;
2959 struct str const *us;
2960 size_t nlen;
2961 char *nbuf, *rv;
2962 struct a_amv_var_map const *avmp;
2963 NYD_ENTER;
2965 assert(oxm & (OXM_PLAIN | OXM_H_P | OXM_U_H_P));
2967 /* For simplicity: allow this case too */
2968 if(!(oxm & (OXM_H_P | OXM_U_H_P))){
2969 nbuf = NULL;
2970 goto jplain;
2973 avc.avc_map = avmp = &a_amv_var_map[okey];
2974 avc.avc_name = &a_amv_var_names[avmp->avm_keyoff];
2975 avc.avc_okey = okey;
2977 us = (oxm & OXM_U_H_P) ? &urlp->url_u_h_p : &urlp->url_h_p;
2978 nlen = strlen(avc.avc_name);
2979 nbuf = n_lofi_alloc(nlen + 1 + us->l +1);
2980 memcpy(nbuf, avc.avc_name, nlen);
2982 /* One of .url_u_h_p and .url_h_p we test in here */
2983 /*avc.avc_is_chain_variant = TRU1;*/
2984 nbuf[nlen++] = '-';
2985 memcpy(&nbuf[nlen], us->s, us->l +1);
2986 avc.avc_name = a_amv_var_canonify(nbuf);
2987 avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
2988 if(a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE))
2989 goto jvar;
2991 /* The second */
2992 if((oxm & (OXM_U_H_P | OXM_H_P)) == (OXM_U_H_P | OXM_H_P)){
2993 us = &urlp->url_h_p;
2994 memcpy(&nbuf[nlen], us->s, us->l +1);
2995 avc.avc_name = a_amv_var_canonify(nbuf);
2996 avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
2997 if(a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE)){
2998 jvar:
2999 rv = avc.avc_var->av_value;
3000 goto jleave;
3004 jplain:
3005 /*avc.avc_is_chain_variant = FAL0;*/
3006 rv = (oxm & OXM_PLAIN) ? n_var_oklook(okey) : NULL;
3007 jleave:
3008 if(nbuf != NULL)
3009 n_lofi_free(nbuf);
3010 NYD_LEAVE;
3011 return rv;
3013 #endif /* HAVE_SOCKETS */
3015 FL int
3016 c_set(void *vp){
3017 int err;
3018 char **ap;
3019 NYD_ENTER;
3021 if(*(ap = vp) == NULL){
3022 a_amv_var_show_all();
3023 err = 0;
3024 }else{
3025 enum a_amv_var_setclr_flags avscf;
3027 if(!(n_pstate & n_PS_ARGMOD_LOCAL))
3028 avscf = a_AMV_VSETCLR_NONE;
3029 else{
3030 if(a_amv_lopts == NULL){
3031 n_err(_("`set': cannot use `local' in this context\n"));
3032 err = 1;
3033 goto jleave;
3035 avscf = a_AMV_VSETCLR_LOCAL;
3037 err = !a_amv_var_c_set(ap, avscf);
3039 jleave:
3040 NYD_LEAVE;
3041 return err;
3044 FL int
3045 c_unset(void *vp){
3046 struct a_amv_var_carrier avc;
3047 char **ap;
3048 int err;
3049 enum a_amv_var_setclr_flags avscf;
3050 NYD_ENTER;
3052 if(!(n_pstate & n_PS_ARGMOD_LOCAL))
3053 avscf = a_AMV_VSETCLR_NONE;
3054 else{
3055 if(a_amv_lopts == NULL){
3056 n_err(_("`unset': cannot use `local' in this context\n"));
3057 err = 1;
3058 goto jleave;
3060 avscf = a_AMV_VSETCLR_LOCAL;
3063 for(err = 0, ap = vp; *ap != NULL; ++ap){
3064 a_amv_var_revlookup(&avc, *ap);
3066 err |= !a_amv_var_clear(&avc, avscf);
3068 jleave:
3069 NYD_LEAVE;
3070 return err;
3073 FL int
3074 c_varshow(void *v){
3075 char **ap;
3076 NYD_ENTER;
3078 if(*(ap = v) == NULL)
3079 v = NULL;
3080 else{
3081 struct n_string msg, *msgp = &msg;
3083 msgp = n_string_creat(msgp);
3084 for(; *ap != NULL; ++ap)
3085 a_amv_var_show(*ap, n_stdout, msgp);
3086 n_string_gut(msgp);
3088 NYD_LEAVE;
3089 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
3092 FL int
3093 c_varedit(void *v){ /* TODO v15 drop */
3094 struct a_amv_var_carrier avc;
3095 FILE *of, *nf;
3096 char *val, **argv;
3097 int err;
3098 sighandler_type sigint;
3099 NYD_ENTER;
3101 sigint = safe_signal(SIGINT, SIG_IGN);
3103 for(err = 0, argv = v; *argv != NULL; ++argv){
3104 memset(&avc, 0, sizeof avc);
3106 a_amv_var_revlookup(&avc, *argv);
3108 if(avc.avc_map != NULL){
3109 if(avc.avc_map->avm_flags & a_AMV_VF_BOOL){
3110 n_err(_("`varedit': cannot edit boolean variable: %s\n"),
3111 avc.avc_name);
3112 continue;
3114 if(avc.avc_map->avm_flags & a_AMV_VF_RDONLY){
3115 n_err(_("`varedit': cannot edit read-only variable: %s\n"),
3116 avc.avc_name);
3117 continue;
3121 a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE);
3123 if((of = Ftmp(NULL, "varedit", OF_RDWR | OF_UNLINK | OF_REGISTER)) ==
3124 NULL){
3125 n_perr(_("`varedit': cannot create temporary file"), 0);
3126 err = 1;
3127 break;
3128 }else if(avc.avc_var != NULL && *(val = avc.avc_var->av_value) != '\0' &&
3129 sizeof *val != fwrite(val, strlen(val), sizeof *val, of)){
3130 n_perr(_("`varedit' failed to write old value to temporary file"), 0);
3131 Fclose(of);
3132 err = 1;
3133 continue;
3136 fflush_rewind(of);
3137 nf = run_editor(of, (off_t)-1, 'e', FAL0, NULL, NULL, SEND_MBOX, sigint);
3138 Fclose(of);
3140 if(nf != NULL){
3141 int c;
3142 char const *varres;
3143 off_t l;
3145 l = fsize(nf);
3146 if(UICMP(64, l, >=, UIZ_MAX -42)){
3147 n_err(_("`varedit': not enough memory to store variable: %s\n"),
3148 avc.avc_name);
3149 varres = n_empty;
3150 err = 1;
3151 }else{
3152 varres = val = n_autorec_alloc(l +1);
3153 for(; l > 0 && (c = getc(nf)) != EOF; --l)
3154 *val++ = c;
3155 *val++ = '\0';
3156 if(l != 0){
3157 n_err(_("`varedit': I/O while reading new value of: %s\n"),
3158 avc.avc_name);
3159 err = 1;
3163 if(!a_amv_var_set(&avc, varres, a_AMV_VSETCLR_NONE))
3164 err = 1;
3166 Fclose(nf);
3167 }else{
3168 n_err(_("`varedit': cannot start $EDITOR\n"));
3169 err = 1;
3170 break;
3174 safe_signal(SIGINT, sigint);
3175 NYD_LEAVE;
3176 return err;
3179 FL int
3180 c_environ(void *v){
3181 struct a_amv_var_carrier avc;
3182 int err;
3183 char **ap;
3184 bool_t islnk;
3185 NYD_ENTER;
3187 if((islnk = is_asccaseprefix(*(ap = v), "link")) ||
3188 is_asccaseprefix(*ap, "unlink")){
3189 for(err = 0; *++ap != NULL;){
3190 a_amv_var_revlookup(&avc, *ap);
3192 if(a_amv_var_lookup(&avc, a_AMV_VLOOK_NONE) && (islnk ||
3193 (avc.avc_var->av_flags & a_AMV_VF_EXT_LINKED))){
3194 if(!islnk){
3195 avc.avc_var->av_flags &= ~a_AMV_VF_EXT_LINKED;
3196 continue;
3197 }else if(avc.avc_var->av_flags &
3198 (a_AMV_VF_ENV | a_AMV_VF_EXT_LINKED)){
3199 if(n_poption & n_PO_D_V)
3200 n_err(_("`environ': link: already established: %s\n"), *ap);
3201 continue;
3203 avc.avc_var->av_flags |= a_AMV_VF_EXT_LINKED;
3204 if(!(avc.avc_var->av_flags & a_AMV_VF_ENV))
3205 a_amv_var__putenv(&avc, avc.avc_var);
3206 }else if(!islnk){
3207 n_err(_("`environ': unlink: no link established: %s\n"), *ap);
3208 err = 1;
3209 }else{
3210 char const *evp = getenv(*ap);
3212 if(evp != NULL)
3213 err |= !a_amv_var_set(&avc, evp, a_AMV_VSETCLR_ENV);
3214 else{
3215 n_err(_("`environ': link: cannot link to non-existent: %s\n"),
3216 *ap);
3217 err = 1;
3221 }else if(is_asccaseprefix(*ap, "set"))
3222 err = !a_amv_var_c_set(++ap, a_AMV_VSETCLR_ENV);
3223 else if(is_asccaseprefix(*ap, "unset")){
3224 for(err = 0; *++ap != NULL;){
3225 a_amv_var_revlookup(&avc, *ap);
3227 if(!a_amv_var_clear(&avc, a_AMV_VSETCLR_ENV))
3228 err = 1;
3230 }else{
3231 n_err(_("Synopsis: environ: <link|set|unset> <variable>...\n"));
3232 err = 1;
3234 NYD_LEAVE;
3235 return err;
3238 FL int
3239 c_vexpr(void *v){ /* TODO POSIX expr(1) comp. exit status; overly complicat. */
3240 char pbase, op, iencbuf[2+1/* BASE# prefix*/ + n_IENC_BUFFER_SIZE + 1];
3241 size_t i;
3242 enum n_idec_state ids;
3243 enum n_idec_mode idm;
3244 si64_t lhv, rhv;
3245 char const **argv, *varname, *varres, *cp;
3246 enum{
3247 a_ERR = 1u<<0,
3248 a_SOFTOVERFLOW = 1u<<1,
3249 a_ISNUM = 1u<<2,
3250 a_ISDECIMAL = 1u<<3, /* Print only decimal result */
3251 a_SATURATED = 1u<<4,
3252 a_ICASE = 1u<<5,
3253 a_UNSIGNED_OP = 1u<<6, /* Unsigned right shift (share bit ok) */
3254 a_PBASE = 1u<<7, /* Print additional number base */
3255 a_TMP = 1u<<30
3256 } f;
3257 NYD_ENTER;
3259 f = a_ERR;
3260 argv = v;
3261 varname = (n_pstate & n_PS_ARGMOD_VPUT) ? *argv++ : NULL;
3262 n_UNINIT(varres, n_empty);
3263 n_UNINIT(pbase, '\0');
3265 if((cp = argv[0])[0] == '\0')
3266 goto jesubcmd;
3268 if(cp[1] == '\0'){
3269 op = cp[0];
3270 jnumop:
3271 f |= a_ISNUM;
3272 switch(op){
3273 case '=':
3274 case '~':
3275 if(argv[1] == NULL || argv[2] != NULL)
3276 goto jesynopsis;
3278 if(*(cp = *++argv) == '\0')
3279 lhv = 0;
3280 else{
3281 idm = ((*cp == 'u' || *cp == 'U')
3282 ? (++cp, n_IDEC_MODE_NONE)
3283 : ((*cp == 's' || *cp == 'S')
3284 ? (++cp, n_IDEC_MODE_SIGNED_TYPE)
3285 : n_IDEC_MODE_SIGNED_TYPE |
3286 n_IDEC_MODE_POW2BASE_UNSIGNED));
3287 if(((ids = n_idec_cp(&lhv, cp, 0, idm, NULL)
3288 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3289 ) != n_IDEC_STATE_CONSUMED){
3290 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
3291 goto jenum_range;
3292 f |= a_SOFTOVERFLOW;
3293 break;
3296 if(op == '~')
3297 lhv = ~lhv;
3298 break;
3300 case '+':
3301 case '-':
3302 case '*':
3303 case '/':
3304 case '%':
3305 case '|':
3306 case '&':
3307 case '^':
3308 case '<':
3309 case '>':
3310 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
3311 goto jesynopsis;
3312 else{
3313 char xop;
3315 if(*(cp = *++argv) == '\0')
3316 lhv = 0;
3317 else{
3318 idm = ((*cp == 'u' || *cp == 'U')
3319 ? (++cp, n_IDEC_MODE_NONE)
3320 : ((*cp == 's' || *cp == 'S')
3321 ? (++cp, n_IDEC_MODE_SIGNED_TYPE)
3322 : n_IDEC_MODE_SIGNED_TYPE |
3323 n_IDEC_MODE_POW2BASE_UNSIGNED));
3324 if(((ids = n_idec_cp(&lhv, cp, 0, idm, NULL)
3325 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3326 ) != n_IDEC_STATE_CONSUMED){
3327 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
3328 goto jenum_range;
3329 f |= a_SOFTOVERFLOW;
3330 break;
3334 if(*(cp = *++argv) == '\0')
3335 rhv = 0;
3336 else{
3337 idm = ((*cp == 'u' || *cp == 'U')
3338 ? (++cp, n_IDEC_MODE_NONE)
3339 : ((*cp == 's' || *cp == 'S')
3340 ? (++cp, n_IDEC_MODE_SIGNED_TYPE)
3341 : n_IDEC_MODE_SIGNED_TYPE |
3342 n_IDEC_MODE_POW2BASE_UNSIGNED));
3343 if(((ids = n_idec_cp(&rhv, cp, 0, idm, NULL)
3344 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3345 ) != n_IDEC_STATE_CONSUMED){
3346 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
3347 goto jenum_range;
3348 f |= a_SOFTOVERFLOW;
3349 lhv = rhv;
3350 break;
3354 xop = op;
3355 jnumop_again:
3356 switch(xop){
3357 case '+':
3358 if(rhv < 0){
3359 if(rhv != SI64_MIN){
3360 rhv = -rhv;
3361 xop = '-';
3362 goto jnumop_again;
3363 }else if(lhv < 0)
3364 goto jenum_plusminus;
3365 else if(lhv == 0){
3366 lhv = rhv;
3367 break;
3369 }else if(SI64_MAX - rhv < lhv)
3370 goto jenum_plusminus;
3371 lhv += rhv;
3372 break;
3373 case '-':
3374 if(rhv < 0){
3375 if(rhv != SI64_MIN){
3376 rhv = -rhv;
3377 xop = '+';
3378 goto jnumop_again;
3379 }else if(lhv > 0)
3380 goto jenum_plusminus;
3381 else if(lhv == 0){
3382 lhv = rhv;
3383 break;
3385 }else if(SI64_MIN + rhv > lhv){
3386 jenum_plusminus:
3387 if(!(f & a_SATURATED))
3388 goto jenum_overflow;
3389 f |= a_SOFTOVERFLOW;
3390 lhv = (lhv < 0 || xop == '-') ? SI64_MIN : SI64_MAX;
3391 break;
3393 lhv -= rhv;
3394 break;
3395 case '*':
3396 /* Will the result be positive? */
3397 if((lhv < 0) == (rhv < 0)){
3398 if(lhv > 0){
3399 lhv = -lhv;
3400 rhv = -rhv;
3402 if(rhv != 0 && lhv != 0 && SI64_MAX / rhv > lhv){
3403 if(!(f & a_SATURATED))
3404 goto jenum_overflow;
3405 f |= a_SOFTOVERFLOW;
3406 lhv = SI64_MAX;
3407 }else
3408 lhv *= rhv;
3409 }else{
3410 if(rhv > 0){
3411 if(lhv != 0 && SI64_MIN / lhv < rhv){
3412 if(!(f & a_SATURATED))
3413 goto jenum_overflow;
3414 f |= a_SOFTOVERFLOW;
3415 lhv = SI64_MIN;
3416 }else
3417 lhv *= rhv;
3418 }else{
3419 if(rhv != 0 && lhv != 0 && SI64_MIN / rhv < lhv){
3420 if(!(f & a_SATURATED))
3421 goto jenum_overflow;
3422 f |= a_SOFTOVERFLOW;
3423 lhv = SI64_MIN;
3424 }else
3425 lhv *= rhv;
3428 break;
3429 case '/':
3430 if(rhv == 0){
3431 if(!(f & a_SATURATED))
3432 goto jenum_range;
3433 f |= a_SOFTOVERFLOW;
3434 lhv = SI64_MAX;
3435 }else
3436 lhv /= rhv;
3437 break;
3438 case '%':
3439 if(rhv == 0){
3440 if(!(f & a_SATURATED))
3441 goto jenum_range;
3442 f |= a_SOFTOVERFLOW;
3443 lhv = SI64_MAX;
3444 }else
3445 lhv %= rhv;
3446 break;
3447 case '|':
3448 lhv |= rhv;
3449 break;
3450 case '&':
3451 lhv &= rhv;
3452 break;
3453 case '^':
3454 lhv ^= rhv;
3455 break;
3456 case '<':
3457 case '>':
3458 if(!(f & a_TMP)){
3459 argv -= 2;
3460 goto jesubcmd;
3462 if(rhv > 63){ /* xxx 63? */
3463 if(!(f & a_SATURATED))
3464 goto jenum_overflow;
3465 rhv = 63;
3467 if(op == '<')
3468 lhv <<= (ui8_t)rhv;
3469 else if(f & a_UNSIGNED_OP)
3470 lhv = (ui64_t)lhv >> (ui8_t)rhv;
3471 else
3472 lhv >>= (ui8_t)rhv;
3473 break;
3476 break;
3477 default:
3478 goto jesubcmd;
3480 }else if(cp[0] == '<'){
3481 if(*++cp != '<')
3482 goto jesubcmd;
3483 if(*++cp == '@'){
3484 n_OBSOLETE(_("`vexpr': please use @ modifier as prefix not suffix"));
3485 f |= a_SATURATED;
3486 ++cp;
3488 if(*cp != '\0')
3489 goto jesubcmd;
3490 f |= a_TMP;
3491 op = '<';
3492 goto jnumop;
3493 }else if(cp[0] == '>'){
3494 if(*++cp != '>')
3495 goto jesubcmd;
3496 if(*++cp == '>'){
3497 f |= a_UNSIGNED_OP;
3498 ++cp;
3500 if(*cp == '@'){
3501 n_OBSOLETE(_("`vexpr': please use @ modifier as prefix not suffix"));
3502 f |= a_SATURATED;
3503 ++cp;
3505 if(*cp != '\0')
3506 goto jesubcmd;
3507 f |= a_TMP;
3508 op = '>';
3509 goto jnumop;
3510 }else if(cp[2] == '\0' && cp[1] == '@'){
3511 n_OBSOLETE(_("`vexpr': please use @ modifier as prefix, not suffix"));
3512 f |= a_SATURATED;
3513 op = cp[0];
3514 goto jnumop;
3515 }else if(cp[0] == '@'){
3516 f |= a_SATURATED;
3517 op = *++cp;
3518 if(*++cp != '\0'){
3519 if(op != *cp)
3520 goto jesubcmd;
3521 switch(op){
3522 case '<':
3523 if(*++cp != '\0')
3524 goto jesubcmd;
3525 f |= a_TMP;
3526 break;
3527 case '>':
3528 if(*++cp != '\0'){
3529 if(*cp != '>' || *++cp != '\0')
3530 goto jesubcmd;
3531 f |= a_UNSIGNED_OP;
3533 f |= a_TMP;
3534 break;
3535 default:
3536 goto jesubcmd;
3539 goto jnumop;
3540 }else if(is_asccaseprefix(cp, "pbase")){
3541 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
3542 goto jesynopsis;
3544 if(((ids = n_idec_si8_cp(&pbase, argv[1], 0, NULL)
3545 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3546 ) != n_IDEC_STATE_CONSUMED || pbase < 2 || pbase > 36)
3547 goto jenum_range;
3549 f |= a_PBASE;
3550 op = *(argv[0] = cp = "=");
3551 argv[1] = argv[2];
3552 argv[2] = NULL;
3553 goto jnumop;
3554 }else if(is_asccaseprefix(cp, "length")){
3555 f |= a_ISNUM | a_ISDECIMAL;
3556 if(argv[1] == NULL || argv[2] != NULL)
3557 goto jesynopsis;
3559 i = strlen(*++argv);
3560 if(UICMP(64, i, >, SI64_MAX))
3561 goto jestr_overflow;
3562 lhv = (si64_t)i;
3563 }else if(is_asccaseprefix(cp, "hash")){
3564 f |= a_ISNUM | a_ISDECIMAL;
3565 if(argv[1] == NULL || argv[2] != NULL)
3566 goto jesynopsis;
3568 i = n_torek_hash(*++argv);
3569 lhv = (si64_t)i;
3570 }else if(is_asccaseprefix(cp, "find")){
3571 f |= a_ISNUM | a_ISDECIMAL;
3572 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
3573 goto jesynopsis;
3575 if((cp = strstr(argv[1], argv[2])) == NULL)
3576 goto jestr_nodata;
3577 i = PTR2SIZE(cp - argv[1]);
3578 if(UICMP(64, i, >, SI64_MAX))
3579 goto jestr_overflow;
3580 lhv = (si64_t)i;
3581 }else if(is_asccaseprefix(cp, "ifind")){
3582 f |= a_ISNUM | a_ISDECIMAL;
3583 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
3584 goto jesynopsis;
3586 if((cp = asccasestr(argv[1], argv[2])) == NULL)
3587 goto jestr_nodata;
3588 i = PTR2SIZE(cp - argv[1]);
3589 if(UICMP(64, i, >, SI64_MAX))
3590 goto jestr_overflow;
3591 lhv = (si64_t)i;
3592 }else if(is_asccaseprefix(cp, "substring")){
3593 if(argv[1] == NULL || argv[2] == NULL)
3594 goto jesynopsis;
3595 if(argv[3] != NULL && argv[4] != NULL)
3596 goto jesynopsis;
3598 i = strlen(varres = *++argv);
3600 if(*(cp = *++argv) == '\0')
3601 lhv = 0;
3602 else if((n_idec_si64_cp(&lhv, cp, 0, NULL
3603 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3604 ) != n_IDEC_STATE_CONSUMED)
3605 goto jestr_numrange;
3606 if(lhv < 0){
3607 if(UICMP(64, i, <, -lhv))
3608 goto jesubstring_off;
3609 lhv = i + lhv;
3611 if(UICMP(64, i, >=, lhv)){
3612 i -= lhv;
3613 varres += lhv;
3614 }else{
3615 jesubstring_off:
3616 if(n_poption & n_PO_D_V)
3617 n_err(_("`vexpr': substring: offset argument too large: %s\n"),
3618 n_shexp_quote_cp(argv[-1], FAL0));
3619 f |= a_SOFTOVERFLOW;
3622 if(argv[1] != NULL){
3623 if(*(cp = *++argv) == '\0')
3624 lhv = 0;
3625 else if((n_idec_si64_cp(&lhv, cp, 0, NULL
3626 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3627 ) != n_IDEC_STATE_CONSUMED)
3628 goto jestr_numrange;
3629 if(lhv < 0){
3630 if(UICMP(64, i, <, -lhv))
3631 goto jesubstring_len;
3632 lhv = i + lhv;
3634 if(UICMP(64, i, >=, lhv)){
3635 if(UICMP(64, i, !=, lhv))
3636 varres = savestrbuf(varres, (size_t)lhv);
3637 }else{
3638 jesubstring_len:
3639 if(n_poption & n_PO_D_V)
3640 n_err(_("`vexpr': substring: length argument too large: %s\n"),
3641 n_shexp_quote_cp(argv[-2], FAL0));
3642 f |= a_SOFTOVERFLOW;
3645 }else if(is_asccaseprefix(cp, "trim")) Jtrim: {
3646 struct str trim;
3647 enum n_str_trim_flags stf;
3649 if(argv[1] == NULL || argv[2] != NULL)
3650 goto jesynopsis;
3652 if(is_asccaseprefix(cp, "trim-front"))
3653 stf = n_STR_TRIM_FRONT;
3654 else if(is_asccaseprefix(cp, "trim-end"))
3655 stf = n_STR_TRIM_END;
3656 else
3657 stf = n_STR_TRIM_BOTH;
3659 trim.l = strlen(trim.s = n_UNCONST(argv[1]));
3660 (void)n_str_trim(&trim, stf);
3661 varres = savestrbuf(trim.s, trim.l);
3662 }else if(is_asccaseprefix(cp, "trim-front"))
3663 goto Jtrim;
3664 else if(is_asccaseprefix(cp, "trim-end"))
3665 goto Jtrim;
3666 else if(is_asccaseprefix(cp, "random")){
3667 if(argv[1] == NULL || argv[2] != NULL)
3668 goto jesynopsis;
3670 if((n_idec_si64_cp(&lhv, argv[1], 0, NULL
3671 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3672 ) != n_IDEC_STATE_CONSUMED || lhv < 0 || lhv > PATH_MAX)
3673 goto jestr_numrange;
3674 if(lhv == 0)
3675 lhv = NAME_MAX;
3676 varres = n_random_create_cp((size_t)lhv, NULL);
3677 }else if(is_asccaseprefix(cp, "file-expand")){
3678 if(argv[1] == NULL || argv[2] != NULL)
3679 goto jesynopsis;
3681 if((varres = fexpand(argv[1], FEXP_NVAR | FEXP_NOPROTO)) == NULL)
3682 goto jestr_nodata;
3683 }else if(is_asccaseprefix(cp, "makeprint")){
3684 struct str sin, sout;
3686 if(argv[1] == NULL || argv[2] != NULL)
3687 goto jesynopsis;
3689 /* XXX using strlen for `vexpr makeprint' is wrong for UTF-16 */
3690 sin.l = strlen(sin.s = n_UNCONST(argv[1]));
3691 makeprint(&sin, &sout);
3692 varres = savestrbuf(sout.s, sout.l);
3693 n_free(sout.s);
3694 /* TODO `vexpr': (wide) string length, find, etc!! */
3695 #ifdef HAVE_REGEX
3696 }else if(is_asccaseprefix(cp, "regex")) Jregex:{
3697 regmatch_t rema[1 + n_VEXPR_REGEX_MAX];
3698 regex_t re;
3699 int reflrv;
3701 f |= a_ISNUM | a_ISDECIMAL;
3702 if(argv[1] == NULL || argv[2] == NULL ||
3703 (argv[3] != NULL && argv[4] != NULL))
3704 goto jesynopsis;
3706 reflrv = REG_EXTENDED;
3707 if(f & a_ICASE)
3708 reflrv |= REG_ICASE;
3709 if((reflrv = regcomp(&re, argv[2], reflrv))){
3710 n_err(_("`vexpr': invalid regular expression: %s: %s\n"),
3711 n_shexp_quote_cp(argv[2], FAL0), n_regex_err_to_doc(NULL, reflrv));
3712 assert(f & a_ERR);
3713 n_pstate_err_no = n_ERR_INVAL;
3714 goto jestr;
3716 reflrv = regexec(&re, argv[1], n_NELEM(rema), rema, 0);
3717 regfree(&re);
3718 if(reflrv == REG_NOMATCH)
3719 goto jestr_nodata;
3721 /* Search only? Else replace, which is a bit */
3722 if(argv[3] == NULL){
3723 if(UICMP(64, rema[0].rm_so, >, SI64_MAX))
3724 goto jestr_overflow;
3725 lhv = (si64_t)rema[0].rm_so;
3726 }else{
3727 /* We need to setup some kind of pseudo macro environment for this */
3728 struct a_amv_lostack los;
3729 struct a_amv_mac_call_args amca;
3730 char const **reargv;
3732 memset(&amca, 0, sizeof amca);
3733 amca.amca_name = savestrbuf(&argv[1][rema[0].rm_so],
3734 rema[0].rm_eo - rema[0].rm_so);
3735 amca.amca_amp = a_AMV_MACKY_MACK;
3736 for(i = 1; i < n_NELEM(rema) && rema[i].rm_so != -1; ++i)
3738 amca.amca_pospar.app_count = (ui32_t)i - 1;
3739 amca.amca_pospar.app_not_heap = TRU1;
3740 amca.amca_pospar.app_dat =
3741 reargv = n_autorec_alloc(sizeof(char*) * i);
3742 for(i = 1; i < n_NELEM(rema) && rema[i].rm_so != -1; ++i)
3743 *reargv++ = savestrbuf(&argv[1][rema[i].rm_so],
3744 rema[i].rm_eo - rema[i].rm_so);
3745 *reargv = NULL;
3747 memset(&los, 0, sizeof los);
3748 hold_all_sigs(); /* TODO DISLIKE! */
3749 los.as_global_saved = a_amv_lopts;
3750 los.as_amcap = &amca;
3751 los.as_up = los.as_global_saved;
3752 a_amv_lopts = &los;
3754 /* C99 */{
3755 struct str templ;
3756 struct n_string s_b;
3757 enum n_shexp_state shs;
3759 templ.s = n_UNCONST(argv[3]);
3760 templ.l = UIZ_MAX;
3761 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
3762 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
3763 n_SHEXP_PARSE_QUOTE_AUTO_DSQ),
3764 n_string_creat_auto(&s_b), &templ, NULL);
3765 if((shs & (n_SHEXP_STATE_ERR_MASK | n_SHEXP_STATE_STOP)
3766 ) == n_SHEXP_STATE_STOP){
3767 varres = n_string_cp(&s_b);
3768 n_string_drop_ownership(&s_b);
3769 }else
3770 varres = NULL;
3773 a_amv_lopts = los.as_global_saved;
3774 rele_all_sigs(); /* TODO DISLIKE! */
3776 if(varres == NULL)
3777 goto jestr_nodata;
3778 f &= ~(a_ISNUM | a_ISDECIMAL);
3780 }else if(is_asccaseprefix(argv[0], "iregex")){
3781 f |= a_ICASE;
3782 goto Jregex;
3783 #endif /* HAVE_REGEX */
3784 }else
3785 goto jesubcmd;
3787 n_pstate_err_no = (f & a_SOFTOVERFLOW) ? n_ERR_OVERFLOW : n_ERR_NONE;
3788 f &= ~a_ERR;
3790 /* Generate the variable value content for numerics.
3791 * Anticipate in our handling below! (Don't do needless work) */
3792 jleave:
3793 if((f & a_ISNUM) && ((f & (a_ISDECIMAL | a_PBASE)) || varname != NULL)){
3794 cp = n_ienc_buf(iencbuf, lhv, (f & a_PBASE ? pbase : 10),
3795 n_IENC_MODE_SIGNED_TYPE);
3796 if(cp != NULL)
3797 varres = cp;
3798 else{
3799 f |= a_ERR;
3800 varres = n_empty;
3804 if(varname == NULL){
3805 /* If there was no error and we are printing a numeric result, print some
3806 * more bases for the fun of it */
3807 if((f & (a_ERR | a_ISNUM | a_ISDECIMAL)) == a_ISNUM){
3808 char binabuf[64 + 64 / 8 +1];
3809 size_t j;
3811 for(j = 1, i = 0; i < 64; ++i){
3812 binabuf[63 + 64 / 8 -j - i] = (lhv & ((ui64_t)1 << i)) ? '1' : '0';
3813 if((i & 7) == 7 && i != 63){
3814 ++j;
3815 binabuf[63 + 64 / 8 -j - i] = ' ';
3818 binabuf[64 + 64 / 8 -1] = '\0';
3820 if(fprintf(n_stdout,
3821 "0b %s\n0%" PRIo64 " | 0x%" PRIX64 " | %" PRId64 "\n",
3822 binabuf, lhv, lhv, lhv) < 0 ||
3823 ((f & a_PBASE) && (assert(varres != NULL),
3824 fprintf(n_stdout, "%s\n", varres) < 0))){
3825 n_pstate_err_no = n_err_no;
3826 f |= a_ERR;
3828 }else if(varres != NULL && fprintf(n_stdout, "%s\n", varres) < 0){
3829 n_pstate_err_no = n_err_no;
3830 f |= a_ERR;
3832 }else if(!n_var_vset(varname, (uintptr_t)varres)){
3833 n_pstate_err_no = n_ERR_NOTSUP;
3834 f |= a_ERR;
3836 NYD_LEAVE;
3837 return (f & a_ERR) ? 1 : 0;
3839 jerr:
3840 f = a_ERR | a_ISNUM;
3841 lhv = -1;
3842 goto jleave;
3843 jesubcmd:
3844 n_err(_("`vexpr': invalid subcommand: %s\n"),
3845 n_shexp_quote_cp(*argv, FAL0));
3846 n_pstate_err_no = n_ERR_INVAL;
3847 goto jerr;
3848 jesynopsis:
3849 n_err(_("Synopsis: vexpr: <operator> <:argument:>\n"));
3850 n_pstate_err_no = n_ERR_INVAL;
3851 goto jerr;
3853 jenum_range:
3854 n_err(_("`vexpr': numeric argument invalid or out of range: %s\n"),
3855 n_shexp_quote_cp(*argv, FAL0));
3856 n_pstate_err_no = n_ERR_RANGE;
3857 goto jerr;
3858 jenum_overflow:
3859 n_err(_("`vexpr': expression overflows datatype: %" PRId64 " %c %" PRId64
3860 "\n"), lhv, op, rhv);
3861 n_pstate_err_no = n_ERR_OVERFLOW;
3862 goto jerr;
3864 jestr_numrange:
3865 n_err(_("`vexpr': numeric argument invalid or out of range: %s\n"),
3866 n_shexp_quote_cp(*argv, FAL0));
3867 n_pstate_err_no = n_ERR_RANGE;
3868 goto jestr;
3869 jestr_overflow:
3870 n_err(_("`vexpr': string length or offset overflows datatype\n"));
3871 n_pstate_err_no = n_ERR_OVERFLOW;
3872 goto jestr;
3873 jestr_nodata:
3874 n_pstate_err_no = n_ERR_NODATA;
3875 /* FALLTHRU */
3876 jestr:
3877 varres = n_empty;
3878 f &= ~a_ISNUM;
3879 f |= a_ERR;
3880 goto jleave;
3883 FL int
3884 c_vpospar(void *v){
3885 struct n_cmd_arg *cap;
3886 size_t i;
3887 struct a_amv_pospar *appp;
3888 enum{
3889 a_NONE = 0,
3890 a_ERR = 1u<<0,
3891 a_SET = 1u<<1,
3892 a_CLEAR = 1u<<2,
3893 a_QUOTE = 1u<<3
3894 } f;
3895 char const *varres;
3896 struct n_cmd_arg_ctx *cacp;
3897 NYD_ENTER;
3899 n_pstate_err_no = n_ERR_NONE;
3900 n_UNINIT(varres, n_empty);
3901 cacp = v;
3902 cap = cacp->cac_arg;
3904 if(is_asccaseprefix(cap->ca_arg.ca_str.s, "set"))
3905 f = a_SET;
3906 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "clear"))
3907 f = a_CLEAR;
3908 else if(is_asccaseprefix(cap->ca_arg.ca_str.s, "quote"))
3909 f = a_QUOTE;
3910 else{
3911 n_err(_("`vpospar': invalid subcommand: %s\n"),
3912 n_shexp_quote_cp(cap->ca_arg.ca_str.s, FAL0));
3913 n_pstate_err_no = n_ERR_INVAL;
3914 f = a_ERR;
3915 goto jleave;
3917 --cacp->cac_no;
3919 if((f & (a_CLEAR | a_QUOTE)) && cap->ca_next != NULL){
3920 n_err(_("`vpospar': `%s': takes no argument\n"), cap->ca_arg.ca_str.s);
3921 n_pstate_err_no = n_ERR_INVAL;
3922 f = a_ERR;
3923 goto jleave;
3926 cap = cap->ca_next;
3928 /* If in a macro, we need to overwrite the local instead of global argv */
3929 appp = (a_amv_lopts != NULL) ? &a_amv_lopts->as_amcap->amca_pospar
3930 : &a_amv_pospar;
3932 if(f & (a_SET | a_CLEAR)){
3933 if(cacp->cac_vput != NULL)
3934 n_err(_("`vpospar': `vput' only supported for `quote' subcommand\n"));
3935 if(!appp->app_not_heap && appp->app_maxcount > 0){
3936 for(i = appp->app_maxcount; i-- != 0;)
3937 n_free(n_UNCONST(appp->app_dat[i]));
3938 n_free(appp->app_dat);
3940 memset(appp, 0, sizeof *appp);
3942 if(f & a_SET){
3943 if((i = cacp->cac_no) > a_AMV_POSPAR_MAX){
3944 n_err(_("`vpospar': overflow: %" PRIuZ " arguments!\n"), i);
3945 n_pstate_err_no = n_ERR_OVERFLOW;
3946 f = a_ERR;
3947 goto jleave;
3950 memset(appp, 0, sizeof *appp);
3951 if(i > 0){
3952 appp->app_maxcount = appp->app_count = (ui16_t)i;
3953 /* XXX Optimize: store it all in one chunk! */
3954 ++i;
3955 i *= sizeof *appp->app_dat;
3956 appp->app_dat = n_alloc(i);
3958 for(i = 0; cap != NULL; ++i, cap = cap->ca_next){
3959 appp->app_dat[i] = n_alloc(cap->ca_arg.ca_str.l +1);
3960 memcpy(n_UNCONST(appp->app_dat[i]), cap->ca_arg.ca_str.s,
3961 cap->ca_arg.ca_str.l +1);
3964 appp->app_dat[i] = NULL;
3967 }else{
3968 if(appp->app_count == 0)
3969 varres = n_empty;
3970 else{
3971 struct str in;
3972 struct n_string s, *sp;
3973 char sep1, sep2;
3975 sp = n_string_creat_auto(&s);
3977 sep1 = *ok_vlook(ifs);
3978 sep2 = *ok_vlook(ifs_ws);
3979 if(sep1 == sep2)
3980 sep2 = '\0';
3981 if(sep1 == '\0')
3982 sep1 = ' ';
3984 for(i = 0; i < appp->app_count; ++i){
3985 if(sp->s_len){
3986 if(!n_string_can_book(sp, 2))
3987 goto jeover;
3988 sp = n_string_push_c(sp, sep1);
3989 if(sep2 != '\0')
3990 sp = n_string_push_c(sp, sep2);
3992 in.l = strlen(in.s = n_UNCONST(appp->app_dat[i + appp->app_idx]));
3994 if(!n_string_can_book(sp, in.l)){
3995 jeover:
3996 n_err(_("`vpospar': overflow: string too long!\n"));
3997 n_pstate_err_no = n_ERR_OVERFLOW;
3998 f = a_ERR;
3999 goto jleave;
4001 sp = n_shexp_quote(sp, &in, TRU1);
4004 varres = n_string_cp(sp);
4007 if(cacp->cac_vput == NULL){
4008 if(fprintf(n_stdout, "%s\n", varres) < 0){
4009 n_pstate_err_no = n_err_no;
4010 f |= a_ERR;
4012 }else if(!n_var_vset(cacp->cac_vput, (uintptr_t)varres)){
4013 n_pstate_err_no = n_ERR_NOTSUP;
4014 f |= a_ERR;
4017 jleave:
4018 NYD_LEAVE;
4019 return (f & a_ERR) ? 1 : 0;
4022 /* s-it-mode */