1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
/*
 * Sai server - src/server/notification.c
 *
 * Copyright (C) 2019 - 2025 Andy Green <andy@warmcat.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation:
 *  version 2.1 of the License.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *  MA  02110-1301  USA
 *
 * The same ws interface is connected-to by builders (on path /builder), and
 * provides the query transport for browsers (on path /browse).
 */

#include <libwebsockets.h>
#include "s-private.h"

/* starts from +1 of sai_notification_action_t */

static const char *notifaction_action_names[] = {
	"repo-update"
};

static const char * const paths[] = {
	"schema",
	"action",
	"repository.name",
	"repository.fetchurl",
	"repository.weburl",
	"ref",
	"hash",
	"nonce",
	"saifile_len",
	"saifile",
	"sec",
};

enum enum_paths {
	LEJPN_SCHEMA,
	LEJPN_ACTION,
	LEJPN_REPOSITORY_NAME,
	LEJPN_REPOSITORY_FETCHURL,
	LEJPN_REPOSITORY_WEBURL,
	LEJPN_REF,
	LEJPN_HASH,
	LEJPN_NONCE,
	LEJPN_SAIFILE_LEN,
	LEJPN_SAIFILE,
	LEJPN_SEC,
};

/*
 * Security: git refs, hashes, repository names and fetch URLs arrive in signed
 * hook notifications but their values are controlled by whoever can push to the
 * watched repo.  They are later interpolated into shell scripts on the builder
 * (b-nspawn.c export SAI_REMOTE_REF / git_helper.sh invocation) and into
 * filesystem paths.  Reject any value containing shell metacharacters or
 * control bytes here at the only ingress point, before it can reach task
 * creation or the builder.
 *
 * The validation helpers (sai_str_has_shell_metachars, sai_is_git_hash,
 * sai_is_safe_ref) live in src/common/c-utils.c and are shared with s-task.c
 * for defense-in-depth re-checks at task-offer time.
 */

/*
 * Saifile parser
 */

static const char * const saifile_paths[] = {
	"schema",
	"platforms.*.build[]",
	"platforms.*.build",
	"platforms.*.build.*",
	"platforms.*.default",
	"platforms.*",
	"configurations.*.prep",
	"configurations.*.cmake",
	"configurations.*.deps",
	"configurations.*.platforms",
	"configurations.*.artifacts",
	"configurations.*.cpack",
	"configurations.*.branches",
	"configurations.*.task_log_limit",
	"configurations.*.idle",
	"configurations.*.pool",
	"configurations.*",
};

enum enum_saifile_paths {
	LEJPNSAIF_SCHEMA,
	LEJPNSAIF_PLAT_BUILD_STAGE,
	LEJPNSAIF_PLAT_BUILD,
	LEJPNSAIF_PLAT_BUILD_ELEMENT,
	LEJPNSAIF_PLAT_DEFAULT,
	LEJPNSAIF_PLAT_NAME,
	LEJPNSAIF_CONFIGURATIONS_PREP,
	LEJPNSAIF_CONFIGURATIONS_CMAKE,
	LEJPNSAIF_CONFIGURATIONS_DEPS,
	LEJPNSAIF_CONFIGURATIONS_PLATFORMS,
	LEJPNSAIF_CONFIGURATIONS_ARTIFACTS,
	LEJPNSAIF_CONFIGURATIONS_CPACK,
	LEJPNSAIF_CONFIGURATIONS_BRANCHES,
	LEJPNSAIF_CONFIGURATIONS_TASK_LOG_LIMIT,
	LEJPNSAIF_CONFIGURATIONS_IDLE,
	LEJPNSAIF_CONFIGURATIONS_POOL,
	LEJPNSAIF_CONFIGURATIONS_NAME,
};

/* do the string subst for ${cmake} etc */

static int
exp_cmake(void *priv, const char *name, char *out, size_t *pos, size_t olen,
	  size_t *exp_ofs)
{
	sai_notification_t *sn = (sai_notification_t *)priv;
	const char *replace = NULL;
	size_t replace_len, rem_out;

	if (!strcmp(name, "prep")) {
		replace = sn->t.prep;
		replace_len = strlen(sn->t.prep);
		goto expand;
	}

	if (!strcmp(name, "cmake")) {
		replace = sn->t.cmake;
		replace_len = strlen(sn->t.cmake);
		goto expand;
	}

	if (!strcmp(name, "cpack")) {
		replace = sn->t.cpack;
		replace_len = strlen(sn->t.cpack);
		goto expand;
	}

	return LSTRX_FATAL_NAME_UNKNOWN;

expand:
	rem_out = olen - *pos;		/* remaining rhs */
	replace_len -= *exp_ofs;
	if (replace_len < rem_out)
		rem_out = replace_len;

	memcpy(out + *pos, replace + (*exp_ofs), rem_out);
	*exp_ofs += rem_out;
	*pos += rem_out;

	if (rem_out == replace_len)
		return LSTRX_DONE;

	return LSTRX_FILLED_OUT;
}

static int
arg_to_bool(const char *s)
{
	static const char * const on[] = { "on", "yes", "true" };
	int n = atoi(s);

	if (n)
		return 1;

	for (n = 0; n < (int)LWS_ARRAY_SIZE(on); n++)
		if (!strcasecmp(s, on[n]))
			return 1;

	return 0;
}

