(BWDIC!) No! Let $! be errno, and $? the sole exit status..
[s-mailx.git] / accmacvar.c
blobe2d048a2be2de6e31a31d7a9a00a8eda2622d1f3
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Account, macro and variable handling.
3 *@ HOWTO add a new non-dynamic boolean or value option:
4 *@ - add an entry to nail.h:enum okeys
5 *@ - run mk-okey-map.pl
6 *@ - update the manual!
7 *@ TODO . should be recursive environment based.
8 *@ TODO Otherwise, the `localopts' should be an attribute of the go.c
9 *@ TODO command context, so that it belongs to the execution context
10 *@ TODO we are running in, instead of being global data. See, e.g.,
11 *@ TODO the a_GO_SPLICE comment in go.c.
12 *@ TODO . once we can have non-fatal !0 returns for commands, we should
13 *@ TODO return error if "(environ)? unset" goes for non-existent.
15 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
16 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
19 * Copyright (c) 1980, 1993
20 * The Regents of the University of California. All rights reserved.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. Neither the name of the University nor the names of its contributors
31 * may be used to endorse or promote products derived from this software
32 * without specific prior written permission.
34 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44 * SUCH DAMAGE.
46 #undef n_FILE
47 #define n_FILE accmacvar
49 #ifndef HAVE_AMALGAMATION
50 # include "nail.h"
51 #endif
53 #if !defined HAVE_SETENV && !defined HAVE_PUTENV
54 # error Exactly one of HAVE_SETENV and HAVE_PUTENV
55 #endif
57 /* Special "pseudo macro" that stabs you from the back */
58 #define a_AMV_MACKY_MACK ((struct a_amv_mac*)-1)
60 /* Note: changing the hash function must be reflected in mk-okey-map.pl */
61 #define a_AMV_PRIME HSHSIZE
62 #define a_AMV_NAME2HASH(N) n_torek_hash(N)
63 #define a_AMV_HASH2PRIME(H) ((H) % a_AMV_PRIME)
65 enum a_amv_mac_flags{
66 a_AMV_MF_NONE = 0,
67 a_AMV_MF_ACCOUNT = 1<<0, /* This macro is an `account' */
68 a_AMV_MF_TYPE_MASK = a_AMV_MF_ACCOUNT,
69 a_AMV_MF_UNDEF = 1<<1, /* Unlink after lookup */
70 a_AMV_MF_DELETE = 1<<7, /* Delete in progress, free once refcnt==0 */
71 a_AMV_MF__MAX = 0xFF
74 /* mk-okey-map.pl ensures that _VIRT implies _RDONLY and _NODEL, and that
75 * _IMPORT implies _ENV; it doesn't verify anything... */
76 enum a_amv_var_flags{
77 a_AMV_VF_NONE = 0,
78 a_AMV_VF_BOOL = 1<<0, /* ok_b_* */
79 a_AMV_VF_VIRT = 1<<1, /* "Stateless" automatic variable */
80 a_AMV_VF_NOLOPTS = 1<<2, /* May not be tracked by `localopts' */
81 a_AMV_VF_RDONLY = 1<<3, /* May not be set by user */
82 a_AMV_VF_NODEL = 1<<4, /* May not be deleted */
83 a_AMV_VF_NOTEMPTY = 1<<5, /* May not be assigned an empty value */
84 a_AMV_VF_NOCNTRLS = 1<<6, /* Value may not contain control characters */
85 a_AMV_VF_NUM = 1<<7, /* Value must be a 32-bit number */
86 a_AMV_VF_POSNUM = 1<<8, /* Value must be positive 32-bit number */
87 a_AMV_VF_LOWER = 1<<9, /* Values will be stored in a lowercase version */
88 a_AMV_VF_VIP = 1<<10, /* Wants _var_check_vips() evaluation */
89 a_AMV_VF_IMPORT = 1<<11, /* Import ONLY from environ (pre n_PSO_STARTED) */
90 a_AMV_VF_ENV = 1<<12, /* Update environment on change */
91 a_AMV_VF_I3VAL = 1<<13, /* Has an initial value */
92 a_AMV_VF_DEFVAL = 1<<14, /* Has a default value */
93 a_AMV_VF_LINKED = 1<<15, /* `environ' linked */
94 a_AMV_VF__MASK = (1<<(15+1)) - 1
97 /* We support some special parameter names for one-letter variable names;
98 * note these have counterparts in the code that manages shell expansion!
99 * Macro-local variables are solely backed by n_var_vlook(), and besides there
100 * is only a_amv_var_revlookup() which knows about them.
101 * The ARGV $[1-9][0-9]* variables are also special, but they are special ;] */
102 enum a_amv_var_special_category{
103 a_AMV_VSC_NONE, /* Normal variable, no special treatment */
104 a_AMV_VSC_GLOBAL, /* ${[?!]} are specially mapped, but global */
105 a_AMV_VSC_MULTIPLEX, /* ${^.*} circumflex accent multiplexer */
106 a_AMV_VSC_MAC, /* ${[*@#]} macro argument access */
107 a_AMV_VSC_MAC_ARGV /* ${[1-9][0-9]*} macro ARGV access */
110 enum a_amv_var_special_type{
111 /* _VSC_GLOBAL */
112 a_AMV_VST_QM, /* ? */
113 a_AMV_VST_EM, /* ! */
114 /* _VSC_MULTIPLEX */
115 /* This is special in that it is a multiplex indicator, the ^ is followed by
116 * a normal variable */
117 a_AMV_VST_CACC, /* ^ (circumflex accent) */
118 /* _VSC_MAC */
119 a_AMV_VST_STAR, /* * */
120 a_AMV_VST_AT, /* @ */
121 a_AMV_VST_NOSIGN /* # */
124 enum a_amv_var_vip_mode{
125 a_AMV_VIP_SET_PRE,
126 a_AMV_VIP_SET_POST,
127 a_AMV_VIP_CLEAR
130 struct a_amv_mac{
131 struct a_amv_mac *am_next;
132 ui32_t am_maxlen; /* of any line in .am_line_dat */
133 ui32_t am_line_cnt; /* of *.am_line_dat (but NULL terminated) */
134 struct a_amv_mac_line **am_line_dat; /* TODO use deque? */
135 struct a_amv_var *am_lopts; /* `localopts' unroll list */
136 ui32_t am_refcnt; /* 0-based for `un{account,define}' purposes */
137 ui8_t am_flags; /* enum a_amv_mac_flags */
138 char am_name[n_VFIELD_SIZE(3)]; /* of this macro */
140 n_CTA(a_AMV_MF__MAX <= UI8_MAX, "Enumeration excesses storage datatype");
142 struct a_amv_mac_line{
143 ui32_t aml_len;
144 ui32_t aml_prespc; /* Number of leading SPC, for display purposes */
145 char aml_dat[n_VFIELD_SIZE(0)];
148 struct a_amv_mac_call_args{
149 char const *amca_name; /* For MACKY_MACK, this is *0*! */
150 struct a_amv_mac *amca_amp; /* "const", but for am_refcnt */
151 struct a_amv_var **amca_unroller;
152 void (*amca_hook_pre)(void *);
153 void *amca_hook_arg;
154 bool_t amca_lopts_on;
155 bool_t amca_ps_hook_mask;
156 ui8_t amca__pad[4];
157 ui16_t amca_argc; /* Max is SI16_MAX */
158 char const **amca_argv;
161 struct a_amv_lostack{
162 struct a_amv_lostack *as_global_saved; /* Saved global XXX due to jump */
163 struct a_amv_mac_call_args *as_amcap;
164 struct a_amv_lostack *as_up; /* Outer context */
165 struct a_amv_var *as_lopts;
166 bool_t as_unroll; /* Unrolling enabled? */
167 ui8_t avs__pad[7];
170 struct a_amv_var{
171 struct a_amv_var *av_link;
172 char *av_value;
173 #ifdef HAVE_PUTENV
174 char *av_env; /* Actively managed putenv(3) memory */
175 #endif
176 ui16_t av_flags; /* enum a_amv_var_flags */
177 char av_name[n_VFIELD_SIZE(6)];
179 n_CTA(a_AMV_VF__MASK <= UI16_MAX, "Enumeration excesses storage datatype");
181 struct a_amv_var_map{
182 ui32_t avm_hash;
183 ui16_t avm_keyoff;
184 ui16_t avm_flags; /* enum a_amv_var_flags */
186 n_CTA(a_AMV_VF__MASK <= UI16_MAX, "Enumeration excesses storage datatype");
188 struct a_amv_var_virt{
189 ui32_t avv_okey;
190 ui8_t avv__dummy[4];
191 struct a_amv_var const *avv_var;
194 struct a_amv_var_defval{
195 ui32_t avdv_okey;
196 ui8_t avdv__pad[4];
197 char const *avdv_value; /* Only for !BOOL (otherwise plain existence) */
200 struct a_amv_var_carrier{
201 char const *avc_name;
202 ui32_t avc_hash;
203 ui32_t avc_prime;
204 struct a_amv_var *avc_var;
205 struct a_amv_var_map const *avc_map;
206 enum okeys avc_okey;
207 ui8_t avc__pad[1];
208 ui8_t avc_special_cat;
209 /* Numerical parameter name if .avc_special_cat=a_AMV_VSC_MAC_ARGV,
210 * otherwise a enum a_amv_var_special_type */
211 ui16_t avc_special_prop;
214 /* Include the constant mk-okey-map.pl output, and the generated version data */
215 #include "gen-version.h"
216 #include "gen-okeys.h"
218 /* The currently active account */
219 static struct a_amv_mac *a_amv_acc_curr;
221 static struct a_amv_mac *a_amv_macs[a_AMV_PRIME]; /* TODO dynamically spaced */
223 /* Unroll list of currently running macro stack */
224 static struct a_amv_lostack *a_amv_lopts;
226 static struct a_amv_var *a_amv_vars[a_AMV_PRIME]; /* TODO dynamically spaced */
228 /* TODO We really deserve localopts support for *folder-hook*s, so hack it in
229 * TODO today via a static lostack, it should be a field in mailbox, once that
230 * TODO is a real multi-instance object */
231 static struct a_amv_var *a_amv_folder_hook_lopts;
233 /* TODO Rather ditto (except for storage -> cmd_ctx), compose hooks */
234 static struct a_amv_var *a_amv_compose_lopts;
236 /* Lookup for macros/accounts: if newamp is not NULL it will be linked in the
237 * map, if _MF_UNDEF is set a possibly existing entry will be removed (first).
238 * Returns NULL if a lookup failed, or if newamp was set, the found entry in
239 * plain lookup cases or when _UNDEF was performed on a currently active entry
240 * (the entry will have been unlinked, and the _MF_DELETE will be honoured once
241 * the reference count reaches 0), and (*)-1 if an _UNDEF was performed */
242 static struct a_amv_mac *a_amv_mac_lookup(char const *name,
243 struct a_amv_mac *newamp, enum a_amv_mac_flags amf);
245 /* `call', `call_if' */
246 static int a_amv_mac_call(void *v, bool_t silent_nexist);
248 /* Execute a macro; amcap must reside in LOFI memory */
249 static bool_t a_amv_mac_exec(struct a_amv_mac_call_args *amcap);
251 static void a_amv_mac__finalize(void *vp);
253 /* User display helpers */
254 static bool_t a_amv_mac_show(enum a_amv_mac_flags amf);
256 /* _def() returns error for faulty definitions and already existing * names,
257 * _undef() returns error if a named thing doesn't exist */
258 static bool_t a_amv_mac_def(char const *name, enum a_amv_mac_flags amf);
259 static bool_t a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf);
261 /* */
262 static void a_amv_mac_free(struct a_amv_mac *amp);
264 /* Update replay-log */
265 static void a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
266 struct a_amv_var *oavp);
267 static void a_amv_lopts_unroll(struct a_amv_var **avpp);
269 /* Special cased value string allocation */
270 static char *a_amv_var_copy(char const *str);
271 static void a_amv_var_free(char *cp);
273 /* Check for special housekeeping. _VIP_SET_POST and _VIP_CLEAR do not fail
274 * (or propagate errors), _VIP_SET_PRE may and should case abortion */
275 static bool_t a_amv_var_check_vips(enum a_amv_var_vip_mode avvm,
276 enum okeys okey, char const *val);
278 /* _VF_NOCNTRLS, _VF_NUM / _VF_POSNUM */
279 static bool_t a_amv_var_check_nocntrls(char const *val);
280 static bool_t a_amv_var_check_num(char const *val, bool_t posnum);
282 /* If a variable name begins with a lowercase-character and contains at
283 * least one '@', it is converted to all-lowercase. This is necessary
284 * for lookups of names based on email addresses.
285 * Following the standard, only the part following the last '@' should
286 * be lower-cased, but practice has established otherwise here */
287 static char const *a_amv_var_canonify(char const *vn);
289 /* Try to reverse lookup an option name to an enum okeys mapping.
290 * Updates .avc_name and .avc_hash; .avc_map is NULL if none found */
291 static bool_t a_amv_var_revlookup(struct a_amv_var_carrier *avcp,
292 char const *name);
294 /* Lookup a variable from .avc_(map|name|hash), return whether it was found.
295 * Sets .avc_prime; .avc_var is NULL if not found.
296 * Here it is where we care for _I3VAL and _DEFVAL, too.
297 * An _I3VAL will be "consumed" as necessary anyway, but it won't be used to
298 * create a new variable if i3val_nonew is true; if i3val_nonew is TRUM1 then
299 * we set .avc_var to -1 and return true if that was the case, otherwise we'll
300 * return FAL0, then! */
301 static bool_t a_amv_var_lookup(struct a_amv_var_carrier *avcp,
302 bool_t i3val_nonew);
304 /* Lookup functions for special category variables, _mac drives all macro etc.
305 * local special categories */
306 static char const *a_amv_var_vsc_global(struct a_amv_var_carrier *avcp);
307 static char const *a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp);
308 static char const *a_amv_var_vsc_mac(struct a_amv_var_carrier *avcp);
310 /* Set var from .avc_(map|name|hash), return success */
311 static bool_t a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
312 bool_t force_env);
314 static bool_t a_amv_var__putenv(struct a_amv_var_carrier *avcp,
315 struct a_amv_var *avp);
317 /* Clear var from .avc_(map|name|hash); sets .avc_var=NULL, return success */
318 static bool_t a_amv_var_clear(struct a_amv_var_carrier *avcp, bool_t force_env);
320 static bool_t a_amv_var__clearenv(char const *name, char *value);
322 /* List all variables */
323 static void a_amv_var_show_all(void);
325 static int a_amv_var__show_cmp(void const *s1, void const *s2);
327 /* Actually do print one, return number of lines written */
328 static size_t a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp);
330 /* Shared c_set() and c_environ():set impl, return success */
331 static bool_t a_amv_var_c_set(char **ap, bool_t issetenv);
333 static struct a_amv_mac *
334 a_amv_mac_lookup(char const *name, struct a_amv_mac *newamp,
335 enum a_amv_mac_flags amf){
336 struct a_amv_mac *amp, **ampp;
337 ui32_t h;
338 enum a_amv_mac_flags save_amf;
339 NYD2_ENTER;
341 save_amf = amf;
342 amf &= a_AMV_MF_TYPE_MASK;
343 h = a_AMV_NAME2HASH(name);
344 h = a_AMV_HASH2PRIME(h);
345 ampp = &a_amv_macs[h];
347 for(amp = *ampp; amp != NULL; ampp = &(*ampp)->am_next, amp = amp->am_next){
348 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf &&
349 !strcmp(amp->am_name, name)){
350 if(n_LIKELY((save_amf & a_AMV_MF_UNDEF) == 0))
351 goto jleave;
353 *ampp = amp->am_next;
355 if(amp->am_refcnt > 0){
356 amp->am_flags |= a_AMV_MF_DELETE;
357 if(n_poption & n_PO_D_V)
358 n_err(_("Delayed deletion of currently active %s: %s\n"),
359 (amp->am_flags & a_AMV_MF_ACCOUNT ? "account" : "define"),
360 name);
361 }else{
362 a_amv_mac_free(amp);
363 amp = (struct a_amv_mac*)-1;
365 break;
369 if(newamp != NULL){
370 ampp = &a_amv_macs[h];
371 newamp->am_next = *ampp;
372 *ampp = newamp;
373 amp = NULL;
375 jleave:
376 NYD2_LEAVE;
377 return amp;
380 static int
381 a_amv_mac_call(void *v, bool_t silent_nexist){
382 int rv;
383 struct a_amv_mac *amp;
384 char const *name;
385 NYD_ENTER;
387 name = *(char const**)v;
389 if((amp = a_amv_mac_lookup(name, NULL, a_AMV_MF_NONE)) != NULL){
390 struct a_amv_mac_call_args *amcap;
392 amcap = n_lofi_alloc(sizeof *amcap);
393 memset(amcap, 0, sizeof *amcap);
394 amcap->amca_name = name;
395 amcap->amca_amp = amp;
396 /* C99 */{
397 char const **argv;
398 ui32_t argc;
400 for(argc = 0, argv = v; *++argv != NULL; ++argc)
402 if(argc > 0){
403 amcap->amca_argc = argc;
404 amcap->amca_argv = &(argv = v)[1];
408 rv = a_amv_mac_exec(amcap);
409 rv = n_pstate_ex_no;
410 }else{
411 if((rv = (silent_nexist == FAL0)))
412 n_err(_("Undefined macro `call'ed: %s\n"),
413 n_shexp_quote_cp(name, FAL0));
414 n_pstate_err_no = n_ERR_NOENT;
415 rv = 1;
417 NYD_LEAVE;
418 return rv;
421 static bool_t
422 a_amv_mac_exec(struct a_amv_mac_call_args *amcap){
423 struct a_amv_lostack *losp;
424 struct a_amv_mac_line **amlp;
425 char **args_base, **args;
426 struct a_amv_mac *amp;
427 bool_t rv;
428 NYD2_ENTER;
430 amp = amcap->amca_amp;
431 assert(amp != NULL && amp != a_AMV_MACKY_MACK);
432 ++amp->am_refcnt;
433 /* XXX Unfortunately we yet need to dup the macro lines! :( */
434 args_base = args = smalloc(sizeof(*args) * (amp->am_line_cnt +1));
435 for(amlp = amp->am_line_dat; *amlp != NULL; ++amlp)
436 *(args++) = sbufdup((*amlp)->aml_dat, (*amlp)->aml_len);
437 *args = NULL;
439 losp = n_lofi_alloc(sizeof *losp);
440 losp->as_global_saved = a_amv_lopts;
441 if((losp->as_amcap = amcap)->amca_unroller == NULL){
442 losp->as_up = losp->as_global_saved;
443 losp->as_lopts = NULL;
444 }else{
445 losp->as_up = NULL;
446 losp->as_lopts = *amcap->amca_unroller;
448 losp->as_unroll = amcap->amca_lopts_on;
450 a_amv_lopts = losp;
451 if(amcap->amca_hook_pre != NULL)
452 n_PS_ROOT_BLOCK((*amcap->amca_hook_pre)(amcap->amca_hook_arg));
453 rv = n_go_macro(n_GO_INPUT_NONE, amp->am_name, args_base,
454 &a_amv_mac__finalize, losp);
455 NYD2_LEAVE;
456 return rv;
459 static void
460 a_amv_mac__finalize(void *vp){
461 struct a_amv_mac *amp;
462 struct a_amv_mac_call_args *amcap;
463 struct a_amv_lostack *losp;
464 NYD2_ENTER;
466 losp = vp;
467 a_amv_lopts = losp->as_global_saved;
469 if((amcap = losp->as_amcap)->amca_unroller == NULL){
470 if(losp->as_lopts != NULL)
471 a_amv_lopts_unroll(&losp->as_lopts);
472 }else
473 *amcap->amca_unroller = losp->as_lopts;
475 if(amcap->amca_ps_hook_mask)
476 n_pstate &= ~n_PS_HOOK_MASK;
478 if((amp = amcap->amca_amp) != a_AMV_MACKY_MACK && amp != NULL &&
479 --amp->am_refcnt == 0 && (amp->am_flags & a_AMV_MF_DELETE))
480 a_amv_mac_free(amp);
482 n_lofi_free(losp);
483 n_lofi_free(amcap);
484 NYD2_LEAVE;
487 static bool_t
488 a_amv_mac_show(enum a_amv_mac_flags amf){
489 size_t lc, mc, ti, i;
490 char const *typestr;
491 FILE *fp;
492 bool_t rv;
493 NYD2_ENTER;
495 rv = FAL0;
497 if((fp = Ftmp(NULL, "deflist", OF_RDWR | OF_UNLINK | OF_REGISTER)) ==
498 NULL){
499 n_perr(_("Can't create temporary file for `define' or `account' listing"),
501 goto jleave;
504 amf &= a_AMV_MF_TYPE_MASK;
505 typestr = (amf & a_AMV_MF_ACCOUNT) ? "account" : "define";
507 for(lc = mc = ti = 0; ti < a_AMV_PRIME; ++ti){
508 struct a_amv_mac *amp;
510 for(amp = a_amv_macs[ti]; amp != NULL; amp = amp->am_next){
511 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
512 struct a_amv_mac_line **amlpp;
514 if(++mc > 1){
515 putc('\n', fp);
516 ++lc;
518 ++lc;
519 fprintf(fp, "%s %s {\n", typestr, amp->am_name);
520 for(amlpp = amp->am_line_dat; *amlpp != NULL; ++lc, ++amlpp){
521 for(i = (*amlpp)->aml_prespc; i > 0; --i)
522 putc(' ', fp);
523 fputs((*amlpp)->aml_dat, fp);
524 putc('\n', fp);
526 fputs("}\n", fp);
527 ++lc;
531 if(mc > 0)
532 page_or_print(fp, lc);
534 rv = (ferror(fp) == 0);
535 Fclose(fp);
536 jleave:
537 NYD2_LEAVE;
538 return rv;
541 static bool_t
542 a_amv_mac_def(char const *name, enum a_amv_mac_flags amf){
543 struct str line;
544 ui32_t line_cnt, maxlen;
545 struct linelist{
546 struct linelist *ll_next;
547 struct a_amv_mac_line *ll_amlp;
548 } *llp, *ll_head, *ll_tail;
549 union {size_t s; int i; ui32_t ui; size_t l;} n;
550 struct a_amv_mac *amp;
551 bool_t rv;
552 NYD2_ENTER;
554 memset(&line, 0, sizeof line);
555 rv = FAL0;
556 amp = NULL;
558 /* TODO We should have our input state machine which emits Line events,
559 * TODO and hook different consumers dependent on our content, as stated
560 * TODO in i think lex_input; */
561 /* Read in the lines which form the macro content */
562 for(ll_tail = ll_head = NULL, line_cnt = maxlen = 0;;){
563 ui32_t leaspc;
564 char *cp;
566 n.i = n_go_input(n_GO_INPUT_CTX_DEFAULT | n_GO_INPUT_NL_ESC, n_empty,
567 &line.s, &line.l, NULL);
568 if(n.ui == 0)
569 continue;
570 if(n.i < 0){
571 n_err(_("Unterminated %s definition: %s\n"),
572 (amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
573 goto jerr;
576 /* Trim WS, remember amount of leading spaces for display purposes */
577 for(cp = line.s, leaspc = 0; n.ui > 0; ++cp, --n.ui)
578 if(*cp == '\t')
579 leaspc = (leaspc + 8u) & ~7u;
580 else if(*cp == ' ')
581 ++leaspc;
582 else
583 break;
584 for(; n.ui > 0 && spacechar(cp[n.ui - 1]); --n.ui)
586 if(n.ui == 0)
587 continue;
589 maxlen = n_MAX(maxlen, n.ui);
590 cp[n.ui++] = '\0';
592 /* Is is the closing brace? */
593 if(*cp == '}')
594 break;
596 if(n_LIKELY(++line_cnt < UI32_MAX)){
597 struct a_amv_mac_line *amlp;
599 llp = salloc(sizeof *llp);
600 if(ll_head == NULL)
601 ll_head = llp;
602 else
603 ll_tail->ll_next = llp;
604 ll_tail = llp;
605 llp->ll_next = NULL;
606 llp->ll_amlp = amlp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_mac_line,
607 aml_dat) + n.ui);
608 amlp->aml_len = n.ui -1;
609 amlp->aml_prespc = leaspc;
610 memcpy(amlp->aml_dat, cp, n.ui);
611 }else{
612 n_err(_("Too much content in %s definition: %s\n"),
613 (amf & a_AMV_MF_ACCOUNT ? "account" : "macro"), name);
614 goto jerr;
618 /* Create the new macro */
619 n.s = strlen(name) +1;
620 amp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_mac, am_name) + n.s);
621 amp->am_next = NULL;
622 amp->am_maxlen = maxlen;
623 amp->am_line_cnt = line_cnt;
624 amp->am_refcnt = 0;
625 amp->am_flags = amf;
626 amp->am_lopts = NULL;
627 memcpy(amp->am_name, name, n.s);
628 /* C99 */{
629 struct a_amv_mac_line **amlpp;
631 amp->am_line_dat = amlpp = smalloc(sizeof(*amlpp) * ++line_cnt);
632 for(llp = ll_head; llp != NULL; llp = llp->ll_next)
633 *amlpp++ = llp->ll_amlp;
634 *amlpp = NULL;
637 /* Create entry, replace a yet existing one as necessary */
638 a_amv_mac_lookup(name, amp, amf | a_AMV_MF_UNDEF);
639 rv = TRU1;
640 jleave:
641 if(line.s != NULL)
642 free(line.s);
643 NYD2_LEAVE;
644 return rv;
646 jerr:
647 for(llp = ll_head; llp != NULL; llp = llp->ll_next)
648 free(llp->ll_amlp);
649 if(amp != NULL){
650 free(amp->am_line_dat);
651 free(amp);
653 goto jleave;
656 static bool_t
657 a_amv_mac_undef(char const *name, enum a_amv_mac_flags amf){
658 struct a_amv_mac *amp;
659 bool_t rv;
660 NYD2_ENTER;
662 rv = TRU1;
664 if(n_LIKELY(name[0] != '*' || name[1] != '\0')){
665 if((amp = a_amv_mac_lookup(name, NULL, amf | a_AMV_MF_UNDEF)) == NULL){
666 n_err(_("%s not defined: %s\n"),
667 (amf & a_AMV_MF_ACCOUNT ? "Account" : "Macro"), name);
668 rv = FAL0;
670 }else{
671 struct a_amv_mac **ampp, *lamp;
673 for(ampp = a_amv_macs; PTRCMP(ampp, <, &a_amv_macs[n_NELEM(a_amv_macs)]);
674 ++ampp)
675 for(lamp = NULL, amp = *ampp; amp != NULL;){
676 if((amp->am_flags & a_AMV_MF_TYPE_MASK) == amf){
677 /* xxx Expensive but rare: be simple */
678 a_amv_mac_lookup(amp->am_name, NULL, amf | a_AMV_MF_UNDEF);
679 amp = (lamp == NULL) ? *ampp : lamp->am_next;
680 }else{
681 lamp = amp;
682 amp = amp->am_next;
686 NYD2_LEAVE;
687 return rv;
690 static void
691 a_amv_mac_free(struct a_amv_mac *amp){
692 struct a_amv_mac_line **amlpp;
693 NYD2_ENTER;
695 for(amlpp = amp->am_line_dat; *amlpp != NULL; ++amlpp)
696 free(*amlpp);
697 free(amp->am_line_dat);
698 free(amp);
699 NYD2_LEAVE;
702 static void
703 a_amv_lopts_add(struct a_amv_lostack *alp, char const *name,
704 struct a_amv_var *oavp){
705 struct a_amv_var *avp;
706 size_t nl, vl;
707 NYD2_ENTER;
709 /* Propagate unrolling up the stack, as necessary */
710 assert(alp != NULL);
711 for(;;){
712 if(alp->as_unroll)
713 break;
714 if((alp = alp->as_up) == NULL)
715 goto jleave;
718 /* Check whether this variable is handled yet */
719 for(avp = alp->as_lopts; avp != NULL; avp = avp->av_link)
720 if(!strcmp(avp->av_name, name))
721 goto jleave;
723 nl = strlen(name) +1;
724 vl = (oavp != NULL) ? strlen(oavp->av_value) +1 : 0;
725 avp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + nl + vl);
726 avp->av_link = alp->as_lopts;
727 alp->as_lopts = avp;
728 memcpy(avp->av_name, name, nl);
729 if(vl == 0){
730 avp->av_value = NULL;
731 avp->av_flags = 0;
732 #ifdef HAVE_PUTENV
733 avp->av_env = NULL;
734 #endif
735 }else{
736 avp->av_value = &avp->av_name[nl];
737 avp->av_flags = oavp->av_flags;
738 memcpy(avp->av_value, oavp->av_value, vl);
739 #ifdef HAVE_PUTENV
740 avp->av_env = (oavp->av_env == NULL) ? NULL : sstrdup(oavp->av_env);
741 #endif
743 jleave:
744 NYD2_LEAVE;
747 static void
748 a_amv_lopts_unroll(struct a_amv_var **avpp){
749 struct a_amv_lostack *save_alp;
750 struct a_amv_var *x, *avp;
751 NYD2_ENTER;
753 avp = *avpp;
754 *avpp = NULL;
756 save_alp = a_amv_lopts;
757 a_amv_lopts = NULL;
758 while(avp != NULL){
759 x = avp;
760 avp = avp->av_link;
761 n_PS_ROOT_BLOCK(n_var_vset(x->av_name, (uintptr_t)x->av_value));
762 free(x);
764 a_amv_lopts = save_alp;
765 NYD2_LEAVE;
768 static char *
769 a_amv_var_copy(char const *str){
770 char *news;
771 size_t len;
772 NYD2_ENTER;
774 if(*str == '\0')
775 news = n_UNCONST(n_empty);
776 else if(str[1] == '\0'){
777 if(str[0] == '1')
778 news = n_UNCONST(n_1);
779 else if(str[0] == '0')
780 news = n_UNCONST(n_0);
781 else
782 goto jheap;
783 }else if(str[2] == '\0' && str[0] == '-' && str[1] == '1')
784 news = n_UNCONST(n_m1);
785 else{
786 jheap:
787 len = strlen(str) +1;
788 news = smalloc(len);
789 memcpy(news, str, len);
791 NYD2_LEAVE;
792 return news;
795 static void
796 a_amv_var_free(char *cp){
797 NYD2_ENTER;
798 if(cp[0] != '\0' && cp != n_0 && cp != n_1 && cp != n_m1)
799 free(cp);
800 NYD2_LEAVE;
803 static bool_t
804 a_amv_var_check_vips(enum a_amv_var_vip_mode avvm, enum okeys okey,
805 char const *val){
806 bool_t ok;
807 NYD2_ENTER;
809 ok = TRU1;
811 if(avvm == a_AMV_VIP_SET_PRE){
812 switch(okey){
813 default:
814 break;
815 case ok_v_HOME:
816 /* Note this gets called from main.c during initialization, and they
817 * simply set this to pw_dir as a fallback: don't verify _that_ call.
818 * See main.c! */
819 if(!(n_pstate & n_PS_ROOT) && !n_is_dir(val, TRU1)){
820 n_err(_("$HOME is not a directory or not accessible: %s\n"),
821 n_shexp_quote_cp(val, FAL0));
822 ok = FAL0;
823 break;
825 case ok_v_TMPDIR:
826 if(!n_is_dir(val, TRU1)){
827 n_err(_("$TMPDIR is not a directory or not accessible: %s\n"),
828 n_shexp_quote_cp(val, FAL0));
829 ok = FAL0;
831 break;
832 case ok_v_umask:
833 if(*val != '\0'){
834 ui64_t uib;
836 n_idec_ui64_cp(&uib, val, 0, NULL);
837 if(uib & ~0777u){ /* (is valid _VF_POSNUM) */
838 n_err(_("Invalid *umask* setting: %s\n"), val);
839 ok = FAL0;
842 break;
844 }else if(avvm == a_AMV_VIP_SET_POST){
845 switch(okey){
846 default:
847 break;
848 case ok_b_debug:
849 n_poption |= n_PO_DEBUG;
850 break;
851 case ok_v_HOME:
852 /* Invalidate any resolved folder then, too
853 * FALLTHRU */
854 case ok_v_folder:
855 n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
856 break;
857 case ok_b_memdebug:
858 n_poption |= n_PO_MEMDEBUG;
859 break;
860 case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
861 if(!(n_pstate & n_PS_ROOT))
862 n_PS_ROOT_BLOCK(ok_bset(posix));
863 break;
864 case ok_b_posix: /* <-> $POSIXLY_CORRECT */
865 if(!(n_pstate & n_PS_ROOT))
866 n_PS_ROOT_BLOCK(ok_bset(POSIXLY_CORRECT));
867 break;
868 case ok_b_skipemptybody:
869 n_poption |= n_PO_E_FLAG;
870 break;
871 case ok_b_typescript_mode:
872 ok_bset(colour_disable);
873 ok_bset(line_editor_disable);
874 if(!(n_psonce & n_PSO_STARTED))
875 ok_bset(termcap_disable);
876 case ok_v_umask:
877 if(*val != '\0'){
878 ui64_t uib;
880 n_idec_ui64_cp(&uib, val, 0, NULL);
881 umask((mode_t)uib);
883 break;
884 case ok_b_verbose:
885 n_poption |= (n_poption & n_PO_VERB) ? n_PO_VERBVERB : n_PO_VERB;
886 break;
888 }else{
889 switch(okey){
890 default:
891 break;
892 case ok_b_debug:
893 n_poption &= ~n_PO_DEBUG;
894 break;
895 case ok_v_HOME:
896 /* Invalidate any resolved folder then, too
897 * FALLTHRU */
898 case ok_v_folder:
899 n_PS_ROOT_BLOCK(ok_vclear(folder_resolved));
900 break;
901 case ok_b_memdebug:
902 n_poption &= ~n_PO_MEMDEBUG;
903 break;
904 case ok_b_POSIXLY_CORRECT: /* <-> *posix* */
905 if(!(n_pstate & n_PS_ROOT))
906 n_PS_ROOT_BLOCK(ok_bclear(posix));
907 break;
908 case ok_b_posix: /* <-> $POSIXLY_CORRECT */
909 if(!(n_pstate & n_PS_ROOT))
910 n_PS_ROOT_BLOCK(ok_bclear(POSIXLY_CORRECT));
911 break;
912 case ok_b_skipemptybody:
913 n_poption &= ~n_PO_E_FLAG;
914 break;
915 case ok_b_verbose:
916 n_poption &= ~(n_PO_VERB | n_PO_VERBVERB);
917 break;
920 NYD2_LEAVE;
921 return ok;
924 static bool_t
925 a_amv_var_check_nocntrls(char const *val){
926 char c;
927 NYD2_ENTER;
929 while((c = *val++) != '\0')
930 if(cntrlchar(c))
931 break;
932 NYD2_LEAVE;
933 return (c == '\0');
936 static bool_t
937 a_amv_var_check_num(char const *val, bool_t posnum){
938 /* TODO The internal/environment variables which are num= or posnum= should
939 * TODO gain special lookup functions, or the return should be void* and
940 * TODO castable to integer; i.e. no more strtoX() should be needed.
941 * TODO I.e., the result of this function should instead be stored */
942 bool_t rv;
943 NYD2_ENTER;
945 rv = TRU1;
947 if(*val != '\0'){ /* Would be _VF_NOTEMPTY if not allowed */
948 ui64_t uib;
949 enum n_idec_state ids;
951 ids = n_idec_cp(&uib, val, 0,
952 (posnum ? n_IDEC_MODE_SIGNED_TYPE : n_IDEC_MODE_NONE), NULL);
953 if((ids & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
954 ) != n_IDEC_STATE_CONSUMED)
955 rv = FAL0;
956 /* TODO Unless we store integers we need to look and forbid, because
957 * TODO callee may not be able to swallow, e.g., "-1" */
958 if(posnum && (ids & n_IDEC_STATE_SEEN_MINUS))
959 rv = FAL0;
961 NYD2_LEAVE;
962 return rv;
965 static char const *
966 a_amv_var_canonify(char const *vn){
967 NYD2_ENTER;
968 if(!upperchar(*vn)){
969 char const *vp;
971 for(vp = vn; *vp != '\0' && *vp != '@'; ++vp)
973 vn = (*vp == '@') ? i_strdup(vn) : vn;
975 NYD2_LEAVE;
976 return vn;
979 static bool_t
980 a_amv_var_revlookup(struct a_amv_var_carrier *avcp, char const *name){
981 ui32_t hash, i, j;
982 struct a_amv_var_map const *avmp;
983 char c;
984 NYD2_ENTER;
986 /* It may be a special a.k.a. macro-local or one-letter parameter */
987 c = name[0];
988 if(n_UNLIKELY(digitchar(c))){
989 /* (Inline dec. atoi, ugh) */
990 for(j = (ui8_t)c - '0', i = 1;; ++i){
991 c = name[i];
992 if(c == '\0')
993 break;
994 if(!digitchar(c))
995 goto jno_special_param;
996 j = j * 10 + (ui8_t)c - '0';
998 if(j <= SI16_MAX){
999 avcp->avc_special_cat = a_AMV_VSC_MAC_ARGV;
1000 goto jspecial_param;
1002 }else if(n_UNLIKELY(name[1] == '\0')){
1003 switch(c){
1004 case '?':
1005 case '!':
1006 avcp->avc_special_cat = a_AMV_VSC_GLOBAL;
1007 j = (c == '?') ? a_AMV_VST_QM : a_AMV_VST_EM;
1008 goto jspecial_param;
1009 case '^':
1010 goto jmultiplex;
1011 case '*':
1012 avcp->avc_special_cat = a_AMV_VSC_MAC;
1013 j = a_AMV_VST_STAR;
1014 goto jspecial_param;
1015 case '@':
1016 avcp->avc_special_cat = a_AMV_VSC_MAC;
1017 j = a_AMV_VST_AT;
1018 goto jspecial_param;
1019 case '#':
1020 avcp->avc_special_cat = a_AMV_VSC_MAC;
1021 j = a_AMV_VST_NOSIGN;
1022 goto jspecial_param;
1023 default:
1024 break;
1026 }else if(c == '^'){
1027 jmultiplex:
1028 avcp->avc_special_cat = a_AMV_VSC_MULTIPLEX;
1029 j = a_AMV_VST_CACC;
1030 goto jspecial_param;
1033 /* Normal reverse lookup, walk over the hashtable */
1034 jno_special_param:
1035 avcp->avc_special_cat = a_AMV_VSC_NONE;
1036 avcp->avc_name = name = a_amv_var_canonify(name);
1037 avcp->avc_hash = hash = a_AMV_NAME2HASH(name);
1039 for(i = hash % a_AMV_VAR_REV_PRIME, j = 0; j <= a_AMV_VAR_REV_LONGEST; ++j){
1040 ui32_t x;
1042 if((x = a_amv_var_revmap[i]) == a_AMV_VAR_REV_ILL)
1043 break;
1045 avmp = &a_amv_var_map[x];
1046 if(avmp->avm_hash == hash &&
1047 !strcmp(&a_amv_var_names[avmp->avm_keyoff], name)){
1048 avcp->avc_map = avmp;
1049 avcp->avc_okey = (enum okeys)x;
1050 goto jleave;
1053 if(++i == a_AMV_VAR_REV_PRIME){
1054 #ifdef a_AMV_VAR_REV_WRAPAROUND
1055 i = 0;
1056 #else
1057 break;
1058 #endif
1061 avcp->avc_map = NULL;
1062 avcp = NULL;
1063 jleave:
1064 NYD2_LEAVE;
1065 return (avcp != NULL);
1067 /* All these are mapped to *--special-param* */
1068 jspecial_param:
1069 avcp->avc_name = name;
1070 avcp->avc_special_prop = (ui16_t)j;
1071 avmp = &a_amv_var_map[a_AMV_VAR__SPECIAL_PARAM_MAP_IDX];
1072 avcp->avc_hash = avmp->avm_hash;
1073 avcp->avc_map = avmp;
1074 avcp->avc_okey = ok_v___special_param;
1075 goto jleave;
1078 static bool_t
1079 a_amv_var_lookup(struct a_amv_var_carrier *avcp, bool_t i3val_nonew){
1080 size_t i;
1081 char const *cp;
1082 struct a_amv_var_map const *avmp;
1083 struct a_amv_var *avp;
1084 NYD2_ENTER;
1086 /* C99 */{
1087 struct a_amv_var **avpp, *lavp;
1089 avpp = &a_amv_vars[avcp->avc_prime = a_AMV_HASH2PRIME(avcp->avc_hash)];
1091 for(lavp = NULL, avp = *avpp; avp != NULL; lavp = avp, avp = avp->av_link)
1092 if(!strcmp(avp->av_name, avcp->avc_name)){
1093 /* Relink as head, hope it "sorts on usage" over time.
1094 * _clear() relies on this behaviour */
1095 if(lavp != NULL){
1096 lavp->av_link = avp->av_link;
1097 avp->av_link = *avpp;
1098 *avpp = avp;
1100 goto jleave;
1104 /* If this is not an assembled variable we need to consider some special
1105 * initialization cases and eventually create the variable anew */
1106 if(n_LIKELY((avmp = avcp->avc_map) != NULL)){
1107 /* Does it have an import-from-environment flag? */
1108 if(n_UNLIKELY((avmp->avm_flags & (a_AMV_VF_IMPORT | a_AMV_VF_ENV)) != 0)){
1109 if(n_LIKELY((cp = getenv(avcp->avc_name)) != NULL)){
1110 /* May be better not to use that one, though? */
1111 bool_t isempty, isbltin;
1113 isempty = (*cp == '\0' &&
1114 (avmp->avm_flags & a_AMV_VF_NOTEMPTY) != 0);
1115 isbltin = ((avmp->avm_flags & (a_AMV_VF_I3VAL | a_AMV_VF_DEFVAL)
1116 ) != 0);
1118 if(n_UNLIKELY(isempty)){
1119 if(!isbltin)
1120 goto jerr;
1121 }else if(n_LIKELY(*cp != '\0')){
1122 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NOCNTRLS) &&
1123 !a_amv_var_check_nocntrls(cp))){
1124 n_err(_("Ignoring environment, control characters "
1125 "invalid in variable: %s\n"), avcp->avc_name);
1126 goto jerr;
1128 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NUM) &&
1129 !a_amv_var_check_num(cp, FAL0))){
1130 n_err(_("Environment variable value not a number "
1131 "or out of range: %s\n"), avcp->avc_name);
1132 goto jerr;
1134 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_POSNUM) &&
1135 !a_amv_var_check_num(cp, TRU1))){
1136 n_err(_("Environment variable value not a number, "
1137 "negative or out of range: %s\n"), avcp->avc_name);
1138 goto jerr;
1140 goto jnewval;
1141 }else
1142 goto jnewval;
1146 /* A first-time init switch is to be handled now and here */
1147 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_I3VAL) != 0)){
1148 static struct a_amv_var_defval const **arr,
1149 *arr_base[a_AMV_VAR_I3VALS_CNT +1];
1151 if(arr == NULL){
1152 arr = &arr_base[0];
1153 arr[i = a_AMV_VAR_I3VALS_CNT] = NULL;
1154 while(i-- > 0)
1155 arr[i] = &a_amv_var_i3vals[i];
1158 for(i = 0; arr[i] != NULL; ++i)
1159 if(arr[i]->avdv_okey == avcp->avc_okey){
1160 cp = (avmp->avm_flags & a_AMV_VF_BOOL) ? n_empty
1161 : arr[i]->avdv_value;
1162 /* Remove this entry, hope entire block becomes no-op asap */
1164 arr[i] = arr[i + 1];
1165 while(arr[i++] != NULL);
1167 if(!i3val_nonew)
1168 goto jnewval;
1169 if(i3val_nonew == TRUM1)
1170 avp = (struct a_amv_var*)-1;
1171 goto jleave;
1175 /* The virtual variables */
1176 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIRT) != 0)){
1177 for(i = 0; i < a_AMV_VAR_VIRTS_CNT; ++i)
1178 if(a_amv_var_virts[i].avv_okey == avcp->avc_okey){
1179 avp = n_UNCONST(a_amv_var_virts[i].avv_var);
1180 goto jleave;
1182 /* Not reached */
1185 /* Place this last because once it is set first the variable will never
1186 * be removed again and thus match in the first block above */
1187 jdefval:
1188 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_DEFVAL) != 0){
1189 for(i = 0; i < a_AMV_VAR_DEFVALS_CNT; ++i)
1190 if(a_amv_var_defvals[i].avdv_okey == avcp->avc_okey){
1191 cp = (avmp->avm_flags & a_AMV_VF_BOOL) ? n_empty
1192 : a_amv_var_defvals[i].avdv_value;
1193 goto jnewval;
1198 jerr:
1199 avp = NULL;
1200 jleave:
1201 avcp->avc_var = avp;
1202 NYD2_LEAVE;
1203 return (avp != NULL);
1205 jnewval:
1206 /* E.g., $TMPDIR may be set to non-existent, so we need to be able to catch
1207 * that and redirect to a possible default value */
1208 if((avmp->avm_flags & a_AMV_VF_VIP) &&
1209 !a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, cp)){
1210 #ifdef HAVE_SETENV
1211 if(avmp->avm_flags & (a_AMV_VF_IMPORT | a_AMV_VF_ENV))
1212 unsetenv(avcp->avc_name);
1213 #endif
1214 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_DEFVAL) != 0)
1215 goto jdefval;
1216 goto jerr;
1217 }else{
1218 struct a_amv_var **avpp;
1219 size_t l;
1221 l = strlen(avcp->avc_name) +1;
1222 avcp->avc_var =
1223 avp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_var, av_name) + l);
1224 avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
1225 *avpp = avp;
1226 memcpy(avp->av_name, avcp->avc_name, l);
1227 #ifdef HAVE_PUTENV
1228 avp->av_env = NULL;
1229 #endif
1230 avp->av_flags = avmp->avm_flags;
1231 avp->av_value = a_amv_var_copy(cp);
1233 if(avp->av_flags & a_AMV_VF_ENV)
1234 a_amv_var__putenv(avcp, avp);
1235 if(avmp->avm_flags & a_AMV_VF_VIP)
1236 a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, cp);
1237 goto jleave;
1241 static char const *
1242 a_amv_var_vsc_global(struct a_amv_var_carrier *avcp){
1243 char itoabuf[32];
1244 char const *rv;
1245 si32_t *ep;
1246 struct a_amv_var_map const *avmp;
1247 NYD2_ENTER;
1249 /* Not function local, TODO but lazy evaluted for now */
1250 if(avcp->avc_special_prop == a_AMV_VST_QM){
1251 avmp = &a_amv_var_map[a_AMV_VAR__QM_MAP_IDX];
1252 avcp->avc_okey = ok_v___qm;
1253 ep = &n_pstate_ex_no;
1254 }else{
1255 avmp = &a_amv_var_map[a_AMV_VAR__EM_MAP_IDX];
1256 avcp->avc_okey = ok_v___em;
1257 ep = &n_pstate_err_no;
1260 /* XXX Oh heaven, we are responsible to ensure that $?/! is up-to-date
1261 * XXX and represents n_pstate_err_no; TODO unfortunately
1262 * TODO we could num=1 ok_v___[qe]m, but the thing is still a string
1263 * TODO and thus conversion takes places over and over again; also
1264 * TODO for now that would have to occur before we set _that_ value
1265 * TODO so let's special treat it until we store ints as such */
1266 if(*ep >= 0){
1267 switch(*ep){
1268 case 0: rv = n_0; break;
1269 case 1: rv = n_1; break;
1270 default:
1271 snprintf(itoabuf, sizeof itoabuf, "%d", *ep);
1272 rv = itoabuf;
1273 break;
1275 n_PS_ROOT_BLOCK(n_var_okset(avcp->avc_okey, (uintptr_t)rv));
1277 avcp->avc_hash = avmp->avm_hash;
1278 avcp->avc_map = avmp;
1280 rv = a_amv_var_lookup(avcp, TRU1) ? avcp->avc_var->av_value : NULL;
1281 NYD2_LEAVE;
1282 return rv;
1285 static char const *
1286 a_amv_var_vsc_multiplex(struct a_amv_var_carrier *avcp){
1287 char itoabuf[32];
1288 si32_t e;
1289 size_t i;
1290 char const *rv;
1291 NYD2_ENTER;
1293 i = strlen(rv = &avcp->avc_name[1]);
1295 /* ERR, ERRDOC, ERRNAME, plus *-NAME variants */
1296 if(rv[0] == 'E' && i >= 3 && rv[1] == 'R' && rv[2] == 'R'){
1297 if(i == 3){
1298 e = n_pstate_err_no;
1299 goto jeno;
1300 }else if(rv[3] == '-'){
1301 e = n_err_from_name(&rv[4]);
1302 jeno:
1303 switch(e){
1304 case 0: rv = n_0; break;
1305 case 1: rv = n_1; break;
1306 default:
1307 snprintf(itoabuf, sizeof itoabuf, "%d", e);
1308 rv = savestr(itoabuf); /* XXX yet, cannot do numbers */
1309 break;
1311 goto jleave;
1312 }else if(i >= 6){
1313 if(!memcmp(&rv[3], "DOC", 3)){
1314 rv += 6;
1315 switch(*rv){
1316 case '\0': e = n_pstate_err_no; break;
1317 case '-': e = n_err_from_name(&rv[1]); break;
1318 default: goto jerr;
1320 rv = n_err_to_doc(e);
1321 goto jleave;
1322 }else if(i >= 7 && !memcmp(&rv[3], "NAME", 4)){
1323 rv += 7;
1324 switch(*rv){
1325 case '\0': e = n_pstate_err_no; break;
1326 case '-': e = n_err_from_name(&rv[1]); break;
1327 default: goto jerr;
1329 rv = n_err_to_name(e);
1330 goto jleave;
1335 jerr:
1336 rv = NULL;
1337 jleave:
1338 NYD2_LEAVE;
1339 return rv;
1342 static char const *
1343 a_amv_var_vsc_mac(struct a_amv_var_carrier *avcp){
1344 bool_t ismacky;
1345 struct a_amv_mac_call_args *amcap;
1346 char const *rv;
1347 NYD2_ENTER;
1349 rv = NULL;
1351 /* These may occur only in a macro.. */
1352 if(n_UNLIKELY(a_amv_lopts == NULL))
1353 goto jmaylog;
1355 amcap = a_amv_lopts->as_amcap;
1357 /* ..in a `call'ed macro only, to be exact. Or in a_AMV_MACKY_MACK */
1358 if(!(ismacky = (amcap->amca_amp == a_AMV_MACKY_MACK)) &&
1359 (amcap->amca_ps_hook_mask ||
1360 (assert(amcap->amca_amp != NULL),
1361 (amcap->amca_amp->am_flags & a_AMV_MF_TYPE_MASK
1362 ) == a_AMV_MF_ACCOUNT)))
1363 goto jleave;
1365 if(avcp->avc_special_cat == a_AMV_VSC_MAC_ARGV){
1366 if(avcp->avc_special_prop > 0){
1367 if(amcap->amca_argc >= avcp->avc_special_prop)
1368 rv = amcap->amca_argv[avcp->avc_special_prop - 1];
1369 }else if(ismacky)
1370 rv = amcap->amca_name;
1371 else
1372 rv = (a_amv_lopts->as_up != NULL
1373 ? a_amv_lopts->as_up->as_amcap->amca_name : n_empty);
1374 goto jleave;
1377 /* MACKY_MACK doesn't know about [*@#] */
1378 if(ismacky)
1379 goto jmaylog;
1381 switch(avcp->avc_special_prop){
1382 case a_AMV_VST_STAR:
1383 case a_AMV_VST_AT:{
1384 ui32_t i, l;
1386 for(i = l = 0; i < amcap->amca_argc; ++i)
1387 l += strlen(amcap->amca_argv[i]) + 1;
1388 if(l == 0)
1389 rv = n_empty;
1390 else{
1391 char *cp;
1393 rv = cp = salloc(l);
1394 for(i = l = 0; i < amcap->amca_argc; ++i){
1395 l = strlen(amcap->amca_argv[i]);
1396 memcpy(cp, amcap->amca_argv[i], l);
1397 cp += l;
1398 *cp++ = ' ';
1400 *--cp = '\0';
1402 } break;
1403 case a_AMV_VST_NOSIGN:{
1404 char *cp;
1406 rv = cp = salloc(sizeof("65535"));
1407 snprintf(cp, sizeof("65535"), "%hu", amcap->amca_argc);
1408 } break;
1409 default:
1410 rv = n_empty;
1411 break;
1414 jleave:
1415 NYD2_LEAVE;
1416 return rv;
1417 jmaylog:
1418 if(n_poption & n_PO_D_V)
1419 n_err(_("Cannot use macro local variable in this context: %s\n"),
1420 n_shexp_quote_cp(avcp->avc_name, FAL0));
1421 goto jleave;
1424 static bool_t
1425 a_amv_var_set(struct a_amv_var_carrier *avcp, char const *value,
1426 bool_t force_env){
1427 struct a_amv_var *avp;
1428 char *oval;
1429 struct a_amv_var_map const *avmp;
1430 bool_t rv;
1431 NYD2_ENTER;
1433 if(value == NULL){
1434 rv = a_amv_var_clear(avcp, force_env);
1435 goto jleave;
1438 if((avmp = avcp->avc_map) != NULL){
1439 rv = FAL0;
1441 /* Validity checks */
1442 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_RDONLY) != 0 &&
1443 !(n_pstate & n_PS_ROOT))){
1444 value = N_("Variable is read-only: %s\n");
1445 goto jeavmp;
1447 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NOTEMPTY) && *value == '\0')){
1448 value = N_("Variable must not be empty: %s\n");
1449 goto jeavmp;
1451 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NOCNTRLS) != 0 &&
1452 !a_amv_var_check_nocntrls(value))){
1453 value = N_("Variable forbids control characters: %s\n");
1454 goto jeavmp;
1456 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NUM) &&
1457 !a_amv_var_check_num(value, FAL0))){
1458 value = N_("Variable value not a number or out of range: %s\n");
1459 goto jeavmp;
1461 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_POSNUM) &&
1462 !a_amv_var_check_num(value, TRU1))){
1463 value = _("Variable value not a number, negative, "
1464 "or out of range: %s\n");
1465 goto jeavmp;
1467 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_IMPORT) != 0 &&
1468 !(n_psonce & n_PSO_STARTED) && !(n_pstate & n_PS_ROOT))){
1469 value = N_("Variable cannot be set in a resource file: %s\n");
1470 goto jeavmp;
1473 /* Any more complicated inter-dependency? */
1474 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIP) != 0 &&
1475 !a_amv_var_check_vips(a_AMV_VIP_SET_PRE, avcp->avc_okey, value))){
1476 value = N_("Assignment of variable aborted: %s\n");
1477 jeavmp:
1478 n_err(V_(value), avcp->avc_name);
1479 goto jleave;
1482 /* Transformations */
1483 if(n_UNLIKELY(avmp->avm_flags & a_AMV_VF_LOWER)){
1484 char c;
1486 oval = savestr(value);
1487 value = oval;
1488 for(; (c = *oval) != '\0'; ++oval)
1489 *oval = lowerconv(c);
1493 rv = TRU1;
1494 a_amv_var_lookup(avcp, TRU1);
1496 /* Don't care what happens later on, store this in the unroll list */
1497 if(a_amv_lopts != NULL &&
1498 (avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
1499 a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
1501 if((avp = avcp->avc_var) == NULL){
1502 struct a_amv_var **avpp;
1503 size_t l;
1505 l = strlen(avcp->avc_name) +1;
1506 avcp->avc_var = avp = smalloc(n_VSTRUCT_SIZEOF(struct a_amv_var, av_name
1507 ) + l);
1508 avp->av_link = *(avpp = &a_amv_vars[avcp->avc_prime]);
1509 *avpp = avp;
1510 #ifdef HAVE_PUTENV
1511 avp->av_env = NULL;
1512 #endif
1513 memcpy(avp->av_name, avcp->avc_name, l);
1514 avp->av_flags = (avmp != NULL) ? avmp->avm_flags : 0;
1515 oval = n_UNCONST(n_empty);
1516 }else
1517 oval = avp->av_value;
1519 if(avmp == NULL)
1520 avp->av_value = a_amv_var_copy(value);
1521 else{
1522 /* Via `set' etc. the user may give even boolean options non-boolean
1523 * values, ignore that and force boolean */
1524 if(avp->av_flags & a_AMV_VF_BOOL){
1525 if(!(n_pstate & n_PS_ROOT) && (n_poption & n_PO_D_VV) &&
1526 *value != '\0')
1527 n_err(_("Ignoring value of boolean variable: %s: %s\n"),
1528 avcp->avc_name, value);
1529 avp->av_value = n_UNCONST(n_1);
1530 }else
1531 avp->av_value = a_amv_var_copy(value);
1534 if(force_env && !(avp->av_flags & a_AMV_VF_ENV))
1535 avp->av_flags |= a_AMV_VF_LINKED;
1536 if(avp->av_flags & (a_AMV_VF_ENV | a_AMV_VF_LINKED))
1537 rv = a_amv_var__putenv(avcp, avp);
1538 if(avp->av_flags & a_AMV_VF_VIP)
1539 a_amv_var_check_vips(a_AMV_VIP_SET_POST, avcp->avc_okey, value);
1540 a_amv_var_free(oval);
1541 jleave:
1542 NYD2_LEAVE;
1543 return rv;
1546 static bool_t
1547 a_amv_var__putenv(struct a_amv_var_carrier *avcp, struct a_amv_var *avp){
1548 #ifndef HAVE_SETENV
1549 char *cp;
1550 #endif
1551 bool_t rv;
1552 NYD2_ENTER;
1554 #ifdef HAVE_SETENV
1555 rv = (setenv(avcp->avc_name, avp->av_value, 1) == 0);
1556 #else
1557 cp = sstrdup(savecatsep(avcp->avc_name, '=', avp->av_value));
1559 if((rv = (putenv(cp) == 0))){
1560 char *ocp;
1562 if((ocp = avp->av_env) != NULL)
1563 free(ocp);
1564 avp->av_env = cp;
1565 }else
1566 free(cp);
1567 #endif
1568 NYD2_LEAVE;
1569 return rv;
1572 static bool_t
1573 a_amv_var_clear(struct a_amv_var_carrier *avcp, bool_t force_env){
1574 struct a_amv_var **avpp, *avp;
1575 struct a_amv_var_map const *avmp;
1576 bool_t rv;
1577 NYD2_ENTER;
1579 rv = FAL0;
1581 if(n_LIKELY((avmp = avcp->avc_map) != NULL)){
1582 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_NODEL) != 0 &&
1583 !(n_pstate & n_PS_ROOT))){
1584 n_err(_("Variable may not be unset: %s\n"), avcp->avc_name);
1585 goto jleave;
1587 if(n_UNLIKELY((avmp->avm_flags & a_AMV_VF_VIP) != 0 &&
1588 !a_amv_var_check_vips(a_AMV_VIP_CLEAR, avcp->avc_okey, NULL))){
1589 n_err(_("Clearance of variable aborted: %s\n"), avcp->avc_name);
1590 goto jleave;
1594 rv = TRU1;
1596 if(n_UNLIKELY(!a_amv_var_lookup(avcp, TRUM1))){
1597 if(force_env){
1598 jforce_env:
1599 rv = a_amv_var__clearenv(avcp->avc_name, NULL);
1600 }else if(!(n_pstate & (n_PS_ROOT | n_PS_ROBOT)) && (n_poption & n_PO_D_V))
1601 n_err(_("Can't unset undefined variable: %s\n"), avcp->avc_name);
1602 goto jleave;
1603 }else if(avcp->avc_var == (struct a_amv_var*)-1){
1604 avcp->avc_var = NULL;
1605 if(force_env)
1606 goto jforce_env;
1607 goto jleave;
1610 if(a_amv_lopts != NULL &&
1611 (avmp == NULL || !(avmp->avm_flags & a_AMV_VF_NOLOPTS)))
1612 a_amv_lopts_add(a_amv_lopts, avcp->avc_name, avcp->avc_var);
1614 avp = avcp->avc_var;
1615 avcp->avc_var = NULL;
1616 avpp = &a_amv_vars[avcp->avc_prime];
1617 assert(*avpp == avp); /* (always listhead after lookup()) */
1618 *avpp = (*avpp)->av_link;
1620 /* C99 */{
1621 char *envval;
1623 #ifdef HAVE_SETENV
1624 envval = NULL;
1625 #else
1626 envval = avp->av_env;
1627 #endif
1628 if((avp->av_flags & (a_AMV_VF_ENV | a_AMV_VF_LINKED)) || envval != NULL)
1629 rv = a_amv_var__clearenv(avp->av_name, envval);
1631 a_amv_var_free(avp->av_value);
1632 free(avp);
1634 /* XXX Fun part, extremely simple-minded for now: if this variable has
1635 * XXX a default value, immediately reinstantiate it! TODO Heh? */
1636 if(n_UNLIKELY(avmp != NULL && (avmp->avm_flags & a_AMV_VF_DEFVAL) != 0))
1637 a_amv_var_lookup(avcp, TRU1);
1638 jleave:
1639 NYD2_LEAVE;
1640 return rv;
1643 static bool_t
1644 a_amv_var__clearenv(char const *name, char *value){
1645 #ifndef HAVE_SETENV
1646 extern char **environ;
1647 char **ecpp;
1648 #endif
1649 bool_t rv;
1650 NYD2_ENTER;
1651 n_UNUSED(value);
1653 #ifdef HAVE_SETENV
1654 unsetenv(name);
1655 rv = TRU1;
1656 #else
1657 if(value != NULL)
1658 for(ecpp = environ; *ecpp != NULL; ++ecpp)
1659 if(*ecpp == value){
1660 free(value);
1662 ecpp[0] = ecpp[1];
1663 while(*ecpp++ != NULL);
1664 break;
1666 rv = TRU1;
1667 #endif
1668 NYD2_LEAVE;
1669 return rv;
1672 static void
1673 a_amv_var_show_all(void){
1674 struct n_string msg, *msgp;
1675 FILE *fp;
1676 size_t no, i;
1677 struct a_amv_var *avp;
1678 char const **vacp, **cap;
1679 NYD2_ENTER;
1681 if((fp = Ftmp(NULL, "setlist", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL){
1682 n_perr(_("Can't create temporary file for `set' listing"), 0);
1683 goto jleave;
1686 /* We need to instantiate first-time-inits and default values here, so that
1687 * they will be regular members of our _vars[] table */
1688 for(i = a_AMV_VAR_I3VALS_CNT; i-- > 0;)
1689 n_var_oklook(a_amv_var_i3vals[i].avdv_okey);
1690 for(i = a_AMV_VAR_DEFVALS_CNT; i-- > 0;)
1691 n_var_oklook(a_amv_var_defvals[i].avdv_okey);
1693 for(no = i = 0; i < a_AMV_PRIME; ++i)
1694 for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
1695 ++no;
1696 no += a_AMV_VAR_VIRTS_CNT;
1698 vacp = salloc(no * sizeof(*vacp));
1700 for(cap = vacp, i = 0; i < a_AMV_PRIME; ++i)
1701 for(avp = a_amv_vars[i]; avp != NULL; avp = avp->av_link)
1702 *cap++ = avp->av_name;
1703 for(i = a_AMV_VAR_VIRTS_CNT; i-- > 0;)
1704 *cap++ = a_amv_var_virts[i].avv_var->av_name;
1706 if(no > 1)
1707 qsort(vacp, no, sizeof *vacp, &a_amv_var__show_cmp);
1709 msgp = &msg;
1710 msgp = n_string_reserve(n_string_creat(msgp), 80);
1711 for(i = 0, cap = vacp; no != 0; ++cap, --no)
1712 i += a_amv_var_show(*cap, fp, msgp);
1713 n_string_gut(&msg);
1715 page_or_print(fp, i);
1716 Fclose(fp);
1717 jleave:
1718 NYD2_LEAVE;
1721 static int
1722 a_amv_var__show_cmp(void const *s1, void const *s2){
1723 int rv;
1724 NYD2_ENTER;
1726 rv = strcmp(*(char**)n_UNCONST(s1), *(char**)n_UNCONST(s2));
1727 NYD2_LEAVE;
1728 return rv;
1731 static size_t
1732 a_amv_var_show(char const *name, FILE *fp, struct n_string *msgp){
1733 struct a_amv_var_carrier avc;
1734 char const *quote;
1735 bool_t isset;
1736 size_t i;
1737 NYD2_ENTER;
1739 msgp = n_string_trunc(msgp, 0);
1740 i = 0;
1742 a_amv_var_revlookup(&avc, name);
1743 isset = a_amv_var_lookup(&avc, FAL0);
1745 if(n_poption & n_PO_D_V){
1746 if(avc.avc_map == NULL){
1747 msgp = n_string_push_cp(msgp, "#assembled variable with value");
1748 i = 1;
1749 }else{
1750 struct{
1751 ui16_t flag;
1752 char msg[22];
1753 } const tbase[] = {
1754 {a_AMV_VF_VIRT, "virtual"},
1755 {a_AMV_VF_RDONLY, "read-only"},
1756 {a_AMV_VF_NODEL, "nodelete"},
1757 {a_AMV_VF_NOTEMPTY, "notempty"},
1758 {a_AMV_VF_NOCNTRLS, "no-control-chars"},
1759 {a_AMV_VF_NUM, "number"},
1760 {a_AMV_VF_POSNUM, "positive-number"},
1761 {a_AMV_VF_IMPORT, "import-environ-first\0"},
1762 {a_AMV_VF_ENV, "sync-environ"},
1763 {a_AMV_VF_I3VAL, "initial-value"},
1764 {a_AMV_VF_DEFVAL, "default-value"},
1765 {a_AMV_VF_LINKED, "`environ' link"}
1766 }, *tp;
1768 for(tp = tbase; PTRCMP(tp, <, &tbase[n_NELEM(tbase)]); ++tp)
1769 if(isset ? (avc.avc_var->av_flags & tp->flag)
1770 : (avc.avc_map->avm_flags & tp->flag)){
1771 msgp = n_string_push_c(msgp, (i++ == 0 ? '#' : ','));
1772 msgp = n_string_push_cp(msgp, tp->msg);
1775 if(i > 0)
1776 msgp = n_string_push_cp(msgp, "\n ");
1779 if(!isset || (avc.avc_var->av_flags & a_AMV_VF_RDONLY)){
1780 msgp = n_string_push_cp(msgp, "#");
1781 if(!isset){
1782 if(avc.avc_map != NULL && (avc.avc_map->avm_flags & a_AMV_VF_BOOL))
1783 msgp = n_string_push_cp(msgp, "boolean; ");
1784 msgp = n_string_push_cp(msgp, "variable not set: ");
1785 msgp = n_string_push_cp(msgp, n_shexp_quote_cp(name, FAL0));
1786 goto jleave;
1790 n_UNINIT(quote, NULL);
1791 if(!(avc.avc_var->av_flags & a_AMV_VF_BOOL)){
1792 quote = n_shexp_quote_cp(avc.avc_var->av_value, TRU1);
1793 if(strcmp(quote, avc.avc_var->av_value))
1794 msgp = n_string_push_cp(msgp, "wysh ");
1795 }else if(n_poption & n_PO_D_V)
1796 msgp = n_string_push_cp(msgp, "wysh ");
1797 if(avc.avc_var->av_flags & a_AMV_VF_LINKED)
1798 msgp = n_string_push_cp(msgp, "environ ");
1799 msgp = n_string_push_cp(msgp, "set ");
1800 msgp = n_string_push_cp(msgp, name);
1801 if(!(avc.avc_var->av_flags & a_AMV_VF_BOOL)){
1802 msgp = n_string_push_c(msgp, '=');
1803 msgp = n_string_push_cp(msgp, quote);
1804 }else if(n_poption & n_PO_D_V)
1805 msgp = n_string_push_cp(msgp, " #boolean");
1807 jleave:
1808 msgp = n_string_push_c(msgp, '\n');
1809 fputs(n_string_cp(msgp), fp);
1810 NYD2_ENTER;
1811 return (i > 0 ? 2 : 1);
1814 static bool_t
1815 a_amv_var_c_set(char **ap, bool_t issetenv){
1816 char *cp, *cp2, *varbuf, c;
1817 size_t errs;
1818 NYD2_ENTER;
1820 errs = 0;
1821 jouter:
1822 while((cp = *ap++) != NULL){
1823 /* Isolate key */
1824 cp2 = varbuf = salloc(strlen(cp) +1);
1826 for(; (c = *cp) != '=' && c != '\0'; ++cp){
1827 if(cntrlchar(c) || spacechar(c)){
1828 n_err(_("Variable name with control character ignored: %s\n"),
1829 ap[-1]);
1830 ++errs;
1831 goto jouter;
1833 *cp2++ = c;
1835 *cp2 = '\0';
1836 if(c == '\0')
1837 cp = n_UNCONST(n_empty);
1838 else
1839 ++cp;
1841 if(varbuf == cp2){
1842 n_err(_("Empty variable name ignored\n"));
1843 ++errs;
1844 }else{
1845 struct a_amv_var_carrier avc;
1846 bool_t isunset;
1848 if((isunset = (varbuf[0] == 'n' && varbuf[1] == 'o')))
1849 varbuf = &varbuf[2];
1851 a_amv_var_revlookup(&avc, varbuf);
1853 if(isunset)
1854 errs += !a_amv_var_clear(&avc, issetenv);
1855 else
1856 errs += !a_amv_var_set(&avc, cp, issetenv);
1859 NYD2_LEAVE;
1860 return (errs == 0);
1863 FL int
1864 c_define(void *v){
1865 int rv;
1866 char **args;
1867 NYD_ENTER;
1869 rv = 1;
1871 if((args = v)[0] == NULL){
1872 rv = (a_amv_mac_show(a_AMV_MF_NONE) == FAL0);
1873 goto jleave;
1876 if(args[1] == NULL || args[1][0] != '{' || args[1][1] != '\0' ||
1877 args[2] != NULL){
1878 n_err(_("Synopsis: define: <name> {\n"));
1879 goto jleave;
1882 rv = (a_amv_mac_def(args[0], a_AMV_MF_NONE) == FAL0);
1883 jleave:
1884 NYD_LEAVE;
1885 return rv;
1888 FL int
1889 c_undefine(void *v){
1890 int rv;
1891 char **args;
1892 NYD_ENTER;
1894 rv = 0;
1895 args = v;
1897 rv |= !a_amv_mac_undef(*args, a_AMV_MF_NONE);
1898 while(*++args != NULL);
1899 NYD_LEAVE;
1900 return rv;
1903 FL int
1904 c_call(void *v){
1905 int rv;
1906 NYD_ENTER;
1908 rv = a_amv_mac_call(v, FAL0);
1909 NYD_LEAVE;
1910 return rv;
1913 FL int
1914 c_call_if(void *v){
1915 int rv;
1916 NYD_ENTER;
1918 rv = a_amv_mac_call(v, TRU1);
1919 NYD_LEAVE;
1920 return rv;
1923 FL int
1924 c_account(void *v){
1925 struct a_amv_mac_call_args *amcap;
1926 struct a_amv_mac *amp;
1927 char **args;
1928 int rv, i, oqf, nqf;
1929 NYD_ENTER;
1931 rv = 1;
1933 if((args = v)[0] == NULL){
1934 rv = (a_amv_mac_show(a_AMV_MF_ACCOUNT) == FAL0);
1935 goto jleave;
1938 if(args[1] && args[1][0] == '{' && args[1][1] == '\0'){
1939 if(args[2] != NULL){
1940 n_err(_("Synopsis: account: <name> {\n"));
1941 goto jleave;
1943 if(!asccasecmp(args[0], ACCOUNT_NULL)){
1944 n_err(_("`account': cannot use reserved name: %s\n"),
1945 ACCOUNT_NULL);
1946 goto jleave;
1948 rv = (a_amv_mac_def(args[0], a_AMV_MF_ACCOUNT) == FAL0);
1949 goto jleave;
1952 if(n_pstate & n_PS_HOOK_MASK){
1953 n_err(_("`account': can't change account from within a hook\n"));
1954 goto jleave;
1957 save_mbox_for_possible_quitstuff();
1959 amp = NULL;
1960 if(asccasecmp(args[0], ACCOUNT_NULL) != 0 &&
1961 (amp = a_amv_mac_lookup(args[0], NULL, a_AMV_MF_ACCOUNT)) == NULL){
1962 n_err(_("`account': account does not exist: %s\n"), args[0]);
1963 goto jleave;
1966 oqf = savequitflags();
1968 if(a_amv_acc_curr != NULL){
1969 if(a_amv_acc_curr->am_lopts != NULL)
1970 a_amv_lopts_unroll(&a_amv_acc_curr->am_lopts);
1971 /* For accounts this lingers */
1972 --a_amv_acc_curr->am_refcnt;
1973 if(a_amv_acc_curr->am_flags & a_AMV_MF_DELETE)
1974 a_amv_mac_free(a_amv_acc_curr);
1977 a_amv_acc_curr = amp;
1979 if(amp != NULL){
1980 bool_t ok;
1981 assert(amp->am_lopts == NULL);
1982 amcap = n_lofi_alloc(sizeof *amcap);
1983 memset(amcap, 0, sizeof *amcap);
1984 amcap->amca_name = amp->am_name;
1985 amcap->amca_amp = amp;
1986 amcap->amca_unroller = &amp->am_lopts;
1987 amcap->amca_lopts_on = TRU1;
1988 ++amp->am_refcnt; /* We may not run 0 to avoid being deleted! */
1989 ok = a_amv_mac_exec(amcap);
1990 if(!ok){
1991 /* XXX account switch incomplete, unroll? */
1992 n_err(_("`account': failed to switch to account: %s\n"), amp->am_name);
1993 goto jleave;
1997 n_PS_ROOT_BLOCK((amp != NULL ? ok_vset(account, amp->am_name)
1998 : ok_vclear(account)));
2000 if((n_psonce & n_PSO_STARTED) && !(n_pstate & n_PS_HOOK_MASK)){
2001 nqf = savequitflags(); /* TODO obsolete (leave -> void -> new box!) */
2002 restorequitflags(oqf);
2003 if((i = setfile("%", 0)) < 0)
2004 goto jleave;
2005 temporary_folder_hook_check(FAL0);
2006 if(i > 0 && !ok_blook(emptystart))
2007 goto jleave;
2008 announce(ok_blook(bsdcompat) || ok_blook(bsdannounce));
2009 restorequitflags(nqf);
2011 rv = 0;
2012 jleave:
2013 NYD_LEAVE;
2014 return rv;
2017 FL int
2018 c_unaccount(void *v){
2019 int rv;
2020 char **args;
2021 NYD_ENTER;
2023 rv = 0;
2024 args = v;
2026 rv |= !a_amv_mac_undef(*args, a_AMV_MF_ACCOUNT);
2027 while(*++args != NULL);
2028 NYD_LEAVE;
2029 return rv;
2032 FL int
2033 c_localopts(void *v){
2034 char **argv;
2035 int rv;
2036 NYD_ENTER;
2038 rv = 1;
2040 if(a_amv_lopts == NULL){
2041 n_err(_("Cannot use `localopts' in this context "
2042 "(not in `define' or `account', nor special hook)\n"));
2043 goto jleave;
2046 rv = 0;
2048 if(n_pstate & (n_PS_HOOK | n_PS_COMPOSE_MODE)){
2049 if(n_poption & n_PO_D_V)
2050 n_err(_("Cannot turn off `localopts' for compose-mode hooks\n"));
2051 goto jleave;
2054 a_amv_lopts->as_unroll = (boolify(*(argv = v), UIZ_MAX, FAL0) > 0);
2055 jleave:
2056 NYD_LEAVE;
2057 return rv;
2060 FL int
2061 c_shift(void *v){
2062 int rv;
2063 NYD_ENTER;
2065 rv = 1;
2067 if(a_amv_lopts != NULL){
2068 ui16_t i, j;
2069 struct a_amv_mac const *amp;
2070 struct a_amv_mac_call_args *amcap;
2072 amp = (amcap = a_amv_lopts->as_amcap)->amca_amp;
2073 if(amp == NULL || amcap->amca_ps_hook_mask ||
2074 (amp->am_flags & a_AMV_MF_TYPE_MASK) == a_AMV_MF_ACCOUNT)
2075 goto jerr;
2077 v = *(char**)v;
2078 if(v == NULL)
2079 i = 1;
2080 else{
2081 si16_t sib;
2083 if((n_idec_si16_cp(&sib, v, 10, NULL
2084 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2085 ) != n_IDEC_STATE_CONSUMED || sib < 0){
2086 n_err(_("`shift': invalid argument: %s\n"), v);
2087 goto jleave;
2089 i = (ui16_t)sib;
2092 if(i > (j = amcap->amca_argc)){
2093 n_err(_("`shift': cannot shift %hu of %hu parameters\n"), i, j);
2094 goto jleave;
2095 }else{
2096 rv = 0;
2097 if(j > 0){
2098 j -= i;
2099 amcap->amca_argc = j;
2100 amcap->amca_argv += i;
2103 }else
2104 jerr:
2105 n_err(_("Can only use `shift' in a `call'ed macro\n"));
2106 jleave:
2107 NYD_LEAVE;
2108 return rv;
2111 FL int
2112 c_return(void *v){ /* TODO the exit status should be m_si64! */
2113 int rv;
2114 NYD_ENTER;
2116 if(a_amv_lopts != NULL){
2117 char const **argv;
2119 n_go_input_force_eof();
2120 n_pstate_err_no = n_ERR_NONE;
2121 rv = 0;
2123 if((argv = v)[0] != NULL){
2124 si32_t i;
2126 if((n_idec_si32_cp(&i, argv[0], 10, NULL
2127 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2128 ) == n_IDEC_STATE_CONSUMED && i >= 0)
2129 rv = (int)i;
2130 else{
2131 n_err(_("`return': return value argument is invalid: %s\n"),
2132 argv[0]);
2133 n_pstate_err_no = n_ERR_INVAL;
2134 rv = 1;
2137 if(argv[1] != NULL){
2138 if((n_idec_si32_cp(&i, argv[1], 10, NULL
2139 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2140 ) == n_IDEC_STATE_CONSUMED && i >= 0)
2141 n_pstate_err_no = i;
2142 else{
2143 n_err(_("`return': error number argument is invalid: %s\n"),
2144 argv[1]);
2145 n_pstate_err_no = n_ERR_INVAL;
2146 rv = 1;
2150 }else{
2151 n_err(_("Can only use `return' in a macro\n"));
2152 n_pstate_err_no = n_ERR_OPNOTSUPP;
2153 rv = 1;
2155 NYD_LEAVE;
2156 return rv;
2159 FL bool_t
2160 temporary_folder_hook_check(bool_t nmail){ /* TODO temporary, v15: drop */
2161 struct a_amv_mac_call_args *amcap;
2162 struct a_amv_mac *amp;
2163 size_t len;
2164 char const *cp;
2165 char *var;
2166 bool_t rv;
2167 NYD_ENTER;
2169 rv = TRU1;
2170 var = salloc(len = strlen(mailname) + sizeof("folder-hook-") -1 +1);
2172 /* First try the fully resolved path */
2173 snprintf(var, len, "folder-hook-%s", mailname);
2174 if((cp = n_var_vlook(var, FAL0)) != NULL)
2175 goto jmac;
2177 /* If we are under *folder*, try the usual +NAME syntax, too */
2178 if(displayname[0] == '+'){
2179 char *x;
2181 for(x = &mailname[len]; x != mailname; --x)
2182 if(x[-1] == '/'){
2183 snprintf(var, len, "folder-hook-+%s", x);
2184 if((cp = n_var_vlook(var, FAL0)) != NULL)
2185 goto jmac;
2186 break;
2190 /* Plain *folder-hook* is our last try */
2191 if((cp = ok_vlook(folder_hook)) == NULL)
2192 goto jleave;
2194 jmac:
2195 if((amp = a_amv_mac_lookup(cp, NULL, a_AMV_MF_NONE)) == NULL){
2196 n_err(_("Cannot call *folder-hook* for %s: macro does not exist: %s\n"),
2197 n_shexp_quote_cp(displayname, FAL0), cp);
2198 rv = FAL0;
2199 goto jleave;
2202 amcap = n_lofi_alloc(sizeof *amcap);
2203 memset(amcap, 0, sizeof *amcap);
2204 amcap->amca_name = cp;
2205 amcap->amca_amp = amp;
2206 n_pstate &= ~n_PS_HOOK_MASK;
2207 if(nmail){
2208 amcap->amca_unroller = NULL;
2209 n_pstate |= n_PS_HOOK_NEWMAIL;
2210 }else{
2211 amcap->amca_unroller = &a_amv_folder_hook_lopts;
2212 n_pstate |= n_PS_HOOK;
2214 amcap->amca_lopts_on = TRU1;
2215 amcap->amca_ps_hook_mask = TRU1;
2216 rv = a_amv_mac_exec(amcap);
2217 n_pstate &= ~n_PS_HOOK_MASK;
2219 jleave:
2220 NYD_LEAVE;
2221 return rv;
2224 FL void
2225 temporary_folder_hook_unroll(void){ /* XXX intermediate hack */
2226 NYD_ENTER;
2227 if(a_amv_folder_hook_lopts != NULL){
2228 void *save = a_amv_lopts;
2230 a_amv_lopts = NULL;
2231 a_amv_lopts_unroll(&a_amv_folder_hook_lopts);
2232 a_amv_folder_hook_lopts = NULL;
2233 a_amv_lopts = save;
2235 NYD_LEAVE;
2238 FL void
2239 temporary_compose_mode_hook_call(char const *macname,
2240 void (*hook_pre)(void *), void *hook_arg){
2241 /* TODO compose_mode_hook_call() temporary, v15: generalize; see a_GO_SPLICE
2242 * TODO comment in go.c for the right way of doing things! */
2243 static struct a_amv_lostack *cmh_losp;
2244 struct a_amv_mac_call_args *amcap;
2245 struct a_amv_mac *amp;
2246 NYD_ENTER;
2248 amp = NULL;
2250 if(macname == (char*)-1){
2251 a_amv_mac__finalize(cmh_losp);
2252 cmh_losp = NULL;
2253 }else if(macname != NULL &&
2254 (amp = a_amv_mac_lookup(macname, NULL, a_AMV_MF_NONE)) == NULL)
2255 n_err(_("Cannot call *on-compose-**: macro does not exist: %s\n"),
2256 macname);
2257 else{
2258 amcap = n_lofi_alloc(sizeof *amcap);
2259 memset(amcap, 0, sizeof *amcap);
2260 amcap->amca_name = (macname != NULL) ? macname
2261 : "on-compose-splice-shell";
2262 amcap->amca_amp = amp;
2263 amcap->amca_unroller = &a_amv_compose_lopts;
2264 amcap->amca_hook_pre = hook_pre;
2265 amcap->amca_hook_arg = hook_arg;
2266 amcap->amca_lopts_on = TRU1;
2267 amcap->amca_ps_hook_mask = TRU1;
2268 n_pstate &= ~n_PS_HOOK_MASK;
2269 n_pstate |= n_PS_HOOK;
2270 if(macname != NULL)
2271 a_amv_mac_exec(amcap);
2272 else{
2273 cmh_losp = n_lofi_alloc(sizeof *cmh_losp);
2274 cmh_losp->as_global_saved = a_amv_lopts;
2275 cmh_losp->as_up = NULL;
2276 cmh_losp->as_lopts = *(cmh_losp->as_amcap = amcap)->amca_unroller;
2277 cmh_losp->as_unroll = TRU1;
2278 a_amv_lopts = cmh_losp;
2281 NYD_LEAVE;
2284 FL void
2285 temporary_compose_mode_hook_unroll(void){ /* XXX intermediate hack */
2286 NYD_ENTER;
2287 if(a_amv_compose_lopts != NULL){
2288 void *save = a_amv_lopts;
2290 a_amv_lopts = NULL;
2291 a_amv_lopts_unroll(&a_amv_compose_lopts);
2292 a_amv_compose_lopts = NULL;
2293 a_amv_lopts = save;
2295 NYD_LEAVE;
2298 FL bool_t
2299 n_var_is_user_writable(char const *name){
2300 struct a_amv_var_carrier avc;
2301 struct a_amv_var_map const *avmp;
2302 bool_t rv;
2303 NYD_ENTER;
2305 a_amv_var_revlookup(&avc, name);
2306 if((avmp = avc.avc_map) == NULL)
2307 rv = TRU1;
2308 else
2309 rv = ((avmp->avm_flags & (a_AMV_VF_BOOL | a_AMV_VF_RDONLY)) == 0);
2310 NYD_LEAVE;
2311 return rv;
2314 FL char *
2315 n_var_oklook(enum okeys okey){
2316 struct a_amv_var_carrier avc;
2317 char *rv;
2318 struct a_amv_var_map const *avmp;
2319 NYD_ENTER;
2321 avc.avc_map = avmp = &a_amv_var_map[okey];
2322 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2323 avc.avc_hash = avmp->avm_hash;
2324 avc.avc_okey = okey;
2326 if(a_amv_var_lookup(&avc, FAL0))
2327 rv = avc.avc_var->av_value;
2328 else
2329 rv = NULL;
2330 NYD_LEAVE;
2331 return rv;
2334 FL bool_t
2335 n_var_okset(enum okeys okey, uintptr_t val){
2336 struct a_amv_var_carrier avc;
2337 bool_t ok;
2338 struct a_amv_var_map const *avmp;
2339 NYD_ENTER;
2341 avc.avc_map = avmp = &a_amv_var_map[okey];
2342 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2343 avc.avc_hash = avmp->avm_hash;
2344 avc.avc_okey = okey;
2346 ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val), FAL0);
2347 NYD_LEAVE;
2348 return ok;
2351 FL bool_t
2352 n_var_okclear(enum okeys okey){
2353 struct a_amv_var_carrier avc;
2354 bool_t rv;
2355 struct a_amv_var_map const *avmp;
2356 NYD_ENTER;
2358 avc.avc_map = avmp = &a_amv_var_map[okey];
2359 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2360 avc.avc_hash = avmp->avm_hash;
2361 avc.avc_okey = okey;
2363 rv = a_amv_var_clear(&avc, FAL0);
2364 NYD_LEAVE;
2365 return rv;
2368 FL char const *
2369 n_var_vlook(char const *vokey, bool_t try_getenv){
2370 struct a_amv_var_carrier avc;
2371 char const *rv;
2372 NYD_ENTER;
2374 a_amv_var_revlookup(&avc, vokey);
2376 switch((enum a_amv_var_special_category)avc.avc_special_cat){
2377 default: /* silence CC */
2378 case a_AMV_VSC_NONE:
2379 if(a_amv_var_lookup(&avc, FAL0))
2380 rv = avc.avc_var->av_value;
2381 /* Only check the environment for something that is otherwise unknown */
2382 else if(try_getenv && avc.avc_map == NULL)
2383 rv = getenv(vokey);
2384 else
2385 rv = NULL;
2386 break;
2387 case a_AMV_VSC_GLOBAL:
2388 rv = a_amv_var_vsc_global(&avc);
2389 break;
2390 case a_AMV_VSC_MULTIPLEX:
2391 rv = a_amv_var_vsc_multiplex(&avc);
2392 break;
2393 case a_AMV_VSC_MAC:
2394 case a_AMV_VSC_MAC_ARGV:
2395 rv = a_amv_var_vsc_mac(&avc);
2396 break;
2398 NYD_LEAVE;
2399 return rv;
2402 FL bool_t
2403 n_var_vexplode(void const **cookie){
2404 NYD_ENTER;
2405 /* These may occur only in a macro.. */
2406 *cookie = (a_amv_lopts != NULL) ? a_amv_lopts->as_amcap->amca_argv : NULL;
2407 NYD_LEAVE;
2408 return (*cookie != NULL);
2411 FL bool_t
2412 n_var_vset(char const *vokey, uintptr_t val){
2413 struct a_amv_var_carrier avc;
2414 bool_t ok;
2415 NYD_ENTER;
2417 a_amv_var_revlookup(&avc, vokey);
2419 ok = a_amv_var_set(&avc, (val == 0x1 ? n_empty : (char const*)val), FAL0);
2420 NYD_LEAVE;
2421 return ok;
2424 FL bool_t
2425 n_var_vclear(char const *vokey){
2426 struct a_amv_var_carrier avc;
2427 bool_t ok;
2428 NYD_ENTER;
2430 a_amv_var_revlookup(&avc, vokey);
2432 ok = a_amv_var_clear(&avc, FAL0);
2433 NYD_LEAVE;
2434 return ok;
2437 #ifdef HAVE_SOCKETS
2438 FL char *
2439 n_var_xoklook(enum okeys okey, struct url const *urlp,
2440 enum okey_xlook_mode oxm){
2441 struct a_amv_var_carrier avc;
2442 struct str const *us;
2443 size_t nlen;
2444 char *nbuf, *rv;
2445 struct a_amv_var_map const *avmp;
2446 NYD_ENTER;
2448 assert(oxm & (OXM_PLAIN | OXM_H_P | OXM_U_H_P));
2450 /* For simplicity: allow this case too */
2451 if(!(oxm & (OXM_H_P | OXM_U_H_P))){
2452 nbuf = NULL;
2453 goto jplain;
2456 avc.avc_map = avmp = &a_amv_var_map[okey];
2457 avc.avc_name = a_amv_var_names + avmp->avm_keyoff;
2458 avc.avc_okey = okey;
2460 us = (oxm & OXM_U_H_P) ? &urlp->url_u_h_p : &urlp->url_h_p;
2461 nlen = strlen(avc.avc_name);
2462 nbuf = n_lofi_alloc(nlen + 1 + us->l +1);
2463 memcpy(nbuf, avc.avc_name, nlen);
2464 nbuf[nlen++] = '-';
2466 /* One of .url_u_h_p and .url_h_p we test in here */
2467 memcpy(nbuf + nlen, us->s, us->l +1);
2468 avc.avc_name = a_amv_var_canonify(nbuf);
2469 avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
2470 if(a_amv_var_lookup(&avc, FAL0))
2471 goto jvar;
2473 /* The second */
2474 if(oxm & OXM_H_P){
2475 us = &urlp->url_h_p;
2476 memcpy(nbuf + nlen, us->s, us->l +1);
2477 avc.avc_name = a_amv_var_canonify(nbuf);
2478 avc.avc_hash = a_AMV_NAME2HASH(avc.avc_name);
2479 if(a_amv_var_lookup(&avc, FAL0)){
2480 jvar:
2481 rv = avc.avc_var->av_value;
2482 goto jleave;
2486 jplain:
2487 rv = (oxm & OXM_PLAIN) ? n_var_oklook(okey) : NULL;
2488 jleave:
2489 if(nbuf != NULL)
2490 n_lofi_free(nbuf);
2491 NYD_LEAVE;
2492 return rv;
2494 #endif /* HAVE_SOCKETS */
2496 FL int
2497 c_set(void *v){
2498 char **ap;
2499 int err;
2500 NYD_ENTER;
2502 if(*(ap = v) == NULL){
2503 a_amv_var_show_all();
2504 err = 0;
2505 }else
2506 err = !a_amv_var_c_set(ap, FAL0);
2507 NYD_LEAVE;
2508 return err;
2511 FL int
2512 c_unset(void *v){
2513 char **ap;
2514 int err;
2515 NYD_ENTER;
2517 for(err = 0, ap = v; *ap != NULL; ++ap)
2518 err |= !n_var_vclear(*ap);
2519 NYD_LEAVE;
2520 return err;
2523 FL int
2524 c_varshow(void *v){
2525 char **ap;
2526 NYD_ENTER;
2528 if(*(ap = v) == NULL)
2529 v = NULL;
2530 else{
2531 struct n_string msg, *msgp = &msg;
2533 msgp = n_string_creat(msgp);
2534 for(; *ap != NULL; ++ap)
2535 a_amv_var_show(*ap, n_stdout, msgp);
2536 n_string_gut(msgp);
2538 NYD_LEAVE;
2539 return (v == NULL ? !STOP : !OKAY); /* xxx 1:bad 0:good -- do some */
2542 FL int
2543 c_varedit(void *v){
2544 struct a_amv_var_carrier avc;
2545 FILE *of, *nf;
2546 char *val, **argv;
2547 int err;
2548 sighandler_type sigint;
2549 NYD_ENTER;
2551 sigint = safe_signal(SIGINT, SIG_IGN);
2553 for(err = 0, argv = v; *argv != NULL; ++argv){
2554 memset(&avc, 0, sizeof avc);
2556 a_amv_var_revlookup(&avc, *argv);
2558 if(avc.avc_map != NULL){
2559 if(avc.avc_map->avm_flags & a_AMV_VF_BOOL){
2560 n_err(_("`varedit': cannot edit boolean variable: %s\n"),
2561 avc.avc_name);
2562 continue;
2564 if(avc.avc_map->avm_flags & a_AMV_VF_RDONLY){
2565 n_err(_("`varedit': cannot edit read-only variable: %s\n"),
2566 avc.avc_name);
2567 continue;
2571 a_amv_var_lookup(&avc, FAL0);
2573 if((of = Ftmp(NULL, "varedit", OF_RDWR | OF_UNLINK | OF_REGISTER)) ==
2574 NULL){
2575 n_perr(_("`varedit': can't create temporary file, bailing out"), 0);
2576 err = 1;
2577 break;
2578 }else if(avc.avc_var != NULL && *(val = avc.avc_var->av_value) != '\0' &&
2579 sizeof *val != fwrite(val, strlen(val), sizeof *val, of)){
2580 n_perr(_("`varedit' failed to write old value to temporary file"), 0);
2581 Fclose(of);
2582 err = 1;
2583 continue;
2586 fflush_rewind(of);
2587 nf = run_editor(of, (off_t)-1, 'e', FAL0, NULL, NULL, SEND_MBOX, sigint);
2588 Fclose(of);
2590 if(nf != NULL){
2591 int c;
2592 char *base;
2593 off_t l;
2595 l = fsize(nf);
2596 assert(l >= 0);
2597 base = salloc((size_t)l +1);
2599 for(l = 0, val = base; (c = getc(nf)) != EOF; ++val)
2600 if(c == '\n' || c == '\r'){
2601 *val = ' ';
2602 ++l;
2603 }else{
2604 *val = (char)(uc_i)c;
2605 l = 0;
2607 val -= l;
2608 *val = '\0';
2610 if(!a_amv_var_set(&avc, base, FAL0))
2611 err = 1;
2613 Fclose(nf);
2614 }else{
2615 n_err(_("`varedit': can't start $EDITOR, bailing out\n"));
2616 err = 1;
2617 break;
2621 safe_signal(SIGINT, sigint);
2622 NYD_LEAVE;
2623 return err;
2626 FL int
2627 c_environ(void *v){
2628 struct a_amv_var_carrier avc;
2629 int err;
2630 char **ap;
2631 bool_t islnk;
2632 NYD_ENTER;
2634 if((islnk = is_asccaseprefix(*(ap = v), "link")) ||
2635 is_asccaseprefix(*ap, "unlink")){
2636 for(err = 0; *++ap != NULL;){
2637 a_amv_var_revlookup(&avc, *ap);
2639 if(a_amv_var_lookup(&avc, FAL0) && (islnk ||
2640 (avc.avc_var->av_flags & a_AMV_VF_LINKED))){
2641 if(!islnk){
2642 avc.avc_var->av_flags &= ~a_AMV_VF_LINKED;
2643 continue;
2644 }else if(avc.avc_var->av_flags & (a_AMV_VF_ENV | a_AMV_VF_LINKED)){
2645 if(n_poption & n_PO_D_V)
2646 n_err(_("`environ': link: already established: %s\n"), *ap);
2647 continue;
2649 avc.avc_var->av_flags |= a_AMV_VF_LINKED;
2650 if(!(avc.avc_var->av_flags & a_AMV_VF_ENV))
2651 a_amv_var__putenv(&avc, avc.avc_var);
2652 }else if(!islnk){
2653 n_err(_("`environ': unlink: no link established: %s\n"), *ap);
2654 err = 1;
2655 }else{
2656 char const *evp = getenv(*ap);
2658 if(evp != NULL)
2659 err |= !a_amv_var_set(&avc, evp, TRU1);
2660 else{
2661 n_err(_("`environ': link: cannot link to non-existent: %s\n"),
2662 *ap);
2663 err = 1;
2667 }else if(is_asccaseprefix(*ap, "set"))
2668 err = !a_amv_var_c_set(++ap, TRU1);
2669 else if(is_asccaseprefix(*ap, "unset")){
2670 for(err = 0; *++ap != NULL;){
2671 a_amv_var_revlookup(&avc, *ap);
2673 if(!a_amv_var_clear(&avc, TRU1))
2674 err = 1;
2676 }else{
2677 n_err(_("Synopsis: environ: <link|set|unset> <variable>...\n"));
2678 err = 1;
2680 NYD_LEAVE;
2681 return err;
2684 FL int
2685 c_vexpr(void *v){ /* TODO POSIX expr(1) comp. exit status; overly complicat. */
2686 /* This needs to be here because we need to apply MACKY_MACK for
2687 * search+replace regular expression support :( */
2688 size_t i;
2689 enum n_idec_state ids;
2690 si64_t lhv, rhv;
2691 char op, varbuf[64 + 64 / 8 +1];
2692 char const **argv, *varname, *varres, *cp;
2693 enum{
2694 a_ERR = 1<<0,
2695 a_SOFTOVERFLOW = 1<<1,
2696 a_ISNUM = 1<<2,
2697 a_ISDECIMAL = 1<<3, /* Print only decimal result */
2698 a_SATURATED = 1<<4,
2699 a_ICASE = 1<<5,
2700 a_UNSIGNED = 1<<6, /* Unsigned right shift (share bit ok) */
2701 a_TMP = 1<<30
2702 } f;
2703 NYD_ENTER;
2705 f = a_ERR;
2706 argv = v;
2707 varname = (n_pstate & n_PS_ARGMOD_VPUT) ? *argv++ : NULL;
2708 n_UNINIT(varres, n_empty);
2710 if((cp = argv[0])[0] == '\0')
2711 goto jesubcmd;
2713 if(cp[1] == '\0'){
2714 op = cp[0];
2715 jnumop:
2716 f |= a_ISNUM;
2717 switch(op){
2718 case '=':
2719 case '~':
2720 if(argv[1] == NULL || argv[2] != NULL)
2721 goto jesynopsis;
2723 if(*(cp = *++argv) == '\0')
2724 lhv = 0;
2725 else if(((ids = n_idec_si64_cp(&lhv, cp, 0, NULL)
2726 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2727 ) != n_IDEC_STATE_CONSUMED){
2728 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
2729 goto jenum_range;
2730 f |= a_SOFTOVERFLOW;
2731 break;
2733 if(op == '~')
2734 lhv = ~lhv;
2735 break;
2737 case '+':
2738 case '-':
2739 case '*':
2740 case '/':
2741 case '%':
2742 case '|':
2743 case '&':
2744 case '^':
2745 case '<':
2746 case '>':
2747 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
2748 goto jesynopsis;
2749 else{
2750 char xop;
2752 if(*(cp = *++argv) == '\0')
2753 lhv = 0;
2754 else if(((ids = n_idec_si64_cp(&lhv, cp, 0, NULL)
2755 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2756 ) != n_IDEC_STATE_CONSUMED){
2757 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
2758 goto jenum_range;
2759 f |= a_SOFTOVERFLOW;
2760 break;
2763 if(*(cp = *++argv) == '\0')
2764 rhv = 0;
2765 else if(((ids = n_idec_si64_cp(&rhv, cp, 0, NULL)
2766 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2767 ) != n_IDEC_STATE_CONSUMED){
2768 if(!(ids & n_IDEC_STATE_EOVERFLOW) || !(f & a_SATURATED))
2769 goto jenum_range;
2770 f |= a_SOFTOVERFLOW;
2771 lhv = rhv;
2772 break;
2775 xop = op;
2776 jnumop_again:
2777 switch(xop){
2778 case '+':
2779 if(rhv < 0){
2780 if(rhv != SI64_MIN){
2781 rhv = -rhv;
2782 xop = '-';
2783 goto jnumop_again;
2784 }else if(lhv < 0)
2785 goto jenum_plusminus;
2786 else if(lhv == 0){
2787 lhv = rhv;
2788 break;
2791 if(SI64_MAX - rhv < lhv)
2792 goto jenum_plusminus;
2793 lhv += rhv;
2794 break;
2795 case '-':
2796 if(rhv < 0){
2797 if(rhv != SI64_MIN){
2798 rhv = -rhv;
2799 xop = '+';
2800 goto jnumop_again;
2801 }else if(lhv > 0)
2802 goto jenum_plusminus;
2803 else if(lhv == 0){
2804 lhv = rhv;
2805 break;
2808 if(SI64_MIN + rhv > lhv){
2809 jenum_plusminus:
2810 if(!(f & a_SATURATED))
2811 goto jenum_overflow;
2812 f |= a_SOFTOVERFLOW;
2813 lhv = (lhv < 0 || xop == '-') ? SI64_MIN : SI64_MAX;
2814 }else
2815 lhv -= rhv;
2816 break;
2817 case '*':
2818 /* Will the result be positive? */
2819 if((lhv < 0) == (rhv < 0)){
2820 if(lhv > 0){
2821 lhv = -lhv;
2822 rhv = -rhv;
2824 if(rhv != 0 && lhv != 0 && SI64_MAX / rhv > lhv){
2825 if(!(f & a_SATURATED))
2826 goto jenum_overflow;
2827 f |= a_SOFTOVERFLOW;
2828 lhv = SI64_MAX;
2829 }else
2830 lhv *= rhv;
2831 }else{
2832 if(rhv > 0){
2833 if(lhv != 0 && SI64_MIN / lhv < rhv){
2834 if(!(f & a_SATURATED))
2835 goto jenum_overflow;
2836 f |= a_SOFTOVERFLOW;
2837 lhv = SI64_MIN;
2838 }else
2839 lhv *= rhv;
2840 }else{
2841 if(rhv != 0 && lhv != 0 && SI64_MIN / rhv < lhv){
2842 if(!(f & a_SATURATED))
2843 goto jenum_overflow;
2844 f |= a_SOFTOVERFLOW;
2845 lhv = SI64_MIN;
2846 }else
2847 lhv *= rhv;
2850 break;
2851 case '/':
2852 if(rhv == 0){
2853 if(!(f & a_SATURATED))
2854 goto jenum_range;
2855 f |= a_SOFTOVERFLOW;
2856 lhv = SI64_MAX;
2857 }else
2858 lhv /= rhv;
2859 break;
2860 case '%':
2861 if(rhv == 0){
2862 if(!(f & a_SATURATED))
2863 goto jenum_range;
2864 f |= a_SOFTOVERFLOW;
2865 lhv = SI64_MAX;
2866 }else
2867 lhv %= rhv;
2868 break;
2869 case '|':
2870 lhv |= rhv;
2871 break;
2872 case '&':
2873 lhv &= rhv;
2874 break;
2875 case '^':
2876 lhv ^= rhv;
2877 break;
2878 case '<':
2879 case '>':
2880 if(!(f & a_TMP))
2881 goto jesubcmd;
2882 if(rhv > 63){ /* xxx 63? */
2883 if(!(f & a_SATURATED))
2884 goto jenum_overflow;
2885 rhv = 63;
2887 if(op == '<')
2888 lhv <<= (ui8_t)rhv;
2889 else if(f & a_UNSIGNED)
2890 lhv = (ui64_t)lhv >> (ui8_t)rhv;
2891 else
2892 lhv >>= (ui8_t)rhv;
2893 break;
2896 break;
2897 default:
2898 goto jesubcmd;
2900 }else if(cp[2] == '\0' && cp[1] == '@'){
2901 f |= a_SATURATED;
2902 op = cp[0];
2903 goto jnumop;
2904 }else if(cp[0] == '<'){
2905 if(*++cp != '<')
2906 goto jesubcmd;
2907 if(*++cp == '@'){
2908 f |= a_SATURATED;
2909 ++cp;
2911 if(*cp != '\0')
2912 goto jesubcmd;
2913 f |= a_TMP;
2914 op = '<';
2915 goto jnumop;
2916 }else if(cp[0] == '>'){
2917 if(*++cp != '>')
2918 goto jesubcmd;
2919 if(*++cp == '>'){
2920 f |= a_UNSIGNED;
2921 ++cp;
2923 if(*cp == '@'){
2924 f |= a_SATURATED;
2925 ++cp;
2927 if(*cp != '\0')
2928 goto jesubcmd;
2929 f |= a_TMP;
2930 op = '>';
2931 goto jnumop;
2932 }else if(is_asccaseprefix(cp, "length")){
2933 f |= a_ISNUM | a_ISDECIMAL;
2934 if(argv[1] == NULL || argv[2] != NULL)
2935 goto jesynopsis;
2937 i = strlen(*++argv);
2938 if(UICMP(64, i, >, SI64_MAX))
2939 goto jestr_overflow;
2940 lhv = (si64_t)i;
2941 }else if(is_asccaseprefix(cp, "hash")){
2942 f |= a_ISNUM | a_ISDECIMAL;
2943 if(argv[1] == NULL || argv[2] != NULL)
2944 goto jesynopsis;
2946 i = n_torek_hash(*++argv);
2947 lhv = (si64_t)i;
2948 }else if(is_asccaseprefix(cp, "file-expand")){
2949 if(argv[1] == NULL || argv[2] != NULL)
2950 goto jesynopsis;
2952 if((varres = fexpand(argv[1], FEXP_NVAR | FEXP_NOPROTO)) == NULL)
2953 goto jestr_nodata;
2954 }else if(is_asccaseprefix(cp, "random")){
2955 if(argv[1] == NULL || argv[2] != NULL)
2956 goto jesynopsis;
2958 if((n_idec_si64_cp(&lhv, argv[1], 0, NULL
2959 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2960 ) != n_IDEC_STATE_CONSUMED || lhv < 0 || lhv > PATH_MAX)
2961 goto jestr_numrange;
2962 if(lhv == 0)
2963 lhv = NAME_MAX;
2964 varres = n_random_create_cp((size_t)lhv);
2965 }else if(is_asccaseprefix(cp, "find")){
2966 f |= a_ISNUM | a_ISDECIMAL;
2967 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
2968 goto jesynopsis;
2970 if((cp = strstr(argv[1], argv[2])) == NULL)
2971 goto jestr_nodata;
2972 i = PTR2SIZE(cp - argv[1]);
2973 if(UICMP(64, i, >, SI64_MAX))
2974 goto jestr_overflow;
2975 lhv = (si64_t)i;
2976 }else if(is_asccaseprefix(cp, "ifind")){
2977 f |= a_ISNUM | a_ISDECIMAL;
2978 if(argv[1] == NULL || argv[2] == NULL || argv[3] != NULL)
2979 goto jesynopsis;
2981 if((cp = asccasestr(argv[1], argv[2])) == NULL)
2982 goto jestr_nodata;
2983 i = PTR2SIZE(cp - argv[1]);
2984 if(UICMP(64, i, >, SI64_MAX))
2985 goto jestr_overflow;
2986 lhv = (si64_t)i;
2987 }else if(is_asccaseprefix(cp, "substring")){
2988 if(argv[1] == NULL || argv[2] == NULL)
2989 goto jesynopsis;
2990 if(argv[3] != NULL && argv[4] != NULL)
2991 goto jesynopsis;
2993 i = strlen(varres = *++argv);
2995 if(*(cp = *++argv) == '\0')
2996 lhv = 0;
2997 else if((n_idec_si64_cp(&lhv, cp, 0, NULL
2998 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
2999 ) != n_IDEC_STATE_CONSUMED)
3000 goto jestr_numrange;
3001 if(UICMP(64, i, >=, lhv)){
3002 i -= lhv;
3003 varres += lhv;
3004 }else{
3005 if(n_poption & n_PO_D_V)
3006 n_err(_("`vexpr': substring: offset argument too large: %s\n"),
3007 n_shexp_quote_cp(argv[-1], FAL0));
3008 f |= a_SOFTOVERFLOW;
3011 if(argv[1] != NULL){
3012 if(*(cp = *++argv) == '\0')
3013 lhv = 0;
3014 else if((n_idec_si64_cp(&lhv, cp, 0, NULL
3015 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
3016 ) != n_IDEC_STATE_CONSUMED)
3017 goto jestr_numrange;
3018 if(UICMP(64, i, >=, lhv)){
3019 if(UICMP(64, i, !=, lhv))
3020 varres = savestrbuf(varres, (size_t)lhv);
3021 }else{
3022 if(n_poption & n_PO_D_V)
3023 n_err(_("`vexpr': substring: length argument too large: %s\n"),
3024 n_shexp_quote_cp(argv[-2], FAL0));
3025 f |= a_SOFTOVERFLOW;
3028 #ifdef HAVE_REGEX
3029 }else if(is_asccaseprefix(cp, "regex")) Jregex:{
3030 regmatch_t rema[1 + n_VEXPR_REGEX_MAX];
3031 regex_t re;
3032 int reflrv;
3034 f |= a_ISNUM | a_ISDECIMAL;
3035 if(argv[1] == NULL || argv[2] == NULL ||
3036 (argv[3] != NULL && argv[4] != NULL))
3037 goto jesynopsis;
3039 reflrv = REG_EXTENDED;
3040 if(f & a_ICASE)
3041 reflrv |= REG_ICASE;
3042 if((reflrv = regcomp(&re, argv[2], reflrv))){
3043 n_err(_("`vexpr': invalid regular expression: %s: %s\n"),
3044 n_shexp_quote_cp(argv[2], FAL0), n_regex_err_to_doc(&re, reflrv));
3045 assert(f & a_ERR);
3046 n_pstate_err_no = n_ERR_INVAL;
3047 goto jestr;
3049 reflrv = regexec(&re, argv[1], n_NELEM(rema), rema, 0);
3050 regfree(&re);
3051 if(reflrv == REG_NOMATCH)
3052 goto jestr_nodata;
3054 /* Search only? Else replace, which is a bit */
3055 if(argv[3] == NULL){
3056 if(UICMP(64, rema[0].rm_so, >, SI64_MAX))
3057 goto jestr_overflow;
3058 lhv = (si64_t)rema[0].rm_so;
3059 }else{
3060 /* We need to setup some kind of pseudo macro environment for this */
3061 struct a_amv_lostack los;
3062 struct a_amv_mac_call_args amca;
3063 char const **reargv;
3065 memset(&amca, 0, sizeof amca);
3066 amca.amca_name = savestrbuf(&argv[1][rema[0].rm_so],
3067 rema[0].rm_eo - rema[0].rm_so);
3068 amca.amca_amp = a_AMV_MACKY_MACK;
3069 for(i = 1; rema[i].rm_so != -1 && i < n_NELEM(rema); ++i)
3071 amca.amca_argc = (ui32_t)i - 1;
3072 amca.amca_argv =
3073 reargv = salloc(sizeof(char*) * i);
3074 for(i = 1; rema[i].rm_so != -1 && i < n_NELEM(rema); ++i)
3075 *reargv++ = savestrbuf(&argv[1][rema[i].rm_so],
3076 rema[i].rm_eo - rema[i].rm_so);
3077 *reargv = NULL;
3079 hold_all_sigs(); /* TODO DISLIKE! */
3080 los.as_global_saved = a_amv_lopts;
3081 los.as_amcap = &amca;
3082 los.as_up = los.as_global_saved;
3083 los.as_lopts = NULL;
3084 los.as_unroll = FAL0;
3085 a_amv_lopts = &los;
3087 /* C99 */{
3088 struct str templ;
3089 struct n_string s_b;
3090 enum n_shexp_state shs;
3092 templ.s = n_UNCONST(argv[3]);
3093 templ.l = UIZ_MAX;
3094 shs = n_shexp_parse_token((n_SHEXP_PARSE_LOG |
3095 n_SHEXP_PARSE_IGNORE_EMPTY | n_SHEXP_PARSE_QUOTE_AUTO_FIXED |
3096 n_SHEXP_PARSE_QUOTE_AUTO_DSQ),
3097 n_string_creat_auto(&s_b), &templ, NULL);
3098 if((shs & (n_SHEXP_STATE_ERR_MASK | n_SHEXP_STATE_STOP)
3099 ) == n_SHEXP_STATE_STOP){
3100 varres = n_string_cp(&s_b);
3101 n_string_drop_ownership(&s_b);
3102 }else
3103 varres = NULL;
3106 a_amv_lopts = los.as_global_saved;
3107 rele_all_sigs(); /* TODO DISLIKE! */
3109 if(varres == NULL)
3110 goto jestr_nodata;
3111 f &= ~(a_ISNUM | a_ISDECIMAL);
3113 }else if(is_asccaseprefix(argv[0], "iregex")){
3114 f |= a_ICASE;
3115 goto Jregex;
3116 #endif /* HAVE_REGEX */
3117 }else
3118 goto jesubcmd;
3120 n_pstate_err_no = (f & a_SOFTOVERFLOW) ? n_ERR_OVERFLOW : n_ERR_NONE;
3121 f &= ~a_ERR;
3123 /* Generate the variable value content for numerics.
3124 * Anticipate in our handling below! (Don't do needless work) */
3125 jleave:
3126 if((f & a_ISNUM) && ((f & a_ISDECIMAL) || varname != NULL)){
3127 snprintf(varbuf, sizeof varbuf, "%" PRId64 , lhv);
3128 varres = varbuf;
3131 if(varname == NULL){
3132 /* If there was no error and we are printing a numeric result, print some
3133 * more bases for the fun of it */
3134 if((f & (a_ERR | a_ISNUM | a_ISDECIMAL)) == a_ISNUM){
3135 size_t j;
3137 for(j = 1, i = 0; i < 64; ++i){
3138 varbuf[63 + 64 / 8 -j - i] = (lhv & ((ui64_t)1 << i)) ? '1' : '0';
3139 if((i & 7) == 7 && i != 63){
3140 ++j;
3141 varbuf[63 + 64 / 8 -j - i] = ' ';
3144 varbuf[64 + 64 / 8 -1] = '\0';
3145 if(fprintf(n_stdout,
3146 "%s\n0%" PRIo64 " | 0x%" PRIX64 " | %" PRId64 "\n",
3147 varbuf, lhv, lhv, lhv) < 0){
3148 n_pstate_err_no = n_err_no;
3149 f |= a_ERR;
3151 }else if(fprintf(n_stdout, "%s\n", varres) < 0){
3152 n_pstate_err_no = n_err_no;
3153 f |= a_ERR;
3155 }else if(!n_var_vset(varname, (uintptr_t)varres)){
3156 n_pstate_err_no = n_ERR_NOTSUP;
3157 f |= a_ERR;
3159 NYD_LEAVE;
3160 return (f & a_ERR) ? 1 : 0;
3162 jerr:
3163 f = a_ERR | a_ISNUM;
3164 lhv = -1;
3165 goto jleave;
3166 jesubcmd:
3167 n_err(_("`vexpr': invalid subcommand: %s\n"),
3168 n_shexp_quote_cp(*argv, FAL0));
3169 n_pstate_err_no = n_ERR_INVAL;
3170 goto jerr;
3171 jesynopsis:
3172 n_err(_("Synopsis: vexpr: <operator> <:argument:>\n"));
3173 n_pstate_err_no = n_ERR_INVAL;
3174 goto jerr;
3176 jenum_range:
3177 n_err(_("`vexpr': numeric argument invalid or out of range: %s\n"),
3178 n_shexp_quote_cp(*argv, FAL0));
3179 n_pstate_err_no = n_ERR_RANGE;
3180 goto jerr;
3181 jenum_overflow:
3182 n_err(_("`vexpr': expression overflows datatype: %" PRId64 " %c %" PRId64
3183 "\n"), lhv, op, rhv);
3184 n_pstate_err_no = n_ERR_OVERFLOW;
3185 goto jerr;
3187 jestr_numrange:
3188 n_err(_("`vexpr': numeric argument invalid or out of range: %s\n"),
3189 n_shexp_quote_cp(*argv, FAL0));
3190 n_pstate_err_no = n_ERR_RANGE;
3191 goto jestr;
3192 jestr_overflow:
3193 n_err(_("`vexpr': string length or offset overflows datatype\n"));
3194 n_pstate_err_no = n_ERR_OVERFLOW;
3195 goto jestr;
3196 jestr_nodata:
3197 n_pstate_err_no = n_ERR_NODATA;
3198 /* FALLTHRU */
3199 jestr:
3200 varres = n_empty;
3201 f &= ~a_ISNUM;
3202 f |= a_ERR;
3203 goto jleave;
3206 /* s-it-mode */