fix(all): use explicit configuration and repair update status
Remove redundant environment overrides, unify plugin configuration, and fix cross-drive downloads. Track completed update checks and bundled schedule identities. Restore the previous GameData contract for update verification.
This commit is contained in:
1 parent
c877cbb65a
commit
04296dc409
64 files changed
+563
-434
No files matched your search
+2
-2
@@ -16,8 +16,8 @@ RUN apt-get update \
|
||||
&& useradd --uid 10001 --gid 10001 --no-create-home --shell /usr/sbin/nologin bd2
|
||||
|
||||
WORKDIR /app
|
||||
ENV BD2_UPDATE_METHOD=docker
|
||||
COPY --from=build /out/bd2server /app/bd2server
|
||||
COPY --chmod=755 tools/server/bd2-docker-entrypoint.sh /app/bd2-docker-entrypoint.sh
|
||||
COPY versions.json CHANGELOG.md* UPDATE_FINGERPRINT.json* /app/
|
||||
COPY go/seed /app/go/seed
|
||||
COPY schedules /app/schedules
|
||||
@@ -25,5 +25,5 @@ RUN mkdir -p /app/data && chown 10001:10001 /app/data
|
||||
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/app/bd2server"]
|
||||
ENTRYPOINT ["/app/bd2-docker-entrypoint.sh"]
|
||||
CMD ["serve", "--listen", "0.0.0.0:8080", "--data-dir", "/app/data"]
|
||||
@@ -82,7 +82,7 @@ BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系
|
||||
|
||||
启动器和服务端会自动检查新版本;服务端更新可在网页管理台“版本更新”页或用 `bd2server update status|check|apply|cancel` 应用,应用前会通知在线玩家并保存存档。游戏内“新闻”公告来自签名的 [更新日志](CHANGELOG.md),按玩家的游戏语言显示。
|
||||
|
||||
服务端日志默认输出 INFO 及以上级别,仅终端启用颜色:TRACE 灰、DEBUG 青、INFO 绿、WARN 黄、ERROR 红。可用 `serve --log-level debug --log-color auto` 调整,或设置 `BD2_LOG_LEVEL` 和 `BD2_LOG_COLOR` 环境变量,显式命令行参数优先。级别支持 `trace/debug/info/warn/error`,颜色支持 `auto/always/never`。`auto` 下文件和重定向保持纯文本,`NO_COLOR` 或 `TERM=dumb` 也会关闭颜色;如需在 Docker 日志流中显示颜色,可显式选择 `always`。
|
||||
服务端日志默认输出 INFO 及以上级别,仅终端启用颜色:TRACE 灰、DEBUG 青、INFO 绿、WARN 黄、ERROR 红。可用 `serve --log-level debug --log-color auto` 调整。级别支持 `trace/debug/info/warn/error`,颜色支持 `auto/always/never`。`auto` 下文件和重定向保持纯文本,`NO_COLOR` 或 `TERM=dumb` 也会关闭颜色;如需在 Docker 日志流中显示颜色,可显式选择 `always`。
|
||||
|
||||
### 启动客户端
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"fingerprint":{"client_version":"2.36.7+client.0.2.0","game":{"build_origins":["https://cdn.dev.bd2.pmang.cloud","https://dl.dev.bd2.pmang.cloud"],"bundle_version":"20261007175947","catalog_bytes":67338179,"catalog_hash":"0f90a94601be05737f86a4ec7a1c889f","catalog_sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","data_bytes":191790996,"data_sha256":"0f28881e08029a1a53f86d5b113ba80b70b6d904bec35175b54ecfe90c2b6715","game_bytes":413552979,"game_data_version":"20261012190548","game_path":"/Build/Windows/20261002/StandaloneWindows64.2.36.7.zip","game_sha256":"3ca28b7c94d65b2cb4e33784d843902758415a3a83870c5f6198f5cd90e3bff3","game_version":"2.36.7","platform":"StandaloneWindows64","resource_files":[{"path":"GameData/20261012190548/design.version","sha256":"129dfa96fc813b22a4778a2b64dbd0afef7ab61b63550d0674066a232c40c19f","size":67},{"path":"GameData/20261012190548/release/common-dbdata.bin","sha256":"0f28881e08029a1a53f86d5b113ba80b70b6d904bec35175b54ecfe90c2b6715","size":191790996},{"path":"GameData/20261012190548/release/common-dbdata.info","sha256":"c043d0bc41f19bd06018a0453ca3c07442fa572a00f5ca204ad5c5b29d52b95d","size":10},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.hash","sha256":"743c225766ddb255b707872703dfc7dbf87e2f25b0f2d67214808f55511718e1","size":32},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.json","sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","size":67338179},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_assets_charavatar.bundle","sha256":"c723a309b7b61bc2189f539f6911c852b21783b5fcb0a7a167e2f1d073fc2b5f","size":101738625},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_scenes_charavatar.bundle","sha256":"56676c7f48d3d7c90f8956b02bc3f15f3074af7e8ff0ef64e1f9b8289eb08d52","size":31379},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_1_assets_all.bundle","sha256":"3407127468d588ff84e5158d31f2b791fb144582fc914340d307e7b79b96be22","size":44897},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_l_1_assets_all.bundle","sha256":"78ebf960a6b4f3b83fe28de1597e36f9ba7db1142bc1c0acdc9c65cd974cbbb4","size":2932480},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avataricon_1_assets_all.bundle","sha256":"b11d1072756c56a879f8b18ffc0dcb2ab16405d94418fcd9bc1e3ffb4404e321","size":2839270},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_1_assets_all.bundle","sha256":"1c844bc153dabe18b153157e466d7f7f0fa12e40c3b3ef6fc00af31abcf354e0","size":42443},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_l_1_assets_all.bundle","sha256":"c12e4bae20aedf8889d7f916cca0b3d55167a4b787bd649e07f10d21db0c49bc","size":2334709},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_1_assets_all.bundle","sha256":"bf6b432dc821a6e864993f649fedc1d03244d1ee2c93310bd0ce55d99ab8b743","size":16286},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_l_1_assets_all.bundle","sha256":"528dec1ed0c867bb6dcd59b985dc3911280f5f560c0d4b000a1e979f46f6e335","size":824161},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bgmalbum_1_assets_all.bundle","sha256":"16d606338d9b9e53a8d99d063613a8830dc943cb4225047f23b060f11614a7fc","size":614361},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animation_assets_all.bundle","sha256":"8fb500400acf16f22516a298afbef6435c42c30969c762d7eee92c1d936cf06c","size":26191},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animator_assets_all.bundle","sha256":"098045676a9b7d2c58703745bd608b2f9856027dd461012d3bde66d2f8266a16","size":6987},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-mesh_assets_all.bundle","sha256":"32a77141ffce92a510deb79f6af3309624b274c6e66493832946169a20612075","size":1617979},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-meterial_assets_all.bundle","sha256":"5d252406b5f875ca3add9da3bbbde4f7161f0fdd61f9592b3df780ce8c0ed1e1","size":384695},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group10_assets_all_49ba98afca0c02be2fc3424f638f5847.bundle","sha256":"71724987a41def2769d3bbdf79f1fb02933a0eb557d7f34a87c1e612e355c605","size":524718},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group11_assets_all_43fe4fab9a2c7d550e8bd6cc4f3b05e4.bundle","sha256":"31689c4ca268c96fd04e35d45f0bde1261b2810f32e339761889d1bebaaecfb6","size":665927},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group12_assets_all_622cf72083a2211233519e4d3074b754.bundle","sha256":"e86c377fd87f65a6092545e559a6bdd483e932741c03fe42538e9b9bc7b5dcc0","size":526015},{"path"Line truncated
|
||||
{"fingerprint":{"client_version":"2.36.7+client.0.2.0","game":{"build_origins":["https://cdn.dev.bd2.pmang.cloud","https://dl.dev.bd2.pmang.cloud"],"bundle_version":"20261007175947","catalog_bytes":67338179,"catalog_hash":"0f90a94601be05737f86a4ec7a1c889f","catalog_sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","data_bytes":191754787,"data_sha256":"44cc20963abf800f4b3af449ff901534a1b99089571a820eb7bbb841fd0f0cd1","game_bytes":413552979,"game_data_version":"20261008155037","game_path":"/Build/Windows/20261002/StandaloneWindows64.2.36.7.zip","game_sha256":"3ca28b7c94d65b2cb4e33784d843902758415a3a83870c5f6198f5cd90e3bff3","game_version":"2.36.7","platform":"StandaloneWindows64","resource_files":[{"path":"GameData/20261008155037/design.version","sha256":"df58255444317d71fe52a2029ad61dc7984a08648e182d5e160c1f5ed2ad8f8b","size":67},{"path":"GameData/20261008155037/release/common-dbdata.bin","sha256":"44cc20963abf800f4b3af449ff901534a1b99089571a820eb7bbb841fd0f0cd1","size":191754787},{"path":"GameData/20261008155037/release/common-dbdata.info","sha256":"d1f63cedd4aa4c30c6ba58bca2d833d50b669abdeb60b338f7fc974ac4c1a3bd","size":10},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.hash","sha256":"6fe5835dcb927cfe1cb2a2fc4ba3b440873d06104f8d5cc92dc2993e5cb345c6","size":33},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.json","sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","size":67338179},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_assets_charavatar.bundle","sha256":"c723a309b7b61bc2189f539f6911c852b21783b5fcb0a7a167e2f1d073fc2b5f","size":101738625},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_scenes_charavatar.bundle","sha256":"56676c7f48d3d7c90f8956b02bc3f15f3074af7e8ff0ef64e1f9b8289eb08d52","size":31379},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_1_assets_all.bundle","sha256":"3407127468d588ff84e5158d31f2b791fb144582fc914340d307e7b79b96be22","size":44897},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_l_1_assets_all.bundle","sha256":"78ebf960a6b4f3b83fe28de1597e36f9ba7db1142bc1c0acdc9c65cd974cbbb4","size":2932480},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avataricon_1_assets_all.bundle","sha256":"b11d1072756c56a879f8b18ffc0dcb2ab16405d94418fcd9bc1e3ffb4404e321","size":2839270},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_1_assets_all.bundle","sha256":"1c844bc153dabe18b153157e466d7f7f0fa12e40c3b3ef6fc00af31abcf354e0","size":42443},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_l_1_assets_all.bundle","sha256":"c12e4bae20aedf8889d7f916cca0b3d55167a4b787bd649e07f10d21db0c49bc","size":2334709},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_1_assets_all.bundle","sha256":"bf6b432dc821a6e864993f649fedc1d03244d1ee2c93310bd0ce55d99ab8b743","size":16286},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_l_1_assets_all.bundle","sha256":"528dec1ed0c867bb6dcd59b985dc3911280f5f560c0d4b000a1e979f46f6e335","size":824161},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bgmalbum_1_assets_all.bundle","sha256":"16d606338d9b9e53a8d99d063613a8830dc943cb4225047f23b060f11614a7fc","size":614361},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animation_assets_all.bundle","sha256":"8fb500400acf16f22516a298afbef6435c42c30969c762d7eee92c1d936cf06c","size":26191},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animator_assets_all.bundle","sha256":"098045676a9b7d2c58703745bd608b2f9856027dd461012d3bde66d2f8266a16","size":6987},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-mesh_assets_all.bundle","sha256":"32a77141ffce92a510deb79f6af3309624b274c6e66493832946169a20612075","size":1617979},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-meterial_assets_all.bundle","sha256":"5d252406b5f875ca3add9da3bbbde4f7161f0fdd61f9592b3df780ce8c0ed1e1","size":384695},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group10_assets_all_49ba98afca0c02be2fc3424f638f5847.bundle","sha256":"71724987a41def2769d3bbdf79f1fb02933a0eb557d7f34a87c1e612e355c605","size":524718},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group11_assets_all_43fe4fab9a2c7d550e8bd6cc4f3b05e4.bundle","sha256":"31689c4ca268c96fd04e35d45f0bde1261b2810f32e339761889d1bebaaecfb6","size":665927},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group12_assets_all_622cf72083a2211233519e4d3074b754.bundle","sha256":"e86c377fd87f65a6092545e559a6bdd483e932741c03fe42538e9b9bc7b5dcc0","size":526015},{"path"Line truncated
|
||||
@@ -57,11 +57,8 @@ func (p *sdkPackage) tasks() []taskgraph.Task {
|
||||
return err
|
||||
}},
|
||||
{Name: "sdk:prepare", DependsOn: []string{"sdk:tool"}, Run: func(context.Context) error {
|
||||
cache := os.Getenv("BD2_GAME_SDK_CACHE")
|
||||
if cache == "" {
|
||||
cache = filepath.Join(t.root, ".build", "game-sdk")
|
||||
}
|
||||
if _, err := t.sdkCommand(t.root, map[string]string{"BD2_GAME_SDK_CACHE": cache}, false, filepath.Join(p.tool, "GameSdk.dll"), "prepare-embedded", filepath.Join(p.managed, "Assembly-CSharp.dll"), p.sdk, "--game-version", p.gameVersion); err != nil {
|
||||
cache := filepath.Join(t.root, ".build", "game-sdk")
|
||||
if _, err := t.sdkCommand(t.root, nil, false, filepath.Join(p.tool, "GameSdk.dll"), "prepare-embedded", filepath.Join(p.managed, "Assembly-CSharp.dll"), p.sdk, "--game-version", p.gameVersion, "--cache-directory", cache); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
|
||||
@@ -73,6 +73,5 @@ Usage:
|
||||
bd2server update status|check|apply|cancel [--component server|schedules] [--data-dir DIR] [--in 10m | --now] [--confirm-irreversible] [--json]
|
||||
|
||||
The server binds to loopback by default.
|
||||
Logging: --log-level trace|debug|info|warn|error; --log-color auto|always|never.
|
||||
BD2_LOG_LEVEL and BD2_LOG_COLOR set defaults for all commands.`+developmentUsage())
|
||||
Logging: --log-level trace|debug|info|warn|error; --log-color auto|always|never.`+developmentUsage())
|
||||
}
|
||||
@@ -332,7 +332,11 @@ func (s *Studio) Launch(input Request) (Response, error) {
|
||||
}
|
||||
|
||||
launch := func() (Response, error) {
|
||||
settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings(), versions)
|
||||
configured := input.settings()
|
||||
if s.updates != nil {
|
||||
configured.Runtime = s.updates.Runtime(input.GameDirectory)
|
||||
}
|
||||
settings, err := clientsetup.SaveSettings(input.GameDirectory, configured, versions)
|
||||
if err != nil {
|
||||
return Response{}, err
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import "strings"
|
||||
|
||||
func isGameProxyEnvironmentKey(key string) bool {
|
||||
switch strings.ToLower(key) {
|
||||
case "unity_proxyserver", "unity_noproxy", "http_proxy", "https_proxy", "all_proxy", "no_proxy", "bd2_client_proxy_url":
|
||||
case "unity_proxyserver", "unity_noproxy", "http_proxy", "https_proxy", "all_proxy", "no_proxy":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -20,7 +20,7 @@ func gameProxyEnvironment(environment []string, proxyURL string) []string {
|
||||
result = append(result, entry)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"UNITY_PROXYSERVER", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "BD2_CLIENT_PROXY_URL"} {
|
||||
for _, key := range []string{"UNITY_PROXYSERVER", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"} {
|
||||
result = append(result, key+"="+proxyURL)
|
||||
}
|
||||
for _, key := range []string{"UNITY_NOPROXY", "NO_PROXY", "no_proxy"} {
|
||||
|
||||
@@ -8,9 +8,6 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
clientupdate "bd2server/internal/client/update"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
func ShowFatalError(err error) {
|
||||
@@ -29,7 +26,7 @@ func launchGame(target, proxyURL string) error {
|
||||
}
|
||||
// LaunchServices does not inherit open's environment; --env explicitly
|
||||
// supplies the Unity variables to the newly launched application.
|
||||
args := gameOpenArguments(target, clientupdate.LaunchEnvironment(os.Environ(), target, versionconfig.Current().ClientVersion), proxyURL)
|
||||
args := gameOpenArguments(target, os.Environ(), proxyURL)
|
||||
return exec.Command("open", args...).Start()
|
||||
}
|
||||
|
||||
@@ -38,7 +35,7 @@ func gameOpenArguments(target string, environment []string, proxyURL string) []s
|
||||
args := []string{target}
|
||||
for _, entry := range gameProxyEnvironment(environment, proxyURL) {
|
||||
key, _, found := strings.Cut(entry, "=")
|
||||
if found && (isGameProxyEnvironmentKey(key) || strings.HasPrefix(key, "BD2_")) {
|
||||
if found && isGameProxyEnvironmentKey(key) {
|
||||
args = append(args, "--env", entry)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,6 @@ import (
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
clientupdate "bd2server/internal/client/update"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
@@ -76,7 +73,7 @@ func launchGame(target, proxyURL string) error {
|
||||
}
|
||||
command := visibleCommand(target, gameLaunchArguments()...)
|
||||
command.Dir = filepath.Dir(target)
|
||||
command.Env = clientupdate.LaunchEnvironment(gameProxyEnvironment(os.Environ(), proxyURL), filepath.Dir(target), versionconfig.Current().ClientVersion)
|
||||
command.Env = gameProxyEnvironment(os.Environ(), proxyURL)
|
||||
if err := command.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -27,11 +27,21 @@ const (
|
||||
type CDNMode string
|
||||
|
||||
type Settings struct {
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ServerOrigin string `json:"server_origin"`
|
||||
CDNMode CDNMode `json:"cdn_mode"`
|
||||
LocalResourceDirectory string `json:"local_resource_directory,omitempty"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ServerOrigin string `json:"server_origin"`
|
||||
CDNMode CDNMode `json:"cdn_mode"`
|
||||
LocalResourceDirectory string `json:"local_resource_directory,omitempty"`
|
||||
Runtime *Runtime `json:"runtime,omitempty"`
|
||||
}
|
||||
|
||||
type Runtime struct {
|
||||
ClientVersion string `json:"client_version"`
|
||||
UpdateFingerprint string `json:"update_fingerprint"`
|
||||
ResourceFingerprint string `json:"resource_fingerprint"`
|
||||
GameVersion string `json:"game_version"`
|
||||
BundleVersion string `json:"bundle_version"`
|
||||
GameDataVersion string `json:"game_data_version"`
|
||||
}
|
||||
|
||||
func Path(gameDir string) string {
|
||||
@@ -73,6 +83,7 @@ func Normalize(in Settings) (Settings, error) {
|
||||
ServerOrigin: origin,
|
||||
CDNMode: in.CDNMode,
|
||||
LocalResourceDirectory: localDirectory,
|
||||
Runtime: in.Runtime,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -89,12 +89,9 @@ func (d *downloader) verified(item file) bool {
|
||||
if item.bundle && !validBundle(item.target, info.Size()) {
|
||||
return false
|
||||
}
|
||||
key, err := filepath.Rel(d.root, item.target)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
key := d.receiptKey(item.target)
|
||||
d.mu.Lock()
|
||||
previous := d.records[filepath.ToSlash(key)]
|
||||
previous := d.records[key]
|
||||
d.mu.Unlock()
|
||||
expected := item.digest
|
||||
if expected == "" && previous.Bytes == info.Size() {
|
||||
@@ -174,19 +171,23 @@ func (d *downloader) receiveOnce(ctx context.Context, item file, origin string)
|
||||
if err := os.Rename(temporary.Name(), item.target); err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := filepath.Rel(d.root, item.target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key := d.receiptKey(item.target)
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.records[filepath.ToSlash(key)] = receipt{Bytes: written, SHA256: actual}
|
||||
d.records[key] = receipt{Bytes: written, SHA256: actual}
|
||||
return commonconfig.Save(d.checkpoint, struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Files map[string]receipt `json:"files"`
|
||||
}{1, d.records}, commonconfig.WriteOptions{FileMode: 0644})
|
||||
}
|
||||
|
||||
func (d *downloader) receiptKey(target string) string {
|
||||
if relative, err := filepath.Rel(d.root, target); err == nil {
|
||||
return filepath.ToSlash(relative)
|
||||
}
|
||||
return filepath.ToSlash(filepath.Clean(target))
|
||||
}
|
||||
|
||||
func (d *downloader) receiveAll(ctx context.Context, files []file, origins []string, workers int) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
@@ -36,13 +36,7 @@ func (i Instance) WriteLauncher() (string, error) {
|
||||
body.WriteString(") Then\r\nMsgBox \"This client instance is already running.\", 48, \"BD2\"\r\nWScript.Quit 1\r\nEnd If\r\nEnd If\r\nNext\r\nSet files = CreateObject(\"Scripting.FileSystemObject\")\r\npreviousLog = ")
|
||||
body.WriteString(quote(filepath.Join(i.Root, "logs", "Player.log")))
|
||||
body.WriteString("\r\nIf files.FileExists(previousLog) Then\r\npendingLog = files.BuildPath(files.GetParentFolderName(previousLog), \"bd2-previous.\" & files.GetTempName & \".Player-prev.log\")\r\nfiles.MoveFile previousLog, pendingLog\r\nEnd If\r\n")
|
||||
body.WriteString(`environment("BD2_CLIENT_INSTANCE_ID") = `)
|
||||
body.WriteString(quote(i.ID))
|
||||
body.WriteString("\r\n")
|
||||
body.WriteString(`environment("BD2_CLIENT_INSTANCE_ROOT") = `)
|
||||
body.WriteString(quote(i.Root))
|
||||
body.WriteString("\r\n")
|
||||
for _, key := range []string{"UNITY_PROXYSERVER", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "BD2_CLIENT_PROXY_URL"} {
|
||||
for _, key := range []string{"UNITY_PROXYSERVER", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"} {
|
||||
body.WriteString("environment(")
|
||||
body.WriteString(quote(key))
|
||||
body.WriteString(") = \"\"\r\n")
|
||||
@@ -70,12 +64,7 @@ func (i Instance) WriteLauncher() (string, error) {
|
||||
quote := func(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" }
|
||||
var body strings.Builder
|
||||
body.WriteString("#!/bin/sh\nset -eu\n")
|
||||
body.WriteString("unset HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy\nexport UNITY_PROXYSERVER='' BD2_CLIENT_PROXY_URL=''\nexport UNITY_NOPROXY='localhost,127.0.0.1,::1' NO_PROXY='localhost,127.0.0.1,::1' no_proxy='localhost,127.0.0.1,::1'\n")
|
||||
body.WriteString("export BD2_CLIENT_INSTANCE_ID=")
|
||||
body.WriteString(quote(i.ID))
|
||||
body.WriteString("\nexport BD2_CLIENT_INSTANCE_ROOT=")
|
||||
body.WriteString(quote(i.Root))
|
||||
body.WriteByte('\n')
|
||||
body.WriteString("unset HTTP_PROXY HTTPS_PROXY ALL_PROXY http_proxy https_proxy all_proxy\nexport UNITY_PROXYSERVER=''\nexport UNITY_NOPROXY='localhost,127.0.0.1,::1' NO_PROXY='localhost,127.0.0.1,::1' no_proxy='localhost,127.0.0.1,::1'\n")
|
||||
body.WriteString("cd ")
|
||||
body.WriteString(quote(installation.Root))
|
||||
body.WriteString("\nprevious_log=")
|
||||
|
||||
@@ -114,7 +114,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
|
||||
}},
|
||||
taskgraph.Task{Name: "sdkPrepare", DependsOn: []string{"sdkCompile"}, Run: func(context.Context) error {
|
||||
if !sdkReused {
|
||||
if err := runPluginBuild(ctx, root, progress, sdkTool, "prepare-embedded", filepath.Join(managed, "Assembly-CSharp.dll"), sdkDir, "--game-version", gameVersion); err != nil {
|
||||
if err := runPluginBuild(ctx, root, progress, sdkTool, "prepare-embedded", filepath.Join(managed, "Assembly-CSharp.dll"), sdkDir, "--game-version", gameVersion, "--cache-directory", filepath.Join(root, ".build", "game-sdk")); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -269,13 +269,6 @@ func acquireBuildLock(ctx context.Context, work string, progress io.Writer) (fun
|
||||
func runPluginBuild(ctx context.Context, root string, progress io.Writer, args ...string) error {
|
||||
command := exec.CommandContext(ctx, "dotnet", args...)
|
||||
command.Dir = root
|
||||
for _, entry := range os.Environ() {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if !strings.EqualFold(key, "BD2_GAME_SDK_CACHE") {
|
||||
command.Env = append(command.Env, entry)
|
||||
}
|
||||
}
|
||||
command.Env = append(command.Env, "BD2_GAME_SDK_CACHE="+filepath.Join(root, ".build", "game-sdk"))
|
||||
var output bytes.Buffer
|
||||
command.Stdout = io.MultiWriter(progress, &output)
|
||||
command.Stderr = command.Stdout
|
||||
|
||||
@@ -85,6 +85,13 @@ func SaveSettings(gameDir string, settings clientconfig.Settings, versions versi
|
||||
if err != nil {
|
||||
return clientconfig.Settings{}, err
|
||||
}
|
||||
if normalized.Runtime == nil {
|
||||
if saved, err := clientconfig.Load(gameDir); err == nil {
|
||||
normalized.Runtime = saved.Runtime
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return clientconfig.Settings{}, err
|
||||
}
|
||||
}
|
||||
if normalized.CDNMode == clientconfig.CDNLocal {
|
||||
if err := InstallLocalCatalog(gameDir, normalized.LocalResourceDirectory, versions.BundleVersion); err != nil {
|
||||
return clientconfig.Settings{}, err
|
||||
|
||||
@@ -61,12 +61,37 @@ func gameReceiptMatches(game, id string) bool {
|
||||
|
||||
func (m *Manager) Versions(game string) versionconfig.Config {
|
||||
v := m.options.Versions
|
||||
if receipt, err := readGameReceipt(game); err == nil {
|
||||
if receipt, err := readGameReceipt(game); err == nil && len(receipt.Files) > 0 && gameReceiptMatches(game, receipt.Fingerprint) {
|
||||
v.GameVersion, v.BundleVersion, v.GameDataVersion = receipt.GameVersion, receipt.BundleVersion, receipt.GameDataVersion
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (m *Manager) Runtime(game string) *clientconfig.Runtime {
|
||||
v := m.Versions(game)
|
||||
runtime := &clientconfig.Runtime{ClientVersion: v.ClientVersion, GameVersion: v.GameVersion, BundleVersion: v.BundleVersion, GameDataVersion: v.GameDataVersion}
|
||||
m.mu.Lock()
|
||||
fp := m.fingerprint
|
||||
m.mu.Unlock()
|
||||
if receipt, err := readGameReceipt(game); err == nil && fp != nil && gameReceiptMatches(game, fp.ID) {
|
||||
runtime.UpdateFingerprint = fp.ID
|
||||
if receipt.ResourceFingerprint == fp.GameFingerprint && len(receipt.Files) > 0 {
|
||||
runtime.ResourceFingerprint = receipt.ResourceFingerprint
|
||||
}
|
||||
}
|
||||
return runtime
|
||||
}
|
||||
|
||||
func (m *Manager) configureGame(game string) error {
|
||||
settings, err := clientconfig.Load(game)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
settings.Runtime = m.Runtime(game)
|
||||
_, err = clientconfig.Save(game, settings)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Manager) ensureGame(ctx context.Context, game string) error {
|
||||
m.mu.Lock()
|
||||
fp := m.fingerprint
|
||||
@@ -213,7 +238,11 @@ func (m *Manager) CommitGame(ctx context.Context) error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := m.ensureGame(ctx, game); err != nil && first == nil {
|
||||
err = m.ensureGame(ctx, game)
|
||||
if err == nil {
|
||||
err = m.configureGame(game)
|
||||
}
|
||||
if err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
@@ -246,30 +275,10 @@ func (m *Manager) PrepareGame(ctx context.Context, game, origin string) error {
|
||||
if err := m.CheckServer(ctx, m.options.Client, origin); err != nil {
|
||||
return err
|
||||
}
|
||||
return m.ensureGame(ctx, game)
|
||||
}
|
||||
|
||||
func LaunchEnvironment(environment []string, game, clientVersion string) []string {
|
||||
values := map[string]string{"BD2_CLIENT_VERSION": clientVersion, "BD2_UPDATE_FINGERPRINT": "", "BD2_RESOURCE_FINGERPRINT": "", "BD2_RESOURCE_DIRECTORY": "", "BD2_GAME_VERSION": "", "BD2_BUNDLE_VERSION": "", "BD2_GAME_DATA_VERSION": ""}
|
||||
if receipt, err := readGameReceipt(game); err == nil && gameReceiptMatches(game, receipt.Fingerprint) {
|
||||
values["BD2_UPDATE_FINGERPRINT"] = receipt.Fingerprint
|
||||
values["BD2_RESOURCE_FINGERPRINT"] = receipt.ResourceFingerprint
|
||||
if receipt.ResourceFingerprint != "" && len(receipt.Files) > 0 {
|
||||
values["BD2_RESOURCE_DIRECTORY"] = receipt.Resources
|
||||
}
|
||||
values["BD2_GAME_VERSION"], values["BD2_BUNDLE_VERSION"], values["BD2_GAME_DATA_VERSION"] = receipt.GameVersion, receipt.BundleVersion, receipt.GameDataVersion
|
||||
if err := m.ensureGame(ctx, game); err != nil {
|
||||
return err
|
||||
}
|
||||
result := make([]string, 0, len(environment)+len(values))
|
||||
for _, entry := range environment {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
if _, replace := values[strings.ToUpper(key)]; !replace {
|
||||
result = append(result, entry)
|
||||
}
|
||||
}
|
||||
for key, value := range values {
|
||||
result = append(result, key+"="+value)
|
||||
}
|
||||
return result
|
||||
return m.configureGame(game)
|
||||
}
|
||||
|
||||
func (m *Manager) loadPackagedFingerprint() {
|
||||
|
||||
@@ -34,9 +34,6 @@ import (
|
||||
// StoreFile describes the launcher's plugin store, plugins/plugins.json.
|
||||
const StoreFile = "plugins.json"
|
||||
|
||||
// ManifestEnvironment overrides the built-in manifest URL.
|
||||
const ManifestEnvironment = "BD2_UPDATE_MANIFEST_URL"
|
||||
|
||||
type Store struct {
|
||||
Version string `json:"version"`
|
||||
Files []StoredFile `json:"files"`
|
||||
@@ -111,10 +108,7 @@ func New(options Options) *Manager {
|
||||
if options.Logger == nil {
|
||||
options.Logger = slog.Default()
|
||||
}
|
||||
address := strings.TrimSpace(os.Getenv(ManifestEnvironment))
|
||||
if address == "" {
|
||||
address = release.BuiltinChannel().ManifestURL
|
||||
}
|
||||
address := release.BuiltinChannel().ManifestURL
|
||||
m := &Manager{options: options, manifestURL: address, keys: release.BuiltinChannel().TrustedKeys, pending: map[string]bool{}, gamePending: map[string]bool{}}
|
||||
m.status.Enabled = address != "" && !options.Development
|
||||
m.loadPackagedFingerprint()
|
||||
@@ -255,10 +249,6 @@ func (m *Manager) Check(ctx context.Context) error {
|
||||
}
|
||||
m.status.Error = ""
|
||||
m.manifest = &manifest
|
||||
if manifest.Fingerprint != nil {
|
||||
m.fingerprint = manifest.Fingerprint
|
||||
m.fingerprintErr = nil
|
||||
}
|
||||
m.status.Game = nil
|
||||
if fp := manifest.Fingerprint; fp != nil && fp.RequireGameUpdate && fp.Game != nil {
|
||||
for _, game := range m.instances() {
|
||||
|
||||
@@ -28,26 +28,6 @@ type Options struct {
|
||||
Color ColorMode
|
||||
}
|
||||
|
||||
// OptionsFromEnv reads process-wide BD2 logging defaults.
|
||||
func OptionsFromEnv() (Options, error) {
|
||||
options := Options{Level: slog.LevelInfo, Color: ColorAuto}
|
||||
if value := os.Getenv("BD2_LOG_LEVEL"); value != "" {
|
||||
level, err := ParseLevel(value)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
options.Level = level
|
||||
}
|
||||
if value := os.Getenv("BD2_LOG_COLOR"); value != "" {
|
||||
color, err := ParseColorMode(value)
|
||||
if err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
options.Color = color
|
||||
}
|
||||
return options, nil
|
||||
}
|
||||
|
||||
func ParseLevel(value string) (slog.Level, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "trace":
|
||||
|
||||
@@ -155,13 +155,9 @@ func (c Config) Resolve(relative string) string {
|
||||
return filepath.Join(filepath.Dir(c.SourcePath), filepath.FromSlash(relative))
|
||||
}
|
||||
|
||||
// Find searches an explicit environment override first, then walks upward from
|
||||
// the executable and working directory. Release packages put versions.json
|
||||
// Find walks upward from the executable and working directory. Release packages put versions.json
|
||||
// beside the executable; development commands find the repository root.
|
||||
func Find() (Config, error) {
|
||||
if path := os.Getenv("BD2_VERSION_CONFIG"); path != "" {
|
||||
return Load(path)
|
||||
}
|
||||
var starts []string
|
||||
if executable, err := os.Executable(); err == nil {
|
||||
starts = append(starts, filepath.Dir(executable))
|
||||
@@ -186,7 +182,7 @@ func Find() (Config, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return Config{}, fmt.Errorf("versionconfig: %s not found; pass --version-config or set BD2_VERSION_CONFIG", FileName)
|
||||
return Config{}, fmt.Errorf("versionconfig: %s not found; pass --version-config", FileName)
|
||||
}
|
||||
|
||||
// Use selects an explicitly loaded configuration for all server packages.
|
||||
|
||||
@@ -1032,7 +1032,7 @@ const config = (() => {
|
||||
|
||||
/* ---------- Updates ---------- */
|
||||
const updatesView = (() => {
|
||||
let timer = null, status = null;
|
||||
let timer = null, status = null, checkRequested = false;
|
||||
const when = value => value ? dateTime(value) : '';
|
||||
const named = (group, value) => tr(`console.updates.${group}.${value}`, value);
|
||||
// Release notes arrive as {locale: text}; older servers send one string.
|
||||
@@ -1085,7 +1085,17 @@ const updatesView = (() => {
|
||||
actions.push(el('label', {}, t('console.updates.delay') + ' ', delay), confirm, el('button', {type: 'button', class: 'btn seal', onclick: apply}, t('console.updates.apply')));
|
||||
}
|
||||
$('update-actions').replaceChildren(...actions.filter(Boolean));
|
||||
|
||||
$('update-check').disabled = !!s.checking;
|
||||
if (s.checking) {
|
||||
checkRequested = true;
|
||||
await say($('update-status'), Component.translatable('console.updates.checking'));
|
||||
} else if (s.last_error) {
|
||||
checkRequested = false;
|
||||
await say($('update-status'), s.last_error, 'err');
|
||||
} else if (checkRequested) {
|
||||
checkRequested = false;
|
||||
await say($('update-status'), Component.translatable('console.updates.checked'), 'ok');
|
||||
}
|
||||
} catch (error) { if (error !== staleRender) throw error; }
|
||||
}
|
||||
async function load() {
|
||||
@@ -1109,8 +1119,8 @@ const updatesView = (() => {
|
||||
catch (error) { await say($('update-status'), error, 'err'); }
|
||||
}
|
||||
$('update-check').onclick = async () => {
|
||||
try { await api('updates/check', {method: 'POST'}); await say($('update-status'), Component.translatable('console.updates.checking')); setTimeout(load, 3000); }
|
||||
catch (error) { await say($('update-status'), error, 'err'); }
|
||||
try { checkRequested = true; await api('updates/check', {method: 'POST'}); await load(); }
|
||||
catch (error) { checkRequested = false; await say($('update-status'), error, 'err'); }
|
||||
};
|
||||
return {
|
||||
async open() { await load(); clearInterval(timer); timer = setInterval(load, 5000); },
|
||||
|
||||
@@ -437,8 +437,8 @@
|
||||
"config.updates.field.method.option.none.help": "Only checks and displays releases; updates can't be applied.",
|
||||
"config.updates.field.countdown_minutes.label": "Default countdown (minutes)",
|
||||
"config.updates.field.maintenance_minutes.label": "Expected maintenance length (minutes)",
|
||||
"config.updates.field.webhook_url_env.label": "Webhook environment variable",
|
||||
"config.updates.field.webhook_url_env.help": "When a new release is found, POSTs JSON once to the address held in this environment variable; leave empty to send nothing.",
|
||||
"config.updates.field.webhook_url.label": "Webhook URL",
|
||||
"config.updates.field.webhook_url.help": "POST JSON once to this URL when a new release is found; leave empty to send nothing.",
|
||||
"console.updates.title": "Updates",
|
||||
"console.updates.lead": "The server checks the signed release manifest at an interval and can download and verify releases ahead of time. Applying an update first notifies online players, closes new sign-ins, drains requests and saves, then switches to the new version.",
|
||||
"console.updates.check": "Check now",
|
||||
@@ -487,6 +487,7 @@
|
||||
"console.updates.scheduled": "Maintenance scheduled.",
|
||||
"console.updates.cancelled": "Maintenance cancelled.",
|
||||
"console.updates.checking": "Checking…",
|
||||
"console.updates.checked": "Check completed.",
|
||||
"console.updates.schedules.title": "Schedules",
|
||||
"console.updates.schedules.bundled": "Bundled schedules",
|
||||
"console.updates.schedules.game": "Game version",
|
||||
|
||||
@@ -437,8 +437,8 @@
|
||||
"config.updates.field.method.option.none.help": "リリースの確認と表示のみ行います。アップデートは適用できません。",
|
||||
"config.updates.field.countdown_minutes.label": "既定のカウントダウン(分)",
|
||||
"config.updates.field.maintenance_minutes.label": "メンテナンス予定時間(分)",
|
||||
"config.updates.field.webhook_url_env.label": "Webhook の環境変数",
|
||||
"config.updates.field.webhook_url_env.help": "新リリースを検出すると、この環境変数に設定されたアドレスへ JSON を 1 回 POST します。空欄の場合は送信しません。",
|
||||
"config.updates.field.webhook_url.label": "Webhook URL",
|
||||
"config.updates.field.webhook_url.help": "新リリースを検出すると、この URL に JSON を 1 回 POST します。空欄の場合は送信しません。",
|
||||
"console.updates.title": "アップデート",
|
||||
"console.updates.lead": "サーバーは署名付きのリリースマニフェストを定期的に確認し、事前にリリースをダウンロードして検証できます。適用時はまずオンラインのプレイヤーに通知し、新規ログインを停止して処理の終了を待ち、保存してから新バージョンに切り替えます。",
|
||||
"console.updates.check": "今すぐ確認",
|
||||
@@ -487,6 +487,7 @@
|
||||
"console.updates.scheduled": "メンテナンスを予定しました。",
|
||||
"console.updates.cancelled": "メンテナンスをキャンセルしました。",
|
||||
"console.updates.checking": "確認中…",
|
||||
"console.updates.checked": "確認が完了しました。",
|
||||
"console.updates.schedules.title": "スケジュール更新",
|
||||
"console.updates.schedules.bundled": "同梱スケジュール",
|
||||
"console.updates.schedules.game": "ゲームバージョン",
|
||||
|
||||
@@ -437,8 +437,8 @@
|
||||
"config.updates.field.method.option.none.help": "릴리스 확인과 표시만 하며 업데이트를 적용할 수 없습니다.",
|
||||
"config.updates.field.countdown_minutes.label": "기본 카운트다운 (분)",
|
||||
"config.updates.field.maintenance_minutes.label": "예상 점검 시간 (분)",
|
||||
"config.updates.field.webhook_url_env.label": "Webhook 환경 변수",
|
||||
"config.updates.field.webhook_url_env.help": "새 릴리스를 발견하면 이 환경 변수에 저장된 주소로 JSON을 한 번 POST합니다. 비워 두면 전송하지 않습니다.",
|
||||
"config.updates.field.webhook_url.label": "Webhook URL",
|
||||
"config.updates.field.webhook_url.help": "새 릴리스를 발견하면 이 URL로 JSON을 한 번 POST합니다. 비워 두면 전송하지 않습니다.",
|
||||
"console.updates.title": "업데이트",
|
||||
"console.updates.lead": "서버는 서명된 릴리스 매니페스트를 주기적으로 확인하며 미리 다운로드하고 검증할 수 있습니다. 적용 시 접속 중인 플레이어에게 알리고 신규 로그인을 차단한 뒤 진행 중인 요청을 마무리하고 저장하여 새 버전으로 전환합니다.",
|
||||
"console.updates.check": "지금 확인",
|
||||
@@ -487,6 +487,7 @@
|
||||
"console.updates.scheduled": "점검을 예약했습니다.",
|
||||
"console.updates.cancelled": "점검을 취소했습니다.",
|
||||
"console.updates.checking": "확인 중…",
|
||||
"console.updates.checked": "확인이 완료되었습니다.",
|
||||
"console.updates.schedules.title": "일정 업데이트",
|
||||
"console.updates.schedules.bundled": "기본 제공 일정",
|
||||
"console.updates.schedules.game": "게임 버전",
|
||||
|
||||
@@ -437,8 +437,8 @@
|
||||
"config.updates.field.method.option.none.help": "只检查和展示,不提供应用更新。",
|
||||
"config.updates.field.countdown_minutes.label": "默认倒计时(分钟)",
|
||||
"config.updates.field.maintenance_minutes.label": "预计维护时长(分钟)",
|
||||
"config.updates.field.webhook_url_env.label": "Webhook 环境变量",
|
||||
"config.updates.field.webhook_url_env.help": "发现新版时向该环境变量中的地址 POST 一次 JSON;留空不发送。",
|
||||
"config.updates.field.webhook_url.label": "Webhook 地址",
|
||||
"config.updates.field.webhook_url.help": "发现新版时向此地址 POST 一次 JSON;留空不发送。",
|
||||
"console.updates.title": "版本更新",
|
||||
"console.updates.lead": "服务端按间隔检查签名的发布清单,可提前下载并校验。应用更新会先通知在线玩家、关闭新登录、排空请求并保存,再切换到新版。",
|
||||
"console.updates.check": "立即检查",
|
||||
@@ -487,6 +487,7 @@
|
||||
"console.updates.scheduled": "已安排维护。",
|
||||
"console.updates.cancelled": "已取消维护。",
|
||||
"console.updates.checking": "正在检查……",
|
||||
"console.updates.checked": "检查完成。",
|
||||
"console.updates.schedules.title": "排期更新",
|
||||
"console.updates.schedules.bundled": "随程序附带的排期",
|
||||
"console.updates.schedules.game": "游戏版本",
|
||||
|
||||
@@ -437,8 +437,8 @@
|
||||
"config.updates.field.method.option.none.help": "只檢查和顯示新版本,無法套用更新。",
|
||||
"config.updates.field.countdown_minutes.label": "預設倒數計時(分鐘)",
|
||||
"config.updates.field.maintenance_minutes.label": "預計維護時長(分鐘)",
|
||||
"config.updates.field.webhook_url_env.label": "Webhook 環境變數",
|
||||
"config.updates.field.webhook_url_env.help": "發現新版時向該環境變數中的位址 POST 一次 JSON;留空不傳送。",
|
||||
"config.updates.field.webhook_url.label": "Webhook 位址",
|
||||
"config.updates.field.webhook_url.help": "發現新版時向此位址 POST 一次 JSON;留空不傳送。",
|
||||
"console.updates.title": "版本更新",
|
||||
"console.updates.lead": "伺服器會定期檢查已簽署的發布清單,並可提前下載及驗證。套用更新時,會先通知線上玩家、停止接受新登入、等待進行中的請求完成並儲存,再切換至新版本。",
|
||||
"console.updates.check": "立即檢查",
|
||||
@@ -487,6 +487,7 @@
|
||||
"console.updates.scheduled": "已安排維護。",
|
||||
"console.updates.cancelled": "已取消維護。",
|
||||
"console.updates.checking": "正在檢查……",
|
||||
"console.updates.checked": "檢查完成。",
|
||||
"console.updates.schedules.title": "排期更新",
|
||||
"console.updates.schedules.bundled": "程式隨附的排期",
|
||||
"console.updates.schedules.game": "遊戲版本",
|
||||
|
||||
@@ -67,8 +67,8 @@ type configuration struct {
|
||||
|
||||
func loadConfiguration(args []string) (result *configuration, loadErr error) {
|
||||
fs := flag.NewFlagSet("serve", flag.ContinueOnError)
|
||||
logLevel := fs.String("log-level", "", "log threshold: trace, debug, info, warn, error (default BD2_LOG_LEVEL or info)")
|
||||
logColor := fs.String("log-color", "", "level colors: auto, always, never (default BD2_LOG_COLOR or auto)")
|
||||
logLevel := fs.String("log-level", "", "log threshold: trace, debug, info, warn, error (default info)")
|
||||
logColor := fs.String("log-color", "", "level colors: auto, always, never (default auto)")
|
||||
versionConfigPath := fs.String("version-config", "", "repository versions.json override")
|
||||
authConfigPath := fs.String("authentication-config", "", "authentication.json path (default DATA_DIR/config/authentication.json)")
|
||||
resourceConfigPath := fs.String("resource-config", "", "resources.json path (default DATA_DIR/config/resources.json)")
|
||||
|
||||
@@ -2,15 +2,14 @@ package app
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
|
||||
"bd2server/internal/common/logging"
|
||||
)
|
||||
|
||||
func ConfigureLogging(writer io.Writer, levelOverride, colorOverride string) error {
|
||||
options, err := logging.OptionsFromEnv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
options := logging.Options{Level: slog.LevelInfo, Color: logging.ColorAuto}
|
||||
var err error
|
||||
if levelOverride != "" {
|
||||
options.Level, err = logging.ParseLevel(levelOverride)
|
||||
if err != nil {
|
||||
|
||||
@@ -8,7 +8,6 @@ package updates
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -35,7 +34,7 @@ type Config struct {
|
||||
MaintenanceMinutes int `json:"maintenance_minutes"`
|
||||
ManifestURL string `json:"manifest_url,omitempty"`
|
||||
ChangelogURLs []string `json:"changelog_urls,omitempty"`
|
||||
WebhookURLEnv string `json:"webhook_url_env,omitempty"`
|
||||
WebhookURL string `json:"webhook_url,omitempty"`
|
||||
Changelog ChangelogFlags `json:"changelog"`
|
||||
}
|
||||
|
||||
@@ -44,12 +43,8 @@ type ChangelogFlags struct {
|
||||
}
|
||||
|
||||
func Default() Config {
|
||||
method := os.Getenv("BD2_UPDATE_METHOD")
|
||||
if method == "" {
|
||||
method = MethodNative
|
||||
}
|
||||
return Config{
|
||||
Check: true, CheckInterval: "6h", Download: true, Method: method,
|
||||
Check: true, CheckInterval: "6h", Download: true, Method: MethodNative,
|
||||
CountdownMinutes: 10, MaintenanceMinutes: 5,
|
||||
|
||||
Changelog: ChangelogFlags{Notices: true},
|
||||
@@ -84,7 +79,7 @@ var Document = commonconfig.Document[Config]{
|
||||
}},
|
||||
{Path: "countdown_minutes", Kind: commonconfig.KindInteger, Label: "默认倒计时(分钟)", Min: countdownMin, Max: countdownMax},
|
||||
{Path: "maintenance_minutes", Kind: commonconfig.KindInteger, Label: "预计维护时长(分钟)", Min: downtimeMin, Max: downtimeMax},
|
||||
{Path: "webhook_url_env", Kind: commonconfig.KindString, Label: "Webhook 环境变量", Format: "env", Advanced: true, Help: "发现新版时向该环境变量中的地址 POST 一次 JSON;留空不发送。"},
|
||||
{Path: "webhook_url", Kind: commonconfig.KindString, Label: "Webhook 地址", Format: "url", Advanced: true, Help: "发现新版时向此地址 POST 一次 JSON;留空不发送。"},
|
||||
}},
|
||||
},
|
||||
},
|
||||
@@ -98,7 +93,7 @@ var Document = commonconfig.Document[Config]{
|
||||
default:
|
||||
problems = append(problems, commonconfig.Problem{Path: "method", Rule: commonconfig.RuleEnum, Message: "部署方式必须是 native、docker 或 none"})
|
||||
}
|
||||
for field, addresses := range map[string][]string{"manifest_url": {c.ManifestURL}, "changelog_urls": c.ChangelogURLs} {
|
||||
for field, addresses := range map[string][]string{"manifest_url": {c.ManifestURL}, "changelog_urls": c.ChangelogURLs, "webhook_url": {c.WebhookURL}} {
|
||||
for _, address := range addresses {
|
||||
if address == "" && field != "changelog_urls" {
|
||||
continue
|
||||
@@ -132,10 +127,7 @@ func (c Config) changelogURLs() []string {
|
||||
}
|
||||
|
||||
func (c Config) webhook() string {
|
||||
if c.WebhookURLEnv == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(os.Getenv(c.WebhookURLEnv))
|
||||
return strings.TrimSpace(c.WebhookURL)
|
||||
}
|
||||
|
||||
//go:embed lang/*.json
|
||||
|
||||
@@ -180,17 +180,43 @@ func loadScheduleSet(dataDir, id, game, gameData string) (string, error) {
|
||||
func ScheduleDirectory(dataDir, bundled, game, gameData string) (string, string, error) {
|
||||
var selected scheduleSelection
|
||||
if err := readJSON(filepath.Join(directory(dataDir), scheduleSelectionFile), &selected); errors.Is(err, os.ErrNotExist) {
|
||||
return bundled, "", nil
|
||||
id, err := bundledScheduleID(bundled, game, gameData)
|
||||
return bundled, id, err
|
||||
} else if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if selected.GameVersion != game || selected.GameDataVersion != gameData {
|
||||
return bundled, "", nil
|
||||
id, err := bundledScheduleID(bundled, game, gameData)
|
||||
return bundled, id, err
|
||||
}
|
||||
path, err := loadScheduleSet(dataDir, selected.ID, game, gameData)
|
||||
return path, selected.ID, err
|
||||
}
|
||||
|
||||
func bundledScheduleID(root, game, gameData string) (string, error) {
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
set := release.Schedules{GameVersion: game, GameDataVersion: gameData}
|
||||
for _, entry := range entries {
|
||||
if !entry.Type().IsRegular() || !strings.HasSuffix(entry.Name(), ".bd2schedule") {
|
||||
return "", fmt.Errorf("unexpected bundled schedule entry %s", entry.Name())
|
||||
}
|
||||
path := filepath.Join(root, entry.Name())
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
digest, err := release.HashFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
set.Files = append(set.Files, release.File{Name: entry.Name(), Size: info.Size(), SHA256: digest})
|
||||
}
|
||||
return set.ContentID(), nil
|
||||
}
|
||||
|
||||
func (s *Service) prepareSchedules(ctx context.Context, a *ScheduleAvailable) (string, error) {
|
||||
if a == nil {
|
||||
return "", errors.New("no schedule update available")
|
||||
|
||||
@@ -160,6 +160,13 @@ func (s *Service) Run(ctx context.Context) {
|
||||
|
||||
// CheckNow asks Run to check as soon as possible.
|
||||
func (s *Service) CheckNow() {
|
||||
s.mu.Lock()
|
||||
if s.status.Checking {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.status.Checking = true
|
||||
s.mu.Unlock()
|
||||
select {
|
||||
case s.wake <- struct{}{}:
|
||||
default:
|
||||
@@ -213,6 +220,16 @@ func (s *Service) reportChangelogFailure(message string) {
|
||||
}
|
||||
|
||||
func (s *Service) check(ctx context.Context) {
|
||||
s.mu.Lock()
|
||||
s.status.Checking = true
|
||||
s.mu.Unlock()
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
s.status.Checking = false
|
||||
s.status.LastCheck = s.options.Now().UTC()
|
||||
s.persistLocked()
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
if s.options.Config.Changelog.Notices {
|
||||
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
raw, signature, source, err := release.FetchSigned(fetchCtx, s.options.Client, s.options.Config.changelogURLs(), s.keys)
|
||||
|
||||
@@ -31,6 +31,7 @@ type Status struct {
|
||||
Countdown int `json:"countdown_minutes"`
|
||||
ManifestURL string `json:"manifest_url"`
|
||||
LastCheck time.Time `json:"last_check,omitzero"`
|
||||
Checking bool `json:"checking"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
Available *Available `json:"available,omitempty"`
|
||||
Schedules *ScheduleStatus `json:"schedules,omitempty"`
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="../Shared/ClientSettings.cs" Link="ClientSettings.cs" />
|
||||
|
||||
<Reference Include="BepInEx">
|
||||
<HintPath>$(BD2BepInExDir)\core\BepInEx.dll</HintPath>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Bd2.Client;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
@@ -191,14 +192,8 @@ public sealed class Plugin : BaseUnityPlugin
|
||||
request.Timeout = 10000;
|
||||
request.ReadWriteTimeout = 10000;
|
||||
request.AllowAutoRedirect = false;
|
||||
string proxy = Environment.GetEnvironmentVariable("BD2_CLIENT_PROXY_URL");
|
||||
if (new Uri(origin).IsLoopback || string.IsNullOrWhiteSpace(proxy)) request.Proxy = null;
|
||||
else
|
||||
{
|
||||
if (!Uri.TryCreate(proxy, UriKind.Absolute, out Uri proxyUri) || proxyUri.Scheme != "http" || proxyUri.UserInfo.Length != 0 || proxyUri.AbsolutePath != "/" || proxyUri.Query.Length != 0 || proxyUri.Fragment.Length != 0)
|
||||
throw new InvalidOperationException("Unsupported client commerce proxy");
|
||||
request.Proxy = new WebProxy(proxyUri);
|
||||
}
|
||||
string proxy = ClientSettings.Current.proxy_url;
|
||||
request.Proxy = new Uri(origin).IsLoopback || string.IsNullOrEmpty(proxy) ? null : new WebProxy(proxy);
|
||||
using var response = (HttpWebResponse)request.GetResponse();
|
||||
using Stream stream = response.GetResponseStream();
|
||||
using var reader = new StreamReader(stream);
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
<BD2SdkConfiguration Condition="'$(BD2SdkConfiguration)' == ''">Release</BD2SdkConfiguration>
|
||||
<BD2SdkTool Condition="'$(BD2SdkTool)' == ''">$(BD2PluginsDir)GameSdk/bin/$(BD2SdkConfiguration)/net8.0/GameSdk.dll</BD2SdkTool>
|
||||
<BD2SdkIntermediateFolder Condition="'$(BD2SdkIntermediateFolder)' == ''">game-sdk</BD2SdkIntermediateFolder>
|
||||
<BD2GameSdkCache Condition="'$(BD2GameSdkCache)' == ''">$(BD2_GAME_SDK_CACHE)</BD2GameSdkCache>
|
||||
<BD2GameSdkCache Condition="'$(BD2GameSdkCache)' == ''">$(BD2RepositoryDir).build/game-sdk</BD2GameSdkCache>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -9,6 +9,11 @@
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>$(BD2ManagedDir)/Newtonsoft.Json.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Compile Include="../Shared/ClientSettings.cs" Link="ClientSettings.cs" />
|
||||
<Reference Include="Unity.TextMeshPro">
|
||||
<HintPath>$(BD2ManagedDir)/Unity.TextMeshPro.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Bd2LoginUI;
|
||||
using TextComponent = BD2.GameSdk.Component;
|
||||
using System;
|
||||
using Bd2.Client;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
@@ -130,7 +131,7 @@ internal static class NativeTranslationSettings
|
||||
private static string Scope()
|
||||
{
|
||||
Uri server = ClientSession.ServerOrigin ?? throw new InvalidOperationException(TextComponent.Translatable("fchat.error.server_unconfigured").GetString());
|
||||
string root = Environment.GetEnvironmentVariable("BD2_CLIENT_INSTANCE_ROOT");
|
||||
string root = ClientSettings.CurrentInstance?.Root;
|
||||
root = Path.GetFullPath(string.IsNullOrEmpty(root) ? Paths.GameRootPath : root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
if (Environment.OSVersion.Platform == PlatformID.Win32NT) root = root.ToUpperInvariant();
|
||||
string identity = NormalizeOrigin(server) + "\0" + root;
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
<Error Condition="'$(GameDir)' == '' and '$(BD2ManagedDir)' == ''" Text="Set BD2LocalGameDir in plugins/Directory.Build.local.props, or pass -p:GameDir=<game-directory>." />
|
||||
<Error Condition="!Exists('$(BD2ManagedDir)/Assembly-CSharp.dll')" Text="Assembly-CSharp.dll missing in $(BD2ManagedDir). Set GameDir or BD2ManagedDir." />
|
||||
<Exec StdOutEncoding="utf-8" StdErrEncoding="utf-8" Condition="'$(BD2SdkPrepared)' != 'true' and ('$(DesignTimeBuild)' != 'true' or !Exists('$(BD2SdkTool)'))" Command="dotnet build "$(BD2SdkProject)" -c $(BD2SdkConfiguration) --nologo" />
|
||||
<Exec StdOutEncoding="utf-8" StdErrEncoding="utf-8" Condition="'$(BD2SdkPrepared)' != 'true'" EnvironmentVariables="BD2_GAME_SDK_CACHE=$(BD2GameSdkCache)" Command="dotnet "$(BD2SdkTool)" prepare-embedded "$(BD2ManagedDir)/Assembly-CSharp.dll" "$(BD2SdkDir)" --game-version "$(BD2GameVersion)"" />
|
||||
<Exec StdOutEncoding="utf-8" StdErrEncoding="utf-8" Condition="'$(BD2SdkPrepared)' != 'true'" Command="dotnet "$(BD2SdkTool)" prepare-embedded "$(BD2ManagedDir)/Assembly-CSharp.dll" "$(BD2SdkDir)" --game-version "$(BD2GameVersion)" --cache-directory "$(BD2GameSdkCache)"" />
|
||||
<Error Condition="!Exists('$(BD2SdkDir)/shared-sdk.txt') or !Exists('$(BD2SdkDir)/GameSdkIdentity.g.cs')" Text="Prepared game SDK is incomplete: $(BD2SdkDir)." />
|
||||
<ReadLinesFromFile File="$(BD2SdkDir)/shared-sdk.txt"><Output TaskParameter="Lines" PropertyName="BD2SharedSdkDir" /></ReadLinesFromFile>
|
||||
<Error Condition="!Exists('$(BD2SharedSdkDir)/names.json') or !Exists('$(BD2SharedSdkDir)/ref/Assembly-CSharp.Readable.dll')" Text="Prepared shared SDK is incomplete: $(BD2SharedSdkDir)." />
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
<PropertyGroup>
|
||||
<BD2GameSdkEnabled Condition="'$(BD2GameSdkEnabled)' == ''">true</BD2GameSdkEnabled>
|
||||
<BD2GameSdkPackageRoot>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)../'))</BD2GameSdkPackageRoot>
|
||||
<BD2GameSdkCache Condition="'$(BD2GameSdkCache)' == ''">$(BD2_GAME_SDK_CACHE)</BD2GameSdkCache>
|
||||
<BD2GameSdkCache Condition="'$(BD2GameSdkCache)' == ''">$([System.Environment]::GetFolderPath(SpecialFolder.LocalApplicationData))/BD2/GameSdk/navigation</BD2GameSdkCache>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -30,7 +30,7 @@
|
||||
<Error Condition="'$(GameDir)' == '' and '$(BD2ManagedDir)' == '/BrownDust II_Data/Managed'" Text="BD2.GameSdk: set GameDir in Directory.Build.props or pass -p:GameDir=<game-directory>." />
|
||||
<Error Condition="!Exists('$(BD2ManagedDir)/Assembly-CSharp.dll')" Text="BD2.GameSdk: Assembly-CSharp.dll missing in $(BD2ManagedDir). Set GameDir or BD2ManagedDir." />
|
||||
<Error Condition="'$(BD2AddBepInExReferences)' != 'false' and !Exists('$(BD2BepInExDir)/core/BepInEx.dll')" Text="BD2.GameSdk: install BepInEx or set BD2BepInExDir. Custom hosts can disable BD2AddBepInExReferences." />
|
||||
<Exec StdOutEncoding="utf-8" StdErrEncoding="utf-8" EnvironmentVariables="BD2_GAME_SDK_CACHE=$(BD2GameSdkCache)" Command="dotnet "$(BD2SdkTool)" prepare-embedded "$(BD2ManagedDir)/Assembly-CSharp.dll" "$(BD2SdkDir)" --game-version "$(BD2GameVersion)"" />
|
||||
<Exec StdOutEncoding="utf-8" StdErrEncoding="utf-8" Command="dotnet "$(BD2SdkTool)" prepare-embedded "$(BD2ManagedDir)/Assembly-CSharp.dll" "$(BD2SdkDir)" --game-version "$(BD2GameVersion)" --cache-directory "$(BD2GameSdkCache)"" />
|
||||
<ReadLinesFromFile File="$(BD2SdkDir)/shared-sdk.txt"><Output TaskParameter="Lines" PropertyName="BD2SharedSdkDir" /></ReadLinesFromFile>
|
||||
<ItemGroup>
|
||||
<Reference Remove="Assembly-CSharp.Readable" />
|
||||
|
||||
+25
-10
@@ -20,9 +20,8 @@ internal static class Program
|
||||
switch (args.FirstOrDefault())
|
||||
{
|
||||
case "prepare" when args.Length == 5: Prepare(args[1], args[2], args[3], args[4]); break;
|
||||
case "prepare-embedded" when args.Length is 3 or 5:
|
||||
if (args.Length == 5 && args[3] != "--game-version") throw new ArgumentException("Invalid prepare-embedded options");
|
||||
PrepareEmbedded(args[1], args[2], args.Length == 5 ? args[4] : null); break;
|
||||
case "prepare-embedded" when args.Length >= 3:
|
||||
PrepareEmbeddedCommand(args); break;
|
||||
case "export-names" when args.Length == 2: ExportNames(args[1]); break;
|
||||
case "names" when args.Length == 5: NameGenerator.Generate(args[1], args[2], args[3], args[4]); break;
|
||||
case "shell" when args.Length == 4: ShellGenerator.Generate(args[1], args[2], args[3]); break;
|
||||
@@ -32,7 +31,7 @@ internal static class Program
|
||||
case "verify" when args.Length is 3 or 4: Verify(args[1], args[2], args.Length == 4 ? args[3] : null); break;
|
||||
case "validate-lang" when args.Length == 2: LanguageAssets.Validate(args[1]); break;
|
||||
|
||||
default: throw new ArgumentException("Usage: prepare-embedded <Assembly-CSharp.dll> <output-dir> [--game-version version] | export-names <names.json> | names <Assembly-CSharp.dll> <mapping.obfuscate> <versions.json> <names.json> | shell <names.json> <Assembly-CSharp.dll> <output.dll> | source-navigation <readable-implementation.dll> <dependency-directory> | verify-navigation <sdk-directory> | reobf <names.json> <input.dll> <output.dll> [Assembly-CSharp.dll] [dependency-directory] | verify <names.json> <plugin.dll> [Assembly-CSharp.dll]");
|
||||
default: throw new ArgumentException("Usage: prepare-embedded <Assembly-CSharp.dll> <output-dir> [--game-version version] [--cache-directory directory] | export-names <names.json> | names <Assembly-CSharp.dll> <mapping.obfuscate> <versions.json> <names.json> | shell <names.json> <Assembly-CSharp.dll> <output.dll> | source-navigation <readable-implementation.dll> <dependency-directory> | verify-navigation <sdk-directory> | reobf <names.json> <input.dll> <output.dll> [Assembly-CSharp.dll] [dependency-directory] | verify <names.json> <plugin.dll> [Assembly-CSharp.dll]");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -69,13 +68,30 @@ internal static class Program
|
||||
return File.Exists(pointer) ? File.ReadAllText(pointer).Trim() : Path.GetFullPath(directory);
|
||||
}
|
||||
|
||||
internal static void PrepareEmbedded(string assembly, string output, string expectedGameVersion = null) =>
|
||||
PrepareShared(EmbeddedNames(), assembly, output, expectedGameVersion);
|
||||
private static void PrepareEmbeddedCommand(string[] args)
|
||||
{
|
||||
string gameVersion = null, cacheDirectory = null;
|
||||
for (int index = 3; index < args.Length; index += 2)
|
||||
{
|
||||
if (index + 1 >= args.Length || string.IsNullOrWhiteSpace(args[index + 1]))
|
||||
throw new ArgumentException("Invalid prepare-embedded options");
|
||||
switch (args[index])
|
||||
{
|
||||
case "--game-version" when gameVersion == null: gameVersion = args[index + 1]; break;
|
||||
case "--cache-directory" when cacheDirectory == null: cacheDirectory = args[index + 1]; break;
|
||||
default: throw new ArgumentException("Invalid prepare-embedded options");
|
||||
}
|
||||
}
|
||||
PrepareEmbedded(args[1], args[2], gameVersion, cacheDirectory);
|
||||
}
|
||||
|
||||
internal static void PrepareEmbedded(string assembly, string output, string expectedGameVersion = null, string cacheDirectory = null) =>
|
||||
PrepareShared(EmbeddedNames(), assembly, output, expectedGameVersion, cacheDirectory);
|
||||
|
||||
internal static void PreparePackage(string compressedTable, string assembly, string output) =>
|
||||
PrepareShared(File.ReadAllBytes(compressedTable), assembly, output, null);
|
||||
PrepareShared(File.ReadAllBytes(compressedTable), assembly, output, null, null);
|
||||
|
||||
private static void PrepareShared(byte[] compressed, string assembly, string output, string expectedGameVersion)
|
||||
private static void PrepareShared(byte[] compressed, string assembly, string output, string expectedGameVersion, string cacheDirectory)
|
||||
{
|
||||
output = Path.GetFullPath(output);
|
||||
Directory.CreateDirectory(output);
|
||||
@@ -90,8 +106,7 @@ internal static class Program
|
||||
throw new InvalidDataException($"Plugin requires game {expectedGameVersion}, but SDK names target game {gameVersion}. Install the matching SDK package.");
|
||||
if (Hash(assembly) != table.assembly_sha256)
|
||||
throw new InvalidDataException("Game DLL does not match SDK names for game " + gameVersion);
|
||||
string cacheRoot = Environment.GetEnvironmentVariable("BD2_GAME_SDK_CACHE");
|
||||
if (string.IsNullOrEmpty(cacheRoot)) cacheRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "BD2", "GameSdk", "navigation");
|
||||
string cacheRoot = cacheDirectory ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "BD2", "GameSdk", "navigation");
|
||||
string tableHash = Convert.ToHexString(SHA256.HashData(compressed)).ToLowerInvariant();
|
||||
string inputs = tableHash + "|" + GenerationInputs.Stamp() + "|" + DependencyStamp(assembly);
|
||||
// Game version is the public grouping; the fingerprint prevents incompatible
|
||||
|
||||
@@ -82,7 +82,7 @@ IDE 项目加载时构建会准备可读引用,CLI 首次构建同样会自动
|
||||
|
||||
构建核对声明值、SDK 内嵌表、真实游戏 DLL 指纹。缺少声明或版本不匹配会报错;不会自动选用其他版本。NuGet 项目仍需安装带对应游戏版本的包。
|
||||
|
||||
仓库默认缓存根为 `.build/game-sdk`,与源码位于同一盘。第三方 NuGet 项目默认使用 `%LOCALAPPDATA%\BD2\GameSdk\navigation`;可在本机 `Directory.Build.props` 设置 `BD2GameSdkCache`,或设置环境变量 `BD2_GAME_SDK_CACHE`。 `obj` 不影响共享缓存。缺失的共享源码可在下次准备时从 PDB 恢复。真实游戏 DLL、映射表、游戏依赖、生成逻辑或反编译依赖改变时会生成新的缓存。
|
||||
仓库默认缓存根为 `.build/game-sdk`,与源码位于同一盘。第三方 NuGet 项目默认使用 `%LOCALAPPDATA%\BD2\GameSdk\navigation`;可在本机 `Directory.Build.props` 设置 `BD2GameSdkCache`。 `obj` 不影响共享缓存。缺失的共享源码可在下次准备时从 PDB 恢复。真实游戏 DLL、映射表、游戏依赖、生成逻辑或反编译依赖改变时会生成新的缓存。
|
||||
|
||||
`lib` 中的程序集仅供开发导航,**不要部署或执行**。这里展示的是当前 DLL 的反编译源码,局部变量名和语法可能与原始工程不同。导航 PDB 对应可读程序集,不能用于真实混淆游戏 DLL 的逐行调试。
|
||||
|
||||
@@ -125,7 +125,7 @@ owner.StartCoroutine(Game.MemberName(owner.GetType(), "ReadableCoroutineName"));
|
||||
| `GameDir` | 游戏根目录,本机安装路径(另须在插件 csproj 声明 BD2GameVersion) |
|
||||
| `BD2ManagedDir` | 自定义 Managed 路径,默认 `GameDir/BrownDust II_Data/Managed` |
|
||||
| `BD2BepInExDir` | 自定义 BepInEx 路径,默认 `GameDir/BepInEx` |
|
||||
| `BD2GameSdkCache` | 共享导航缓存目录,可在 `Directory.Build.props` 配置;默认取 `BD2_GAME_SDK_CACHE` 环境变量或用户缓存目录 |
|
||||
| `BD2GameSdkCache` | 共享导航缓存目录,可在 `Directory.Build.props` 配置;默认取用户缓存目录 |
|
||||
| `BD2AddBepInExReferences=false` | 使用其他宿主或自己提供 BepInEx/Harmony 引用时关闭自动引用 |
|
||||
| `BD2AddUnityReferences=false` | 自己提供 Unity 引用时关闭自动引用 |
|
||||
| `BD2GameSdkEnabled=false` | 暂时关闭壳生成与 reobf;只适用于不依赖可读游戏 API 的项目 |
|
||||
@@ -8,6 +8,7 @@ using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using BD2.GameNames;
|
||||
using Bd2.Client;
|
||||
using BepInEx;
|
||||
using BepInEx.Logging;
|
||||
using HarmonyLib;
|
||||
@@ -29,29 +30,13 @@ internal static class ClientInstanceIsolation
|
||||
|
||||
internal static void Install(Harmony harmony, ManualLogSource log)
|
||||
{
|
||||
string id = Environment.GetEnvironmentVariable("BD2_CLIENT_INSTANCE_ID");
|
||||
string root = Environment.GetEnvironmentVariable("BD2_CLIENT_INSTANCE_ROOT");
|
||||
Log = log;
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(id) && string.IsNullOrEmpty(root))
|
||||
{
|
||||
string instanceRoot = Directory.GetParent(Paths.GameRootPath)?.FullName;
|
||||
if (instanceRoot != null && File.Exists(Path.Combine(instanceRoot, "instance.json")))
|
||||
throw new InvalidOperationException("This client belongs to an isolated instance. Start it using the instance .vbs launcher so Unity logs and credentials remain isolated");
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(id) || id.Length > 64 || id == "." || id == "..")
|
||||
throw new InvalidDataException("BD2_CLIENT_INSTANCE_ID must be a safe instance name");
|
||||
foreach (char character in id)
|
||||
if (!(character >= 'a' && character <= 'z') && !(character >= 'A' && character <= 'Z') &&
|
||||
!(character >= '0' && character <= '9') && character != '-' && character != '_')
|
||||
throw new InvalidDataException("BD2_CLIENT_INSTANCE_ID contains an unsupported character");
|
||||
if (string.IsNullOrEmpty(root) || !Path.IsPathFullyQualified(root))
|
||||
throw new InvalidDataException("BD2_CLIENT_INSTANCE_ROOT must be an absolute directory");
|
||||
root = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
if (root.Length <= Path.GetPathRoot(root).Length)
|
||||
throw new InvalidDataException("BD2_CLIENT_INSTANCE_ROOT cannot be a filesystem root");
|
||||
ClientInstance instance = ClientSettings.CurrentInstance;
|
||||
if (instance == null) return;
|
||||
string id = instance.ID;
|
||||
string root = instance.Root;
|
||||
|
||||
using (var sha = SHA256.Create())
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Bd2.Client;
|
||||
using BD2.GameNames;
|
||||
using static BD2.GameNames.Game;
|
||||
using System.Reflection;
|
||||
@@ -16,7 +17,7 @@ internal static class ClientPresentation
|
||||
|
||||
internal static void InstallStartupFullscreen(Harmony harmony, Type appManager)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BD2_CLIENT_INSTANCE_ID")))
|
||||
if (ClientSettings.CurrentInstance != null)
|
||||
{
|
||||
Log?.LogInfo("Client instance startup respects launcher window parameters");
|
||||
return;
|
||||
|
||||
@@ -5,7 +5,7 @@ using HarmonyLib;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using BepInEx;
|
||||
using Bd2.Client;
|
||||
using BepInEx.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
@@ -14,7 +14,6 @@ namespace Bd2LocalIdentity;
|
||||
|
||||
internal sealed class ClientRouting : IDisposable
|
||||
{
|
||||
private static readonly char[] InvalidOriginCharacters = ['?', '#', '@', '%'];
|
||||
private static ClientRouting installedRouting;
|
||||
private static ManualLogSource routingLog;
|
||||
|
||||
@@ -58,30 +57,15 @@ internal sealed class ClientRouting : IDisposable
|
||||
}
|
||||
|
||||
|
||||
private const string ConfigFileName = "bd2.client.json";
|
||||
private const string OfficialServerData = "https://bd2-cdn.akamaized.net/ServerData";
|
||||
private const string OfficialGameData = "https://bd2-cdn.akamaized.net/GameData";
|
||||
private const int MaximumResponseBytes = 16 * 1024;
|
||||
private static readonly string BundleVersion = LauncherResourceVersion("BD2_BUNDLE_VERSION", Bd2Build.Versions.Bundle);
|
||||
private static readonly string GameDataVersion = LauncherResourceVersion("BD2_GAME_DATA_VERSION", Bd2Build.Versions.GameData);
|
||||
|
||||
private static string LauncherResourceVersion(string name, string fallback)
|
||||
{
|
||||
string value = Environment.GetEnvironmentVariable(name);
|
||||
if (string.IsNullOrEmpty(value)) return fallback;
|
||||
string fingerprint = Environment.GetEnvironmentVariable("BD2_UPDATE_FINGERPRINT");
|
||||
if (string.IsNullOrEmpty(fingerprint) || fingerprint.Length != 64 || value.Length != 14)
|
||||
throw new InvalidDataException("Launcher resource versions require a verified update fingerprint");
|
||||
foreach (char digit in value)
|
||||
if (digit < '0' || digit > '9') throw new InvalidDataException("Invalid launcher resource version");
|
||||
foreach (char digit in fingerprint)
|
||||
if (!(digit >= '0' && digit <= '9') && !(digit >= 'a' && digit <= 'f'))
|
||||
throw new InvalidDataException("Invalid launcher update fingerprint");
|
||||
return value;
|
||||
}
|
||||
private static string BundleVersion => ClientSettings.Current.BundleVersion;
|
||||
private static string GameDataVersion => ClientSettings.Current.GameDataVersion;
|
||||
internal static bool IsActive => installedRouting != null;
|
||||
|
||||
private readonly ManualLogSource log;
|
||||
private readonly ClientConfig config;
|
||||
private readonly ClientSettings config;
|
||||
internal string ServerOrigin => config.server_origin;
|
||||
internal Uri ServerRoot => new(config.server_origin + "/");
|
||||
private readonly ResourcePolicy resources;
|
||||
@@ -89,7 +73,7 @@ internal sealed class ClientRouting : IDisposable
|
||||
|
||||
private ClientRouting(
|
||||
ManualLogSource log,
|
||||
ClientConfig config,
|
||||
ClientSettings config,
|
||||
ResourcePolicy resources,
|
||||
LocalResourceServer localResourceServer)
|
||||
{
|
||||
@@ -101,31 +85,10 @@ internal sealed class ClientRouting : IDisposable
|
||||
|
||||
internal static ClientRouting Load(ManualLogSource log)
|
||||
{
|
||||
Environment.SetEnvironmentVariable("BD2_CLIENT_SERVER_ORIGIN", null);
|
||||
string path = Path.Combine(Paths.ConfigPath, ConfigFileName);
|
||||
ClientConfig config = ParseConfig(ReadBoundedFile(path, MaximumResponseBytes));
|
||||
// Set only our process-local choice. Login UI also uses this value when
|
||||
// the game is launched directly; it never imports a system proxy.
|
||||
Environment.SetEnvironmentVariable("BD2_CLIENT_PROXY_URL", config.proxy_url);
|
||||
ValidateOrigin(config.server_origin, "server_origin");
|
||||
config.server_origin = config.server_origin.TrimEnd('/');
|
||||
|
||||
ClientSettings config = ClientSettings.Current;
|
||||
ResourcePolicy resources;
|
||||
LocalResourceServer localResourceServer = null;
|
||||
string verifiedResources = Environment.GetEnvironmentVariable("BD2_RESOURCE_DIRECTORY");
|
||||
string effectiveMode = config.cdn_mode;
|
||||
if (!string.IsNullOrEmpty(verifiedResources))
|
||||
{
|
||||
string fingerprint = Environment.GetEnvironmentVariable("BD2_RESOURCE_FINGERPRINT");
|
||||
if (string.IsNullOrEmpty(fingerprint) || fingerprint.Length != 64 ||
|
||||
string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BD2_UPDATE_FINGERPRINT")) ||
|
||||
!Path.IsPathRooted(verifiedResources))
|
||||
throw new InvalidDataException("Launcher resource directory requires a verified update fingerprint");
|
||||
foreach (char digit in fingerprint)
|
||||
if (!(digit >= '0' && digit <= '9') && !(digit >= 'a' && digit <= 'f'))
|
||||
throw new InvalidDataException("Invalid launcher resource fingerprint");
|
||||
effectiveMode = "local";
|
||||
}
|
||||
try
|
||||
{
|
||||
if (effectiveMode == "official")
|
||||
@@ -144,7 +107,7 @@ internal sealed class ClientRouting : IDisposable
|
||||
{
|
||||
localResourceServer = LocalResourceServer.Start(
|
||||
log,
|
||||
string.IsNullOrEmpty(verifiedResources) ? config.local_resource_directory : verifiedResources,
|
||||
config.local_resource_directory,
|
||||
BundleVersion,
|
||||
GameDataVersion);
|
||||
resources = new ResourcePolicy
|
||||
@@ -163,7 +126,6 @@ internal sealed class ClientRouting : IDisposable
|
||||
resources = RequestResourcePolicy(log, config);
|
||||
}
|
||||
ValidatePolicy(effectiveMode, resources);
|
||||
Environment.SetEnvironmentVariable("BD2_CLIENT_SERVER_ORIGIN", config.server_origin);
|
||||
return new ClientRouting(log, config, resources, localResourceServer);
|
||||
}
|
||||
catch
|
||||
@@ -200,7 +162,7 @@ internal sealed class ClientRouting : IDisposable
|
||||
" game_data_version=" + resources.game_data_version);
|
||||
}
|
||||
|
||||
private static ResourcePolicy RequestResourcePolicy(ManualLogSource log, ClientConfig config)
|
||||
private static ResourcePolicy RequestResourcePolicy(ManualLogSource log, ClientSettings config)
|
||||
{
|
||||
var endpoint = new Uri(new Uri(config.server_origin + "/"), "client/resources");
|
||||
byte[] body = Encoding.UTF8.GetBytes("{\"cdn_mode\":\"" + config.cdn_mode + "\"}");
|
||||
@@ -245,61 +207,6 @@ internal sealed class ClientRouting : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static ClientConfig ParseConfig(string json)
|
||||
{
|
||||
JObject value = ParseObject(json, "client configuration");
|
||||
RequireOnly(value, "schema_version", "server_origin", "cdn_mode", "local_resource_directory", "proxy_url");
|
||||
var config = new ClientConfig
|
||||
{
|
||||
schema_version = RequiredInteger(value, "schema_version"),
|
||||
server_origin = RequiredString(value, "server_origin"),
|
||||
cdn_mode = RequiredString(value, "cdn_mode"),
|
||||
local_resource_directory = OptionalString(value, "local_resource_directory"),
|
||||
proxy_url = NormalizeClientProxy(OptionalString(value, "proxy_url"))
|
||||
};
|
||||
if (config.schema_version != 2)
|
||||
{
|
||||
throw new InvalidDataException("bd2.client.json schema_version must be 2");
|
||||
}
|
||||
if (config.cdn_mode != "official" && config.cdn_mode != "local" && config.cdn_mode != "server")
|
||||
{
|
||||
throw new InvalidDataException("bd2.client.json cdn_mode must be official, local, or server");
|
||||
}
|
||||
if (config.cdn_mode == "local" && string.IsNullOrWhiteSpace(config.local_resource_directory))
|
||||
{
|
||||
throw new InvalidDataException("local_resource_directory is required when cdn_mode is local");
|
||||
}
|
||||
if (config.cdn_mode != "local" && !string.IsNullOrWhiteSpace(config.local_resource_directory))
|
||||
{
|
||||
throw new InvalidDataException("local_resource_directory is only valid when cdn_mode is local");
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
private static string NormalizeClientProxy(string raw)
|
||||
{
|
||||
raw = raw.Trim();
|
||||
if (raw.Length == 0) return string.Empty;
|
||||
const string error = "proxy_url must be an HTTP proxy address with an explicit port and no credentials or path";
|
||||
if (raw.IndexOfAny(InvalidOriginCharacters) >= 0) throw new InvalidDataException(error);
|
||||
foreach (char character in raw)
|
||||
if (char.IsWhiteSpace(character) || char.IsControl(character)) throw new InvalidDataException(error);
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out Uri proxy) || proxy.Scheme != "http" ||
|
||||
string.IsNullOrEmpty(proxy.Host) || !string.IsNullOrEmpty(proxy.UserInfo) ||
|
||||
!string.IsNullOrEmpty(proxy.Query) || !string.IsNullOrEmpty(proxy.Fragment) || proxy.AbsolutePath != "/")
|
||||
throw new InvalidDataException(error);
|
||||
string authority = raw[(raw.IndexOf("://", StringComparison.Ordinal) + 3)..].TrimEnd('/');
|
||||
int separator = authority.LastIndexOf(':');
|
||||
if (separator <= 0) throw new InvalidDataException(error);
|
||||
string portText = authority[(separator + 1)..];
|
||||
foreach (char character in portText) if (character < '0' || character > '9') throw new InvalidDataException(error);
|
||||
if (!int.TryParse(portText, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture,
|
||||
out int port) || port < 1 || port > 65535) throw new InvalidDataException(error);
|
||||
string host = proxy.IdnHost.Trim('[', ']');
|
||||
if (proxy.HostNameType == UriHostNameType.IPv6) host = "[" + host + "]";
|
||||
return "http://" + host + ":" + port.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static ResourcePolicy ParsePolicy(string json)
|
||||
{
|
||||
JObject value = ParseObject(json, "resource policy");
|
||||
@@ -360,17 +267,6 @@ internal sealed class ClientRouting : IDisposable
|
||||
policy.game_data_url = policy.game_data_url.TrimEnd('/');
|
||||
}
|
||||
|
||||
private static void ValidateOrigin(string raw, string name)
|
||||
{
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out Uri uri) ||
|
||||
!string.IsNullOrEmpty(uri.UserInfo) || uri.AbsolutePath != "/" ||
|
||||
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) ||
|
||||
(uri.Scheme != Uri.UriSchemeHttps && !(uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback)))
|
||||
{
|
||||
throw new InvalidDataException(name + " must be an HTTPS origin, except that loopback may use HTTP");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateResourceURL(string raw, string name)
|
||||
{
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out Uri uri) ||
|
||||
@@ -381,16 +277,6 @@ internal sealed class ClientRouting : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static string ReadBoundedFile(string path, int maximumBytes)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
throw new FileNotFoundException("Client routing configuration is missing", path);
|
||||
}
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
return ReadBoundedStream(stream, maximumBytes);
|
||||
}
|
||||
|
||||
private static string ReadBoundedStream(Stream stream, int maximumBytes)
|
||||
{
|
||||
using var output = new MemoryStream();
|
||||
@@ -432,39 +318,6 @@ internal sealed class ClientRouting : IDisposable
|
||||
return (string)token;
|
||||
}
|
||||
|
||||
private static int RequiredInteger(JObject value, string name)
|
||||
{
|
||||
JToken token = value[name];
|
||||
if (token == null || token.Type != JTokenType.Integer)
|
||||
{
|
||||
throw new InvalidDataException(name + " must be an integer");
|
||||
}
|
||||
return (int)token;
|
||||
}
|
||||
|
||||
private static string OptionalString(JObject value, string name)
|
||||
{
|
||||
JToken token = value[name];
|
||||
if (token == null || token.Type == JTokenType.Null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
if (token.Type != JTokenType.String)
|
||||
{
|
||||
throw new InvalidDataException(name + " must be a string when present");
|
||||
}
|
||||
return (string)token;
|
||||
}
|
||||
|
||||
private sealed class ClientConfig
|
||||
{
|
||||
public int schema_version;
|
||||
public string server_origin;
|
||||
public string cdn_mode;
|
||||
public string local_resource_directory;
|
||||
public string proxy_url;
|
||||
}
|
||||
|
||||
private sealed class ResourcePolicy
|
||||
{
|
||||
public string mode;
|
||||
|
||||
@@ -31,7 +31,7 @@ internal static class EventHubPresentation
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
|
||||
private static void ReceivePostfix(IMessage __0, int __2, bool __result)
|
||||
{
|
||||
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BD2_CLIENT_SERVER_ORIGIN")) || BDNetwork.CommonPacket.UserInfo == null || !__result || __2 > 0 ||
|
||||
if (!ClientRouting.IsActive || BDNetwork.CommonPacket.UserInfo == null || !__result || __2 > 0 ||
|
||||
__0 is not MiniEventHubInfoResponse response || response.MiniEventHubInfo.Count != 0) return;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -44,7 +44,7 @@ internal static class EventRequestDiagnostics
|
||||
catch (Exception error) { Log?.LogWarning("Event diagnostic binding unavailable: target=" + type.Name + "." + name + " exception=" + error.GetType().Name); }
|
||||
}
|
||||
|
||||
private static bool Enabled => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BD2_CLIENT_SERVER_ORIGIN")) && BDNetwork.CommonPacket.UserInfo != null;
|
||||
private static bool Enabled => ClientRouting.IsActive && BDNetwork.CommonPacket.UserInfo != null;
|
||||
private static bool ShouldLog(string key, out string sample)
|
||||
{
|
||||
sample = "";
|
||||
|
||||
@@ -58,7 +58,7 @@ internal static class FieldTransitionDiagnostics
|
||||
postfix: postfix == null ? null : new HarmonyMethod(typeof(FieldTransitionDiagnostics), postfix));
|
||||
}
|
||||
|
||||
private static bool Local => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("BD2_CLIENT_SERVER_ORIGIN"));
|
||||
private static bool Local => ClientRouting.IsActive;
|
||||
private static bool Capturing => Local && Time.realtimeSinceStartup <= CaptureUntil && Sequence != 0;
|
||||
|
||||
private static void Begin(int questId, bool accept)
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="../Shared/ClientSettings.cs" Link="ClientSettings.cs" />
|
||||
<Reference Include="Google.Protobuf">
|
||||
<HintPath>$(BD2ManagedDir)/Google.Protobuf.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System;
|
||||
using Bd2Login;
|
||||
using Bd2.Client;
|
||||
|
||||
namespace Bd2LoginUI;
|
||||
|
||||
@@ -14,13 +14,6 @@ public static class ClientSession
|
||||
|
||||
private static Uri ReadConfiguredOrigin()
|
||||
{
|
||||
string configured = Environment.GetEnvironmentVariable("BD2_CLIENT_SERVER_ORIGIN");
|
||||
if (string.IsNullOrEmpty(configured)) return null;
|
||||
if (!Uri.TryCreate(configured, UriKind.Absolute, out Uri origin) ||
|
||||
(origin.Scheme != Uri.UriSchemeHttps && !(origin.Scheme == Uri.UriSchemeHttp && origin.IsLoopback)) ||
|
||||
string.IsNullOrEmpty(origin.Host) || origin.UserInfo.Length != 0 ||
|
||||
origin.AbsolutePath != "/" || origin.Query.Length != 0 || origin.Fragment.Length != 0)
|
||||
throw new InvalidOperationException("Validated client server origin is unavailable");
|
||||
return new Uri(ServerLoginPreferences.NormalizeOrigin(origin) + "/");
|
||||
return new Uri(ClientSettings.Current.server_origin + "/");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@
|
||||
<BD2GameVersion>2.36.7</BD2GameVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>$(BD2ManagedDir)/Newtonsoft.Json.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Compile Include="../Shared/ClientSettings.cs" Link="ClientSettings.cs" />
|
||||
<Reference Include="Unity.TextMeshPro">
|
||||
<HintPath>$(BD2ManagedDir)/Unity.TextMeshPro.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Bd2.Client;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
@@ -21,46 +21,15 @@ internal sealed class NativeProxySettings
|
||||
}
|
||||
}
|
||||
|
||||
// Only the player's persisted client choice controls owned HTTP requests.
|
||||
// Local Identity and Client Studio supply this process-local value; inherited
|
||||
// system, Unity and standard HTTP proxy settings are never used as a fallback.
|
||||
internal static class NativeProxyPolicy
|
||||
{
|
||||
private static readonly char[] InvalidProxyCharacters = ['?', '#', '@', '%'];
|
||||
private const string ProxyVariable = "BD2_CLIENT_PROXY_URL";
|
||||
|
||||
public static NativeProxySettings Resolve(Uri destination)
|
||||
{
|
||||
if (destination == null || !destination.IsAbsoluteUri) throw new ArgumentException("Invalid proxy destination");
|
||||
if (destination.IsLoopback) return new NativeProxySettings(null, "loopback");
|
||||
string selected = Environment.GetEnvironmentVariable(ProxyVariable);
|
||||
string selected = ClientSettings.Current.proxy_url;
|
||||
if (string.IsNullOrWhiteSpace(selected)) return new NativeProxySettings(null, "client-direct");
|
||||
string proxy = NormalizeProxy(selected);
|
||||
return new NativeProxySettings(proxy, "client-manual");
|
||||
return new NativeProxySettings(selected, "client-manual");
|
||||
}
|
||||
|
||||
private static string NormalizeProxy(string raw)
|
||||
{
|
||||
raw = raw.Trim();
|
||||
if (raw.IndexOfAny(InvalidProxyCharacters) >= 0) throw InvalidProxy();
|
||||
foreach (char value in raw)
|
||||
if (char.IsWhiteSpace(value) || char.IsControl(value)) throw InvalidProxy();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out Uri proxy) || proxy.Scheme != "http" ||
|
||||
string.IsNullOrEmpty(proxy.Host) || !string.IsNullOrEmpty(proxy.UserInfo) ||
|
||||
!string.IsNullOrEmpty(proxy.Query) || !string.IsNullOrEmpty(proxy.Fragment) || proxy.AbsolutePath != "/")
|
||||
throw InvalidProxy();
|
||||
string authority = raw[(raw.IndexOf("://", StringComparison.Ordinal) + 3)..].TrimEnd('/');
|
||||
int separator = authority.LastIndexOf(':');
|
||||
if (separator <= 0) throw InvalidProxy();
|
||||
string portText = authority[(separator + 1)..];
|
||||
foreach (char value in portText) if (value < '0' || value > '9') throw InvalidProxy();
|
||||
if (!int.TryParse(portText, NumberStyles.None, CultureInfo.InvariantCulture, out int port) || port < 1 || port > 65535)
|
||||
throw InvalidProxy();
|
||||
string host = proxy.IdnHost.Trim('[', ']');
|
||||
if (proxy.HostNameType == UriHostNameType.IPv6) host = "[" + host + "]";
|
||||
return "http://" + host + ":" + port.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static NativeProxyConfigurationException InvalidProxy() =>
|
||||
new("Client proxy must be an HTTP proxy address with an explicit port and no credentials or path");
|
||||
}
|
||||
@@ -35,9 +35,6 @@ public sealed class Plugin : BaseUnityPlugin
|
||||
{
|
||||
Log = Logger;
|
||||
PlatformControlHttp.SetCompletionLogger(message => Logger.LogInfo(message));
|
||||
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("UNITY_PROXYSERVER")) &&
|
||||
!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("UNITY_NOPROXY")))
|
||||
Logger.LogInfo("Game loopback transport uses launch-time Unity proxy bypass");
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
|
||||
{
|
||||
DisposeGameRelay();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using Bd2.Client;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
@@ -24,11 +25,11 @@ internal static class UpdateCompatibility
|
||||
new("local_identity", "bd2.localidentity"), new("login_ui", Plugin.PluginId),
|
||||
new("cash_shop", "bd2.cashshop"), new("fchat", "bd2.fchat")
|
||||
];
|
||||
private static readonly string Fingerprint = Environment.GetEnvironmentVariable("BD2_UPDATE_FINGERPRINT") ?? string.Empty;
|
||||
private static readonly string ResourceFingerprint = Environment.GetEnvironmentVariable("BD2_RESOURCE_FINGERPRINT") ?? string.Empty;
|
||||
private static readonly string ClientVersion = LaunchVersion("BD2_CLIENT_VERSION", Bd2Build.Versions.ClientRelease);
|
||||
private static readonly string BundleVersion = LaunchVersion("BD2_BUNDLE_VERSION", Bd2Build.Versions.Bundle);
|
||||
private static readonly string GameDataVersion = LaunchVersion("BD2_GAME_DATA_VERSION", Bd2Build.Versions.GameData);
|
||||
private static readonly string Fingerprint = ClientSettings.Current.runtime.update_fingerprint;
|
||||
private static readonly string ResourceFingerprint = ClientSettings.Current.runtime.resource_fingerprint;
|
||||
private static readonly string ClientVersion = ClientSettings.Current.ClientVersion;
|
||||
private static readonly string BundleVersion = ClientSettings.Current.BundleVersion;
|
||||
private static readonly string GameDataVersion = ClientSettings.Current.GameDataVersion;
|
||||
private static IReadOnlyDictionary<string, string> headers;
|
||||
private static Dictionary<string, string> plugins;
|
||||
private static int blocked;
|
||||
@@ -38,12 +39,6 @@ internal static class UpdateCompatibility
|
||||
internal static bool LoginCheckInProgress;
|
||||
internal static bool IsBlocked => Volatile.Read(ref blocked) != 0;
|
||||
|
||||
private static string LaunchVersion(string name, string fallback)
|
||||
{
|
||||
string value = Environment.GetEnvironmentVariable(name);
|
||||
return string.IsNullOrEmpty(value) ? fallback : value;
|
||||
}
|
||||
|
||||
internal static IReadOnlyDictionary<string, string> Headers
|
||||
{
|
||||
get
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using BepInEx;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Bd2.Client;
|
||||
|
||||
internal sealed class ClientSettings
|
||||
{
|
||||
private static readonly Lazy<ClientSettings> Loaded = new(() => ParseConfig(ReadFile(Path.Combine(Paths.ConfigPath, "bd2.client.json"))));
|
||||
private static readonly Lazy<ClientInstance> Instance = new(FindInstance);
|
||||
private static readonly char[] InvalidOriginCharacters = ['?', '#', '@', '%'];
|
||||
internal static ClientSettings Current => Loaded.Value;
|
||||
internal static ClientInstance CurrentInstance => Instance.Value;
|
||||
internal int schema_version;
|
||||
internal string server_origin;
|
||||
internal string cdn_mode;
|
||||
internal string local_resource_directory;
|
||||
internal string proxy_url;
|
||||
internal ClientRuntime runtime;
|
||||
internal string BundleVersion => string.IsNullOrEmpty(runtime.bundle_version) ? Bd2Build.Versions.Bundle : runtime.bundle_version;
|
||||
internal string GameDataVersion => string.IsNullOrEmpty(runtime.game_data_version) ? Bd2Build.Versions.GameData : runtime.game_data_version;
|
||||
internal string ClientVersion => string.IsNullOrEmpty(runtime.client_version) ? Bd2Build.Versions.ClientRelease : runtime.client_version;
|
||||
|
||||
private static ClientRuntime ParseRuntime(JToken token)
|
||||
{
|
||||
if (token == null || token.Type == JTokenType.Null) return new ClientRuntime();
|
||||
if (token is not JObject value) throw new InvalidDataException("runtime must be an object");
|
||||
RequireOnly(value, "client_version", "update_fingerprint", "resource_fingerprint", "game_version", "bundle_version", "game_data_version");
|
||||
var runtime = new ClientRuntime
|
||||
{
|
||||
client_version = OptionalString(value, "client_version"),
|
||||
update_fingerprint = OptionalString(value, "update_fingerprint"),
|
||||
resource_fingerprint = OptionalString(value, "resource_fingerprint"),
|
||||
game_version = OptionalString(value, "game_version"),
|
||||
bundle_version = OptionalString(value, "bundle_version"),
|
||||
game_data_version = OptionalString(value, "game_data_version")
|
||||
};
|
||||
ValidateFingerprint(runtime.update_fingerprint, "update_fingerprint");
|
||||
ValidateFingerprint(runtime.resource_fingerprint, "resource_fingerprint");
|
||||
ValidateResourceVersion(runtime.bundle_version, "bundle_version");
|
||||
ValidateResourceVersion(runtime.game_data_version, "game_data_version");
|
||||
return runtime;
|
||||
}
|
||||
|
||||
private static void ValidateFingerprint(string value, string name)
|
||||
{
|
||||
if (value.Length == 0) return;
|
||||
if (value.Length != 64) throw new InvalidDataException("runtime." + name + " must be a SHA-256 fingerprint");
|
||||
foreach (char digit in value)
|
||||
if (!(digit >= '0' && digit <= '9') && !(digit >= 'a' && digit <= 'f'))
|
||||
throw new InvalidDataException("runtime." + name + " must be a lowercase SHA-256 fingerprint");
|
||||
}
|
||||
|
||||
private static void ValidateResourceVersion(string value, string name)
|
||||
{
|
||||
if (value.Length == 0) return;
|
||||
if (value.Length != 14)
|
||||
throw new InvalidDataException("runtime." + name + " must be a 14-digit resource version");
|
||||
foreach (char digit in value)
|
||||
if (digit < '0' || digit > '9') throw new InvalidDataException("runtime." + name + " must contain only digits");
|
||||
}
|
||||
|
||||
private static void ValidateOrigin(string raw)
|
||||
{
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out Uri uri) || string.IsNullOrEmpty(uri.Host) ||
|
||||
!string.IsNullOrEmpty(uri.UserInfo) || uri.AbsolutePath != "/" ||
|
||||
!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) ||
|
||||
(uri.Scheme != Uri.UriSchemeHttps && !(uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback)))
|
||||
throw new InvalidDataException("server_origin must be an HTTPS origin, except that loopback may use HTTP");
|
||||
}
|
||||
|
||||
private static ClientInstance FindInstance()
|
||||
{
|
||||
DirectoryInfo game = new(Path.GetFullPath(Paths.GameRootPath));
|
||||
DirectoryInfo container = game.Name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) ? game.Parent : game;
|
||||
DirectoryInfo root = container?.Parent;
|
||||
if (root == null || !File.Exists(Path.Combine(root.FullName, "instance.json"))) return null;
|
||||
if (container.Name != "game") throw new InvalidDataException("Client instance game directory must be named game");
|
||||
JObject manifest = ParseObject(ReadFile(Path.Combine(root.FullName, "instance.json")), "client instance manifest");
|
||||
RequireOnly(manifest, "schema_version", "id", "source", "game_version");
|
||||
if (RequiredInteger(manifest, "schema_version") != 1) throw new InvalidDataException("Unsupported client instance manifest schema_version");
|
||||
string id = RequiredString(manifest, "id");
|
||||
if (id.Length > 32 || id == "default" || root.Name != id) throw new InvalidDataException("Invalid client instance name");
|
||||
foreach (char character in id)
|
||||
if (!(character >= 'a' && character <= 'z') && !(character >= '0' && character <= '9') && character != '-' && character != '_')
|
||||
throw new InvalidDataException("Invalid client instance name");
|
||||
return new ClientInstance(id, root.FullName);
|
||||
}
|
||||
|
||||
private static string ReadFile(string path)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
const int maximumBytes = 16 * 1024;
|
||||
if (stream.Length > maximumBytes) throw new InvalidDataException("Client JSON document exceeds 16384 bytes");
|
||||
using var reader = new StreamReader(stream, new UTF8Encoding(false, true));
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
private static ClientSettings ParseConfig(string json)
|
||||
{
|
||||
JObject value = ParseObject(json, "client configuration");
|
||||
RequireOnly(value, "schema_version", "server_origin", "cdn_mode", "local_resource_directory", "proxy_url", "runtime");
|
||||
var config = new ClientSettings
|
||||
{
|
||||
schema_version = RequiredInteger(value, "schema_version"),
|
||||
server_origin = RequiredString(value, "server_origin"),
|
||||
cdn_mode = RequiredString(value, "cdn_mode"),
|
||||
local_resource_directory = OptionalString(value, "local_resource_directory"),
|
||||
proxy_url = NormalizeClientProxy(OptionalString(value, "proxy_url")),
|
||||
runtime = ParseRuntime(value["runtime"])
|
||||
};
|
||||
if (config.schema_version != 2)
|
||||
{
|
||||
throw new InvalidDataException("bd2.client.json schema_version must be 2");
|
||||
}
|
||||
if (config.cdn_mode != "official" && config.cdn_mode != "local" && config.cdn_mode != "server")
|
||||
{
|
||||
throw new InvalidDataException("bd2.client.json cdn_mode must be official, local, or server");
|
||||
}
|
||||
if (config.cdn_mode == "local" && string.IsNullOrWhiteSpace(config.local_resource_directory))
|
||||
{
|
||||
throw new InvalidDataException("local_resource_directory is required when cdn_mode is local");
|
||||
}
|
||||
if (config.cdn_mode != "local" && !string.IsNullOrWhiteSpace(config.local_resource_directory))
|
||||
{
|
||||
throw new InvalidDataException("local_resource_directory is only valid when cdn_mode is local");
|
||||
}
|
||||
ValidateOrigin(config.server_origin);
|
||||
config.server_origin = config.server_origin.TrimEnd('/');
|
||||
return config;
|
||||
}
|
||||
|
||||
private static string NormalizeClientProxy(string raw)
|
||||
{
|
||||
raw = raw.Trim();
|
||||
if (raw.Length == 0) return string.Empty;
|
||||
const string error = "proxy_url must be an HTTP proxy address with an explicit port and no credentials or path";
|
||||
if (raw.IndexOfAny(InvalidOriginCharacters) >= 0) throw new InvalidDataException(error);
|
||||
foreach (char character in raw)
|
||||
if (char.IsWhiteSpace(character) || char.IsControl(character)) throw new InvalidDataException(error);
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out Uri proxy) || proxy.Scheme != "http" ||
|
||||
string.IsNullOrEmpty(proxy.Host) || !string.IsNullOrEmpty(proxy.UserInfo) ||
|
||||
!string.IsNullOrEmpty(proxy.Query) || !string.IsNullOrEmpty(proxy.Fragment) || proxy.AbsolutePath != "/")
|
||||
throw new InvalidDataException(error);
|
||||
string authority = raw[(raw.IndexOf("://", StringComparison.Ordinal) + 3)..].TrimEnd('/');
|
||||
int separator = authority.LastIndexOf(':');
|
||||
if (separator <= 0) throw new InvalidDataException(error);
|
||||
string portText = authority[(separator + 1)..];
|
||||
foreach (char character in portText) if (character < '0' || character > '9') throw new InvalidDataException(error);
|
||||
if (!int.TryParse(portText, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture,
|
||||
out int port) || port < 1 || port > 65535) throw new InvalidDataException(error);
|
||||
string host = proxy.IdnHost.Trim('[', ']');
|
||||
if (proxy.HostNameType == UriHostNameType.IPv6) host = "[" + host + "]";
|
||||
return "http://" + host + ":" + port.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static JObject ParseObject(string json, string description)
|
||||
{
|
||||
using var input = new StringReader(json);
|
||||
using var reader = new JsonTextReader(input)
|
||||
{
|
||||
DateParseHandling = DateParseHandling.None
|
||||
};
|
||||
JObject result;
|
||||
try
|
||||
{
|
||||
result = JObject.Load(reader, new JsonLoadSettings
|
||||
{
|
||||
DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error
|
||||
});
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException("Invalid " + description + " JSON", ex);
|
||||
}
|
||||
if (reader.Read())
|
||||
{
|
||||
throw new InvalidDataException(description + " contains trailing JSON");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void RequireOnly(JObject value, params string[] names)
|
||||
{
|
||||
foreach (JProperty property in value.Properties())
|
||||
{
|
||||
if (Array.IndexOf(names, property.Name) < 0)
|
||||
{
|
||||
throw new InvalidDataException("unknown JSON field " + property.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string RequiredString(JObject value, string name)
|
||||
{
|
||||
JToken token = value[name];
|
||||
if (token == null || token.Type != JTokenType.String || string.IsNullOrEmpty((string)token))
|
||||
{
|
||||
throw new InvalidDataException(name + " must be a non-empty string");
|
||||
}
|
||||
return (string)token;
|
||||
}
|
||||
|
||||
private static int RequiredInteger(JObject value, string name)
|
||||
{
|
||||
JToken token = value[name];
|
||||
if (token == null || token.Type != JTokenType.Integer)
|
||||
{
|
||||
throw new InvalidDataException(name + " must be an integer");
|
||||
}
|
||||
return (int)token;
|
||||
}
|
||||
|
||||
private static string OptionalString(JObject value, string name)
|
||||
{
|
||||
JToken token = value[name];
|
||||
if (token == null || token.Type == JTokenType.Null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
if (token.Type != JTokenType.String)
|
||||
{
|
||||
throw new InvalidDataException(name + " must be a string when present");
|
||||
}
|
||||
return (string)token;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal sealed class ClientRuntime
|
||||
{
|
||||
internal string client_version = string.Empty;
|
||||
internal string update_fingerprint = string.Empty;
|
||||
internal string resource_fingerprint = string.Empty;
|
||||
internal string game_version = string.Empty;
|
||||
internal string bundle_version = string.Empty;
|
||||
internal string game_data_version = string.Empty;
|
||||
}
|
||||
|
||||
internal sealed class ClientInstance(string id, string root)
|
||||
{
|
||||
internal string ID { get; } = id;
|
||||
internal string Root { get; } = root;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using System.Globalization;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
using Bd2.Client;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Bd2Login;
|
||||
@@ -33,9 +33,9 @@ internal static class ServerLoginPreferences
|
||||
|
||||
internal static string KeychainService(string origin)
|
||||
{
|
||||
string root = Environment.GetEnvironmentVariable("BD2_CLIENT_INSTANCE_ROOT");
|
||||
if (string.IsNullOrEmpty(root)) return "BD2 Login UI OAuth: " + origin;
|
||||
string scope = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
ClientInstance instance = ClientSettings.CurrentInstance;
|
||||
if (instance == null) return "BD2 Login UI OAuth: " + origin;
|
||||
string scope = instance.Root;
|
||||
return Key("BD2 Login UI OAuth instance " + scope + ": ", origin);
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
data_dir=/app/data
|
||||
update_config=
|
||||
next=
|
||||
for argument in "$@"; do
|
||||
if [ -n "$next" ]; then
|
||||
case "$next" in
|
||||
data) data_dir=$argument ;;
|
||||
update) update_config=$argument ;;
|
||||
esac
|
||||
next=
|
||||
continue
|
||||
fi
|
||||
case "$argument" in
|
||||
--data-dir|-data-dir) next=data ;;
|
||||
--data-dir=*|-data-dir=*) data_dir=${argument#*=} ;;
|
||||
--update-config|-update-config) next=update ;;
|
||||
--update-config=*|-update-config=*) update_config=${argument#*=} ;;
|
||||
esac
|
||||
done
|
||||
[ -z "$next" ] || { printf '%s\n' 'Missing configuration path argument' >&2; exit 2; }
|
||||
if [ -z "$update_config" ]; then
|
||||
update_config=$data_dir/config/updates.json
|
||||
if [ ! -e "$update_config" ]; then
|
||||
mkdir -p "$(dirname "$update_config")"
|
||||
(umask 077; set -C; printf '%s\n' '{"method":"docker"}' >"$update_config")
|
||||
fi
|
||||
fi
|
||||
exec /app/bd2server "$@"
|
||||
@@ -11,8 +11,6 @@ Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
UMask=0077
|
||||
Environment=BD2_DATA_DIR=/opt/bd2/data BD2_SOURCE_DIR=/opt/bd2/src BD2_COMPOSE_DIR=/opt/server-infra/bd2
|
||||
Environment=BD2_GIT_REMOTE_URL=https://git.sighs.cc/Flechazo/bd2
|
||||
ExecStart=/opt/bd2/bd2-docker-update.sh
|
||||
# Builds can exceed the default oneshot timeout. flock also covers manual runs.
|
||||
TimeoutStartSec=30min
|
||||
|
||||
@@ -4,13 +4,31 @@
|
||||
set -eu
|
||||
umask 077
|
||||
|
||||
DATA_DIR=${BD2_DATA_DIR:-/opt/bd2/data}
|
||||
SOURCE_DIR=${BD2_SOURCE_DIR:-/opt/bd2/src}
|
||||
COMPOSE_DIR=${BD2_COMPOSE_DIR:-/opt/server-infra/bd2}
|
||||
SERVICE=${BD2_COMPOSE_SERVICE:-server}
|
||||
REMOTE_URL=${BD2_GIT_REMOTE_URL:-https://git.sighs.cc/Flechazo/bd2}
|
||||
READY_URL=${BD2_READY_URL:-http://127.0.0.1:8080/readyz}
|
||||
ENV_FILE=${BD2_ENV_FILE:-$COMPOSE_DIR/.env}
|
||||
DATA_DIR=/opt/bd2/data
|
||||
SOURCE_DIR=/opt/bd2/src
|
||||
COMPOSE_DIR=/opt/server-infra/bd2
|
||||
SERVICE=server
|
||||
REMOTE_URL=https://git.sighs.cc/Flechazo/bd2
|
||||
READY_URL=http://127.0.0.1:8080/readyz
|
||||
ENV_FILE=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--data-dir|--source-dir|--compose-dir|--service|--remote-url|--ready-url|--env-file)
|
||||
[ "$#" -ge 2 ] && [ -n "$2" ] || { printf '%s\n' "Missing value for $1" >&2; exit 2; }
|
||||
case "$1" in
|
||||
--data-dir) DATA_DIR=$2 ;;
|
||||
--source-dir) SOURCE_DIR=$2 ;;
|
||||
--compose-dir) COMPOSE_DIR=$2 ;;
|
||||
--service) SERVICE=$2 ;;
|
||||
--remote-url) REMOTE_URL=$2 ;;
|
||||
--ready-url) READY_URL=$2 ;;
|
||||
--env-file) ENV_FILE=$2 ;;
|
||||
esac
|
||||
shift 2 ;;
|
||||
*) printf '%s\n' "Unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$ENV_FILE" ] || ENV_FILE=$COMPOSE_DIR/.env
|
||||
UPDATES="$DATA_DIR/updates"
|
||||
REQUEST="$UPDATES/docker-request.json"
|
||||
PROCESSING="$UPDATES/docker-request.processing.json"
|
||||
@@ -105,7 +123,7 @@ for dependency in docker curl nsenter git mktemp stat cp; do
|
||||
command -v "$dependency" >/dev/null || fail "$dependency is required"
|
||||
done
|
||||
# This URL is resolved inside the new container's network namespace.
|
||||
case "$READY_URL" in http://127.0.0.1:*/readyz) ;; *) fail 'BD2_READY_URL must use http://127.0.0.1:PORT/readyz' ;; esac
|
||||
case "$READY_URL" in http://127.0.0.1:*/readyz) ;; *) fail '--ready-url must use http://127.0.0.1:PORT/readyz' ;; esac
|
||||
ready_port=${READY_URL#http://127.0.0.1:}
|
||||
ready_port=${ready_port%/readyz}
|
||||
case "$ready_port" in ''|*[!0-9]*) fail 'invalid readiness port' ;; esac
|
||||
@@ -123,7 +141,7 @@ case "$previous" in sha256:*) ;; *) fail 'previous container has no immutable im
|
||||
actual_url=$(git -C "$SOURCE_DIR" remote get-url --all origin) || fail 'cannot read source origin'
|
||||
actual_url=${actual_url%/}
|
||||
expected_url=${REMOTE_URL%/}
|
||||
[ "${actual_url%.git}" = "${expected_url%.git}" ] || fail 'source origin does not match BD2_GIT_REMOTE_URL'
|
||||
[ "${actual_url%.git}" = "${expected_url%.git}" ] || fail 'source origin does not match --remote-url'
|
||||
source_status=$(git -C "$SOURCE_DIR" status --porcelain --untracked-files=all) || fail 'cannot inspect source checkout'
|
||||
[ -z "$source_status" ] || fail 'source checkout has local changes'
|
||||
git -C "$SOURCE_DIR" fetch --quiet --no-tags --prune origin '+refs/heads/*:refs/bd2-update/*' || fail 'cannot fetch source origin'
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"game_version": "2.36.7",
|
||||
"client_version": "2.36.7+client.0.2.0",
|
||||
"server_version": "2.36.7+server.0.2.0",
|
||||
"game_data_version": "20261012190548",
|
||||
"game_data_version": "20261008155037",
|
||||
"bundle_version": "20261007175947",
|
||||
"seed_directory": "go/seed/v2_36_7",
|
||||
"plugins": {
|
||||
|
||||
Reference in new issue
Block a user