static int
sai_tuple_element_compare(const char *e1, const char *e2)
{
	const char *p;

	// lwsl_notice("%s: comp '%s' '%s'\n", __func__, e1, e2);

	if (strlen(e1) > strlen(e2))
		/* can't match if req is longer than plat */
		return -1;

	p = strchr(e2, '/');
	if (p && lws_ptr_diff(p, e2) < (int)strlen(e1))
		/* e2 contains a / section terminal inside e1 scope */
		return 1;

	return strncmp(e1, e2, strlen(e1));
}

static int
sai_tuple_compare(const char *req, size_t req_len, const char *plat)
{
	const char *pos = req;
	char e1[96];
	int n;

	do {
		n = 0;
		while (n < (int)sizeof(e1) - 1 && req_len && *pos != '/') {
			e1[n++] = *pos++;
			req_len--;
		}
		e1[n] = '\0';
		if (*pos == '/' && req_len) {
			req_len--;
			pos++;
		}

		if (n == sizeof(e1) - 1) {
			// lwsl_notice("%s: NOMATCH 3 '%s' '%s'\n", __func__, req, plat);
			/* element too long */
			return 1;
		}

		if (n && /* let it pass if empty match section, eg, linux//gcc */
		    sai_tuple_element_compare(e1, plat)) {
			// lwsl_notice("%s: NOMATCH 2 '%s' '%s'\n", __func__, req, plat);
			/* section does not match */
			return 1;
		}

		while (*plat && *plat != '/')
			plat++;
		if (*plat == '/')
			plat++;

		if (!*plat && req_len) {
			// lwsl_notice("%s: NOMATCH 1 '%s' '%s'\n", __func__, req, plat);
			/* FAIL: req had more than we had */
			return 1;
		}

		if (!req_len) {
			// lwsl_notice("%s: MATCH '%s' '%s'\n", __func__, req, plat);
			/* MATCH: we matched at least as far as we had */
			return 0;
		}

	} while (1);

	return 1;
}

/*
 * We parse the saifile JSON
 *
 * The backdrop of this is the remote's hook that's letting us know all this
 * won't update his refs to the push described here until he's finished
 * uploading the saifile POST.
 *
 * So although we are going to add the tasks as we parse them, in fact we
 * can't hand any of them out to builders until a short time after we got to
 * the end of the POST, otherwise the builders are not going to find the
 * right refs in the repo yet.
 */

