Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <sys/wait.h>
22 #include <assert.h>
23 #include <endian.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <event.h>
27 #include <fcntl.h>
28 #include <inttypes.h>
29 #include <poll.h>
30 #include <pwd.h>
31 #include <regex.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <syslog.h>
37 #include <unistd.h>
39 #include "client.h"
40 #include "kami.h"
41 #include "kamid.h"
42 #include "log.h"
43 #include "script.h"
44 #include "utils.h"
46 #define DEBUG 0
48 #ifndef INFTIM
49 #define INFTIM -1
50 #endif
52 static const char *argv0;
53 static const char *dir;
54 static uid_t uid;
56 static uint8_t *lastmsg;
58 static struct imsgbuf ibuf;
59 static int ibuf_inuse;
60 static int child_out = -1;
62 static struct procs procs = TAILQ_HEAD_INITIALIZER(procs);
63 static struct tests tests = TAILQ_HEAD_INITIALIZER(tests);
65 static int ntests;
67 static struct opstacks blocks = TAILQ_HEAD_INITIALIZER(blocks);
68 static struct opstacks args = TAILQ_HEAD_INITIALIZER(args);
70 #define STACK_HEIGHT 64
71 static struct value vstack[STACK_HEIGHT];
72 static int stackh;
74 static struct envs envs = TAILQ_HEAD_INITIALIZER(envs);
76 static struct value v_false = {.type = V_NUM, .v = {.num = 0}};
77 static struct value v_true = {.type = V_NUM, .v = {.num = 1}};
79 static uint8_t lasttag;
81 static int debug;
82 static int syntaxcheck;
84 static const char *filler;
86 static inline void
87 before_printing(void)
88 {
89 if (filler != NULL) {
90 printf("%s", filler);
91 filler = NULL;
92 }
93 }
95 static inline void
96 check_for_output(void)
97 {
98 static char buf[BUFSIZ];
99 struct pollfd pfd;
100 ssize_t r;
102 pfd.fd = child_out;
103 pfd.events = POLLIN;
104 if (poll(&pfd, 1, 0) == -1)
105 fatal("poll");
107 if (!(pfd.revents & POLLIN))
108 return;
110 for (;;) {
111 if ((r = read(child_out, buf, sizeof(buf))) == -1) {
112 if (errno == EAGAIN)
113 break;
114 fatal("read");
116 if (r == 0)
117 break;
118 before_printing();
119 fwrite(buf, 1, r, stdout);
123 static inline void
124 peekn(int depth, struct value *v)
126 if (depth > stackh)
127 errx(1, "can't peek the stack at %d: underflow",
128 depth);
129 memcpy(v, &vstack[stackh - depth], sizeof(*v));
131 #if DEBUG
132 printf("peeking(%d) ", depth); pp_val(v); printf("\n");
133 #endif
136 static inline void
137 popv(struct value *v)
139 if (stackh == 0)
140 errx(1, "can't pop the stack: underflow");
141 memcpy(v, &vstack[--stackh], sizeof(*v));
143 #if DEBUG
144 printf("popping "); pp_val(v); printf("\n");
145 #endif
148 static inline void
149 popvn(int n)
151 struct value v;
153 while (n-- > 0)
154 popv(&v);
157 static inline void
158 pushv(struct value *v)
160 if (stackh == STACK_HEIGHT)
161 errx(1, "can't push the stack: overflow");
163 #if DEBUG
164 printf("pushing "); pp_val(v); printf("\n");
165 #endif
167 memcpy(&vstack[stackh++], v, sizeof(*v));
170 static inline void
171 pushbool(int n)
173 pushv(n ? &v_true : &v_false);
176 static inline void
177 pushnum(int64_t n)
179 struct value v;
181 v.type = V_NUM;
182 v.v.num = n;
183 pushv(&v);
186 static inline struct opstack *
187 pushstack(struct opstacks *stack)
189 struct opstack *ops;
191 ops = xcalloc(1, sizeof(*ops));
192 TAILQ_INSERT_HEAD(stack, ops, entry);
193 return ops;
196 static inline struct opstack *
197 peek(struct opstacks *stack)
199 if (TAILQ_EMPTY(stack))
200 errx(1, "%s: args underflow", __func__);
202 return TAILQ_FIRST(stack);
205 static inline struct op *
206 finalize(struct opstacks *stack, int *argc)
208 struct opstack *ops;
209 struct op *op;
211 if (TAILQ_EMPTY(stack))
212 errx(1, "%s: args underflow", __func__);
214 ops = peek(stack);
215 TAILQ_REMOVE(&args, ops, entry);
216 op = ops->base.next;
218 if (argc != NULL)
219 *argc = ops->counter;
221 free(ops);
222 return op;
225 static inline void
226 push(struct opstacks *stack, struct op *op)
228 struct opstack *ops;
230 ops = peek(stack);
231 if (ops->last == NULL) {
232 ops->base.next = op;
233 ops->last = op;
234 } else {
235 ops->last->next = op;
236 ops->last = op;
239 ops->counter++;
242 static inline void
243 pushenv(void)
245 struct env *e;
247 e = xcalloc(1, sizeof(*e));
248 TAILQ_INSERT_HEAD(&envs, e, entry);
251 static inline struct env *
252 currentenv(void)
254 assert(!TAILQ_EMPTY(&envs));
255 return TAILQ_FIRST(&envs);
258 static void
259 popenv(void)
261 struct env *e;
262 struct binding *b, *tb;
264 e = currentenv();
265 TAILQ_REMOVE(&envs, e, entry);
267 TAILQ_FOREACH_SAFE(b, &e->bindings, entry, tb)
268 free(b);
270 free(e);
273 static inline int
274 setvar(char *sym, struct op *op)
276 struct binding *b;
277 struct env *e;
278 int ret, height;
280 height = stackh;
281 if ((ret = eval(op)) != EVAL_OK)
282 return ret;
284 if (stackh != height + 1) {
285 before_printing();
286 printf("trying to assign to `%s' a void value: ", sym);
287 pp_op(op);
288 printf("\n");
289 return EVAL_ERR;
292 b = xcalloc(1, sizeof(*b));
293 b->name = sym;
294 popv(&b->val);
296 e = TAILQ_FIRST(&envs);
297 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
299 return EVAL_OK;
302 static inline void
303 setvar_raw(char *sym, struct op *op)
305 struct binding *b;
306 struct env *e;
308 b = xcalloc(1, sizeof(*b));
309 b->name = sym;
310 b->raw = op;
312 e = TAILQ_FIRST(&envs);
313 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
316 static inline int
317 getvar(const char *sym, struct value *v)
319 struct env *e;
320 struct binding *b;
322 TAILQ_FOREACH(e, &envs, entry) {
323 TAILQ_FOREACH(b, &e->bindings, entry) {
324 if (!strcmp(sym, b->name)) {
325 memcpy(v, &b->val, sizeof(*v));
326 return EVAL_OK;
331 before_printing();
332 fprintf(stderr, "unbound variable %s\n", sym);
333 return EVAL_ERR;
336 static inline int
337 getvar_raw(const char *sym, struct op **raw)
339 struct env *e;
340 struct binding *b;
342 TAILQ_FOREACH(e, &envs, entry) {
343 TAILQ_FOREACH(b, &e->bindings, entry) {
344 if (!strcmp(sym, b->name)) {
345 *raw = b->raw;
346 return EVAL_OK;
351 return EVAL_ERR;
354 int
355 global_set(char *sym, struct op *op)
357 struct binding *b;
358 struct env *e;
360 /* TODO: check for duplicates */
362 if (op->type != OP_LITERAL &&
363 (op->type == OP_CAST && op->v.cast.expr->type != OP_LITERAL))
364 return 0;
366 b = xcalloc(1, sizeof(*b));
367 b->name = sym;
369 /* it's only a cast on a literal! */
370 if (op->type == OP_CAST) {
371 if (eval(op) != EVAL_OK) {
372 free(b);
373 return 0;
375 popv(&b->val);
376 } else
377 memcpy(&b->val, &op->v.literal, sizeof(b->val));
379 e = TAILQ_LAST(&envs, envs);
380 TAILQ_INSERT_HEAD(&e->bindings, b, entry);
382 return 1;
385 struct op *
386 newop(int type)
388 struct op *op;
390 op = xcalloc(1, sizeof(*op));
391 op->type = type;
393 return op;
396 void
397 free_op_rec(struct op *op)
399 struct op *n;
401 while (op != NULL) {
402 n = op->next;
403 free_op(op);
404 op = n;
408 void
409 free_op(struct op *op)
411 if (op == NULL)
412 return;
414 switch (op->type) {
415 case OP_REST:
416 case OP_LITERAL:
417 case OP_VARGS:
418 break;
419 case OP_ASSIGN:
420 free(op->v.assign.name);
421 free_op_rec(op->v.assign.expr);
422 break;
423 case OP_ASSERT:
424 free_op_rec(op->v.assert);
425 break;
426 case OP_FUNCALL:
427 free_op_rec(op->v.funcall.argv);
428 break;
429 case OP_VAR:
430 free(op->v.var);
431 break;
432 case OP_CAST:
433 free_op_rec(op->v.cast.expr);
434 break;
435 case OP_CMP_EQ:
436 case OP_CMP_LEQ:
437 free_op_rec(op->v.bin_cmp.a);
438 free_op_rec(op->v.bin_cmp.b);
439 break;
440 case OP_FACCESS:
441 free_op_rec(op->v.faccess.expr);
442 free(op->v.faccess.field);
443 break;
444 case OP_SFAIL:
445 free(op->v.sfail.msg);
446 free_op_rec(op->v.sfail.expr);
447 break;
448 default:
449 /* unreachable */
450 abort();
453 free(op);
456 struct op *
457 op_rest(void)
459 return newop(OP_REST);
462 struct op *
463 op_assign(char *sym, struct op *expr)
465 struct op *op;
467 op = newop(OP_ASSIGN);
468 op->v.assign.name = sym;
469 op->v.assign.expr = expr;
471 return op;
474 struct op *
475 op_assert(struct op *expr)
477 struct op *op;
479 op = newop(OP_ASSERT);
480 op->v.assert = expr;
482 return op;
485 struct op *
486 op_var(char *sym)
488 struct op *op;
490 op = newop(OP_VAR);
491 op->v.var = sym;
493 return op;
496 struct op *
497 op_lit_str(char *str)
499 struct op *op;
501 op = newop(OP_LITERAL);
502 op->v.literal.type = V_STR;
503 op->v.literal.v.str = str;
505 return op;
508 struct op *
509 op_lit_num(uint64_t n)
511 struct op *op;
513 op = newop(OP_LITERAL);
514 op->v.literal.type = V_NUM;
515 op->v.literal.v.num = n;
517 return op;
520 struct op *
521 op_cmp_eq(struct op *a, struct op *b)
523 struct op *op;
525 op = newop(OP_CMP_EQ);
526 op->v.bin_cmp.a = a;
527 op->v.bin_cmp.b = b;
529 return op;
532 struct op *
533 op_cmp_leq(struct op *a, struct op *b)
535 struct op *op;
537 op = newop(OP_CMP_LEQ);
538 op->v.bin_cmp.a = a;
539 op->v.bin_cmp.b = b;
541 return op;
544 struct op *
545 op_cast(struct op *expr, int totype)
547 struct op *op;
549 op = newop(OP_CAST);
550 op->v.cast.expr = expr;
551 op->v.cast.totype = totype;
553 return op;
556 struct op *
557 op_faccess(struct op *expr, char *field)
559 struct op *op;
561 op = newop(OP_FACCESS);
562 op->v.faccess.expr = expr;
563 op->v.faccess.field = field;
565 return op;
568 struct op *
569 op_sfail(struct op *expr, char *msg)
571 struct op *op;
573 op = newop(OP_SFAIL);
574 op->v.sfail.expr = expr;
575 op->v.sfail.msg = msg;
577 return op;
580 struct op *
581 op_vargs(void)
583 struct op *op;
585 op = newop(OP_VARGS);
587 return op;
590 void
591 ppf_val(FILE *f, struct value *val)
593 size_t i;
595 switch (val->type) {
596 case V_SYM:
597 fprintf(f, "%s", val->v.str);
598 break;
599 case V_STR:
600 fprintf(f, "\"%s\"", val->v.str);
601 break;
602 case V_NUM:
603 fprintf(f, "%"PRIi64, val->v.num);
604 break;
605 case V_U8:
606 fprintf(f, "%"PRIu8, val->v.u8);
607 break;
608 case V_U16:
609 fprintf(f, "%"PRIu16, val->v.u16);
610 break;
611 case V_U32:
612 fprintf(f, "%"PRIu32, val->v.u32);
613 break;
614 case V_MSG:
615 fprintf(f, "(");
616 for (i = 0; i < val->v.msg.len; ++i)
617 fprintf(f, "%x%s", val->v.msg.msg[i],
618 i == val->v.msg.len-1 ? "" : " ");
619 fprintf(f, ")");
620 break;
621 case V_QIDVEC:
622 fprintf(f, "qids[n=%zu]", val->v.qidvec.len);
623 break;
624 default:
625 fprintf(f, "<unknown value>");
626 break;
630 void
631 pp_val(struct value *val)
633 ppf_val(stdout, val);
636 const char *
637 val_type(struct value *v)
639 switch (v->type) {
640 case V_SYM: return "symbol";
641 case V_STR: return "string";
642 case V_NUM: return "number";
643 case V_MSG: return "message";
644 case V_QID: return "qid";
645 case V_U8: return "u8";
646 case V_U16: return "u16";
647 case V_U32: return "u32";
648 default: return "unknown";
652 int
653 val_trueish(struct value *a)
655 if (val_isnum(a))
656 return val_tonum(a);
657 return 1;
660 int
661 val_isnum(struct value *a)
663 return a->type == V_NUM
664 || a->type == V_U8
665 || a->type == V_U16
666 || a->type == V_U32;
669 int64_t
670 val_tonum(struct value *a)
672 switch (a->type) {
673 case V_NUM: return a->v.num;
674 case V_U8: return a->v.u8;
675 case V_U16: return a->v.u16;
676 case V_U32: return a->v.u32;
677 default:
678 before_printing();
679 fprintf(stderr, "%s: given value is not a number\n", __func__);
680 abort();
684 int
685 val_eq(struct value *a, struct value *b)
687 if (val_isnum(a) && val_isnum(b))
688 return val_tonum(a) == val_tonum(b);
690 if (a->type != b->type)
691 return 0;
693 switch (a->type) {
694 case V_STR:
695 case V_SYM:
696 return !strcmp(a->v.str, b->v.str);
699 return 0;
702 int
703 val_leq(struct value *a, struct value *b)
705 if (val_isnum(a) && val_isnum(b))
706 return val_tonum(a) <= val_tonum(b);
707 return 0;
710 static inline const char *
711 pp_totype(int totype)
713 /*
714 * Not all of these are valid cast type thought, including
715 * every possibility only to aid debugging.
716 */
717 switch (totype) {
718 case V_STR: return "str";
719 case V_SYM: return "sym";
720 case V_NUM: return "num";
721 case V_QID: return "qid";
722 case V_U8: return "u8";
723 case V_U16: return "u16";
724 case V_U32: return "u32";
725 default: return "unknown";
729 int
730 val_cast(struct value *a, int totype)
732 int64_t v;
734 #define NUMCAST(val, t, c, totype, max) do { \
735 if (val > max) { \
736 before_printing(); \
737 fprintf(stderr, "can't cast %"PRIu64 \
738 " to %s\n", val, pp_totype(totype)); \
739 return EVAL_ERR; \
740 } \
741 a->type = totype; \
742 a->v.t = (c)val; \
743 return EVAL_OK; \
744 } while (0)
746 if (a->type == totype)
747 return EVAL_OK;
749 if (!val_isnum(a)) {
750 before_printing();
751 fprintf(stderr, "can't cast ");
752 ppf_val(stderr, a);
753 fprintf(stderr, " to type %s\n", pp_totype(totype));
754 return EVAL_ERR;
757 v = a->v.num;
758 switch (totype) {
759 case V_U8: NUMCAST(v, u8, uint8_t, totype, UINT8_MAX);
760 case V_U16: NUMCAST(v, u16, uint16_t, totype, UINT16_MAX);
761 case V_U32: NUMCAST(v, u32, uint32_t, totype, UINT32_MAX);
762 default:
763 before_printing();
764 fprintf(stderr, "can't cast %"PRIu64" to %s\n",
765 v, pp_totype(totype));
766 return EVAL_ERR;
769 #undef NUMCAST
772 int
773 val_faccess(struct value *a, const char *field, struct value *ret)
775 uint8_t mtype;
776 uint16_t len;
777 const char *errstr;
779 #define MSGTYPE(m) *(m.msg + 4) /* skip the length */
781 switch (a->type) {
782 case V_QID:
783 /* TODO: add path. needs uint64_t values thought! */
784 if (!strcmp(field, "vers")) {
785 ret->type = V_U32;
786 memcpy(&ret->v.u32, a->v.qid+1, 4);
787 return EVAL_OK;
788 } else if (!strcmp(field, "type")) {
789 ret->type = V_U8;
790 ret->v.u8 = *a->v.qid;
791 return EVAL_OK;
793 break;
795 case V_MSG:
796 mtype = MSGTYPE(a->v.msg);
797 if (!strcmp(field, "type")) {
798 ret->type = V_U8;
799 ret->v.u8 = MSGTYPE(a->v.msg);
800 return EVAL_OK;
801 } else if (!strcmp(field, "tag")) {
802 ret->type = V_U16;
803 memcpy(&ret->v.u16, &a->v.msg.msg[5], 2);
804 ret->v.u16 = le16toh(ret->v.u16);
805 return EVAL_OK;
806 } else if (!strcmp(field, "msize") && mtype == Rversion) {
807 ret->type = V_U32;
808 memcpy(&ret->v.u32, &a->v.msg.msg[7], 4);
809 ret->v.u32 = le32toh(ret->v.u32);
810 return EVAL_OK;
811 } else if (!strcmp(field, "qid") && mtype == Rattach) {
812 ret->type = V_QID;
813 memcpy(&ret->v.qid, &a->v.msg.msg[7], QIDSIZE);
814 return EVAL_OK;
815 } else if (!strcmp(field, "nwqid") && mtype == Rwalk) {
816 ret->type = V_U16;
817 memcpy(&ret->v.u16, &a->v.msg.msg[7], 2);
818 ret->v.u16 = le16toh(ret->v.u16);
819 return EVAL_OK;
820 } else if (!strcmp(field, "wqid") && mtype == Rwalk) {
821 ret->type = V_QIDVEC;
822 ret->v.qidvec.start = &a->v.msg.msg[9];
823 memcpy(&len, &a->v.msg.msg[7], 2);
824 len = le16toh(len);
825 ret->v.qidvec.len = len;
826 return EVAL_OK;
828 break;
830 case V_QIDVEC:
831 len = strtonum(field, 0, MAXWELEM, &errstr);
832 if (errstr != NULL) {
833 before_printing();
834 printf("can't access qid #%s: %s\n", field, errstr);
835 return EVAL_ERR;
838 if (len >= a->v.qidvec.len) {
839 before_printing();
840 printf("can't access qid #%d: out-of-bound "
841 "(max %zu)\n", len, a->v.qidvec.len);
842 return EVAL_ERR;
845 ret->type = V_QID;
846 memcpy(&ret->v.qid, a->v.qidvec.start + len * QIDSIZE,
847 QIDSIZE);
849 return EVAL_OK;
851 default:
852 break;
855 before_printing();
856 printf("can't access field `%s' on type %s (", field, val_type(a));
857 pp_val(a);
858 printf(")\n");
859 return EVAL_ERR;
861 #undef MSGTYPE
864 void
865 pp_op(struct op *op)
867 struct op *aux;
869 switch (op->type) {
870 case OP_REST:
871 printf("...");
872 break;
873 case OP_ASSIGN:
874 printf("%s = ", op->v.assign.name);
875 pp_op(op->v.assign.expr);
876 break;
877 case OP_ASSERT:
878 printf("assert ");
879 pp_op(op->v.assert);
880 break;
881 case OP_FUNCALL:
882 printf("funcall %s(", op->v.funcall.proc->name);
883 for (aux = op->v.funcall.argv; aux != NULL; aux = aux->next) {
884 pp_op(aux);
885 if (aux->next != NULL)
886 printf(", ");
888 printf(")");
889 break;
890 case OP_LITERAL:
891 pp_val(&op->v.literal);
892 break;
893 case OP_VAR:
894 printf("%s", op->v.var);
895 break;
896 case OP_CAST:
897 pp_op(op->v.cast.expr);
898 printf(":");
899 switch (op->v.cast.totype) {
900 case V_U8: printf("u8"); break;
901 case V_U16: printf("u16"); break;
902 case V_U32: printf("u32"); break;
903 case V_STR: printf("str"); break;
904 default: printf("???"); break;
906 break;
907 case OP_CMP_EQ:
908 pp_op(op->v.bin_cmp.a);
909 printf(" == ");
910 pp_op(op->v.bin_cmp.b);
911 break;
912 case OP_CMP_LEQ:
913 pp_op(op->v.bin_cmp.a);
914 printf(" <= ");
915 pp_op(op->v.bin_cmp.b);
916 break;
917 case OP_FACCESS:
918 pp_op(op->v.faccess.expr);
919 printf(".%s", op->v.faccess.field);
920 break;
921 case OP_SFAIL:
922 printf("should-fail ");
923 pp_op(op->v.sfail.expr);
924 if (op->v.sfail.msg != NULL)
925 printf(": \"%s\"", op->v.sfail.msg);
926 break;
927 case OP_VARGS:
928 printf("vargs");
929 break;
930 default:
931 printf(" ???[%d] ", op->type);
935 void
936 pp_block(struct op *op)
938 while (op != NULL) {
939 printf("> ");
940 pp_op(op);
941 printf("\n");
943 op = op->next;
947 int
948 eval(struct op *op)
950 struct value a, b;
951 struct proc *proc;
952 struct op *t, *tnext;
953 int i, ret;
955 #if DEBUG
956 pp_op(op);
957 printf("\n");
958 #endif
960 switch (op->type) {
961 case OP_REST:
962 /*
963 * Try to load the rest argument. Note that it can be
964 * empty!
965 */
966 if ((ret = getvar_raw("...", &t)) == EVAL_OK)
967 if ((ret = eval(t)) != EVAL_OK)
968 return ret;
969 break;
971 case OP_ASSIGN:
972 ret = setvar(op->v.assign.name, op->v.assign.expr);
973 if (ret != EVAL_OK)
974 return ret;
975 break;
977 case OP_ASSERT:
978 if ((ret = eval(op->v.assert)) != EVAL_OK)
979 return ret;
980 popv(&a);
981 if (!val_trueish(&a)) {
982 before_printing();
983 printf("assertion failed: ");
984 pp_op(op->v.assert);
985 printf("\n");
986 return EVAL_ERR;
988 break;
990 case OP_FUNCALL:
991 /* assume airity matches */
993 proc = op->v.funcall.proc;
994 if (proc->nativefn != NULL) {
995 /*
996 * Push arguments on the stack for builtin
997 * functions. Counting the height of the
998 * stack is done to compute the correct number
999 * in the vararg case. argc only counts the
1000 * "syntactical" arguments, i.e. foo(x, ...)
1001 * has argc == 2, but at runtime argc may be
1002 * 1, 2 or a greater number!
1005 i = stackh;
1006 t = op->v.funcall.argv;
1007 if (t != NULL && (ret = eval(t)) != EVAL_OK)
1008 return ret;
1009 i = stackh - i;
1011 assert(i >= 0);
1013 if ((ret = proc->nativefn(i))
1014 != EVAL_OK)
1015 return ret;
1016 } else {
1017 if (proc->body == NULL) {
1018 before_printing();
1019 printf("warn: calling the empty proc `%s'\n",
1020 proc->name);
1021 break;
1024 pushenv();
1026 for (t = op->v.funcall.argv, i = 0;
1027 t != NULL;
1028 t = t->next, i++) {
1030 * Push a pseudo variable `...' (and
1031 * don't evaluate it) in the vararg
1032 * case. A special case is when the
1033 * variable is itself `...'.
1035 if (proc->vararg && i == proc->minargs) {
1036 if (t->type != OP_REST)
1037 setvar_raw(xstrdup("..."), t);
1038 break;
1042 * The arguments are a linked list of
1043 * ops. Setvar will call eval that
1044 * will evaluate *all* the arguments.
1045 * The dance here that sets next to
1046 * NULL and then restores it is to
1047 * avoid this behaviour.
1049 tnext = t->next;
1050 t->next = NULL;
1051 ret = setvar(proc->args[i], t);
1052 t->next = tnext;
1054 if (ret != EVAL_OK)
1055 return ret;
1058 if ((ret = eval(proc->body)) != EVAL_OK)
1059 return ret;
1061 popenv();
1064 break;
1066 case OP_LITERAL:
1067 pushv(&op->v.literal);
1068 break;
1070 case OP_VAR:
1071 if ((ret = getvar(op->v.var, &a)) != EVAL_OK)
1072 return ret;
1073 pushv(&a);
1074 break;
1076 case OP_CAST:
1077 if ((ret = eval(op->v.cast.expr)) != EVAL_OK)
1078 return ret;
1079 popv(&a);
1080 if ((ret = val_cast(&a, op->v.cast.totype)) != EVAL_OK)
1081 return ret;
1082 pushv(&a);
1083 break;
1085 case OP_CMP_EQ:
1086 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1087 return ret;
1088 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1089 return ret;
1091 popv(&b);
1092 popv(&a);
1093 pushbool(val_eq(&a, &b));
1094 break;
1096 case OP_CMP_LEQ:
1097 if ((ret = eval(op->v.bin_cmp.a)) != EVAL_OK)
1098 return ret;
1099 if ((ret = eval(op->v.bin_cmp.b)) != EVAL_OK)
1100 return ret;
1102 popv(&b);
1103 popv(&a);
1104 pushbool(val_leq(&a, &b));
1105 break;
1107 case OP_FACCESS:
1108 if ((ret = eval(op->v.faccess.expr)) != EVAL_OK)
1109 return ret;
1110 popv(&a);
1111 if ((ret = val_faccess(&a, op->v.faccess.field, &b))
1112 != EVAL_OK)
1113 return ret;
1114 pushv(&b);
1115 break;
1117 case OP_SFAIL:
1118 if ((ret = eval(op->v.sfail.expr)) == EVAL_OK) {
1119 before_printing();
1120 printf("expecting failure");
1121 if (op->v.sfail.msg != NULL)
1122 printf(" \"%s\"", op->v.sfail.msg);
1123 printf("\n");
1124 printf("expression: ");
1125 pp_op(op->v.sfail.expr);
1126 printf("\n");
1127 return EVAL_ERR;
1129 if (ret == EVAL_SKIP)
1130 return ret;
1131 break;
1133 case OP_VARGS:
1134 if ((ret = getvar_raw("...", &t)) == EVAL_OK) {
1135 for (i = 0; t != NULL; t = t->next)
1136 i++;
1137 pushnum(i);
1138 } else
1139 pushnum(0);
1140 break;
1142 default:
1143 before_printing();
1144 fprintf(stderr, "invalid op, aborting.\n");
1145 abort();
1148 if (op->next)
1149 return eval(op->next);
1150 return EVAL_OK;
1153 void
1154 prepare_funcall(void)
1156 pushstack(&args);
1159 void
1160 push_arg(struct op *op)
1162 push(&args, op);
1165 struct op *
1166 op_funcall(struct proc *proc)
1168 struct op *op, *argv;
1169 int argc;
1171 argv = finalize(&args, &argc);
1173 op = newop(OP_FUNCALL);
1174 op->v.funcall.proc = proc;
1175 op->v.funcall.argv = argv;
1176 op->v.funcall.argc = argc;
1178 return op;
1181 void
1182 add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg)
1184 struct proc *proc;
1186 proc = xcalloc(1, sizeof(*proc));
1187 proc->name = xstrdup(name);
1188 proc->nativefn = fn;
1189 proc->minargs = argc;
1190 proc->vararg = vararg;
1192 TAILQ_INSERT_HEAD(&procs, proc, entry);
1195 void
1196 prepare_proc(void)
1198 pushstack(&args);
1201 int
1202 proc_setup_body(void)
1204 struct opstack *argv;
1205 struct op *op;
1206 int i;
1208 argv = peek(&args);
1209 for (i = 0, op = argv->base.next; op != NULL; i++) {
1211 * TODO: should free the whole list on error but..,
1212 * we're gonna exit real soon(tm)!
1214 if (op->type != OP_VAR && op->type != OP_REST)
1215 return 0;
1217 op = op->next;
1220 assert(i == argv->counter);
1221 pushstack(&blocks);
1222 return 1;
1225 void
1226 proc_done(char *name)
1228 struct proc *proc;
1229 struct op *op, *next, *argv, *body;
1230 int i, argc;
1232 argv = finalize(&args, &argc);
1233 body = finalize(&blocks, NULL);
1235 proc = xcalloc(1, sizeof(*proc));
1236 proc->name = name;
1237 proc->minargs = argc;
1239 for (i = 0, op = argv; op != NULL; ++i) {
1240 if (op->type == OP_REST) {
1241 proc->vararg = 1;
1242 proc->minargs = i;
1243 break;
1246 proc->args[i] = xstrdup(op->v.var);
1248 next = op->next;
1249 free_op(op);
1250 op = next;
1252 assert(i == argc || (proc->vararg && i == proc->minargs));
1254 proc->body = body;
1256 TAILQ_INSERT_HEAD(&procs, proc, entry);
1259 void
1260 block_push(struct op *op)
1262 push(&blocks, op);
1265 struct proc *
1266 proc_by_name(const char *name)
1268 struct proc *p;
1270 TAILQ_FOREACH(p, &procs, entry) {
1271 if (!strcmp(p->name, name))
1272 return p;
1275 return NULL;
1278 void
1279 prepare_test(void)
1281 pushstack(&blocks);
1284 void
1285 test_done(int shouldfail, char *name)
1287 struct test *test;
1289 test = xcalloc(1, sizeof(*test));
1290 test->shouldfail = shouldfail;
1291 test->name = name;
1292 test->body = finalize(&blocks, NULL);
1294 if (TAILQ_EMPTY(&tests))
1295 TAILQ_INSERT_HEAD(&tests, test, entry);
1296 else
1297 TAILQ_INSERT_TAIL(&tests, test, entry);
1299 ntests++;
1302 static int
1303 builtin_print(int argc)
1305 struct value v;
1306 int i;
1308 before_printing();
1310 for (i = argc; i > 0; --i) {
1311 peekn(i, &v);
1312 if (v.type == V_STR)
1313 printf("%s", v.v.str);
1314 else
1315 pp_val(&v);
1316 printf(" ");
1319 printf("\n");
1321 popvn(argc);
1323 return EVAL_OK;
1326 static int
1327 builtin_debug(int argc)
1329 if (debug)
1330 return builtin_print(argc);
1332 popvn(argc);
1333 return EVAL_OK;
1336 static int
1337 builtin_skip(int argc)
1339 return EVAL_SKIP;
1342 static int
1343 builtin_iota(int argc)
1345 struct value v;
1347 v.type = V_U16;
1348 if ((v.v.u16 = ++lasttag) == 255)
1349 v.v.u16 = ++lasttag;
1351 pushv(&v);
1352 return EVAL_OK;
1355 static int
1356 builtin_send(int argc)
1358 struct ibuf *buf;
1359 struct value v;
1360 uint32_t len;
1361 uint16_t slen;
1362 int i;
1364 check_for_output();
1367 * Compute the length of the packet. 4 is for the initial
1368 * length field
1370 len = 4;
1372 for (i = argc; i > 0; --i) {
1373 peekn(i, &v);
1374 switch (v.type) {
1375 case V_STR:
1376 len += 2; /* count */
1377 len += strlen(v.v.str);
1378 break;
1380 case V_U8:
1381 len += 1;
1382 break;
1384 case V_U16:
1385 len += 2;
1386 break;
1388 case V_U32:
1389 len += 4;
1390 break;
1392 default:
1393 before_printing();
1394 printf("%s: can't serialize ", __func__);
1395 pp_val(&v);
1396 printf("\n");
1397 return EVAL_ERR;
1401 if (len > UINT16_MAX) {
1402 before_printing();
1403 printf("%s: message size too long: got %d when max is %d\n",
1404 __func__, len, UINT16_MAX);
1405 return EVAL_ERR;
1408 if ((buf = imsg_create(&ibuf, IMSG_BUF, 0, 0, len)) == NULL)
1409 fatal("imsg_create(%d)", len);
1411 len = htole32(len);
1412 imsg_add(buf, &len, sizeof(len));
1414 for (i = argc; i > 0; --i) {
1415 peekn(i, &v);
1416 switch (v.type) {
1417 case V_STR:
1418 slen = strlen(v.v.str);
1419 slen = htole16(slen);
1420 imsg_add(buf, &slen, sizeof(slen));
1421 imsg_add(buf, v.v.str, strlen(v.v.str));
1422 break;
1424 case V_U8:
1425 imsg_add(buf, &v.v.u8, 1);
1426 break;
1428 case V_U16:
1429 v.v.u16 = htole16(v.v.u16);
1430 imsg_add(buf, &v.v.u16, 2);
1431 break;
1433 case V_U32:
1434 v.v.u32 = htole32(v.v.u32);
1435 imsg_add(buf, &v.v.u32, 4);
1436 break;
1440 imsg_close(&ibuf, buf);
1442 if (imsg_flush(&ibuf) == -1) {
1443 i = errno;
1444 before_printing();
1445 printf("%s: imsg_flush failed: %s\n", __func__, strerror(i));
1446 return EVAL_ERR;
1449 check_for_output();
1450 return EVAL_OK;
1453 static int
1454 builtin_recv(int argc)
1456 struct pollfd pfd;
1457 struct value v;
1458 struct imsg imsg;
1459 ssize_t n, datalen;
1460 int serrno;
1462 if (lastmsg != NULL) {
1463 free(lastmsg);
1464 lastmsg = NULL;
1467 pfd.fd = ibuf.fd;
1468 pfd.events = POLLIN;
1469 if (poll(&pfd, 1, INFTIM) == -1) {
1470 serrno = errno;
1471 before_printing();
1472 printf("%s: poll failed: %s\n", __func__, strerror(serrno));
1473 return EVAL_ERR;
1476 again:
1477 if ((n = imsg_read(&ibuf)) == -1) {
1478 if (errno == EAGAIN)
1479 goto again;
1480 fatal("imsg_read");
1482 if (n == 0) {
1483 disconnect:
1484 before_printing();
1485 printf("child disconnected\n");
1486 return EVAL_ERR;
1489 nextmessage:
1490 check_for_output();
1492 /* read only one message */
1493 if ((n = imsg_get(&ibuf, &imsg)) == -1)
1494 fatal("imsg_get");
1495 if (n == 0)
1496 goto disconnect;
1498 datalen = imsg.hdr.len - IMSG_HEADER_SIZE;
1499 switch (imsg.hdr.type) {
1500 case IMSG_BUF:
1501 v.type = V_MSG;
1502 if ((v.v.msg.msg = malloc(datalen)) == NULL)
1503 fatal("malloc");
1504 memcpy(v.v.msg.msg, imsg.data, datalen);
1505 v.v.msg.len = datalen;
1506 pushv(&v);
1507 imsg_free(&imsg);
1508 return EVAL_OK;
1510 case IMSG_CLOSE:
1511 before_printing();
1512 printf("subprocess closed the connection\n");
1513 imsg_free(&imsg);
1514 return EVAL_ERR;
1516 case IMSG_MSIZE:
1517 imsg_free(&imsg);
1518 goto nextmessage;
1520 default:
1521 before_printing();
1522 printf("got unknown message from subprocess: %d\n",
1523 imsg.hdr.type);
1524 imsg_free(&imsg);
1525 return EVAL_ERR;
1529 static pid_t
1530 spawn_client_proc(void)
1532 const char *argv[4];
1533 int p[2], out[2], argc = 0;
1534 pid_t pid;
1536 if (child_out != -1)
1537 close(child_out);
1539 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1540 PF_UNSPEC, p) == -1)
1541 fatal("socketpair");
1543 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1544 PF_UNSPEC, out) == -1)
1545 fatal("socketpair");
1547 switch (pid = fork()) {
1548 case -1:
1549 fatal("cannot fork");
1550 case 0:
1551 break;
1552 default:
1553 close(p[1]);
1554 close(out[1]);
1555 child_out = out[0];
1556 if (ibuf_inuse) {
1557 msgbuf_clear(&ibuf.w);
1558 close(ibuf.fd);
1560 imsg_init(&ibuf, p[0]);
1561 ibuf_inuse = 1;
1562 return pid;
1565 close(p[0]);
1566 close(out[0]);
1568 if (dup2(out[1], 1) == -1 ||
1569 dup2(out[1], 2) == -1)
1570 fatal("dup2");
1572 if (p[1] != 3) {
1573 if (dup2(p[1], 3) == -1)
1574 fatal("cannot setup imsg fd");
1575 } else if (fcntl(F_SETFD, 0) == -1)
1576 fatal("cannot setup imsg fd");
1578 argv[argc++] = argv0;
1579 argv[argc++] = "-Tc";
1581 #if DEBUG
1582 argv[argc++] = "-v";
1583 #endif
1585 argv[argc++] = NULL;
1587 execvp(argv0, (char *const *)argv);
1588 fatal("execvp");
1591 static void
1592 prepare_child_for_test(struct test *t)
1594 struct passwd *pw;
1596 if ((pw = getpwuid(uid)) == NULL)
1597 fatal("getpwuid(%d)", uid);
1599 imsg_compose(&ibuf, IMSG_AUTH, 0, 0, -1,
1600 pw->pw_name, strlen(pw->pw_name)+1);
1601 imsg_compose(&ibuf, IMSG_AUTH_DIR, 0, 0, -1,
1602 dir, strlen(dir)+1);
1604 if (imsg_flush(&ibuf) == -1)
1605 fatal("imsg_flush");
1608 static int
1609 run_test(struct test *t)
1611 pid_t pid;
1612 int ret;
1614 #if DEBUG
1615 before_printing();
1616 puts("=====================");
1617 pp_block(t->body);
1618 puts("=====================");
1619 #endif
1621 if (stackh != 0)
1622 popvn(stackh);
1624 if (t->body == NULL) {
1625 before_printing();
1626 printf("no instructions, skipping...\n");
1627 return EVAL_SKIP;
1630 pid = spawn_client_proc();
1631 prepare_child_for_test(t);
1632 ret = eval(t->body);
1634 imsg_compose(&ibuf, IMSG_CONN_GONE, 0, 0, -1, NULL, 0);
1635 imsg_flush(&ibuf);
1637 while (waitpid(pid, NULL, 0) != pid)
1638 ; /* nop */
1640 check_for_output();
1642 if (t->shouldfail) {
1643 if (ret == EVAL_OK) {
1644 before_printing();
1645 printf("test was expected to fail\n");
1646 return EVAL_ERR;
1647 } else if (ret == EVAL_ERR)
1648 return EVAL_OK;
1651 return ret;
1654 int
1655 main(int argc, char **argv)
1657 struct stat sb;
1658 struct test *t;
1659 int ch, i, r, passed = 0, failed = 0, skipped = 0;
1660 int runclient = 0;
1661 const char *pat = NULL;
1662 regex_t reg;
1664 assert(argv0 = argv[0]);
1666 signal(SIGPIPE, SIG_IGN);
1668 log_init(1, LOG_DAEMON);
1669 log_setverbose(1);
1671 /* prepare the global env */
1672 pushenv();
1674 add_builtin_proc("print", builtin_print, 1, 1);
1675 add_builtin_proc("debug", builtin_debug, 1, 1);
1676 add_builtin_proc("skip", builtin_skip, 0, 0);
1677 add_builtin_proc("iota", builtin_iota, 0, 0);
1678 add_builtin_proc("send", builtin_send, 2, 1);
1679 add_builtin_proc("recv", builtin_recv, 0, 0);
1681 while ((ch = getopt(argc, argv, "nT:r:vx:")) != -1) {
1682 switch (ch) {
1683 case 'n':
1684 syntaxcheck = 1;
1685 break;
1686 case 'T':
1687 assert(*optarg == 'c');
1688 runclient = 1;
1689 break;
1690 case 'r':
1691 dir = optarg;
1692 break;
1693 case 'v':
1694 debug = 1;
1695 break;
1696 case 'x':
1697 pat = optarg;
1698 break;
1699 default:
1700 fprintf(stderr, "Usage: %s [-nv] [files...]\n",
1701 *argv);
1702 exit(1);
1705 argc -= optind;
1706 argv += optind;
1708 if (runclient)
1709 client(1, debug);
1711 if (dir == NULL)
1712 fatal("missing root test dir");
1714 if (stat(dir, &sb) == -1)
1715 fatal("stat(\"%s\")", dir);
1716 uid = sb.st_uid;
1718 if (pat == NULL)
1719 pat = ".*";
1721 if (regcomp(&reg, pat, REG_ICASE | REG_NOSUB) != 0)
1722 fatalx("invalid regexp: %s", pat);
1724 for (i = 0; i < argc; ++i)
1725 loadfile(argv[i]);
1727 if (syntaxcheck) {
1728 fprintf(stderr, "files OK\n");
1729 return 0;
1732 /* Check for root privileges. */
1733 if (geteuid())
1734 fatalx("need root privileges");
1736 i = 0;
1737 TAILQ_FOREACH(t, &tests, entry) {
1738 if (regexec(&reg, t->name, 0, NULL, 0) != 0)
1739 continue;
1741 printf("===> [%d/%d] running test \"%s\"... ", i+1, ntests,
1742 t->name);
1743 fflush(stdout);
1745 filler = "\n";
1746 r = run_test(t);
1747 if (filler == NULL)
1748 printf("=> test ");
1750 switch (r) {
1751 case EVAL_OK:
1752 printf("passed\n");
1753 passed++;
1754 break;
1755 case EVAL_ERR:
1756 failed++;
1757 printf("failed\n");
1758 break;
1759 case EVAL_SKIP:
1760 printf("skipped\n");
1761 skipped++;
1762 break;
1765 if (filler == NULL)
1766 printf("\n");
1767 i++;
1770 printf("\n");
1771 printf("%d/%d passed (%d skipped and %d failed)\n",
1772 passed, i, skipped, failed);
1774 popenv();
1775 free(lastmsg);
1776 regfree(&reg);
1778 return failed != 0;