Repository navigation
Expand file tree
/
Copy pathkpanel.conf
More file actions
2356 lines (2186 loc) · 91.2 KB
/
Copy pathkpanel.conf
File metadata and controls
2356 lines (2186 loc) · 91.2 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
# shellcheck shell=bash disable=SC2034,SC2168
# KPanel systemd unit copies: v1
# --- 基础信息 / Basic Information ---
local app_id="kpanel"
local app_name="KPanel"
local app_text="完全贴合 kejilion.sh 业务的现代化 Linux Web 管理面板"
local app_url="https://github.com/kejilion/KPanel"
local docker_name="kejilion-panel"
local docker_port="8080"
local app_size="1"
# Keep the executing lifecycle as the recovery entry until the transaction ends.
# A target release (including a downgrade to stable) may contain older helpers.
KPANEL_ACTIVE_LIFECYCLE_SOURCE="$(readlink -f "${BASH_SOURCE[0]}")"
kpanel_valid_release_version() {
local value="$1"
local core=""
local candidate=""
local major=""
local minor=""
local patch=""
[[ "${value}" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-rc\.([1-9][0-9]*))?$ ]] || return 1
core="${value%%-rc.*}"
IFS=. read -r major minor patch <<<"${core}"
[ "${#major}" -le 6 ] && [ "${#minor}" -le 6 ] && [ "${#patch}" -le 6 ] || return 1
[ "${major}" -le 999999 ] && [ "${minor}" -le 999999 ] && [ "${patch}" -le 999999 ] || return 1
case "${value}" in
*-rc.*)
candidate="${value##*-rc.}"
[ "${#candidate}" -le 6 ] && [ "${candidate}" -le 999999 ]
;;
*) return 0 ;;
esac
}
kpanel_write_compose() {
local app_dir="/home/docker/kpanel"
local panel_gid="$1"
local panel_image="${2:-docker.io/kjlion/kejilion-panel:latest}"
printf '%s\n' "${panel_image}" |
grep -Eq '^docker\.io/kjlion/kejilion-panel:(latest|[0-9]+\.[0-9]+\.[0-9]+)$|^docker\.io/kjlion/kejilion-panel@sha256:[0-9a-f]{64}$' || {
echo "KPanel 镜像引用无效,拒绝写入 Compose。" >&2
return 1
}
cat <<EOF > "${app_dir}/docker-compose.yml"
services:
panel:
image: ${panel_image}
container_name: kejilion-panel
restart: unless-stopped
user: "65532:65532"
group_add:
- "${panel_gid}"
read_only: true
pids_limit: 128
mem_limit: 256m
cpus: 1.0
cap_drop:
- ALL
extra_hosts:
- "host.docker.internal:host-gateway"
security_opt:
- no-new-privileges:true
tmpfs:
- /tmp:size=16m,mode=1777
ports:
- "${docker_port}:8080"
environment:
KEJILION_PANEL_LISTEN: ":8080"
KEJILION_PANEL_DATA_DIR: /var/lib/kejilion-panel
KEJILION_PANEL_AGENT_SOCKET: /run/kejilion-panel/agent.sock
KEJILION_PANEL_AGENT_TOKEN_FILE: /run/secrets/agent-token
KEJILION_PANEL_WEB_ROOT: /app/web
KEJILION_PANEL_PUBLIC_URL: \${KPANEL_PUBLIC_URL}
KEJILION_PANEL_ALLOW_IP_HOSTS: \${KPANEL_ALLOW_IP_HOSTS:-true}
KEJILION_PANEL_SECURE_COOKIE: \${KPANEL_SECURE_COOKIE:-false}
KEJILION_PANEL_TRUSTED_PROXY_CIDRS: \${KPANEL_TRUSTED_PROXY_CIDRS}
KEJILION_PANEL_CLUSTER_PRIVATE_CIDRS: \${KPANEL_CLUSTER_PRIVATE_CIDRS:-}
volumes:
- ./data/panel:/var/lib/kejilion-panel
- ./run:/run/kejilion-panel:ro
- ./secrets/agent.token:/run/secrets/agent-token:ro
networks:
- kpanel-internal
- kpanel-egress
healthcheck:
test: ["CMD", "/paneld", "healthcheck"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
networks:
kpanel-internal:
name: kejilion-panel-internal
internal: true
kpanel-egress:
name: kejilion-panel-egress
EOF
}
kpanel_write_agent_service() {
local app_dir="/home/docker/kpanel"
cat <<EOF > "${app_dir}/kejilion-agent.service"
[Unit]
Description=KPanel Host Agent
Documentation=https://hub.docker.com/r/kjlion/kejilion-panel
After=local-fs.target docker.service
[Service]
Type=simple
User=root
Group=kejilion-panel
EnvironmentFile=${app_dir}/agent.env
ExecStart=${app_dir}/bin/kejilion-agent
Restart=on-failure
RestartSec=3s
UMask=0077
NoNewPrivileges=true
CapabilityBoundingSet=CAP_SYS_ADMIN CAP_SYS_MODULE CAP_NET_ADMIN CAP_SYS_RESOURCE CAP_DAC_OVERRIDE CAP_CHOWN CAP_LINUX_IMMUTABLE CAP_SYS_PTRACE CAP_KILL
AmbientCapabilities=CAP_SYS_ADMIN CAP_SYS_MODULE CAP_NET_ADMIN CAP_SYS_RESOURCE CAP_DAC_OVERRIDE CAP_CHOWN CAP_LINUX_IMMUTABLE CAP_SYS_PTRACE CAP_KILL
PrivateTmp=true
PrivateDevices=true
ProtectClock=true
ProtectControlGroups=true
ProtectHostname=false
ProtectKernelLogs=true
ProtectKernelModules=false
ProtectKernelTunables=false
ProtectProc=default
# KPanel file management is explicitly rooted at /. ProtectSystem=strict keeps
# that root read-only even with ReadWritePaths=/ on some supported systemd
# releases. The typed, audited file API remains the write boundary, while Panel
# state is protected explicitly below.
ProtectSystem=false
ProtectHome=false
ReadOnlyPaths=${app_dir}/data/panel
# File mutations still pass through the typed, audited file API, which rejects
# KPanel state and credential paths, symlinks and kernel virtual filesystems.
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
RestrictNamespaces=true
RestrictRealtime=true
RestrictSUIDSGID=true
LockPersonality=true
MemoryDenyWriteExecute=true
SystemCallArchitectures=native
SystemCallFilter=@system-service @module @swap sethostname
SystemCallErrorNumber=EPERM
[Install]
WantedBy=multi-user.target
EOF
cat <<EOF > "${app_dir}/kejilion-agent.openrc"
#!/sbin/openrc-run
name="KPanel Host Agent"
description="Privileged, typed host API for KPanel"
command="${app_dir}/bin/kejilion-agent"
command_user="root:kejilion-panel"
directory="/"
pidfile="${app_dir}/run/agent.pid"
supervisor="supervise-daemon"
respawn_delay=3
respawn_max=10
respawn_period=60
retry="TERM/30/KILL/5"
stopgroup=true
umask=0077
output_logger="logger -t kejilion-agent"
error_logger="logger -t kejilion-agent"
no_new_privs=true
export KEJILION_AGENT_SOCKET="${app_dir}/run/agent.sock"
export KEJILION_AGENT_TOKEN_FILE="${app_dir}/secrets/agent.token"
export KEJILION_AGENT_STATE_DIR="${app_dir}/data/agent"
export KEJILION_WEB_ROOT="/home/web"
export KEJILION_DOCKER_SOCKET="/var/run/docker.sock"
export KEJILION_DOCKER_PID_FILE="/run/docker.pid"
export KEJILION_DOCKER_ALLOW_SOCKET_ACTIVATION="false"
export KEJILION_SYSTEM_WRITES_ENABLED="true"
export KEJILION_PUBLIC_NETWORK_LOOKUP_ENABLED="true"
depend() {
need localmount docker
use net logger
after firewall
}
start_pre() {
checkpath --directory --mode 0750 --owner root:kejilion-panel "${app_dir}/run"
}
EOF
chmod 755 "${app_dir}/kejilion-agent.openrc"
cat <<EOF > "${app_dir}/agent.env"
KEJILION_AGENT_SOCKET=${app_dir}/run/agent.sock
KEJILION_AGENT_TOKEN_FILE=${app_dir}/secrets/agent.token
KEJILION_AGENT_STATE_DIR=${app_dir}/data/agent
KEJILION_AGENT_SELF_UPDATE_STATE_DIR=${app_dir}/update-state
KEJILION_WEB_ROOT=/home/web
KEJILION_DOCKER_SOCKET=/var/run/docker.sock
KEJILION_DOCKER_PID_FILE=/run/docker.pid
KEJILION_DOCKER_ALLOW_SOCKET_ACTIVATION=false
KEJILION_SYSTEM_WRITES_ENABLED=true
KEJILION_PUBLIC_NETWORK_LOOKUP_ENABLED=true
EOF
chmod 600 "${app_dir}/agent.env"
}
kpanel_write_update_units() {
local app_dir="/home/docker/kpanel"
[ "${KPANEL_INIT_SYSTEM:-}" = systemd ] || return 0
cat <<EOF > "${app_dir}/kejilion-panel-update.service"
[Unit]
Description=KPanel Managed Release Update
Documentation=https://github.com/kejilion/KPanel
After=network-online.target docker.service kejilion-agent.service
Wants=network-online.target
ConditionPathExists=${app_dir}/.managed-by-kejilion-app
[Service]
Type=oneshot
User=root
Group=root
ExecStart=${app_dir}/bin/kejilion-agent self-update-run --state-dir ${app_dir}/update-state --script ${app_dir}/bin/kejilion.sh --agent ${app_dir}/bin/kejilion-agent --lifecycle ${app_dir}/bin/kpanel.conf
UMask=0077
TimeoutStartSec=45min
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7
NoNewPrivileges=false
PrivateTmp=true
ProtectSystem=false
ProtectHome=false
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
LockPersonality=true
[Install]
WantedBy=multi-user.target
EOF
cat <<EOF > "${app_dir}/kejilion-panel-update.timer"
[Unit]
Description=Check the selected KPanel release channel
Documentation=https://github.com/kejilion/KPanel
[Timer]
OnBootSec=15min
OnCalendar=*-*-* 04:00:00
RandomizedDelaySec=30min
AccuracySec=5min
Persistent=true
Unit=kejilion-panel-update.service
[Install]
WantedBy=timers.target
EOF
chmod 600 "${app_dir}/kejilion-panel-update.service" \
"${app_dir}/kejilion-panel-update.timer"
}
kpanel_inherit_script_preferences() {
local destination="$1"
local source=""
local candidate=""
local mode=""
local owner=""
local region="default"
local license_answer=""
for candidate in \
/home/docker/kpanel/bin/kejilion.sh \
/usr/local/bin/k \
/usr/bin/k \
/root/kejilion.sh
do
[ "${candidate}" != "${destination}" ] || continue
[ -f "${candidate}" ] && [ ! -L "${candidate}" ] || continue
owner="$(stat -c '%u' "${candidate}" 2>/dev/null || true)"
mode="$(stat -c '%a' "${candidate}" 2>/dev/null || true)"
[ "${owner}" = "0" ] || continue
case "${mode}" in
*[2367][0-7]|*[0-7][2367]) continue ;;
esac
if grep -Fx 'permission_granted="true"' "${candidate}" >/dev/null 2>&1; then
source="${candidate}"
break
fi
done
if [ -z "${source}" ]; then
echo "未能从本机可信 kejilion.sh 继承许可状态(需 root 所有、非符号链接、组和其他用户不可写,且已接受许可)。"
if [ ! -t 0 ]; then
echo "请在交互终端重新安装并接受许可协议,或先运行 k 接受许可并检查脚本权限。"
return 1
fi
echo "用户许可协议: https://blog.kejilion.pro/user-license-agreement/"
printf '是否同意以上条款并继续安装 KPanel?(y/n): '
IFS= read -r license_answer || return 1
case "${license_answer}" in
y|Y) ;;
*) echo "未接受许可协议,已取消。"; return 1 ;;
esac
fi
sed -i 's/^permission_granted="false"$/permission_granted="true"/' "${destination}" || return 1
if [ -n "${source}" ] && grep -Fx 'ENABLE_STATS="false"' "${source}" >/dev/null 2>&1; then
sed -i 's/^ENABLE_STATS="true"$/ENABLE_STATS="false"/' "${destination}" || return 1
fi
region=""
if [ -n "${source}" ]; then
region="$(sed -n 's/^canshu="\(CN\|V6\)"$/\1/p' "${source}" | head -n 1)"
fi
if [ -n "${region}" ]; then
sed -i "s/^canshu=\"default\"$/canshu=\"${region}\"/" "${destination}" || return 1
fi
grep -Fx 'permission_granted="true"' "${destination}" >/dev/null || return 1
}
kpanel_extract_release() {
local image="$1"
local agent_destination="$2"
local script_destination="$3"
local lifecycle_destination="${4:-}"
local expected_version="${5:-}"
local release_container="kpanel-release-$$-$RANDOM"
local release_version_destination="${agent_destination}.release-version.$$.$RANDOM"
local image_version=""
local image_revision=""
local script_revision=""
local script_sha256=""
local release_version=""
if ! image_version="$(docker image inspect --format \
'{{index .Config.Labels "org.opencontainers.image.version"}}' "${image}" 2>/dev/null)" ||
! image_revision="$(docker image inspect --format \
'{{index .Config.Labels "org.opencontainers.image.revision"}}' "${image}" 2>/dev/null)" ||
! script_revision="$(docker image inspect --format \
'{{index .Config.Labels "io.kejilion.script.revision"}}' "${image}" 2>/dev/null)" ||
! script_sha256="$(docker image inspect --format \
'{{index .Config.Labels "io.kejilion.script.sha256"}}' "${image}" 2>/dev/null)"; then
echo "KPanel 镜像发布元数据读取失败,拒绝继续。"
return 1
fi
kpanel_valid_release_version "${image_version}" &&
printf '%s\n' "${image_revision}" | grep -Eq '^[0-9a-f]{40}$' &&
printf '%s\n' "${script_revision}" | grep -Eq '^[0-9a-f]{40}$' &&
printf '%s\n' "${script_sha256}" | grep -Eq '^[0-9a-f]{64}$' || {
echo "KPanel 镜像发布元数据无效,拒绝继续。"
return 1
}
docker create --name "${release_container}" "${image}" >/dev/null || return 1
if ! docker cp "${release_container}:/release/kejilion-agent" "${agent_destination}" ||
! docker cp "${release_container}:/release/kejilion.sh" "${script_destination}" ||
! docker cp "${release_container}:/release/VERSION" "${release_version_destination}" ||
! { [ -z "${lifecycle_destination}" ] ||
docker cp "${release_container}:/release/kpanel.conf" "${lifecycle_destination}"; }; then
docker rm -f "${release_container}" >/dev/null 2>&1
rm -f "${agent_destination}" "${script_destination}" "${lifecycle_destination}" \
"${release_version_destination}"
return 1
fi
if ! docker rm "${release_container}" >/dev/null ||
! release_version="$(tr -d '\r\n' <"${release_version_destination}")" ||
! rm -f "${release_version_destination}" ||
! chmod 755 "${agent_destination}" ||
! chmod 700 "${script_destination}" ||
! { [ -z "${lifecycle_destination}" ] || chmod 600 "${lifecycle_destination}"; }; then
rm -f "${agent_destination}" "${script_destination}" "${lifecycle_destination}" \
"${release_version_destination}"
return 1
fi
if [ -n "${expected_version}" ] && [ "${release_version}" != "${expected_version}" ]; then
echo "KPanel 镜像版本与自动更新目标不一致,拒绝继续。"
rm -f "${agent_destination}" "${script_destination}" "${lifecycle_destination}"
return 1
fi
[ "${release_version}" = "${image_version}" ] &&
[ "$("${agent_destination}" version 2>/dev/null)" = "${image_version} v1alpha1" ] || {
echo "Agent 版本校验失败,拒绝继续。"
rm -f "${agent_destination}" "${script_destination}" "${lifecycle_destination}"
return 1
}
command -v sha256sum >/dev/null 2>&1 &&
[ "$(sha256sum "${script_destination}" | awk '{print $1}')" = "${script_sha256}" ] || {
echo "kejilion.sh 完整性校验失败,拒绝继续。"
rm -f "${agent_destination}" "${script_destination}" "${lifecycle_destination}"
return 1
}
kpanel_inherit_script_preferences "${script_destination}" || {
rm -f "${agent_destination}" "${script_destination}" "${lifecycle_destination}"
return 1
}
}
# BEGIN KPanel IPC permissions (also embedded in the standalone app config).
kpanel_prepare_ipc_permissions() (
# Only callers' private IPC directories are touched, never their parents or
# descendants. Validate the complete set before changing any permissions.
ipc_gid=$1
ipc_run=$2
ipc_secrets=$3
case "$ipc_gid" in ''|*[!0-9]*) return 1 ;; esac
for ipc_path in "$ipc_run" "$ipc_secrets"; do
[ ! -L "$ipc_path" ] && [ -d "$ipc_path" ] &&
[ "$(stat -c %u -- "$ipc_path")" = 0 ] || {
echo "KPanel IPC directory must be a root-owned real directory: $ipc_path" >&2
return 1
}
done
set -- "$ipc_run" "$ipc_secrets"
for ipc_path in "$ipc_run/agent.sock" "$ipc_secrets/agent.token"; do
[ ! -L "$ipc_path" ] || return 1
if [ -e "$ipc_path" ]; then
case "$ipc_path" in
"$ipc_run/agent.sock") [ -S "$ipc_path" ] || return 1 ;;
*) [ -f "$ipc_path" ] || return 1 ;;
esac
[ "$(stat -c '%u:%h' -- "$ipc_path")" = 0:1 ] || return 1
set -- "$@" "$ipc_path"
fi
done
if command -v setfacl >/dev/null 2>&1; then
# chmod alone updates the ACL mask, not the owning group's ACL entry.
# Remove default ACLs too, so recreated sockets/tokens stay accessible.
setfacl -b -- "$@" && setfacl -k -- "$ipc_run" "$ipc_secrets" || {
echo 'KPanel could not normalize private IPC ACLs; installation/update stopped.' >&2
return 1
}
else
ipc_modes=$(LC_ALL=C ls -ld -- "$@") || return 1
if printf '%s\n' "$ipc_modes" | awk '$1 ~ /\+/ {found=1} END {exit !found}'; then
echo 'KPanel IPC has POSIX ACLs; install the acl package (setfacl), then retry.' >&2
return 1
fi
fi
chown root:"$ipc_gid" -- "$@" && chmod 750 -- "$ipc_run" "$ipc_secrets" || return 1
[ ! -f "$ipc_secrets/agent.token" ] || chmod 640 -- "$ipc_secrets/agent.token" || return 1
[ ! -S "$ipc_run/agent.sock" ] || chmod 660 -- "$ipc_run/agent.sock" || return 1
)
# END KPanel IPC permissions.
kpanel_create_agent_token() {
local app_dir="/home/docker/kpanel"
local panel_gid="$1"
local destination="${app_dir}/secrets/agent.token"
local temporary=""
local token=""
kpanel_prepare_ipc_permissions "${panel_gid}" "${app_dir}/run" "${app_dir}/secrets" || return 1
[ ! -e "${destination}" ] || {
echo "Agent Token 已存在,拒绝覆盖。"
return 1
}
[ -r /dev/urandom ] && command -v od >/dev/null 2>&1 &&
command -v tr >/dev/null 2>&1 || {
echo "系统缺少安全随机数或必要的 coreutils 工具。"
return 1
}
temporary="$(mktemp "${app_dir}/secrets/.agent.token.XXXXXX")" || return 1
token="$(LC_ALL=C od -An -N32 -tx1 /dev/urandom | tr -d ' \n')" || {
rm -f "${temporary}"
return 1
}
[ "${#token}" -eq 64 ] || {
echo "Agent Token 生成失败。"
rm -f "${temporary}"
return 1
}
if ! printf '%s\n' "${token}" >"${temporary}" ||
! chown root:"${panel_gid}" "${temporary}" ||
! chmod 0640 "${temporary}" ||
! mv -f "${temporary}" "${destination}"; then
rm -f "${temporary}"
return 1
fi
}
kpanel_systemctl() {
local systemctl_bin=""
if [ -x /bin/systemctl ]; then
systemctl_bin=/bin/systemctl
elif [ -x /usr/bin/systemctl ]; then
systemctl_bin=/usr/bin/systemctl
else
echo "未找到 systemd systemctl,KPanel Host Agent 无法安装。"
return 1
fi
"${systemctl_bin}" "$@"
}
kpanel_openrc_tool() {
local name="$1"
shift
local candidate=""
for candidate in "/sbin/${name}" "/usr/sbin/${name}"; do
if [ -x "${candidate}" ]; then
"${candidate}" "$@"
return $?
fi
done
echo "未找到 OpenRC ${name},KPanel Host Agent 无法管理。"
return 1
}
kpanel_system_group_add() {
local name="$1"
if command -v groupadd >/dev/null 2>&1; then
groupadd --system "${name}"
elif command -v addgroup >/dev/null 2>&1; then
addgroup -S "${name}"
else
echo "缺少系统组创建工具 groupadd/addgroup。"
return 1
fi
}
kpanel_system_group_delete() {
local name="$1"
if command -v groupdel >/dev/null 2>&1; then
groupdel "${name}"
elif command -v delgroup >/dev/null 2>&1; then
delgroup "${name}"
else
return 1
fi
}
kpanel_detect_init_system() {
if [ -d /run/systemd/system ] &&
{ [ -x /bin/systemctl ] || [ -x /usr/bin/systemctl ]; }; then
KPANEL_INIT_SYSTEM=systemd
return 0
fi
if [ -d /run/openrc ] &&
{ [ -x /sbin/rc-service ] || [ -x /usr/sbin/rc-service ]; } &&
{ [ -x /sbin/rc-update ] || [ -x /usr/sbin/rc-update ]; } &&
{ [ -x /sbin/start-stop-daemon ] || [ -x /usr/sbin/start-stop-daemon ]; } &&
{ [ -x /sbin/supervise-daemon ] || [ -x /usr/sbin/supervise-daemon ]; } &&
command -v logger >/dev/null 2>&1; then
KPANEL_INIT_SYSTEM=openrc
return 0
fi
KPANEL_INIT_SYSTEM=
return 1
}
kpanel_agent_service_managed() {
local app_dir="/home/docker/kpanel"
case "${KPANEL_INIT_SYSTEM:-}" in
systemd)
kpanel_systemd_unit_managed kejilion-agent.service "${app_dir}/kejilion-agent.service"
;;
openrc)
[ -L /etc/init.d/kejilion-agent ] &&
[ "$(readlink -f /etc/init.d/kejilion-agent)" = "$(readlink -f "${app_dir}/kejilion-agent.openrc")" ]
;;
*) return 1 ;;
esac
}
kpanel_agent_service_link() {
local app_dir="/home/docker/kpanel"
case "${KPANEL_INIT_SYSTEM}" in
systemd) kpanel_link_managed_unit kejilion-agent.service "${app_dir}/kejilion-agent.service" ;;
openrc)
[ ! -e /etc/init.d/kejilion-agent ] && [ ! -L /etc/init.d/kejilion-agent ] || return 1
ln -s "${app_dir}/kejilion-agent.openrc" /etc/init.d/kejilion-agent
;;
*) return 1 ;;
esac
}
kpanel_agent_service_reload() {
if [ "${KPANEL_INIT_SYSTEM}" = systemd ]; then
# Refresh copies after both updates and rollback of the source files.
local unit_name=""
for unit_name in kejilion-agent.service kejilion-panel-update.service kejilion-panel-update.timer; do
if [ -e "/etc/systemd/system/${unit_name}" ] || [ -L "/etc/systemd/system/${unit_name}" ]; then
kpanel_link_managed_unit "${unit_name}" "/home/docker/kpanel/${unit_name}" || return 1
fi
done
kpanel_systemctl daemon-reload
else
[ "${KPANEL_INIT_SYSTEM}" = openrc ]
fi
}
kpanel_agent_service_enable_start() {
case "${KPANEL_INIT_SYSTEM}" in
systemd) kpanel_systemctl enable --now kejilion-agent.service ;;
openrc)
kpanel_openrc_tool rc-update add kejilion-agent default &&
kpanel_openrc_tool rc-service kejilion-agent start
;;
*) return 1 ;;
esac
}
kpanel_agent_service_start() {
case "${KPANEL_INIT_SYSTEM}" in
systemd) kpanel_systemctl start kejilion-agent.service ;;
openrc) kpanel_openrc_tool rc-service kejilion-agent start ;;
*) return 1 ;;
esac
}
kpanel_agent_service_stop() {
case "${KPANEL_INIT_SYSTEM}" in
systemd) kpanel_systemctl stop kejilion-agent.service ;;
openrc) kpanel_openrc_tool rc-service kejilion-agent stop ;;
*) return 1 ;;
esac
}
kpanel_agent_service_disable_stop() {
case "${KPANEL_INIT_SYSTEM}" in
systemd) kpanel_systemctl disable --now kejilion-agent.service ;;
openrc)
kpanel_openrc_tool rc-service kejilion-agent stop >/dev/null 2>&1 || true
kpanel_openrc_tool rc-update del kejilion-agent default
;;
*) return 1 ;;
esac
}
kpanel_agent_service_unlink() {
local app_dir="/home/docker/kpanel"
if [ "${KPANEL_INIT_SYSTEM}" = systemd ]; then
kpanel_remove_managed_unit_link kejilion-agent.service "${app_dir}/kejilion-agent.service"
elif [ "${KPANEL_INIT_SYSTEM}" = openrc ] &&
[ -L /etc/init.d/kejilion-agent ] &&
[ "$(readlink -f /etc/init.d/kejilion-agent)" = "$(readlink -f "${app_dir}/kejilion-agent.openrc")" ]; then
rm -f /etc/init.d/kejilion-agent
fi
}
kpanel_update_service_link() {
local app_dir="/home/docker/kpanel"
case "${KPANEL_INIT_SYSTEM}" in
systemd)
kpanel_link_managed_unit kejilion-panel-update.service "${app_dir}/kejilion-panel-update.service" &&
kpanel_link_managed_unit kejilion-panel-update.timer "${app_dir}/kejilion-panel-update.timer"
;;
openrc) return 0 ;;
*) return 1 ;;
esac
}
kpanel_update_service_enable_start() {
case "${KPANEL_INIT_SYSTEM}" in
systemd) kpanel_systemctl enable --now kejilion-panel-update.timer ;;
openrc) return 0 ;;
*) return 1 ;;
esac
}
kpanel_update_service_disable_stop() {
case "${KPANEL_INIT_SYSTEM}" in
systemd) kpanel_systemctl disable --now kejilion-panel-update.timer ;;
openrc) return 0 ;;
*) return 1 ;;
esac
}
kpanel_update_service_unlink() {
local app_dir="/home/docker/kpanel"
case "${KPANEL_INIT_SYSTEM}" in
systemd)
kpanel_remove_managed_unit_link kejilion-panel-update.timer \
"${app_dir}/kejilion-panel-update.timer"
kpanel_remove_managed_unit_link kejilion-panel-update.service \
"${app_dir}/kejilion-panel-update.service"
;;
openrc) return 0 ;;
*) return 1 ;;
esac
}
kpanel_restore_agent_definitions() {
local app_dir="/home/docker/kpanel"
local openrc_preexisted="$1"
mv "${app_dir}/kejilion-agent.service.rollback" "${app_dir}/kejilion-agent.service" || return 1
mv "${app_dir}/agent.env.rollback" "${app_dir}/agent.env" || return 1
if [ "${openrc_preexisted}" = true ]; then
mv "${app_dir}/kejilion-agent.openrc.rollback" "${app_dir}/kejilion-agent.openrc" || return 1
else
rm -f "${app_dir}/kejilion-agent.openrc" "${app_dir}/kejilion-agent.openrc.rollback"
fi
}
kpanel_remove_agent_definition_backups() {
local app_dir="/home/docker/kpanel"
rm -f "${app_dir}/kejilion-agent.service.rollback" \
"${app_dir}/kejilion-agent.openrc.rollback" "${app_dir}/agent.env.rollback"
}
kpanel_wait_ready() {
local app_dir="/home/docker/kpanel"
local attempt=0
while [ "${attempt}" -lt 30 ]; do
if KEJILION_AGENT_SOCKET="${app_dir}/run/agent.sock" \
KEJILION_AGENT_TOKEN_FILE="${app_dir}/secrets/agent.token" \
"${app_dir}/bin/kejilion-agent" healthcheck >/dev/null 2>&1 &&
[ "$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' kejilion-panel 2>/dev/null)" = "healthy" ] &&
docker exec kejilion-panel /paneld agent-healthcheck >/dev/null 2>&1; then
return 0
fi
attempt=$((attempt + 1))
sleep 2
done
return 1
}
kpanel_running_image_id() {
local image_id=""
image_id="$(docker inspect --format '{{.Image}}' kejilion-panel 2>/dev/null)" || {
echo "无法读取当前 KPanel 容器镜像,拒绝执行可能无法回滚的更新。" >&2
return 1
}
printf '%s\n' "${image_id}" | grep -Eq '^sha256:[0-9a-f]{64}$' || {
echo "无法确认当前 KPanel 镜像 ID,拒绝执行可能无法回滚的更新。" >&2
return 1
}
printf '%s\n' "${image_id}"
}
kpanel_running_host_port() {
local host_port=""
host_port="$(docker inspect --format \
'{{with (index .HostConfig.PortBindings "8080/tcp")}}{{(index . 0).HostPort}}{{end}}' \
kejilion-panel 2>/dev/null)" || {
echo "无法读取当前 KPanel 端口映射,拒绝覆盖现有端口配置。" >&2
return 1
}
case "${host_port}" in
''|*[!0-9]*)
echo "无法确认当前 KPanel 访问端口,拒绝覆盖现有端口配置。" >&2
return 1
;;
esac
[ "${host_port}" -ge 1 ] && [ "${host_port}" -le 65535 ] || {
echo "当前 KPanel 访问端口无效,拒绝覆盖现有端口配置。" >&2
return 1
}
printf '%s\n' "${host_port}"
}
kpanel_ensure_runtime_env() {
local app_dir="/home/docker/kpanel"
local write_changes="${1:-true}"
local public_url=""
local secure_cookie=""
local secure_cookie_count=""
[ "${write_changes}" = true ] || [ "${write_changes}" = false ] || return 1
[ "$(grep -c '^KPANEL_PUBLIC_URL=' "${app_dir}/.env")" -eq 1 ] || {
echo "KPANEL_PUBLIC_URL 必须且只能配置一次。" >&2
return 1
}
public_url="$(sed -n 's/^KPANEL_PUBLIC_URL=//p' "${app_dir}/.env")"
secure_cookie_count="$(grep -c '^KPANEL_SECURE_COOKIE=' "${app_dir}/.env" || true)"
case "${secure_cookie_count}" in
0)
if printf '%s\n' "${public_url}" | grep -Eq '^https://[^/?#]+$'; then
secure_cookie=true
else
secure_cookie=false
fi
if [ "${write_changes}" = true ]; then
printf 'KPANEL_SECURE_COOKIE=%s\n' "${secure_cookie}" >>"${app_dir}/.env" || return 1
fi
;;
1)
secure_cookie="$(sed -n 's/^KPANEL_SECURE_COOKIE=//p' "${app_dir}/.env")"
;;
*)
echo "KPANEL_SECURE_COOKIE 必须且只能配置一次。" >&2
return 1
;;
esac
case "${secure_cookie}" in
true|false) ;;
*)
echo "KPANEL_SECURE_COOKIE 只允许 true 或 false。" >&2
return 1
;;
esac
}
kpanel_preflight_docker_port_publish() {
local image_id="$1"
local container_name="kpanel-network-preflight-$$-${RANDOM}"
local container_id=""
local network_name=""
network_name="$(docker inspect --format \
'{{range $name, $_ := .NetworkSettings.Networks}}{{$name}}{{"\n"}}{{end}}' \
kejilion-panel 2>/dev/null | sed -n '1p')" || return 1
[ -n "${network_name}" ] || {
echo "无法确认当前 KPanel Docker 网络,更新尚未切换任何文件或服务。" >&2
return 1
}
container_id="$(docker container create \
--name "${container_name}" \
--label io.kejilion.kpanel.network-preflight=true \
--network "${network_name}" \
--publish '127.0.0.1::8080' \
--entrypoint /paneld \
"${image_id}" healthcheck)" || {
echo "Docker 端口映射预检无法创建临时容器,更新尚未切换任何文件或服务。" >&2
return 1
}
if ! docker container start "${container_id}" >/dev/null; then
docker container rm -f "${container_id}" >/dev/null 2>&1 || true
echo "Docker 端口映射预检失败,更新尚未切换任何文件或服务。" >&2
echo "请先修复 Docker 防火墙状态(例如缺失的 DOCKER iptables 链),确认其他容器正常后重试。" >&2
return 1
fi
docker container rm -f "${container_id}" >/dev/null 2>&1 || {
echo "Docker 端口映射预检容器无法清理,拒绝继续更新。" >&2
return 1
}
}
kpanel_restore_image_tag() {
local image_id="$1"
local image="$2"
docker image tag "${image_id}" "${image}"
}
kpanel_abort_update() {
local image_id="$1"
local image="$2"
if ! kpanel_restore_image_tag "${image_id}" "${image}"; then
echo "KPanel 更新未切换服务,但旧镜像标签恢复失败;当前容器仍保持运行,请人工检查。" >&2
fi
return 0
}
kpanel_cleanup_old_images() {
local current_image_id="$1"
local image_id=""
local container_ids=""
printf '%s\n' "${current_image_id}" | grep -Eq '^sha256:[0-9a-f]{64}$' || return 0
docker image ls --all --no-trunc --quiet \
--filter 'label=org.opencontainers.image.title=KPanel' \
--filter 'label=org.opencontainers.image.source=https://github.com/kejilion/KPanel' \
2>/dev/null | sort -u | while IFS= read -r image_id; do
printf '%s\n' "${image_id}" | grep -Eq '^sha256:[0-9a-f]{64}$' || continue
[ "${image_id}" != "${current_image_id}" ] || continue
container_ids="$(docker ps -aq --filter "ancestor=${image_id}" 2>/dev/null)" || continue
[ -z "${container_ids}" ] || continue
docker image rm "${image_id}" >/dev/null 2>&1 || true
done
}
kpanel_wait_for_lifecycle_lock() {
local lock_fd="$1"
local deadline=$((SECONDS + $2))
# BusyBox flock has -n but no -w; keep the same bounded wait without
# weakening the exclusive lock shared by install, update and uninstall.
until flock -n "${lock_fd}"; do
(( SECONDS < deadline )) || return 1
sleep 1 || return 1
done
}
kpanel_with_lifecycle_lock() {
local lock_file="/run/lock/kejilion-kpanel-lifecycle.lock"
local lock_fd=""
local status=0
command -v flock >/dev/null 2>&1 || {
echo "系统缺少 flock,拒绝执行无法串行化的 KPanel 生命周期操作。" >&2
return 1
}
mkdir -p /run/lock || return 1
exec {lock_fd}>"${lock_file}" || return 1
if ! kpanel_wait_for_lifecycle_lock "${lock_fd}" 300; then
echo "另一个 KPanel 安装、更新或卸载任务仍在运行。" >&2
exec {lock_fd}>&-
return 1
fi
local KJ_KPANEL_LIFECYCLE_LOCK_HELD=1
if "$@"; then
status=0
else
status=$?
fi
flock -u "${lock_fd}" >/dev/null 2>&1 || true
exec {lock_fd}>&-
return "${status}"
}
kpanel_systemd_unit_managed() {
local unit_name="$1"
local source_path="$2"
local link_path="/etc/systemd/system/${unit_name}"
if [ -L "${link_path}" ]; then
[ -e "${source_path}" ] &&
[ "$(readlink -f "${link_path}")" = "$(readlink -f "${source_path}")" ]
else
[ -f "${link_path}" ] || return 1
case "$(stat -c '%u:%a' "${link_path}")" in 0:600|0:644) ;; *) return 1 ;; esac
[ "$(head -n 1 "${link_path}")" = "# KPanel managed unit: ${source_path}" ]
fi
}
kpanel_remove_managed_unit_link() {
if kpanel_systemd_unit_managed "$1" "$2"; then
rm -f "/etc/systemd/system/$1"
fi
}
# Return 0 for the root mount, 1 for a separate mount, 2 if undetermined.
# Mount points matter: bind mounts/subvolumes can share the root device number
# while still requiring a separate boot-time mount operation.
kpanel_path_on_root_mount() {
KPANEL_MOUNT_PATH="$1" awk '
BEGIN { path = ENVIRON["KPANEL_MOUNT_PATH"]; best = -1 }
{
mount = $5
gsub(/\\040/, " ", mount)
gsub(/\\011/, "\t", mount)
gsub(/\\012/, "\n", mount)
# Avoid awk-specific backslash replacement semantics.
count = split(mount, pieces, /\\134/)
mount = pieces[1]
for (i = 2; i <= count; i++) mount = mount sprintf("%c", 92) pieces[i]
if (mount == "/") root = 1
if (mount == "/" || path == mount || index(path, mount "/") == 1) {
if (length(mount) > best) {
best = length(mount)
selected = mount
}
}
}
END {
if (!root || best < 0) exit 2
exit (selected == "/" ? 0 : 1)
}
' /proc/self/mountinfo
}
kpanel_link_managed_unit() {
local unit_name="$1"
local source_path="$2"
local link_path="/etc/systemd/system/${unit_name}"
local mount_path=""
local temporary=""
local wants_link=""
local mount_status=0
[ -f "${source_path}" ] && [ ! -L "${source_path}" ] || return 1
if [ -e "${link_path}" ] || [ -L "${link_path}" ]; then
kpanel_systemd_unit_managed "${unit_name}" "${source_path}" || return 1
fi
mount_path="$(readlink -f /home/docker/kpanel)" || return 1
case "${mount_path}" in /*) ;; *) return 1 ;; esac
case "${mount_path}" in *$'\n'*|*$'\r'*) return 1 ;; esac
if grep -Fxq '# KPanel systemd unit copies: v1' \
"${KPANEL_UNIT_LIFECYCLE_SOURCE:-${KPANEL_ACTIVE_LIFECYCLE_SOURCE}}"; then
kpanel_path_on_root_mount "${mount_path}" || mount_status=$?
if [ "${mount_status}" -gt 1 ]; then
# Do not migrate a linked installation on inconclusive detection.
# Keep an already owned copy in its existing representation too.
if [ -f "${link_path}" ] && [ ! -L "${link_path}" ]; then
mount_status=1
else
mount_status=0
fi
fi