static signed char
sai_saifile_lejp_cb(struct lejp_ctx *ctx, char reason)
{
	struct pss *pss = (struct pss *)ctx->user;
	sai_notification_t *sn = (sai_notification_t *)&pss->sn;
	sqlite3 *pdb = NULL;
	size_t n;

	// lwsl_notice("%s: reason %d, %s\n", __func__, reason, ctx->path);

	if (reason == LEJPCB_COMPLETE) {

		if (!pss->dry)
			lwsl_notice("%s: saifile decode completed\n", __func__);

		return 0;
	}

	if (reason == LEJPCB_OBJECT_START &&
	    ctx->path_match - 1 == LEJPNSAIF_CONFIGURATIONS_NAME) {
		/*
		 * We're at the testname part of "testname" : { }
		 */
		lws_strncpy(sn->t.taskname, &ctx->path[15],
			    sizeof(sn->t.taskname));
		sn->t.prep[0]			= '\0';
		sn->t.packages[0]		= '\0';
		sn->t.cmake[0]			= '\0';
		sn->t.cpack[0]			= '\0';
		sn->t.artifacts[0]		= '\0';
		sn->t.branches[0]		= '\0';
		sn->explicit_platforms[0]	= '\0';
		sn->idle_lanes			= 0;
		sn->t.pool[0]			= '\0';
		return 0;
	}

	if (reason == LEJPCB_OBJECT_END &&
	    ctx->path_match - 1 == LEJPNSAIF_CONFIGURATIONS_NAME &&
	    sn->t.taskname[0]) {
		char *err;

		/*
		 * We're at the testname part of "testname" : { }
		 */
		if (pss->dry) {
			sn->t.taskname[0] = '\0';

			return 0;
		}

		/*
		 * Iterate through each platform creating task entries for this
		 * configuration customized for each platform... first time just
		 * check the string subst for all of them is OK...
		 */

		lwsl_notice("%s: Creating task entries for notification\n", __func__);

		lws_start_foreach_dll(struct lws_dll2 *, p,
					   pss->platform_owner.head) {
			sai_platform_t *pl =
				lws_container_of(p, sai_platform_t, list);
			size_t used_in, used_out;
			struct lws_tokenize ts;
			int n, match = 0;
			lws_strexp_t sx;

			if (!pl->nondefault)
				/*
				 * If it's a default platform, then match
				 * by default
				 */
				match = 1;

			/*
			 * The configuration restricts itself to only
			 * existing on certain branches?
			 */

			if (sn->t.branches[0]) {
				char ref[256];

				lws_snprintf(ref, sizeof(ref), "refs/heads/%s", sn->t.branches);

				if (strcmp(ref, sn->e.ref)) {
					lwsl_notice("%s: config %s skipped as only applies to %s not %s\n",
							__func__, sn->t.taskname, ref, sn->e.ref);
					goto next_plat;
				}
			}

			if (sn->explicit_platforms[0]) {
				char not = 0;

				/*
				 * If the configuration gives explicit
				 * platforms, we have to filter the platform
				 * against the comma-separated list.
				 *
				 * "none" - don't match any plats just because
				 *	    they are default
				 *
				 * "not plat" - disallow specific plat "plat",
				 *		implies you're not using "none"
				 *
				 * "plat" - allow specific plat "plat"
				 */
				memset(&ts, 0, sizeof(ts));
				ts.start = (char *)sn->explicit_platforms;
				ts.len = strlen(ts.start);
				ts.flags = LWS_TOKENIZE_F_DOT_NONTERM |
					   LWS_TOKENIZE_F_SLASH_NONTERM |
					   LWS_TOKENIZE_F_MINUS_NONTERM;
				do {
					ts.e = (int8_t)lws_tokenize(&ts);
					if (ts.e != LWS_TOKZE_TOKEN)
						continue;

			//		lwsl_notice("%s: check %.*s\n", __func__,
			//			    (int)ts.token_len, ts.token);

					if (!strncmp(ts.token, "none",
						     ts.token_len)) {
						not = 0;
						match = 0;
						continue;
					}
					if (!strncmp(ts.token, "not",
						     ts.token_len)) {
						not = 1;
						continue;
					}
					/*
					 * We need to check with per-slash
					 * minimal matching, ie, "linux"
					 * matches "linux-ubuntu/x86_64/gcc"
					 */
					if (!sai_tuple_compare(ts.token,
						     ts.token_len, pl->name)) {
						match = !not;
						if (match)
							break;
					}
					not = 0;
				} while (ts.e > 0);
			}

			if (match) {

				/*
				 * The platform build string (pl->build) is the
				 * base, with optional entries like ${cmake}
				 * that are filled in with the corresponding
				 * info from the specific configuration's
				 * "cmake" entry (sn->t.cmake)...
				 *
				 * sn->t.build becomes the string-substituted
				 * copy that is serialized
				 */

				lws_strexp_init(&sx, sn, exp_cmake, sn->t.build,
						sizeof(sn->t.build));

				n = lws_strexp_expand(&sx, pl->build,
						      strlen(pl->build),
						      &used_in, &used_out);
				if (n != LSTRX_DONE) {
					lwsl_notice("%s: strsubst fail n=%d %s %s\n",
						    __func__, n, pl->build,
						    sn->t.cmake);
					return -1;
				}
			}

next_plat: ;

		} lws_end_foreach_dll(p);

		/*
		 * ...now we know the string handling will go well, create the
		 * event database file and create task entries in there for this
		 * configuration's tasks for each platform
		 */

		if (sai_event_db_ensure_open(pss->vhd->context, &pss->vhd->sqlite3_cache,
				      pss->vhd->sqlite3_path_lhs, pss->sn.e.uuid, 1, &pdb)) {
			lwsl_err("%s: unable to open event-specific db\n", __func__);
			return -1;
		}

		sqlite3_exec(pdb, "BEGIN TRANSACTION", NULL, NULL, &err);
		if (err)
			sqlite3_free(err);

		lws_start_foreach_dll(struct lws_dll2 *, p,
					   pss->platform_owner.head) {
			sai_platform_t *pl =
				lws_container_of(p, sai_platform_t, list);
			size_t used_in, used_out;
			struct lws_tokenize ts;
			int n, match = 0;
			lws_strexp_t sx;

			if (!pl->nondefault)
				/*
				 * If it's a nondefault platform, then match
				 * by default
				 */
				match = 1;

			if (sn->explicit_platforms[0]) {
				char not = 0;

				/*
				 * If the configuration gives explicit
				 * platforms, we have to filter the platform
				 * against the comma-separated list.
				 *
				 * "none" - don't match any plats just because
				 *	    they are default
				 *
				 * "not plat" - disallow specific plat "plat",
				 *		implies you're not using "none"
				 *
				 * "plat" - allow specific plat "plat"
				 */

				memset(&ts, 0, sizeof(ts));
				ts.start = (char *)sn->explicit_platforms;
				ts.len = strlen(ts.start);
				ts.flags = LWS_TOKENIZE_F_DOT_NONTERM |
					   LWS_TOKENIZE_F_SLASH_NONTERM |
					   LWS_TOKENIZE_F_MINUS_NONTERM;

				do {
					ts.e = (int8_t)lws_tokenize(&ts);
					if (ts.e != LWS_TOKZE_TOKEN)
						continue;

			//		lwsl_notice("%s: check %.*s\n", __func__,
			//			    (int)ts.token_len, ts.token);

					if (!strncmp(ts.token, "none",
						     ts.token_len)) {
						not = 0;
						match = 0;
						continue;
					}
					if (!strncmp(ts.token, "not",
						     ts.token_len)) {
						not = 1;
						continue;
					}
					if (!sai_tuple_compare(ts.token,
						     ts.token_len, pl->name)) {
						match = !not;
						if (match)
							break;
					}
					not = 0;
				} while (ts.e > 0);
			}

			if (match) {
				/*
				 * For this platform, we want to create a task
				 * associated with this event.  Tasks and logs
				 * associated with an event go in an event-
				 * specific database file for scalability.
				 */

				lws_strexp_init(&sx, sn, exp_cmake, sn->t.build,
						sizeof(sn->t.build));

				n = lws_strexp_expand(&sx, pl->build,
						      strlen(pl->build),
						      &used_in, &used_out);
				if (n != LSTRX_DONE) {
					lwsl_notice("%s: strsubst failed %s %s\n",
						    __func__, pl->build,
						    sn->t.cmake);
					sqlite3_exec(pdb, "END TRANSACTION", NULL, NULL, &err);
					if (err)
						sqlite3_free(err);
					sai_event_db_close(&pss->vhd->sqlite3_cache, &pdb);
					return -1;
				}

				lws_strncpy(pss->sn.t.platform, pl->name,
					    sizeof(pss->sn.t.platform));

				/*
				 * Mint the uuids / nonces and create the task
				 * in the event-specific database
				 */
				pss->sn.t.idle = 0;
				if (sais_task_insert(lws_get_context(pss->wsi),
						     pdb, &pss->sn.e, &pss->sn.t,
						     pss->sn.event_task_index++) < 0)
					goto insert_fail;

				/*
				 * ... and the idle tasks ("lanes") the
				 * configuration asks for on this platform, if
				 * any.  They are the same task, but only run
				 * later in idle time, see s-idle.c
				 */

				for (n = 0; n < sn->idle_lanes; n++) {
					pss->sn.t.idle = 1;
					if (sais_task_insert(lws_get_context(pss->wsi),
							     pdb, &pss->sn.e, &pss->sn.t,
							     pss->sn.event_task_index++) < 0)
						goto insert_fail;
					sn->e.idle++;
				}
				pss->sn.t.idle = 0;
			}

		} lws_end_foreach_dll(p);

		sqlite3_exec(pdb, "END TRANSACTION", NULL, NULL, &err);
		if (err)
			sqlite3_free(err);

		sai_event_db_close(&pss->vhd->sqlite3_cache, &pdb);

		/*
		 * Recompute startable task platforms and broadcast to all sai-power,
		 * after there has been a change in tasks
		 */
		sais_platforms_with_tasks_pending(pss->vhd);

		sn->t.taskname[0] = '\0';
		return 0;

insert_fail:
		lwsl_err("%s: task insert failed\n", __func__);
		pss->sn.t.idle = 0;
		sqlite3_exec(pdb, "END TRANSACTION", NULL, NULL, &err);
		if (err)
			sqlite3_free(err);
		sai_event_db_close(&pss->vhd->sqlite3_cache, &pdb);

		return -1;
	}

	if (reason == LEJPCB_OBJECT_START &&
	    ctx->path_match - 1 == LEJPNSAIF_PLAT_NAME) {
		/*
		 * We're at the platformname part of "platformname" : { }
		 */
		lws_strncpy(sn->platname, &ctx->path[10], sizeof(sn->platname));
		sn->t.prep[0] = '\0';
		sn->t.cmake[0] = '\0';
		sn->t.cpack[0] = '\0';
		sn->platbuild[0] = '\0';
		sn->nondefault = 0;
		return 0;
	}

	if (reason == LEJPCB_OBJECT_END &&
	    ctx->path_match - 1 == LEJPNSAIF_PLAT_NAME &&
	    sn->platname[0] && sn->platbuild[0]) {
		sai_platform_t *pl;
		uint8_t *plb;
		size_t pnl;

		if (pss->dry) {
			sn->t.platform[0] = '\0';
			return 0;
		}

		/*
		 * We create a platform object with space for its strings after
		 */

		pnl = strlen(sn->platname);
		pl = (sai_platform_t *)malloc(sizeof(*pl) + pnl +
					      strlen(sn->platbuild) + 2);
		if (!pl)
			return -1;

		memset(pl, 0, sizeof(*pl));
		plb = (uint8_t *)&pl[1];

		/*
		 * Platforms are malloc'd up and added to pss
		 * .platform_owner
		 */

		pl->name = (const char *)plb;
		memcpy(plb, sn->platname, pnl + 1);
		plb += pnl + 1;

		pl->build = (const char *)plb;
		memcpy(plb, sn->platbuild, strlen(sn->platbuild) + 1);

		pl->nondefault = sn->nondefault;

		lws_dll2_add_head(&pl->list, &pss->platform_owner);

//		lwsl_notice("%s: New platform '%s', build '%s', notdefault %d\n",
//			    __func__, pl->name, pl->build, pl->nondefault);

		sn->platbuild[0] = '\0';
		return 0;
	}

	if (ctx->path_match - 1 == LEJPNSAIF_PLAT_BUILD_STAGE &&
	    reason == LEJPCB_VAL_STR_START) {
		n = strlen(sn->platbuild);

		if (n && n < sizeof(sn->platbuild) - 2) {
			sn->platbuild[n++] = '\n';
			sn->platbuild[n] = '\0';
		}
		return 0;
	}

	/* we only match on the prepared path strings */
	if (!(reason & LEJP_FLAG_CB_IS_VALUE) || !ctx->path_match)
		return 0;

	/*
	 * Some of these will be long strings, accept all the string parts
	 * and accumilate them
	 */

	switch (ctx->path_match - 1) {
	case LEJPNSAIF_SCHEMA:
		sn->event_task_index = 0;
		return 0;

	case LEJPNSAIF_CONFIGURATIONS_PREP:
		/* the additional cmake options for this test configuration */
		n = strlen(sn->t.prep);
		if (n < sizeof(sn->t.prep) - 2)
			lws_strnncpy(sn->t.prep + n, ctx->buf, ctx->npos,
				     sizeof(sn->t.prep) - n);
		break;

	case LEJPNSAIF_CONFIGURATIONS_CMAKE:
		/* the additional cmake options for this test configuration */
		n = strlen(sn->t.cmake);
		if (n < sizeof(sn->t.cmake) - 2)
			lws_strnncpy(sn->t.cmake + n, ctx->buf, ctx->npos,
				     sizeof(sn->t.cmake) - n);
		break;

	case LEJPNSAIF_CONFIGURATIONS_DEPS:
		/* the necessary dependent package strings */
		n = strlen(sn->t.packages);
		if (n < sizeof(sn->t.packages) - 2) {
			if (n)
				sn->t.packages[n++] = ',';
			lws_strncpy(sn->t.packages + n, ctx->buf,
				    sizeof(sn->t.packages) - n);
		}
		break;

	case LEJPNSAIF_CONFIGURATIONS_PLATFORMS:
		/* the necessary dependent package strings... can be huge */
		n = strlen(sn->explicit_platforms);
		if (n < sizeof(sn->explicit_platforms) - 2)
			lws_strnncpy(sn->explicit_platforms + n, ctx->buf, ctx->npos,
				     sizeof(sn->explicit_platforms) - n);
		break;

	case LEJPNSAIF_CONFIGURATIONS_ARTIFACTS:
		lws_strncpy(sn->t.artifacts, ctx->buf, sizeof(sn->t.artifacts));
		/*
		 * The builder scans these globs under the task's instance dir
		 * and renames what matches into its uploads dir, for publish
		 * as downloadable artifacts.  Reject path escapes at intake
		 * like the other hostile-field cases; the builder checks
		 * again on its side.
		 */
		if (!sai_artifacts_list_safe(sn->t.artifacts)) {
			lwsl_notice("%s: rejecting artifacts list with path "
				    "escape '%s'\n", __func__, sn->t.artifacts);
			return -1;
		}
		break;

	case LEJPNSAIF_CONFIGURATIONS_CPACK:
		n = strlen(sn->t.cpack);
		if (n < sizeof(sn->t.cpack) - 2)
			lws_strnncpy(sn->t.cpack + n, ctx->buf, ctx->npos,
				     sizeof(sn->t.cpack) - n);
		break;

	case LEJPNSAIF_CONFIGURATIONS_BRANCHES:
		lws_strncpy(sn->t.branches, ctx->buf, sizeof(sn->t.branches));
		break;

	case LEJPNSAIF_CONFIGURATIONS_TASK_LOG_LIMIT:
		sn->t.task_log_limit = (unsigned int)atoi(ctx->buf);
		break;

	case LEJPNSAIF_CONFIGURATIONS_IDLE:
		/*
		 * How many idle tasks ("lanes") to create for this
		 * configuration on each platform it runs on, in addition to
		 * the normal task.  Each lane can have an idle builder
		 * working on it at the same time.
		 */
		sn->idle_lanes = atoi(ctx->buf);
		if (sn->idle_lanes < 0)
			sn->idle_lanes = 0;
		if (sn->idle_lanes > SAI_IDLE_LANES_MAX)
			sn->idle_lanes = SAI_IDLE_LANES_MAX;
		break;

	case LEJPNSAIF_CONFIGURATIONS_POOL:
		/*
		 * The repo's named pool the configuration's tasks work with,
		 * which builders keep synced with us while they run them.  It
		 * becomes a path component on the builder and part of our db
		 * filename, so it has to be a plain short name.
		 */
		lws_strncpy(sn->t.pool, ctx->buf, sizeof(sn->t.pool));
		if (ctx->npos >= sizeof(sn->t.pool) ||
		    !sai_pool_name_ok(sn->t.pool)) {
			lwsl_notice("%s: rejecting pool name '%s'\n",
				    __func__, sn->t.pool);
			return -1;
		}
		break;

	case LEJPNSAIF_PLAT_BUILD:
	case LEJPNSAIF_PLAT_BUILD_STAGE:
		/*
		 * The overall build script for this platform
		 * is appended into the temp sn.platbuild
		 */

		lwsl_err("%s: LEJPNSAIF_PLAT_BUILD_STAGE: %.*s\n", __func__, (int)ctx->npos, (const char *)ctx->buf);

		n = strlen(sn->platbuild);
		if (n < sizeof(sn->platbuild) - 2 && ctx->npos)
			lws_strnncpy(sn->platbuild + n, ctx->buf, ctx->npos,
				     sizeof(sn->platbuild) - n);
		break;

	case LEJPNSAIF_PLAT_BUILD_ELEMENT:
		n = strlen(sn->platbuild);
		if (n) {
			if (n > sizeof(sn->platbuild) - 2)
				break;
			sn->platbuild[n++] = '\n';
		}
		if (n < sizeof(sn->platbuild) - 2)
			lws_strnncpy(sn->platbuild + n, ctx->buf, ctx->npos,
				     sizeof(sn->platbuild) - n);
		break;

	case LEJPNSAIF_PLAT_DEFAULT:
		sn->nondefault = !arg_to_bool(ctx->buf);
		break;

	default:
		return 0;
	}

	return 0;
}

