Repository navigation
Expand file tree
/
Copy pathsetup.sh
More file actions
3153 lines (2975 loc) · 121 KB
/
Copy pathsetup.sh
File metadata and controls
3153 lines (2975 loc) · 121 KB
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
#!/bin/sh
# Copyright (c) 2026 Costas Kirgoussios
#
# This software is licensed under the PolyForm Noncommercial License 1.0.0.
# You may obtain a copy of the License at:
# https://polyformproject.org/licenses/noncommercial/1.0.0
# setup.sh: takes a stock machine to a running clavity-ls session with morluto/rea registered in an
# isolated agent-profile Claude profile. POSIX sh, one file. Run with --help for the flags.
# --- pins begin ---
PIN_SCRIPT_VERSION=0.1.1
PIN_GHIDRA_VERSION=12.2
PIN_GHIDRA_TOPDIR=ghidra_12.2_PUBLIC
PIN_GHIDRA_URL=https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_12.2_build/ghidra_12.2_PUBLIC_20261016.zip
PIN_GHIDRA_SHA256=2c2cd776db3c1f6a097ba418922378ac3649cadd5e844a6f5f088ae628a7be67
PIN_GHIDRA_ZIP_BYTES=569712708
PIN_GHIDRA_UNPACKED_MB=879
PIN_JDK_MAJOR=25
PIN_JDK_UNPACKED_MB=350
PIN_JDK_FALLBACK_RELEASE=jdk-25.0.5.1+2
PIN_JDK_FALLBACK_LINUX_X64=OpenJDK25U-jdk_x64_linux_hotspot_25.0.5.1_2.tar.gz:760f91b22c3efc9bd1b64ff950598231be82928cc807e30691a0e7a2995a62c0
PIN_JDK_FALLBACK_MAC_X64=OpenJDK25U-jdk_x64_mac_hotspot_25.0.5.1_2.tar.gz:b4b96fb7b9babd1b4faab1238e1835d0d7dd77b0690d220643c749a9ac00db36
PIN_JDK_FALLBACK_MAC_AARCH64=OpenJDK25U-jdk_aarch64_mac_hotspot_25.0.5.1_2.tar.gz:248353ea41be39d5d2c1c67c7ce0ae4d1668966aacd0c5308464bc1be42f677b
PIN_JDK_FALLBACK_WINDOWS_X64=OpenJDK25U-jdk_x64_windows_hotspot_25.0.5.1_2.zip:849d380ab0a64d9098e7d3a2de28beb73841c3b255c8284f019ccd8748c5eb5b
PIN_JDK_FALLBACK_URL_BASE=https://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.5.1%2B2/
PIN_AGENT_PROFILE_REPO=ckir/aiprofiles
PIN_CLAVITY_REPO=ckir/clavity
PIN_REA_SPEC=rea-agents@latest
PIN_ALLOWED_HOSTS="github.com api.github.com release-assets.githubusercontent.com api.adoptium.net registry.npmjs.org raw.githubusercontent.com"
# --- pins end ---
EX_OK=0
EX_STEP=1
EX_USAGE=2
EX_PLATFORM=3
EX_PREREQ=4
EX_VERIFY=5
CONSOLE_LEVEL=${CONSOLE_LEVEL:-INFO}
LOG_FILE=${LOG_FILE:-/dev/null}
OS=""
ARCH=""
TMP_FILES=""
usage() {
cat <<'EOF'
Usage: sh setup.sh [options]
--profile NAME profile name (default: rea)
--folder PATH folder handed to clavity-ls start (default: current directory)
--ghidra-dir PATH use this Ghidra install (env GHIDRA_INSTALL_DIR)
--java-home PATH use this JDK (env JAVA_HOME)
--tools-dir PATH where the JDK and Ghidra are installed
--bin-dir PATH where agent-profile and clavity-ls are installed (default: ~/.local/bin)
--install-hopper pass --install-hopper to rea setup (Linux and macOS only)
--yes do not prompt; without a terminal and without --yes, refuse (exit 2)
--dry-run plan only
--no-launch do everything except clavity-ls start
--check-upstream read-only drift check of every pinned and resolved release
--verbose console level DEBUG
--quiet console level WARN
--log-dir PATH log location
--help print this text and exit 0
Exit codes: 0 ok, 1 step failed, 2 usage, 3 unsupported platform, 4 prerequisite, 5 verification failed.
EOF
}
# --- logging ---
# level_rank LEVEL: prints 0..3 for DEBUG INFO WARN ERROR (unknown levels rank as INFO)
level_rank() {
case "$1" in
DEBUG) echo 0 ;;
INFO) echo 1 ;;
WARN) echo 2 ;;
ERROR) echo 3 ;;
*) echo 1 ;;
esac
}
# log_format LEVEL STEP MSG [TIMESTAMP]: the one log line on stdout; the timestamp argument is for tests
log_format() {
lf_ts=${4:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}
printf '%s %-5s [%s] %s\n' "$lf_ts" "$1" "$2" "$3"
}
# log LEVEL STEP MSG: the file always gets the line; stderr gets it when LEVEL >= CONSOLE_LEVEL
log() {
l_line=$(log_format "$1" "$2" "$(abbrev_text "$(redact "$3")")")
if ! { printf '%s\n' "$l_line" >>"$LOG_FILE"; } 2>/dev/null; then
LOG_FILE=/dev/null
printf 'warning: cannot write the log file; continuing without one\n' >&2
fi
if [ "$(level_rank "$1")" -ge "$(level_rank "$CONSOLE_LEVEL")" ]; then
printf '%s\n' "$l_line" >&2
fi
return 0
}
# die CODE STEP MSG: logs ERROR with the log path and exits CODE
die() {
d_code=$1
d_step=$2
shift 2
log ERROR "$d_step" "$*"
if [ "$LOG_FILE" != /dev/null ]; then
log ERROR "$d_step" "details: $(abbrev_home "$LOG_FILE")"
fi
exit "$d_code"
}
# trim_ws_end TEXT / trim_ws TEXT: TEXT without its trailing (and leading) whitespace, CR and newlines included
trim_ws_end() {
tw_s=$1
tw_t=${tw_s##*[![:space:]]}
printf '%s\n' "${tw_s%"$tw_t"}"
}
trim_ws() {
tw_s=$(trim_ws_end "$1")
tw_l=${tw_s%%[![:space:]]*}
printf '%s\n' "${tw_s#"$tw_l"}"
}
# run_cmd STEP cmd...: logs the argument list, exit code and duration; stdout goes to the file named by
# RUN_STDOUT, stderr to the log (bounded to 4000 characters on failure) and its last 1000 bytes to
# RUN_STDERR_TAIL (redacted, cut at a line boundary). RUN_STDOUT is registered for cleanup. Returns the command's exit code.
run_cmd() {
rc_step=$1
shift
RUN_STDOUT=$(mktemp "${TMPDIR:-/tmp}/rea-setup-out.XXXXXX") || return 1
register_tmp "$RUN_STDOUT"
rc_nl='
'
rc_err=$(mktemp "${TMPDIR:-/tmp}/rea-setup-err.XXXXXX") || {
rm -f "$RUN_STDOUT"
return 1
}
log DEBUG "$rc_step" "run: $*"
rc_start=$(date +%s)
rc=0
"$@" >"$RUN_STDOUT" 2>"$rc_err" || rc=$?
rc_secs=$(($(date +%s) - rc_start))
log DEBUG "$rc_step" "exit $rc after ${rc_secs}s"
# the tail is cut from the redacted end of stderr, so a secret name sliced by the cut cannot leak its value
rc_win=$(tail -c 20000 "$rc_err")
rc_win=$(trim_ws_end "$(redact "$rc_win")")
RUN_STDERR_TAIL=$(trim_ws "$rc_win")
rc_size=$(printf '%s' "$rc_win" | wc -c | tr -d ' ')
if [ "$rc_size" -gt 1000 ]; then
# the last 1000 bytes without their partial first line; one long line has no boundary: its last 1000 bytes
rc_win=$(printf '%s' "$rc_win" | tail -c 1000)
rc_rest=""
case "$rc_win" in
*"$rc_nl"*) rc_rest=$(trim_ws "${rc_win#*"$rc_nl"}") ;;
esac
if [ -n "$rc_rest" ]; then
RUN_STDERR_TAIL=$rc_rest
else
RUN_STDERR_TAIL="...$rc_win"
fi
fi
if [ "$rc" -ne 0 ]; then
log DEBUG "$rc_step" "stderr: $(head -c 4000 "$rc_err")"
fi
rm -f "$rc_err"
return "$rc"
}
# --- temporary files ---
# register_tmp PATH: remembers PATH (a file or a directory) for cleanup_tmp. One path per line, so a name
# containing a newline is not supported.
register_tmp() {
TMP_FILES="${TMP_FILES}${TMP_FILES:+
}$1"
}
# cleanup_tmp: removes every registered path; safe to call again, and with an empty list. Later steps that
# create temporary files register them here, and the locks and staging directories are released by
# cleanup_install (called first); nothing adds its own traps.
cleanup_tmp() {
cleanup_install
ct_list=$TMP_FILES
TMP_FILES=""
[ -n "$ct_list" ] || return 0
printf '%s\n' "$ct_list" | while IFS= read -r ct_path; do
if [ -n "$ct_path" ]; then
rm -rf -- "$ct_path"
fi
done
return 0
}
# install_traps: cleanup on normal exit and on INT and TERM (exit codes 130 and 143)
install_traps() {
trap cleanup_tmp EXIT
trap 'cleanup_tmp; exit 130' INT
trap 'cleanup_tmp; exit 143' TERM
}
# log_open: creates the log directory and file, keeps the newest 20, prints the file path
log_open() {
lo_dir=${OPT_LOG_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/rea-setup/logs}
lo_file="$lo_dir/setup-$(date -u +%Y%m%dT%H%M%SZ)-$$.log"
if mkdir -p "$lo_dir" 2>/dev/null && : >"$lo_file" 2>/dev/null; then
# Names sort oldest first (UTC timestamp), so drop all but the last 20.
lo_total=0
for lo_old in "$lo_dir"/setup-*.log; do
lo_total=$((lo_total + 1))
done
lo_n=0
for lo_old in "$lo_dir"/setup-*.log; do
lo_n=$((lo_n + 1))
if [ $((lo_total - lo_n)) -ge 20 ]; then
rm -f "$lo_old"
fi
done
printf '%s\n' "$lo_file"
else
printf 'warning: cannot create a log file in %s; continuing without one\n' "$lo_dir" >&2
printf '%s\n' /dev/null
fi
}
# redact TEXT: hides secrets in a log message, line by line (POSIX ERE, sed under LC_ALL=C so that an invalid
# multibyte sequence cannot stop a match and leave the rest of the line in clear; names are matched case-insensitively
# with explicit letter classes, since there is no portable I flag). In this order:
# URL userinfo and query; AUTHORIZATION=value to the end of the line; NAME = value (optional spaces around the
# equals sign, quoted values consumed whole); "NAME": value in JSON form (strings with
# escaped quotes, numbers, true, false, null); NAME: value to the end of the line (headers). NAME contains
# TOKEN, KEY, SECRET or PASSWORD, and for the JSON and colon forms also AUTHORIZATION. setup.ps1 Hide-ReaSecret
# does the same; tests/fixtures/redact-corpus.txt pins both. A JSON value that is an object or an array is
# left alone.
redact() {
rd_q="'"
rd_bs=\\\\
rd_names='[Tt][Oo][Kk][Ee][Nn]|[Kk][Ee][Yy]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]'
rd_auth='[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]'
rd_all="$rd_names|$rd_auth"
rd_key="\"[A-Za-z0-9_.-]*($rd_all)[A-Za-z0-9_.-]*\"[ ]*:[ ]*"
printf '%s\n' "$1" | LC_ALL=C sed -E \
-e 's#(https?://)[^/@ ]*@#\1#g' \
-e 's#(https?://[^ ?]*)\?[^ ]*#\1#g' \
-e "s/([A-Za-z0-9_-]*($rd_auth)[A-Za-z0-9_-]*[ ]*=[ ]*).*/\\1<redacted>/" \
-e "s/([A-Za-z0-9_]*($rd_names)[A-Za-z0-9_]*[ ]*=[ ]*)(\"[^\"]*\"[^ ]*|${rd_q}[^${rd_q}]*${rd_q}[^ ]*|[^ ]*)/\\1<redacted>/g" \
-e "s/($rd_key)\"([^\"$rd_bs]|$rd_bs.)*\"?/\\1\"<redacted>\"/g" \
-e "s/($rd_key)[A-Za-z0-9_.+-]+/\\1<redacted>/g" \
-e "s/([A-Za-z0-9_-]*($rd_all)[A-Za-z0-9_-]*[ ]*:)[ ]*.*/\\1 <redacted>/"
}
# abbrev_home PATH: prints PATH with the home directory as ~ (nothing when HOME is empty or /)
abbrev_home() {
case "${HOME:-}" in
'' | /) printf '%s\n' "$1" ;;
*)
case "$1" in
"$HOME") printf '%s\n' "~" ;;
"$HOME"/*) printf '~%s\n' "${1#"$HOME"}" ;;
*) printf '%s\n' "$1" ;;
esac
;;
esac
}
# abbrev_text TEXT: replaces the home directory inside free text with ~ (whole path components only)
abbrev_text() {
case "${HOME:-}" in
'' | /)
printf '%s\n' "$1"
return 0
;;
esac
at_home=$(printf '%s' "$HOME" | sed -e 's/[][\\.*^$+?(){}|#]/\\&/g')
printf '%s\n' "$1" | sed -E -e "s#(^|[^A-Za-z0-9._/-])${at_home}(/|[^A-Za-z0-9._-]|\$)#\\1~\\2#g"
}
# --- arguments ---
# need_value FLAG COUNT: dies EX_USAGE when the flag has no value after it
need_value() {
if [ "$2" -lt 2 ]; then
die "$EX_USAGE" args "option $1 needs a value"
fi
}
# abs_path PATH: PATH made absolute against the current directory, without resolving symlinks or dot-dot; leading
# ./ segments and trailing slashes are dropped, so ./ and .// are the current directory; '' stays ''
abs_path() {
ap_p=$1
[ -n "$ap_p" ] || {
printf '\n'
return 0
}
case "$ap_p" in
/*) ap_abs=1 ;;
*) ap_abs=0 ;;
esac
if [ "$ap_abs" -eq 0 ]; then
while :; do
case "$ap_p" in
./*) ap_p=${ap_p#./} ;;
/*) ap_p=${ap_p#/} ;;
*) break ;;
esac
done
fi
while :; do
case "$ap_p" in
?*/) ap_p=${ap_p%/} ;;
*) break ;;
esac
done
if [ "$ap_abs" -eq 1 ]; then
printf '%s\n' "$ap_p"
return 0
fi
case "$ap_p" in
'' | .) printf '%s\n' "$PWD" ;;
*) printf '%s/%s\n' "$PWD" "$ap_p" ;;
esac
}
parse_args() {
OPT_PROFILE=rea
OPT_FOLDER=$PWD
OPT_GHIDRA_DIR=""
OPT_JAVA_HOME=""
OPT_TOOLS_DIR=""
OPT_BIN_DIR=""
OPT_INSTALL_HOPPER=0
OPT_YES=0
OPT_DRY_RUN=0
OPT_NO_LAUNCH=0
OPT_CHECK_UPSTREAM=0
OPT_CONSOLE_LEVEL=INFO
OPT_LOG_DIR=""
while [ $# -gt 0 ]; do
case "$1" in
--profile) need_value "$1" $# && OPT_PROFILE=$2 && shift 2 ;;
--folder) need_value "$1" $# && OPT_FOLDER=$2 && shift 2 ;;
--ghidra-dir) need_value "$1" $# && OPT_GHIDRA_DIR=$2 && shift 2 ;;
--java-home) need_value "$1" $# && OPT_JAVA_HOME=$2 && shift 2 ;;
--tools-dir) need_value "$1" $# && OPT_TOOLS_DIR=$2 && shift 2 ;;
--bin-dir) need_value "$1" $# && OPT_BIN_DIR=$2 && shift 2 ;;
--log-dir) need_value "$1" $# && OPT_LOG_DIR=$2 && shift 2 ;;
--install-hopper) OPT_INSTALL_HOPPER=1 && shift ;;
--yes) OPT_YES=1 && shift ;;
--dry-run) OPT_DRY_RUN=1 && shift ;;
--no-launch) OPT_NO_LAUNCH=1 && shift ;;
--check-upstream) OPT_CHECK_UPSTREAM=1 && shift ;;
--verbose) OPT_CONSOLE_LEVEL=DEBUG && shift ;;
--quiet) OPT_CONSOLE_LEVEL=WARN && shift ;;
--help)
usage
exit "$EX_OK"
;;
*) die "$EX_USAGE" args "unknown option: $1 (see --help)" ;;
esac
done
# The paths are recorded in the profile, env.sh and the printed commands, which run elsewhere: make them absolute now
OPT_FOLDER=$(abs_path "$OPT_FOLDER")
OPT_GHIDRA_DIR=$(abs_path "$OPT_GHIDRA_DIR")
OPT_JAVA_HOME=$(abs_path "$OPT_JAVA_HOME")
OPT_TOOLS_DIR=$(abs_path "$OPT_TOOLS_DIR")
OPT_BIN_DIR=$(abs_path "$OPT_BIN_DIR")
}
# --- platform ---
# platform_detect: sets OS and ARCH; returns 0 only for linux x64, mac x64, mac aarch64, windows x64.
# UNAME_S and UNAME_M override uname for tests; main unsets them first.
platform_detect() {
pd_s=${UNAME_S:-$(uname -s)}
pd_m=${UNAME_M:-$(uname -m)}
case "$pd_s" in
Linux) OS=linux ;;
Darwin) OS=mac ;;
MINGW* | MSYS* | CYGWIN*) OS=windows ;;
*) OS=$pd_s ;;
esac
case "$pd_m" in
x86_64 | amd64) ARCH=x64 ;;
arm64 | aarch64) ARCH=aarch64 ;;
*) ARCH=$pd_m ;;
esac
case "$OS $ARCH" in
"linux x64" | "mac x64" | "mac aarch64" | "windows x64") return 0 ;;
*) return 1 ;;
esac
}
# --- validation ---
# profile_name_valid NAME: agent-profile's naming rules
profile_name_valid() {
pv_name=$1
case "$pv_name" in
'' | *'
'*) return 1 ;;
esac
printf '%s\n' "$pv_name" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._-]*$' || return 1
case "$pv_name" in
*.) return 1 ;;
esac
pv_lower=$(printf '%s' "$pv_name" | tr '[:upper:]' '[:lower:]')
case "$pv_lower" in
agents | profiles | status | list | create | delete | current | resolve | doctor | link | unlink | repositories | completions) return 1 ;;
esac
case "${pv_lower%%.*}" in
con | prn | aux | nul | com[1-9] | lpt[1-9]) return 1 ;;
esac
return 0
}
# semver_from_output TEXT: prints the first X.Y.Z
semver_from_output() {
printf '%s\n' "$1" | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' | head -n 1
}
# semver_part VERSION N: the Nth (1-3) numeric component's leading digits; a missing one counts as 0
semver_part() {
sp_rest=$1
sp_i=1
while [ "$sp_i" -lt "$2" ]; do
case "$sp_rest" in
*.*) sp_rest=${sp_rest#*.} ;;
*) sp_rest="" ;;
esac
sp_i=$((sp_i + 1))
done
sp_part=${sp_rest%%.*}
sp_part=${sp_part%%[!0-9]*}
echo "${sp_part:-0}"
}
# semver_compare A B: prints -1, 0 or 1, comparing the leading numeric X.Y.Z only
semver_compare() {
sc_i=0
while [ "$sc_i" -lt 3 ]; do
sc_i=$((sc_i + 1))
sc_x=$(semver_part "$1" "$sc_i")
sc_y=$(semver_part "$2" "$sc_i")
if [ "$sc_x" -lt "$sc_y" ]; then
echo -1
return 0
fi
if [ "$sc_x" -gt "$sc_y" ]; then
echo 1
return 0
fi
done
echo 0
}
# node_version_ok VERSION: 0 when v22.x >= 22.23.4, v24.x >= 24.22.1 or >= 26.12.1
node_version_ok() {
nv=${1#v}
nv_major=${nv%%.*}
nv_major=${nv_major%%[!0-9]*}
case "$nv_major" in
22) nv_floor=22.23.4 ;;
24) nv_floor=24.22.1 ;;
'' | *[!0-9]*) return 1 ;;
*)
if [ "$nv_major" -ge 26 ]; then
nv_floor=26.12.1
if [ "$nv_major" -gt 26 ]; then
return 0
fi
else
return 1
fi
;;
esac
[ "$(semver_compare "$nv" "$nv_floor")" != -1 ]
}
# confirm PROMPT: 0 when OPT_YES; refuses without a terminal; else reads one line
confirm() {
if [ "${OPT_YES:-0}" -eq 1 ]; then
return 0
fi
if [ ! -t 0 ]; then
die "$EX_USAGE" confirm "no terminal to ask '$1' on; re-run with --yes"
fi
printf '%s [y/N] ' "$1" >&2
read -r cf_answer || return 1
case "$cf_answer" in
y | Y) return 0 ;;
*) return 1 ;;
esac
}
# --- network ---
ALLOWED_SCHEMES=https
ALLOWED_HOSTS=$PIN_ALLOWED_HOSTS
RETRY_WAITS="2 4 8 16"
CURL="curl"
SLEEP="sleep"
# url_scheme URL: the lower-cased scheme; fails when there is no scheme://
url_scheme() {
case "$1" in
*://*) printf '%s\n' "${1%%://*}" | tr '[:upper:]' '[:lower:]' ;;
*) return 1 ;;
esac
}
# url_authority URL: everything between scheme:// and the first / ? or #
url_authority() {
ua_rest=${1#*://}
printf '%s\n' "${ua_rest%%[/?#]*}"
}
# url_host URL: the lower-cased host, without any userinfo or port
url_host() {
uh_auth=$(url_authority "$1")
uh_auth=${uh_auth##*@}
printf '%s\n' "${uh_auth%%:*}" | tr '[:upper:]' '[:lower:]'
}
# url_allowed URL: 0 when the scheme is in ALLOWED_SCHEMES, the host in ALLOWED_HOSTS and the authority
# carries no userinfo; whitespace and backslashes are refused outright
url_allowed() {
case "$1" in
*[[:space:]\\]*) return 1 ;;
esac
ual_scheme=$(url_scheme "$1") || return 1
ual_ok=1
for ual_s in $ALLOWED_SCHEMES; do
if [ "$ual_s" = "$ual_scheme" ]; then
ual_ok=0
fi
done
[ "$ual_ok" -eq 0 ] || return 1
case "$(url_authority "$1")" in
*@*) return 1 ;;
esac
ual_host=$(url_host "$1")
for ual_h in $ALLOWED_HOSTS; do
if [ "$ual_h" = "$ual_host" ]; then
return 0
fi
done
return 1
}
# url_path_safe URL: 1 when the URL has a dot-dot path segment (plain or percent-encoded) or a backslash
url_path_safe() {
case "$1" in
*/../* | */.. | */..\?* | *%2[eE]* | *\\*) return 1 ;;
esac
return 0
}
# net_proto: the value for curl --proto, https only unless ALLOWED_SCHEMES lists http (tests)
net_proto() {
case " $ALLOWED_SCHEMES " in
*" http "*) echo '=https,http' ;;
*) echo '=https' ;;
esac
}
# probe_retry URL [CURL_ARG...]: one metadata request (no body is written) with the retries http_get has: 5xx,
# 429 and curl exits 6 7 28 35 52 56 are retried after the pauses in RETRY_WAITS; anything else stops at once.
# Sets PR_RESP to "<http code> <redirect url>" ("000 " when curl failed). curl's exit code and the first line
# of its stderr go to the DEBUG log. -q is first so a ~/.curlrc (location, insecure...) cannot change the policy.
probe_retry() {
pr_url=$1
shift
PR_RESP="000 "
pr_err=$(mktemp "${TMPDIR:-/tmp}/rea-setup-err.XXXXXX") || return 1
register_tmp "$pr_err"
pr_total=0
for pr_w in $RETRY_WAITS; do
[ -n "$pr_w" ] && pr_total=$((pr_total + 1))
done
pr_attempt=0
for pr_wait in $RETRY_WAITS; do
pr_attempt=$((pr_attempt + 1))
pr_rc=0
PR_RESP=$("$CURL" -q -sS "$@" -o /dev/null -w '%{http_code} %{redirect_url}' --proto "$(net_proto)" --tlsv1.2 \
--connect-timeout 20 --max-time 60 "$pr_url" 2>"$pr_err") || pr_rc=$?
if [ "$pr_rc" -ne 0 ]; then
PR_RESP="000 "
log DEBUG net "curl exit $pr_rc for $pr_url (attempt $pr_attempt of $pr_total): $(head -n 1 "$pr_err" | head -c 300)"
fi
pr_retry=0
if [ "$pr_rc" -eq 0 ]; then
case "${PR_RESP%% *}" in
5?? | 429) pr_retry=1 ;;
esac
else
case "$pr_rc" in
6 | 7 | 28 | 35 | 52 | 56) pr_retry=1 ;;
esac
fi
[ "$pr_retry" -eq 1 ] || break
[ "$pr_attempt" -lt "$pr_total" ] || break
log DEBUG net "retrying in ${pr_wait}s"
"$SLEEP" "$pr_wait"
done
rm -f "$pr_err"
return 0
}
# resolve_redirects URL: prints the final URL after at most 5 redirects, using HEAD (no body is fetched).
# A hop answering 405 or 403 to HEAD is asked again with a one-byte ranged GET. Every hop must pass
# url_allowed and is retried like http_get retries. Returns 1 for a disallowed hop, 2 for more than 5
# redirects, 3 for any other failure.
resolve_redirects() {
rr_url=$1
rr_hops=0
while :; do
url_allowed "$rr_url" || {
log ERROR net "redirect target not allowed: $rr_url"
return 1
}
probe_retry "$rr_url" -I
rr_resp=$PR_RESP
case "$rr_resp" in
403* | 405*)
probe_retry "$rr_url" -r 0-0
rr_resp=$PR_RESP
;;
esac
rr_code=${rr_resp%% *}
rr_next=${rr_resp#* }
log DEBUG net "HEAD $rr_url -> $rr_code"
case "$rr_code" in
2??)
printf '%s\n' "$rr_url"
return 0
;;
3??)
if [ -z "$rr_next" ]; then
return 3
fi
rr_hops=$((rr_hops + 1))
if [ "$rr_hops" -gt 5 ]; then
log ERROR net "more than 5 redirects from $1"
return 2
fi
rr_url=$rr_next
;;
*) return 3 ;;
esac
done
}
# http_get URL DEST [EXTRA_CURL_ARGS...]: GET into DEST with retries. 2xx returns 0; 5xx, 429 and curl exits
# 6 7 28 35 52 56 are retried (RETRY_WAITS gives the pause before each retry, so it also sets the number of
# attempts; Retry-After raises the pause); any other failure returns 1 at once. GITHUB_TOKEN goes to
# api.github.com only, through a private curl config file so it is neither on a command line nor in the log.
http_get() {
hg_url=$1
hg_dest=$2
shift 2
url_allowed "$hg_url" || {
log ERROR net "URL not allowed: $hg_url"
return 1
}
hg_hdr=$(mktemp "${TMPDIR:-/tmp}/rea-setup-hdr.XXXXXX") || return 1
register_tmp "$hg_hdr"
hg_cfg=$(mktemp "${TMPDIR:-/tmp}/rea-setup-cfg.XXXXXX") || {
rm -f "$hg_hdr"
return 1
}
register_tmp "$hg_cfg"
hg_err=$(mktemp "${TMPDIR:-/tmp}/rea-setup-err.XXXXXX") || {
rm -f "$hg_hdr" "$hg_cfg"
return 1
}
register_tmp "$hg_err"
if [ -n "${GITHUB_TOKEN:-}" ] && [ "$(url_host "$hg_url")" = api.github.com ]; then
case "$GITHUB_TOKEN" in
*[!A-Za-z0-9_.-]*) log WARN net "GITHUB_TOKEN ignored: unexpected characters" ;;
*) printf 'header = "Authorization: Bearer %s"\n' "$GITHUB_TOKEN" >"$hg_cfg" ;;
esac
fi
hg_total=0
for hg_w in $RETRY_WAITS; do
[ -n "$hg_w" ] && hg_total=$((hg_total + 1))
done
hg_attempt=0
hg_result=1
for hg_wait in $RETRY_WAITS; do
hg_attempt=$((hg_attempt + 1))
hg_rc=0
: >"$hg_hdr"
hg_code=$("$CURL" -q -sS -K "$hg_cfg" --proto "$(net_proto)" --tlsv1.2 --speed-limit 1024 --speed-time 60 \
--connect-timeout 20 -D "$hg_hdr" -o "$hg_dest" -w '%{http_code}' "$@" "$hg_url" 2>"$hg_err") || hg_rc=$?
log DEBUG net "GET $hg_url -> ${hg_code:-000} (curl exit $hg_rc, attempt $hg_attempt of $hg_total)"
if [ "$hg_rc" -ne 0 ]; then
log DEBUG net "curl: $(head -c 500 "$hg_err")"
fi
hg_retry=0
if [ "$hg_rc" -eq 0 ]; then
case "$hg_code" in
2??)
hg_result=0
break
;;
5?? | 429) hg_retry=1 ;;
*) break ;;
esac
else
case "$hg_rc" in
6 | 7 | 28 | 35 | 52 | 56) hg_retry=1 ;;
*) break ;;
esac
fi
[ "$hg_retry" -eq 1 ] || break
[ "$hg_attempt" -lt "$hg_total" ] || break
hg_ra=$(sed -n 's/^[Rr][Ee][Tt][Rr][Yy]-[Aa][Ff][Tt][Ee][Rr]:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$hg_hdr" | tail -n 1)
if [ "${#hg_ra}" -gt 6 ]; then
hg_ra=""
fi
if [ -n "$hg_ra" ] && [ "$hg_ra" -gt "$hg_wait" ] 2>/dev/null; then
hg_wait=$hg_ra
fi
if [ "$hg_wait" -gt 120 ]; then
hg_wait=120
fi
log DEBUG net "retrying in ${hg_wait}s"
"$SLEEP" "$hg_wait"
done
rm -f "$hg_hdr" "$hg_cfg" "$hg_err"
if [ "$hg_result" -ne 0 ]; then
rm -f "$hg_dest"
log ERROR net "GET failed: $hg_url"
fi
return "$hg_result"
}
# sha256_file FILE: prints the lower-case hex digest
sha256_file() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1" | cut -d ' ' -f 1
elif command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$1" | cut -d ' ' -f 1
else
log ERROR net "neither sha256sum nor shasum is available"
return 1
fi
}
# sidecar_sha256 FILE: prints the first 64-hex token of a .sha256 sidecar, lower-cased (sha256sum, shasum
# and PowerShell layouts); fails when there is none
sidecar_sha256() {
ss_hash=$(sed -n -E 's/^[[:space:]]*([0-9A-Fa-f]{64})([^0-9A-Fa-f].*)?$/\1/p' "$1" | head -n 1 | tr '[:upper:]' '[:lower:]')
[ -n "$ss_hash" ] || return 1
printf '%s\n' "$ss_hash"
}
# download_verified URL DEST SHA256: resolves redirects, downloads to DEST.tmp.$$, checks the digest
# (case-insensitive) and only then moves the file to DEST. Returns 1 on any failure, leaving nothing behind.
download_verified() {
dv_final=$(resolve_redirects "$1") || {
log ERROR net "cannot resolve $1"
return 1
}
dv_tmp="$2.tmp.$$"
register_tmp "$dv_tmp"
http_get "$dv_final" "$dv_tmp" || {
rm -f "$dv_tmp"
return 1
}
dv_got=$(sha256_file "$dv_tmp") || {
rm -f "$dv_tmp"
return 1
}
dv_want=$(printf '%s' "$3" | tr '[:upper:]' '[:lower:]')
if [ "$dv_got" != "$dv_want" ]; then
log ERROR net "checksum mismatch for $1: expected $dv_want got $dv_got"
rm -f "$dv_tmp"
return 1
fi
mv -f "$dv_tmp" "$2"
}
# json_query FILE JS: applies the JavaScript expression JS (a literal from this script, never data) to the
# parsed JSON of FILE as `d` and prints the result; arrays one element per line, null and undefined as empty.
# The expression travels as an argument, so quoting cannot break the program. The last two arguments are
# read, so it does not matter whether this node keeps the -- in process.argv.
json_query() {
node -e 'const a=process.argv.slice(-2);const d=JSON.parse(require("fs").readFileSync(a[0],"utf8"));let r=new Function("d","return ("+a[1]+")")(d);if(r===null||r===undefined)r="";if(Array.isArray(r))r=r.join("\n");process.stdout.write(String(r)+"\n")' -- "$1" "$2"
}
# github_latest_tag REPO: the tag of the latest release, from the redirect of /releases/latest
github_latest_tag() {
gl_url="https://github.com/$1/releases/latest"
url_allowed "$gl_url" || return 1
probe_retry "$gl_url" -I
gl_loc=${PR_RESP#* }
log DEBUG net "latest release of $1 -> $gl_loc"
case "$gl_loc" in
*/releases/tag/?*) gl_tag=${gl_loc##*/} ;;
*) return 1 ;;
esac
# the tag is spliced into later URLs: letters, digits and . _ + - only, never a dot segment
case "$gl_tag" in
'' | .* | *[!A-Za-z0-9._+-]*) return 1 ;;
esac
printf '%s\n' "$gl_tag"
}
# github_release_assets REPO: the asset names of the latest release, one per line, from the API
github_release_assets() {
gr_tmp=$(mktemp "${TMPDIR:-/tmp}/rea-setup-json.XXXXXX") || return 1
if http_get "https://api.github.com/repos/$1/releases/latest" "$gr_tmp"; then
gr_rc=0
json_query "$gr_tmp" '(d.assets||[]).map(a=>a.name)' || gr_rc=1
else
gr_rc=1
fi
rm -f "$gr_tmp"
return "$gr_rc"
}
# github_release_assets_scrape REPO TAG: the asset names of a release, from the HTML of its expanded_assets
# page; the fallback for when the API is rate-limited
github_release_assets_scrape() {
gs_tmp=$(mktemp "${TMPDIR:-/tmp}/rea-setup-html.XXXXXX") || return 1
if http_get "https://github.com/$1/releases/expanded_assets/$2" "$gs_tmp"; then
grep -Eo '/[^"<> ]+/releases/download/[^"<> ]+' "$gs_tmp" | grep -F "/$1/releases/download/$2/" | sed 's#.*/##' | sort -u
gs_rc=0
else
gs_rc=1
fi
rm -f "$gs_tmp"
return "$gs_rc"
}
# jdk_release_valid TAG: 0 when TAG is a Temurin PIN_JDK_MAJOR release name such as jdk-25.0.5.1+2
jdk_release_valid() {
printf '%s\n' "$1" | grep -Eq "^jdk-$PIN_JDK_MAJOR(\\.[0-9]+)*\\+[0-9]+\$"
}
# adoptium_parse FILE: reads the first asset of an Adoptium response and sets JDK_RELEASE, JDK_URL,
# JDK_SHA256, JDK_SIDECAR_URL and JDK_BYTES. Returns 1 unless the release name, the download link (host
# github.com, path /adoptium/temurin<PIN_JDK_MAJOR>-binaries/), the sidecar link and the checksum all pass.
adoptium_parse() {
ap_vals=$(json_query "$1" '[d[0].release_name, d[0].binary.package.link, d[0].binary.package.checksum, d[0].binary.package.checksum_link, d[0].binary.package.size]') || return 1
JDK_RELEASE=$(printf '%s\n' "$ap_vals" | sed -n 1p)
JDK_URL=$(printf '%s\n' "$ap_vals" | sed -n 2p)
JDK_SHA256=$(printf '%s\n' "$ap_vals" | sed -n 3p | tr '[:upper:]' '[:lower:]')
JDK_SIDECAR_URL=$(printf '%s\n' "$ap_vals" | sed -n 4p)
JDK_BYTES=$(printf '%s\n' "$ap_vals" | sed -n 5p)
jdk_release_valid "$JDK_RELEASE" || {
log ERROR net "unexpected JDK release name: $JDK_RELEASE"
return 1
}
url_allowed "$JDK_URL" || return 1
url_path_safe "$JDK_URL" || {
log ERROR net "unexpected JDK download path: $JDK_URL"
return 1
}
[ "$(url_host "$JDK_URL")" = github.com ] || return 1
case "${JDK_URL#*://*/}" in
adoptium/temurin"$PIN_JDK_MAJOR"-binaries/?*) ;;
*)
log ERROR net "unexpected JDK download path: $JDK_URL"
return 1
;;
esac
printf '%s\n' "$JDK_SHA256" | grep -Eq '^[0-9a-f]{64}$' || return 1
printf '%s\n' "$JDK_BYTES" | grep -Eq '^[0-9]+$' || return 1
if [ -n "$JDK_SIDECAR_URL" ]; then
url_allowed "$JDK_SIDECAR_URL" || return 1
url_path_safe "$JDK_SIDECAR_URL" || return 1
fi
return 0
}
# adoptium_resolve OS ARCH: asks the Adoptium API for the latest Temurin PIN_JDK_MAJOR JDK and parses it. Returns 2
# when the API cannot be reached (the caller uses the fallback pin) and 1 when the answer fails validation.
adoptium_resolve() {
ar_tmp=$(mktemp "${TMPDIR:-/tmp}/rea-setup-json.XXXXXX") || return 2
if ! http_get "https://api.adoptium.net/v3/assets/latest/$PIN_JDK_MAJOR/hotspot?architecture=$2&image_type=jdk&os=$1&vendor=eclipse" "$ar_tmp"; then
rm -f "$ar_tmp"
return 2
fi
ar_rc=0
adoptium_parse "$ar_tmp" || ar_rc=1
rm -f "$ar_tmp"
return "$ar_rc"
}
# --- files, locks, archives and staging ---
NL='
'
LOCK_HELD=""
STAGING_DIRS=""
# tools_dir_default / bin_dir_default: where the JDK and Ghidra go, and where the launchers go
tools_dir_default() {
printf '%s\n' "${OPT_TOOLS_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/rea-tools}"
}
bin_dir_default() {
printf '%s\n' "${OPT_BIN_DIR:-$HOME/.local/bin}"
}
# pid_alive PID: 0 when the process exists. kill -0 fails for another user's process, so ps -p decides then.
pid_alive() {
case "$1" in
'' | *[!0-9]*) return 1 ;;
esac
kill -0 "$1" 2>/dev/null && return 0
ps -p "$1" >/dev/null 2>&1
}
# older_than_min PATH MINUTES: 0 when PATH's modification time is more than MINUTES minutes ago
older_than_min() {
[ -n "$(find "$1" -maxdepth 0 -mmin "+$2" 2>/dev/null)" ]
}
# list_has LIST ITEM: 0 when the newline-separated LIST contains ITEM exactly
list_has() {
case "$NL$1$NL" in
*"$NL$2$NL"*) return 0 ;;
esac
return 1
}
# lock_owner_pid DIR: the pid recorded in DIR/.lock/owner, or nothing
lock_owner_pid() {
sed -n 's/^pid=\([0-9][0-9]*\).*/\1/p' "$1/.lock/owner" 2>/dev/null | head -n 1
}
# lock_acquire DIR: takes DIR/.lock (mkdir is atomic) and records pid and start time in DIR/.lock/owner. A
# lock whose owner is dead (or that has no owner file and is over a minute old) is taken over with a WARN. A
# live owner is waited for, 2 s per poll, up to LOCK_POLLS polls (default 60), then the step fails. Taking the
# same lock twice in one process is a no-op. The release is lock_release, or cleanup_install on any exit.
lock_acquire() {
la_dir=$1
la_polls=0
if list_has "$LOCK_HELD" "$la_dir"; then
return 0
fi
mkdir -p -- "$la_dir" || die "$EX_STEP" tools-bin "cannot create directory: $la_dir"
while :; do
if mkdir -- "$la_dir/.lock" 2>/dev/null; then
printf 'pid=%s started=%s\n' "$$" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >"$la_dir/.lock/owner" 2>/dev/null || true
LOCK_HELD="${LOCK_HELD}${LOCK_HELD:+$NL}$la_dir"
return 0
fi
[ -d "$la_dir/.lock" ] || die "$EX_STEP" tools-bin "cannot create lock: $la_dir/.lock"
la_pid=$(lock_owner_pid "$la_dir")
la_stale=0
if [ -n "$la_pid" ]; then
pid_alive "$la_pid" || la_stale=1
elif older_than_min "$la_dir/.lock" 1; then
la_stale=1
fi
if [ "$la_stale" -eq 1 ]; then
# Move the lock aside (atomic) only while its owner is still the one judged dead; a failed move means
# another process took it over first, so fall through to normal polling. Never rm the live name.
la_aside="$la_dir/.lock.stale.$$"
rm -rf -- "$la_aside"
if [ "$(lock_owner_pid "$la_dir")" = "$la_pid" ] && mv -- "$la_dir/.lock" "$la_aside" 2>/dev/null; then
if [ "$(sed -n 's/^pid=\([0-9][0-9]*\).*/\1/p' "$la_aside/owner" 2>/dev/null | head -n 1)" = "$la_pid" ]; then
log WARN tools-bin "stale lock from pid ${la_pid:-unknown} taken over: $la_dir/.lock"
rm -rf -- "$la_aside"
elif [ ! -e "$la_dir/.lock" ]; then
# We moved a lock that changed owner between the check and the move: put it back.
mv -- "$la_aside" "$la_dir/.lock" 2>/dev/null || rm -rf -- "$la_aside"
else
rm -rf -- "$la_aside"
fi
continue
fi
fi
la_polls=$((la_polls + 1))
if [ "$la_polls" -ge "${LOCK_POLLS:-60}" ]; then
die "$EX_STEP" tools-bin "lock held by pid ${la_pid:-unknown}: $la_dir/.lock (if no setup is running, delete $la_dir/.lock)"
fi
sleep 2
done
}
# lock_release DIR: removes DIR/.lock when this process holds it; otherwise does nothing
lock_release() {
list_has "$LOCK_HELD" "$1" || return 0
rm -rf -- "$1/.lock"
lr_rest=""
while IFS= read -r lr_d; do
if [ -n "$lr_d" ] && [ "$lr_d" != "$1" ]; then
lr_rest="${lr_rest}${lr_rest:+$NL}$lr_d"
fi
done <<EOF
$LOCK_HELD
EOF
LOCK_HELD=$lr_rest