static signed char
sai_notification_lejp_cb(struct lejp_ctx *ctx, char reason)
{
	struct pss *pss = (struct pss *)ctx->user;
	sai_notification_t *sn = (sai_notification_t *)&pss->sn;
	size_t ile, ole;
	int n;

	/* we only match on the prepared path strings */
	if (!(reason & LEJP_FLAG_CB_IS_VALUE) || !ctx->path_match)
		return 0;

//	if (reason != LEJPCB_VAL_STR_END)
//		return 0;

	/* only the end part of the string, where we know the length */

	switch (ctx->path_match - 1) {
	case LEJPN_SCHEMA:
		if (strcmp(ctx->buf, "com-warmcat-sai-notification")) {
			lwsl_err("%s: unknown schema '%s'\n", __func__, ctx->buf);
			return -1;
		}
		return 0;

	case LEJPN_ACTION:
		for (n = 0; n < (int)LWS_ARRAY_SIZE(notifaction_action_names);n++)
			if (!strcmp(ctx->buf, notifaction_action_names[n])) {
				sn->action = (sai_notification_action_t)(n + 1);

				return 0;
			}
		lwsl_notice("%s: unknown action '%s' ignored\n",
			    __func__, ctx->buf);
		return -1;

	case LEJPN_REPOSITORY_NAME:
		if (sai_str_has_shell_metachars(ctx->buf)) {
			lwsl_notice("%s: rejecting repo name with shell "
				    "metachars\n", __func__);
			return -1;
		}
		lws_strncpy(sn->e.repo_name, ctx->buf, sizeof(sn->e.repo_name));
		break;

	case LEJPN_REPOSITORY_FETCHURL:
		/*
		 * fetchurl is interpolated into filesystem path and later
		 * used by git on the builder; reject shell metachars.  URLs
		 * legitimately contain ':' '/' '.' etc which we allow.
		 */
		if (sai_str_has_shell_metachars(ctx->buf)) {
			lwsl_notice("%s: rejecting fetchurl with shell "
				    "metachars\n", __func__);
			return -1;
		}
		lws_strncpy(sn->e.repo_fetchurl, ctx->buf,
			    sizeof(sn->e.repo_fetchurl));
		break;

	case LEJPN_REPOSITORY_WEBURL:
		/*
		 * weburl is optional, and only used to build links to the
		 * repo's web ui (eg, gitohashi) in the browser.  Since repo
		 * data is attacker-influenced and this becomes an href, only
		 * accept a clean http(s) URL... anything else is dropped and
		 * the event stored without a weburl rather than rejecting the
		 * whole notification over a UI nicety.
		 */
		sn->e.repo_weburl[0] = '\0';

		if ((!strncasecmp(ctx->buf, "https://", 8) ||
		     !strncasecmp(ctx->buf, "http://", 7)) &&
		    !sai_str_has_shell_metachars(ctx->buf))
			lws_strncpy(sn->e.repo_weburl, ctx->buf,
				    sizeof(sn->e.repo_weburl));
		else
			lwsl_notice("%s: ignoring weburl '%s'\n",
				    __func__, ctx->buf);
		break;

	case LEJPN_REF:
		lws_strncpy(sn->e.ref, ctx->buf, sizeof(sn->e.ref));
		/*
		 * The ref is exported unquoted into SAI_REMOTE_REF and passed
		 * to git_helper.sh on the builder; it MUST be a safe refname.
		 */
		if (!sai_is_safe_ref(sn->e.ref)) {
			lwsl_notice("%s: rejecting unsafe ref '%s'\n",
				    __func__, sn->e.ref);
			return -1;
		}
		break;

	case LEJPN_SEC:
		sn->e.sec = 1;
		break;

	case LEJPN_HASH:
		lws_strncpy(sn->e.hash, ctx->buf, sizeof(sn->e.hash));
		/* git object hashes are hex-only; anything else is rejected */
		if (!sai_is_git_hash(sn->e.hash)) {
			lwsl_notice("%s: rejecting non-hex hash '%s'\n",
				    __func__, sn->e.hash);
			return -1;
		}
		break;

	case LEJPN_NONCE:
		break;

	case LEJPN_SAIFILE_LEN:
		sn->saifile_in_len = (unsigned int)atoi(ctx->buf);
		/* only accept sane base64 size */
		if (sn->saifile_in_len < 8 || sn->saifile_in_len > 65536) {
			lwsl_err("%s: bad saifile_len %u\n", __func__,
					(unsigned int)sn->saifile_in_len);

			return -1;
		}
		sn->saifile_out_len = (sn->saifile_in_len * 3) / 4 + 4;
		sn->saifile = malloc(sn->saifile_out_len);
		if (!sn->saifile) {
			lwsl_err("%s: OOM\n", __func__);

			return -1;
		}
		/*
		 * Caller must take responsibility for sn->saifile allocation
		 */
		sn->saifile_in_seen = sn->saifile_out_pos = 0;
		lws_b64_decode_state_init(&sn->b64);
		break;

	case LEJPN_SAIFILE:
		/*
		 * Base64 encoding of the commit's .sai.json file contents... we
		 * have to treat this with caution since it can be anything,
		 * including unparsable JSON.
		 *
		 * Let's base64-decode it and collect it into an buffer first,
		 * before sn test parse and then sn second parse to extract the
		 * tasks
		 */

		sn->saifile_in_seen += ctx->npos;
		if (sn->saifile_in_seen > sn->saifile_in_len) {
			lwsl_err("%s: SAIFILE: too large in %u vs %u\n", __func__,
				 (unsigned int)sn->saifile_in_seen,
				 (unsigned int)sn->saifile_in_len);
			return -1;
		}
		ile = ctx->npos;
		ole = sn->saifile_out_len - sn->saifile_out_pos;
		lws_b64_decode_stateful(&sn->b64, ctx->buf, &ile,
				(uint8_t *)sn->saifile + sn->saifile_out_pos, &ole,
					sn->saifile_in_seen == sn->saifile_in_len);

		sn->saifile_out_pos += ole;
		break;

	default:
		return 0;
	}

	return 0;
}

int
sai_notification_file_upload_cb(void *data, const char *name,
				const char *filename, char *buf, int len,
				enum lws_spa_fileupload_states state)
{
	struct pss *pss = (struct pss *)data;
	struct lejp_ctx saictx;
	lws_dll2_owner_t owner;
	uint8_t result[64];
	int m;

	switch (state) {
	case LWS_UFS_OPEN:
		lwsl_notice("%s: LWS_UFS_OPEN\n", __func__);
		lejp_construct(&pss->ctx, sai_notification_lejp_cb,
			       pss, paths, LWS_ARRAY_SIZE(paths));

		if (lws_genhmac_init(&pss->hmac, pss->hmac_type,
				      (uint8_t *)pss->vhd->notification_key,
				      strlen(pss->vhd->notification_key))) {
			lwsl_err("%s: failed to init hmac\n", __func__);

			return -1;
		}
		break;
	case LWS_UFS_FINAL_CONTENT:
	case LWS_UFS_CONTENT:
		lwsl_notice("%s: LWS_UFS_[]CONTENT: %p %p, \n", __func__, pss, buf);
		if (len && lws_genhmac_update(&pss->hmac, buf, (unsigned int)len))
			return -1;

		m = lejp_parse(&pss->ctx, (uint8_t *)buf, len);
		if (m < 0 && m != LEJP_CONTINUE) {
			lwsl_notice("%s: notif JSON decode failed '%s' (%d)\n",
					__func__, lejp_error_to_string(m), m);
			return m;
		}

		lwsl_notice("%s: m = %d\n", __func__, m);

		if (state != LWS_UFS_FINAL_CONTENT)
			break;

		lws_genhmac_destroy(&pss->hmac, result);

		if (lws_timingsafe_bcmp(result, pss->notification_sig,
				(uint32_t)lws_genhmac_size(pss->hmac_type))) {
			lwsl_err("%s: hmac mismatch\n", __func__);

			return -1;
		}
		lwsl_notice("%s: hmac OK\n", __func__);

		/*
		 * Remember the (repo, ref) -> hash we were just told about,
		 * for every authenticated notification and before deciding
		 * whether it gets CI'd: ad-hoc builds resolve "the head of
		 * this branch" from here.
		 */
		if (sais_push_record(pss->vhd, pss->sn.e.repo_name,
				     pss->sn.e.ref, pss->sn.e.hash))
			lwsl_warn("%s: unable to record push\n", __func__);

		/*
		 * Branches whose name begins with "_" are scratch branches:
		 * the push is recorded above so an ad-hoc build can target
		 * it, but we don't schedule the whole .sai.json against it.
		 */
		if (!strncmp(pss->sn.e.ref, "refs/heads/_", 12)) {
			lwsl_notice("%s: scratch ref %s recorded, not scheduled\n",
				    __func__, pss->sn.e.ref);
			goto saifile_done;
		}

		/*
		 * We have the notification metadata JSON parsed into pss->sn.e,
		 * eg, pss->sn->e.hash ... since it's common to, eg, push a tree
		 * in a branch and then later tag the same commit, we don't want
		 * to pointlessly repeat CI for the same tree multiple times,
		 * and need to basically dedupe.
		 *
		 * Ad-hoc events are excluded: they are single-task scratch
		 * builds of a hash that may well be pushed for real later.
		 */

		{
			uint64_t rid = 0;
			char qu[192], esc_hash[96];

			lws_sql_purify(esc_hash, pss->sn.e.hash, sizeof(esc_hash));

			lws_snprintf(qu, sizeof(qu), "select rowid from events "
						     "where hash='%s' and "
						     "ifnull(adhoc,0)=0",
						     esc_hash);

			if (sqlite3_exec(pss->vhd->server.pdb, qu,
					 sai_sql3_get_uint64_cb,
					 &rid, NULL) == SQLITE_OK && rid) {
				/* it already exists */
				lwsl_notice("%s: ignoring notification as "
					    "tree hash event exists\n",
					    __func__);

				goto saifile_done;
			}
		}

		if (!pss->sn.saifile)
			return -1;

		/*
		 * We processed the notification JSON, but we only decoded the
		 * base64'd copy of the .sai.json so far... now's the time we
		 * want to process that and break it down into tasks.
		 *
		 * We don't trust it since it's controlled by the guy who pushed
		 * the commit, there can be anything at all in there.  We made
		 * sure he can't attack us until now by base64-ing it at the
		 * server hook, so he's just dumb payload.
		 *
		 * Let's try to parse it in two passes, first without acting on
		 * the content to confirm it's going to succeed...
		 */

		sai_uuid16_create(lws_get_context(pss->wsi), pss->sn.e.uuid);
		m = sai_event_db_ensure_open(pss->vhd->context, &pss->vhd->sqlite3_cache,
				      pss->vhd->sqlite3_path_lhs, pss->sn.e.uuid, 1,
					      (sqlite3 **)&pss->sn.e.pdb);
		if (m) {
			lwsl_err("%s: XX %d unable to open event-specific database\n",
					__func__, m);

			goto saifile_bail;
		}

		pss->dry = 1;
		lejp_construct(&saictx, sai_saifile_lejp_cb, pss, saifile_paths,
			       LWS_ARRAY_SIZE(saifile_paths));
		sai_lejp_enable_comments(&saictx);
		m = lejp_parse(&saictx, (uint8_t *)pss->sn.saifile,
			       (int)pss->sn.saifile_out_pos);
		sai_event_db_close(&pss->vhd->sqlite3_cache, (sqlite3 **)&pss->sn.e.pdb);
		if (m < 0) {
			lwsl_notice("%s: saifile JSON 1 decode failed '%s' (%d)\n",
				    __func__, lejp_error_to_string(m), m);
			goto saifile_bail;
		}

		/* ... then add the 32-char event object in the database ... */

		pss->sn.e.created = (unsigned long long)lws_now_secs();
		pss->sn.e.state = SAIES_WAITING;

		memset(&pss->sn.e.list, 0, sizeof(pss->sn.e.list));
		lws_dll2_owner_clear(&owner);
		lws_dll2_add_head(&pss->sn.e.list, &owner);

		/*
		 * This is our new event going into the event database...
		 */

		lws_struct_sq3_serialize(pss->vhd->server.pdb,
					 lsm_schema_sq3_map_event, &owner, 0);

		/*
		 * ... process the saifile JSON again creating tasks for each
		 * entry in the saifile, for each platform, against that event
		 * object...
		 */

		pss->dry = 0;
		pss->sn.e.idle = 0;
		lejp_construct(&saictx, sai_saifile_lejp_cb, pss, saifile_paths,
			       LWS_ARRAY_SIZE(saifile_paths));
		sai_lejp_enable_comments(&saictx);
		m = lejp_parse(&saictx, (uint8_t *)pss->sn.saifile,
			       (int)pss->sn.saifile_out_pos);

		if (m < 0) {
			lwsl_notice("%s: saifile JSON 2 decode failed '%s' (%d)\n",
				    __func__, lejp_error_to_string(m), m);
			free(pss->sn.saifile);
			pss->sn.saifile = NULL;
			return m;
		}

		free(pss->sn.saifile);
		pss->sn.saifile = NULL;

		lwsl_notice("%s: notification inserted into db\n", __func__);

		if (pss->sn.e.idle) {
			char q[128], esc[96];

			/*
			 * The event row went in before we knew how many idle
			 * tasks the configurations would create
			 */
			lws_sql_purify(esc, pss->sn.e.uuid, sizeof(esc));
			lws_snprintf(q, sizeof(q),
				     "update events set idle=%d where uuid='%s'",
				     pss->sn.e.idle, esc);
			sai_sqlite3_statement(pss->vhd->server.pdb, q,
					      "set event idle count");
		}

		/*
		 * Let sai-web know the event exists now, the same as for an
		 * ad-hoc event: otherwise it only hears about it once its
		 * state first changes, when the tasks start building.
		 */
		sais_eventchange(pss->vhd->h_ss_websrv, pss->sn.e.uuid,
				 SAIES_WAITING);

		/*
		 * The tasks are all in there but set to state
		 * NOT_READY_FOR_BUILD, the periodic central scan
		 * switch them over to WAITING when they have been like that
		 * for a short grace time (eg, 10s)
		 */

		lws_sul_schedule(pss->vhd->context, 0, &pss->vhd->sul_central,
				 sais_central_cb, 1 * LWS_US_PER_SEC);

		return 0;

saifile_done:
		/* notification accepted but nothing to schedule */
		free(pss->sn.saifile);
		pss->sn.saifile = NULL;

		return 0;

saifile_bail:
		free(pss->sn.saifile);
		pss->sn.saifile = NULL;

		return -1;

	case LWS_UFS_CLOSE:
		// lwsl_info("%s: LWS_UFS_CLOSE\n", __func__);
		lejp_destruct(&pss->ctx);
		break;
	}

	return 0;
}