diff --git a/README.md b/README.md index 3ec1915..4905af3 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,8 @@ that exact version is not in the server directory yet, and starts it: - Without `--mod-version` the newest build is used, so a restart picks up a new Paper build or a new recommended Forge. The JAR a newer build replaced is removed. -- Installer-based servers (Forge, NeoForge, Quilt) are installed once per version. Forge +- Installer-based servers (Forge, NeoForge, Quilt) are installed once per version; an + install that failed or was interrupted is repeated on the next start. Forge 1.17+ and NeoForge are started from the JVM argument file the installer writes (`@libraries/.../unix_args.txt`), older Forge from its JAR. A `user_jvm_args.txt` in the server directory is honoured; `--memory` and `--min-memory` win over it. @@ -101,6 +102,46 @@ that exact version is not in the server directory yet, and starts it: be reached, the installed server is started with a warning instead of failing - as long as it matches the requested mod and version. +#### Unreachable download sources + +Every download goes to its source first. When the source cannot be reached (name +resolution, connection, TLS, timeouts), keeps answering with 5xx or 429, or refuses the +client with 403 or 451, the same request is made through the GameAP mirror, +`https://mirror.gameap.ru`. A 404 is final. Later requests to a host that could not be +reached go to the mirror first and to the host itself only when the mirror fails too; +a warning names the host once. +The mirror serves only what mcrun needs and the files are checked against the same +checksums as direct downloads. + +Installers and servers download libraries and the vanilla server on their first start, +and they know nothing about the mirror. mcrun puts these files in place before it starts +them, so a first start needs no network: + +| Server | Prepared by mcrun | +|----------------------------------------|----------------------------------------------------------------------------| +| Paper, Folia, Purpur, Pufferfish, Leaf | the vanilla server Paperclip patches; Leaf 26.2+ also its libraries | +| Waterfall, BungeeCord up to #2107 | the proxy modules | +| Fabric | libraries, the vanilla server and the launch jar | +| Quilt | the whole installation; the Quilt installer is not run | +| Forge, NeoForge | libraries, the vanilla server and Mojang's mappings; installer `--offline` | +| Mohist, Cauldron | the libraries of `libraries.txt` / `mohist_libraries.txt` | +| Banner | libraries, the Fabric loader and the vanilla server | +| SpongeVanilla | libraries, the vanilla server and Mojang's mappings | + +Known limits: + +- SpongeVanilla reads Mojang's version manifest itself on every start and, when Mojang + is out of reach, falls back on the server it has. For 26.x mcrun puts that server in + place, so no start needs Mojang. 1.16.5 needs Mojang on the first start only, to remap + the server. 1.18.2 to 1.21.11 need it on every start: their fallback picks the server + before remapping, which does not start. +- Fabric loaders before 0.12.6 get only the vanilla server; their launcher downloads the + rest. +- Forge installers without `--offline` support run online, as before. + +`MCRUN_MIRRORS` replaces the mirror list (comma-separated base URLs) or turns the +fallback off with `MCRUN_MIRRORS=off`. It is meant for tests and emergencies. + #### Stopping and console input The server reads the console input of `mcrun` directly, so a control panel can write diff --git a/cmd/mcrun/download.go b/cmd/mcrun/download.go index bebb505..ebe4602 100644 --- a/cmd/mcrun/download.go +++ b/cmd/mcrun/download.go @@ -45,9 +45,11 @@ Examples: if jar.ModVersion != "" { fmt.Printf(" Mod Version: %s\n", jar.ModVersion) } - fmt.Printf(" File: %s\n", jar.Filename) + if jar.Filename != "" { + fmt.Printf(" File: %s\n", jar.Filename) + } - if jar.RequiresInstall { + if jar.RequiresInstall && jar.URL != "" { fmt.Println("\n[WARNING] This server requires installation.") fmt.Println(" The installer will run automatically when you use 'mcrun run'") } diff --git a/cmd/mcrun/root.go b/cmd/mcrun/root.go index 4af46f9..dc16fce 100644 --- a/cmd/mcrun/root.go +++ b/cmd/mcrun/root.go @@ -66,6 +66,7 @@ Supported server types: SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { utils.SetVersion(Version) + utils.ConfigureMirrors(os.LookupEnv("MCRUN_MIRRORS")) var err error cfg, err = config.Load(cfgFile, serverDir) diff --git a/internal/preseed/fetch.go b/internal/preseed/fetch.go new file mode 100644 index 0000000..e6485fa --- /dev/null +++ b/internal/preseed/fetch.go @@ -0,0 +1,283 @@ +// Package preseed puts in place the files a server or its installer would +// otherwise download on its own: the vanilla server a patcher works on, +// libraries, modules. mcrun downloads them through its own client, which falls +// back to GameAP's mirrors, and checks every checksum, so the server process +// needs no network. +package preseed + +import ( + "context" + "errors" + "fmt" + "os" + "path" + "path/filepath" + "strings" + "sync" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +// parallel is how many files are downloaded at once +const parallel = 6 + +// File is one file a server would download itself +type File struct { + // Path is where the server looks for the file: relative to the server + // directory, with forward slashes + Path string + // URLs are tried in order + URLs []string + + SHA512 string + SHA256 string + SHA1 string + MD5 string + // AnySHA1 accepts a file whose SHA-1 is any of these, as legacy Forge + // installers do + AnySHA1 []string + + // Sidecar names the checksum file published next to the download + // ("sha1", "sha256") for files whose checksum is not known in advance. A + // repository without one is trusted. + Sidecar string +} + +type checksum struct { + name string + value string + verify func(path, value string) error +} + +// checksum is the strongest checksum known for the file +func (f File) checksum() (checksum, bool) { + switch { + case f.SHA512 != "": + return checksum{"sha512", f.SHA512, utils.VerifySHA512}, true + case f.SHA256 != "": + return checksum{"sha256", f.SHA256, utils.VerifySHA256}, true + case f.SHA1 != "": + return checksum{"sha1", f.SHA1, utils.VerifySHA1}, true + case f.MD5 != "": + return checksum{"md5", f.MD5, utils.VerifyMD5}, true + case len(f.AnySHA1) > 0: + return checksum{"sha1", strings.Join(f.AnySHA1, " or "), verifyAnySHA1(f.AnySHA1)}, true + } + return checksum{}, false +} + +func verifyAnySHA1(accepted []string) func(path, value string) error { + return func(path, _ string) error { + actual, err := utils.CalculateSHA1(path) + if err != nil { + return err + } + for _, sum := range accepted { + if strings.EqualFold(strings.TrimSpace(sum), actual) { + return nil + } + } + return fmt.Errorf("SHA1 mismatch: expected one of %s, got %s", strings.Join(accepted, ", "), actual) + } +} + +// Ensure puts files into dir. A file already there with the right checksum is +// kept, so a prepared server costs no requests; what is a name for the +// messages. +func Ensure(ctx context.Context, client *utils.HTTPClient, dir, what string, files []File) error { + missing := make([]File, 0, len(files)) + seen := make(map[string]bool, len(files)) + + for _, f := range files { + dest, err := Resolve(dir, f.Path) + if err != nil { + return err + } + if seen[dest] { + continue + } + seen[dest] = true + + if !present(dest, f) { + missing = append(missing, f) + } + } + + if len(missing) == 0 { + return nil + } + + if len(missing) == 1 { + fmt.Printf("Downloading %s for %s...\n", missing[0].Path, what) + } else { + fmt.Printf("Downloading %d files for %s...\n", len(missing), what) + } + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + var ( + wg sync.WaitGroup + mu sync.Mutex + errs []error + ) + + queue := make(chan File) + for range min(parallel, len(missing)) { + wg.Go(func() { + for f := range queue { + if err := fetch(ctx, client, dir, f); err != nil { + mu.Lock() + errs = append(errs, err) + mu.Unlock() + cancel() + } + } + }) + } + + for _, f := range missing { + select { + case queue <- f: + case <-ctx.Done(): + } + } + close(queue) + wg.Wait() + + if len(errs) > 0 { + return fmt.Errorf("failed to prepare %s: %w", what, errors.Join(errs...)) + } + // Cancelled before the workers got every file + if err := ctx.Err(); err != nil { + return fmt.Errorf("failed to prepare %s: %w", what, err) + } + + return nil +} + +// Resolve maps a server-relative path from metadata onto dir and refuses +// paths that leave it +func Resolve(dir, rel string) (string, error) { + clean := path.Clean(rel) + if rel == "" || strings.ContainsAny(rel, `\:`) || path.IsAbs(rel) || filepath.IsAbs(rel) || + clean == "." || clean == ".." || strings.HasPrefix(clean, "../") { + return "", fmt.Errorf("refusing to write %q outside the server directory", rel) + } + + return filepath.Join(dir, filepath.FromSlash(clean)), nil +} + +// pathExists tells whether anything is at the server-relative path rel +func pathExists(dir, rel string) (bool, error) { + dest, err := Resolve(dir, rel) + if err != nil { + return false, err + } + _, err = os.Stat(dest) + return err == nil, nil +} + +// present tells whether dest holds the file. Without a known checksum any file +// counts, so it is not downloaded on every start. +func present(dest string, f File) bool { + info, err := os.Stat(dest) + if err != nil || !info.Mode().IsRegular() { + return false + } + + sum, ok := f.checksum() + if !ok { + return true + } + + return sum.verify(dest, sum.value) == nil +} + +func fetch(ctx context.Context, client *utils.HTTPClient, dir string, f File) error { + dest, err := Resolve(dir, f.Path) + if err != nil { + return err + } + + part := dest + ".part" + failures := make([]string, 0, len(f.URLs)) + + for _, url := range f.URLs { + sum, known := f.checksum() + if !known && f.Sidecar != "" { + sum, known, err = sidecar(ctx, client, url, f.Sidecar) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + failures = append(failures, err.Error()) + continue + } + } + + if err := client.DownloadFile(ctx, url, part); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + failures = append(failures, err.Error()) + continue + } + + if known { + if err := sum.verify(part, sum.value); err != nil { + os.Remove(part) + failures = append(failures, fmt.Sprintf("%s: %v", url, err)) + continue + } + } + + if err := os.Rename(part, dest); err != nil { + os.Remove(part) + return fmt.Errorf("%s: %w", f.Path, err) + } + + return nil + } + + if len(failures) == 0 { + return fmt.Errorf("%s: nowhere to download it from", f.Path) + } + + return fmt.Errorf("%s: %s", f.Path, strings.Join(failures, "; ")) +} + +// sidecar reads the checksum published as . +func sidecar(ctx context.Context, client *utils.HTTPClient, url, algorithm string) (checksum, bool, error) { + data, err := client.Get(ctx, url+"."+algorithm) + if err != nil { + var statusErr *utils.StatusError + if errors.As(err, &statusErr) && statusErr.StatusCode == 404 { + return checksum{}, false, nil + } + return checksum{}, false, err + } + + fields := strings.Fields(string(data)) + if len(fields) == 0 { + return checksum{}, false, fmt.Errorf("%s.%s is empty", url, algorithm) + } + + f := File{} + switch algorithm { + case "sha512": + f.SHA512 = fields[0] + case "sha256": + f.SHA256 = fields[0] + case "sha1": + f.SHA1 = fields[0] + case "md5": + f.MD5 = fields[0] + default: + return checksum{}, false, fmt.Errorf("unknown checksum %q", algorithm) + } + + sum, _ := f.checksum() + + return sum, true, nil +} diff --git a/internal/preseed/forge.go b/internal/preseed/forge.go new file mode 100644 index 0000000..2583efe --- /dev/null +++ b/internal/preseed/forge.go @@ -0,0 +1,740 @@ +package preseed + +import ( + "archive/zip" + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "os" + "path" + "path/filepath" + "slices" + "strings" + + "github.com/gameap/minecraft-runner/internal/utils" + "github.com/gameap/minecraft-runner/pkg/api/mojang" +) + +const ( + installProfile = "install_profile.json" + taskDownloadMojmap = "DOWNLOAD_MOJMAPS" +) + +// minecraftLibraries serves the libraries of legacy profiles that name no +// repository +var minecraftLibraries = "https://libraries.minecraft.net/" + +// legacyForgeRepositories maps repositories of old install profiles onto +// where the files live now +var legacyForgeRepositories = map[string]string{ + "http://files.minecraftforge.net/maven/": "https://maven.minecraftforge.net/", + "https://files.minecraftforge.net/maven/": "https://maven.minecraftforge.net/", + "http://maven.minecraftforge.net/": "https://maven.minecraftforge.net/", +} + +// ForgeInstall tells how to run a Forge or NeoForge installer once what it +// downloads is in place +type ForgeInstall struct { + // Installer is the installer to run, relative to the server directory: + // the original one or a repacked copy + Installer string + // Offline tells that the installer has nothing left to download and + // understands --offline + Offline bool + + dir string + repacked bool +} + +// Remove deletes the repacked installer and its log +func (i *ForgeInstall) Remove() { + if i == nil || !i.repacked { + return + } + os.Remove(filepath.Join(i.dir, i.Installer)) + os.Remove(filepath.Join(i.dir, i.Installer+".log")) +} + +type forgeProfile struct { + Minecraft string `json:"minecraft"` + JSON string `json:"json"` + ServerJarPath string `json:"serverJarPath"` + Libraries []forgeLibrary `json:"libraries"` + Processors []forgeProcessor `json:"processors"` + Data map[string]map[string]string `json:"data"` + + // Installers 1.x + Install *struct { + Minecraft string `json:"minecraft"` + } `json:"install"` + VersionInfo *struct { + Libraries []struct { + Name string `json:"name"` + URL string `json:"url"` + Checksums []string `json:"checksums"` + ServerReq bool `json:"serverreq"` + } `json:"libraries"` + } `json:"versionInfo"` +} + +type forgeLibrary struct { + Name string `json:"name"` + Downloads struct { + Artifact struct { + URL string `json:"url"` + SHA1 string `json:"sha1"` + } `json:"artifact"` + } `json:"downloads"` +} + +type forgeProcessor struct { + Sides []string `json:"sides"` + Args []string `json:"args"` + Outputs map[string]string `json:"outputs"` +} + +func (p forgeProcessor) forServer() bool { + return len(p.Sides) == 0 || slices.Contains(p.Sides, "server") +} + +// arg returns the value that follows the option name +func (p forgeProcessor) arg(name string) string { + if i := slices.Index(p.Args, name); i != -1 && i+1 < len(p.Args) { + return p.Args[i+1] + } + return "" +} + +// forgeInstaller prepares one installer +type forgeInstaller struct { + client *utils.HTTPClient + versions Versions + dir string + name string + jar *Jar + profile forgeProfile + vanilla map[string]*mojang.VersionDetail +} + +// ForgeInstaller puts in place everything the Forge or NeoForge installer +// in dir would download: libraries, the vanilla server and Mojang's mappings. +// An installer that would download the mappings itself, with no checksum to +// skip it by, is repacked without that step. name is Forge or NeoForge. +func ForgeInstaller(ctx context.Context, client *utils.HTTPClient, versions Versions, dir, installer, name string) (*ForgeInstall, error) { + installerPath, err := Resolve(dir, installer) + if err != nil { + return nil, err + } + + jar, err := OpenJar(installerPath) + if err != nil { + return nil, err + } + defer jar.Close() + + raw, ok, err := jar.Read(installProfile) + if err != nil { + return nil, err + } + if !ok { + return nil, fmt.Errorf("%s has no install profile", installer) + } + + f := &forgeInstaller{client: client, versions: versions, dir: dir, name: name, jar: jar, + vanilla: make(map[string]*mojang.VersionDetail)} + if err := json.Unmarshal(raw, &f.profile); err != nil { + return nil, fmt.Errorf("failed to parse the install profile of %s: %w", installer, err) + } + + install := &ForgeInstall{Installer: installer, Offline: f.understandsOffline(), dir: dir} + + if f.profile.VersionInfo != nil { + return install, f.legacy(ctx) + } + + replace, err := f.prepare(ctx, raw) + if err != nil { + return nil, err + } + if len(replace) == 0 || !install.Offline { + return install, nil + } + + repacked := strings.TrimSuffix(installer, ".jar") + "-offline.jar" + repackedPath, err := Resolve(dir, repacked) + if err != nil { + return nil, err + } + if err := repackJar(installerPath, repackedPath, replace); err != nil { + return nil, err + } + + return &ForgeInstall{Installer: repacked, Offline: true, dir: dir, repacked: true}, nil +} + +// understandsOffline tells whether the installer has the --offline option +func (f *forgeInstaller) understandsOffline() bool { + data, _, _ := f.jar.Read("net/minecraftforge/installer/SimpleInstaller.class") + return bytes.Contains(data, []byte("offline")) +} + +// prepare handles installers 2.x and NeoForge's. It returns the profile +// files the repacked installer gets instead of the original ones. +func (f *forgeInstaller) prepare(ctx context.Context, rawProfile []byte) (map[string][]byte, error) { + versionFile := strings.TrimPrefix(f.profile.JSON, "/") + rawVersion, ok, err := f.jar.Read(versionFile) + if err != nil { + return nil, err + } + if !ok { + return nil, fmt.Errorf("the installer has no %s", f.profile.JSON) + } + + var version struct { + Libraries []forgeLibrary `json:"libraries"` + } + if err := json.Unmarshal(rawVersion, &version); err != nil { + return nil, fmt.Errorf("failed to parse %s: %w", versionFile, err) + } + + files, err := f.libraryFiles(append(slices.Clone(version.Libraries), f.profile.Libraries...)) + if err != nil { + return nil, err + } + + serverJar, err := f.serverJarPath() + if err != nil { + return nil, err + } + if exists, err := f.exists(serverJar); err != nil { + return nil, err + } else if !exists { + server, err := f.vanillaFile(ctx, f.profile.Minecraft, serverJar) + if err != nil { + return nil, err + } + files = append(files, server) + } + + if err := Ensure(ctx, f.client, f.dir, f.name, files); err != nil { + return nil, err + } + + removed := make(map[int]bool) + for i, proc := range f.profile.Processors { + if !proc.forServer() || proc.arg("--task") != taskDownloadMojmap { + continue + } + skips, err := f.mojmaps(ctx, proc) + if err != nil { + return nil, err + } + if !skips { + removed[i] = true + } + } + + profileSums, err := f.unknownChecksums(f.profile.Libraries) + if err != nil { + return nil, err + } + versionSums, err := f.unknownChecksums(version.Libraries) + if err != nil { + return nil, err + } + + replace := make(map[string][]byte) + if len(removed) > 0 || len(profileSums) > 0 { + patched, err := patchProfile(rawProfile, removed, profileSums) + if err != nil { + return nil, fmt.Errorf("failed to patch the install profile: %w", err) + } + replace[installProfile] = patched + } + if len(versionSums) > 0 { + patched, err := patchProfile(rawVersion, nil, versionSums) + if err != nil { + return nil, fmt.Errorf("failed to patch %s: %w", versionFile, err) + } + replace[versionFile] = patched + } + + return replace, nil +} + +// libraryFiles lists the libraries the installer downloads: the ones with a +// URL that it does not carry itself +func (f *forgeInstaller) libraryFiles(libraries []forgeLibrary) ([]File, error) { + files := make([]File, 0, len(libraries)) + + for _, lib := range libraries { + artifact := lib.Downloads.Artifact + if artifact.URL == "" { + continue + } + + libPath, err := MavenPath(lib.Name) + if err != nil { + return nil, err + } + if f.jar.Has("maven/" + libPath) { + continue + } + + file := File{Path: "libraries/" + libPath, URLs: []string{artifact.URL}, SHA1: artifact.SHA1} + if file.SHA1 == "" { + file.Sidecar = "sha1" + } + files = append(files, file) + } + + return files, nil +} + +// unknownChecksums returns the SHA-1 of the downloaded libraries the profile +// names none for, by their index. NeoForge downloads such a library again on +// every install, and fails offline. +func (f *forgeInstaller) unknownChecksums(libraries []forgeLibrary) (map[int]string, error) { + sums := make(map[int]string) + + for i, lib := range libraries { + if lib.Downloads.Artifact.URL == "" || lib.Downloads.Artifact.SHA1 != "" { + continue + } + + libPath, err := MavenPath(lib.Name) + if err != nil { + return nil, err + } + if f.jar.Has("maven/" + libPath) { + continue + } + + sum, err := utils.CalculateSHA1(filepath.Join(f.dir, "libraries", filepath.FromSlash(libPath))) + if err != nil { + return nil, err + } + sums[i] = sum + } + + return sums, nil +} + +// serverJarPath is where the installer looks for the vanilla server +func (f *forgeInstaller) serverJarPath() (string, error) { + template := f.profile.ServerJarPath + if template == "" { + template = "{ROOT}/minecraft_server.{MINECRAFT_VERSION}.jar" + } + + rel := strings.NewReplacer("{ROOT}", "", "{LIBRARY_DIR}", "/libraries", "{MINECRAFT_VERSION}", f.profile.Minecraft). + Replace(template) + if strings.ContainsAny(rel, "{}[]'") { + return "", fmt.Errorf("unsupported server jar path %q", template) + } + + return strings.TrimPrefix(rel, "/"), nil +} + +func (f *forgeInstaller) exists(rel string) (bool, error) { + return pathExists(f.dir, rel) +} + +func (f *forgeInstaller) version(ctx context.Context, game string) (*mojang.VersionDetail, error) { + if detail, ok := f.vanilla[game]; ok { + return detail, nil + } + + detail, err := f.versions.GetVersion(ctx, game) + if err != nil { + return nil, fmt.Errorf("failed to look up Minecraft %s: %w", game, err) + } + f.vanilla[game] = detail + + return detail, nil +} + +func (f *forgeInstaller) vanillaFile(ctx context.Context, game, rel string) (File, error) { + detail, err := f.version(ctx, game) + if err != nil { + return File{}, err + } + if detail.Downloads.Server.URL == "" { + return File{}, fmt.Errorf("minecraft %s has no server download", game) + } + + return File{Path: rel, URLs: mojangURLs(detail.Downloads.Server.URL), SHA1: detail.Downloads.Server.SHA1}, nil +} + +// mojmaps puts in place the mappings a DOWNLOAD_MOJMAPS processor downloads, +// and tells whether the processor then skips itself: it does when it declares +// the checksum of its output and finds the file in place. +func (f *forgeInstaller) mojmaps(ctx context.Context, proc forgeProcessor) (bool, error) { + output := proc.arg("--output") + rel, err := f.dataPath(output) + if err != nil { + return false, err + } + + want := "" + if sum, ok := proc.Outputs[output]; ok { + if want, err = f.dataLiteral(sum); err != nil { + return false, err + } + } + skips := want != "" + + dest, err := Resolve(f.dir, rel) + if err != nil { + return false, err + } + if skips && present(dest, File{SHA1: want}) { + return true, nil + } + + game := proc.arg("--version") + if game == "" { + game = f.profile.Minecraft + } + detail, err := f.version(ctx, game) + if err != nil { + return false, err + } + mappings := detail.Downloads.ServerMappings + if mappings.URL == "" { + return false, fmt.Errorf("minecraft %s publishes no server mappings", game) + } + + if !slices.Contains(proc.Args, "--sanitize") { + if skips && !strings.EqualFold(want, mappings.SHA1) { + return false, fmt.Errorf("the installer expects mappings %s, Mojang publishes %s", want, mappings.SHA1) + } + file := File{Path: rel, URLs: mojangURLs(mappings.URL), SHA1: mappings.SHA1} + return skips, Ensure(ctx, f.client, f.dir, "Mojang's mappings", []File{file}) + } + + tmp, err := os.MkdirTemp(f.dir, ".mojmaps-") + if err != nil { + return false, fmt.Errorf("failed to create a temporary directory: %w", err) + } + defer os.RemoveAll(tmp) + + file := File{Path: "server.txt", URLs: mojangURLs(mappings.URL), SHA1: mappings.SHA1} + if err := Ensure(ctx, f.client, tmp, "Mojang's mappings", []File{file}); err != nil { + return false, err + } + + sanitized, err := f.sanitize(filepath.Join(tmp, "server.txt"), want) + if err != nil { + return false, err + } + + return skips, writeFileAtomic(dest, sanitized) +} + +// sanitize converts the mappings the way the processor would. Without a +// checksum to meet, nothing checks the result but the next processors, which +// read the mappings, so any SrgUtils ordering does. +func (f *forgeInstaller) sanitize(rawPath, want string) ([]byte, error) { + raw, err := os.Open(rawPath) + if err != nil { + return nil, err + } + defer raw.Close() + + if want == "" { + m, err := parseMappings(raw) + if err != nil { + return nil, err + } + return m.tsrg(srgUtilsLegacyOrder), nil + } + + sanitized, ok, err := SanitizeMappings(raw, want) + if err != nil { + return nil, err + } + if !ok { + return nil, fmt.Errorf("could not reproduce the sanitized mappings %s", want) + } + + return sanitized, nil +} + +// dataPath resolves a {KEY} argument naming a [maven:coordinate] in the +// profile data onto its place in libraries/ +func (f *forgeInstaller) dataPath(arg string) (string, error) { + value, err := f.dataValue(arg) + if err != nil { + return "", err + } + + coord, ok := strings.CutPrefix(value, "[") + if coord, ok = strings.CutSuffix(coord, "]"); !ok { + return "", fmt.Errorf("unsupported processor argument %s = %q", arg, value) + } + + libPath, err := MavenPath(coord) + if err != nil { + return "", err + } + + return "libraries/" + libPath, nil +} + +// dataLiteral resolves a {KEY} argument, or a 'literal', onto the literal +func (f *forgeInstaller) dataLiteral(arg string) (string, error) { + value := arg + if strings.HasPrefix(arg, "{") { + var err error + if value, err = f.dataValue(arg); err != nil { + return "", err + } + } + + literal, ok := strings.CutPrefix(value, "'") + if literal, ok = strings.CutSuffix(literal, "'"); !ok { + return "", fmt.Errorf("unsupported processor argument %s = %q", arg, value) + } + + return literal, nil +} + +func (f *forgeInstaller) dataValue(arg string) (string, error) { + key, ok := strings.CutPrefix(arg, "{") + if key, ok = strings.CutSuffix(key, "}"); !ok { + return "", fmt.Errorf("unsupported processor argument %q", arg) + } + + value := f.profile.Data[key]["server"] + if value == "" { + return "", fmt.Errorf("the install profile has no server value for %s", key) + } + + return value, nil +} + +// legacy handles installers 1.x: the libraries the server requires and the +// vanilla server in the server directory +func (f *forgeInstaller) legacy(ctx context.Context) error { + if f.profile.Install == nil || f.profile.Install.Minecraft == "" { + return fmt.Errorf("the install profile names no Minecraft version") + } + + files := make([]File, 0, len(f.profile.VersionInfo.Libraries)+1) + + for _, lib := range f.profile.VersionInfo.Libraries { + if !lib.ServerReq { + continue + } + + libPath, err := MavenPath(lib.Name) + if err != nil { + return err + } + + repo := lib.URL + if repo == "" { + repo = minecraftLibraries + } + if moved, ok := legacyForgeRepositories[repo]; ok { + repo = moved + } + + file := File{Path: "libraries/" + libPath, URLs: []string{repo + libPath}, AnySHA1: lib.Checksums} + if len(file.AnySHA1) == 0 { + file.Sidecar = "sha1" + } + files = append(files, file) + } + + game := f.profile.Install.Minecraft + serverJar := "minecraft_server." + game + ".jar" + if exists, err := f.exists(serverJar); err != nil { + return err + } else if !exists { + server, err := f.vanillaFile(ctx, game, serverJar) + if err != nil { + return err + } + files = append(files, server) + } + + return Ensure(ctx, f.client, f.dir, f.name, files) +} + +// patchProfile drops processors from an install profile and fills in library +// checksums, keeping everything else as it is +func patchProfile(raw []byte, removeProcessors map[int]bool, sha1s map[int]string) ([]byte, error) { + var doc map[string]json.RawMessage + if err := json.Unmarshal(raw, &doc); err != nil { + return nil, err + } + + if len(removeProcessors) > 0 { + var processors []json.RawMessage + if err := json.Unmarshal(doc["processors"], &processors); err != nil { + return nil, err + } + + kept := make([]json.RawMessage, 0, len(processors)) + for i, proc := range processors { + if !removeProcessors[i] { + kept = append(kept, proc) + } + } + + encoded, err := json.Marshal(kept) + if err != nil { + return nil, err + } + doc["processors"] = encoded + } + + if len(sha1s) > 0 { + decoder := json.NewDecoder(bytes.NewReader(doc["libraries"])) + decoder.UseNumber() + + var libraries []map[string]any + if err := decoder.Decode(&libraries); err != nil { + return nil, err + } + + for i, sum := range sha1s { + if i >= len(libraries) { + return nil, fmt.Errorf("no library %d", i) + } + downloads, _ := libraries[i]["downloads"].(map[string]any) + artifact, _ := downloads["artifact"].(map[string]any) + if artifact == nil { + return nil, fmt.Errorf("library %d has no download", i) + } + artifact["sha1"] = sum + } + + encoded, err := json.Marshal(libraries) + if err != nil { + return nil, err + } + doc["libraries"] = encoded + } + + return json.Marshal(doc) +} + +// repackJar copies the jar at src to dst with the entries in replace swapped +// and the signature dropped, which the changed entries would break +func repackJar(src, dst string, replace map[string][]byte) error { + reader, err := zip.OpenReader(src) + if err != nil { + return fmt.Errorf("failed to open %s: %w", src, err) + } + defer reader.Close() + + tmp := dst + ".tmp" + if err := writeRepacked(tmp, reader, replace); err != nil { + os.Remove(tmp) + return fmt.Errorf("failed to repack %s: %w", filepath.Base(src), err) + } + + if err := os.Rename(tmp, dst); err != nil { + os.Remove(tmp) + return fmt.Errorf("failed to write %s: %w", dst, err) + } + + return nil +} + +func writeRepacked(path string, reader *zip.ReadCloser, replace map[string][]byte) error { + out, err := os.Create(path) + if err != nil { + return err + } + defer out.Close() + + zw := zip.NewWriter(out) + for _, entry := range reader.File { + if signatureFile(entry.Name) { + continue + } + + if data, ok := replace[entry.Name]; ok { + w, err := zw.CreateHeader(&zip.FileHeader{Name: entry.Name, Method: zip.Deflate, Modified: entry.Modified}) + if err != nil { + return err + } + if _, err := w.Write(data); err != nil { + return err + } + continue + } + + if err := copyRawEntry(zw, entry); err != nil { + return err + } + } + + if err := zw.Close(); err != nil { + return err + } + + return out.Close() +} + +func copyRawEntry(zw *zip.Writer, entry *zip.File) error { + // A directory may carry an empty deflate stream, which zip.Writer refuses + if strings.HasSuffix(entry.Name, "/") { + _, err := zw.CreateHeader(&zip.FileHeader{Name: entry.Name, Method: zip.Store, Modified: entry.Modified}) + return err + } + + header := entry.FileHeader + w, err := zw.CreateRaw(&header) + if err != nil { + return err + } + + r, err := entry.OpenRaw() + if err != nil { + return err + } + + _, err = io.Copy(w, r) + return err +} + +// signatureFile tells whether name belongs to a jar signature +func signatureFile(name string) bool { + dir, file := path.Split(strings.ToUpper(name)) + if dir != "META-INF/" { + return false + } + + switch path.Ext(file) { + case ".SF", ".RSA", ".DSA", ".EC": + return true + } + return strings.HasPrefix(file, "SIG-") +} + +// writeFileAtomic writes data next to dest and renames it into place +func writeFileAtomic(dest string, data []byte) error { + if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { + return fmt.Errorf("failed to create %s: %w", filepath.Dir(dest), err) + } + + part := dest + ".part" + if err := os.WriteFile(part, data, 0644); err != nil { + os.Remove(part) + return fmt.Errorf("failed to write %s: %w", dest, err) + } + + if err := os.Rename(part, dest); err != nil { + os.Remove(part) + return fmt.Errorf("failed to write %s: %w", dest, err) + } + + return nil +} diff --git a/internal/preseed/forge_test.go b/internal/preseed/forge_test.go new file mode 100644 index 0000000..67886fd --- /dev/null +++ b/internal/preseed/forge_test.go @@ -0,0 +1,320 @@ +package preseed + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func marshal(t *testing.T, v any) string { + t.Helper() + + data, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + return string(data) +} + +func library(name, url, sha1 string) map[string]any { + return map[string]any{"name": name, "downloads": map[string]any{ + "artifact": map[string]any{"url": url, "sha1": sha1, "size": 4}, + }} +} + +const offlineInstaller = "net/minecraftforge/installer/SimpleInstaller.class" + +func TestForgeInstallerSkipsSanitizedMappingsByChecksum(t *testing.T) { + r := newRepo(t, map[string]string{ + "/server.jar": "vanilla", + "/server.txt": sampleMappings, + "/maven/a.jar": "aaaa", + "/maven/b.jar": "bbbb", + }) + + profile := marshal(t, map[string]any{ + "spec": 1, + "minecraft": "1.21.4", + "json": "/version.json", + "serverJarPath": "{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}-bundled.jar", + "libraries": []any{ + library("net.minecraftforge:installertools:1.4.3", r.URL+"/maven/a.jar", sha1Hex("aaaa")), + library("net.minecraftforge:forge:1.21.4-54.1.22:shim", r.URL+"/maven/missing.jar", sha1Hex("shim")), + }, + "processors": []any{ + map[string]any{ + "jar": "net.minecraftforge:installertools:1.4.3", + "args": []string{"--task", "DOWNLOAD_MOJMAPS", "--sanitize", "--version", "1.21.4", "--side", "{SIDE}", "--output", "{MOJMAPS}"}, + "outputs": map[string]string{"{MOJMAPS}": "{MOJMAPS_SHA}"}, + }, + }, + "data": map[string]any{ + "MOJMAPS": map[string]string{"client": "[net.minecraft:client:1.21.4:mappings@tsrg]", "server": "[net.minecraft:server:1.21.4:mappings@tsrg]"}, + "MOJMAPS_SHA": map[string]string{"client": "'x'", "server": "'" + sha1Hex(sampleLegacyTSRG) + "'"}, + }, + }) + version := marshal(t, map[string]any{"libraries": []any{ + library("org.ow2.asm:asm:9.7", r.URL+"/maven/b.jar", sha1Hex("bbbb")), + library("net.minecraftforge:forge:1.21.4-54.1.22", "", ""), + }}) + + dir := t.TempDir() + writeJar(t, filepath.Join(dir, "forge-installer.jar"), map[string]string{ + "install_profile.json": profile, + "version.json": version, + "maven/net/minecraftforge/forge/1.21.4-54.1.22/forge-1.21.4-54.1.22-shim.jar": "shim", + offlineInstaller: "accepts offline", + "META-INF/FORGE.SF": "signature", + "META-INF/FORGE.RSA": "signature", + }) + + versions := &fakeVersions{ + url: r.URL + "/server.jar", sha1: sha1Hex("vanilla"), + mappingsURL: r.URL + "/server.txt", mappingsSHA1: sha1Hex(sampleMappings), + } + + install, err := ForgeInstaller(context.Background(), client(), versions, dir, "forge-installer.jar", "Forge") + if err != nil { + t.Fatalf("ForgeInstaller: %v", err) + } + if install.Installer != "forge-installer.jar" || !install.Offline || install.repacked { + t.Errorf("install = %+v, want the original installer, offline", install) + } + + for rel, want := range map[string]string{ + "libraries/net/minecraftforge/installertools/1.4.3/installertools-1.4.3.jar": "aaaa", + "libraries/org/ow2/asm/asm/9.7/asm-9.7.jar": "bbbb", + "libraries/net/minecraft/server/1.21.4/server-1.21.4-bundled.jar": "vanilla", + "libraries/net/minecraft/server/1.21.4/server-1.21.4-mappings.tsrg": sampleLegacyTSRG, + } { + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(rel))); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } + + leftovers, _ := filepath.Glob(filepath.Join(dir, ".mojmaps-*")) + if len(leftovers) != 0 { + t.Errorf("temporary files left behind: %v", leftovers) + } + + before, lookups := r.requests(), versions.calls + if _, err := ForgeInstaller(context.Background(), client(), versions, dir, "forge-installer.jar", "Forge"); err != nil { + t.Fatal(err) + } + if r.requests() != before || versions.calls != lookups { + t.Errorf("a prepared installer cost %d requests and %d lookups", r.requests()-before, versions.calls-lookups) + } +} + +func TestForgeInstallerRepacksWithoutMappingsDownload(t *testing.T) { + r := newRepo(t, map[string]string{ + "/server.jar": "vanilla", + "/server.txt": sampleMappings, + "/maven/a.jar": "aaaa", + "/maven/a.jar.sha1": sha1Hex("aaaa"), + }) + + mojmaps := func(side string) map[string]any { + return map[string]any{ + "jar": "net.neoforged.installertools:installertools:2.1.2", + "sides": []string{side}, + "args": []string{"--task", "DOWNLOAD_MOJMAPS", "--version", "1.21.1", "--side", "{SIDE}", "--output", "{MOJMAPS}"}, + } + } + profile := marshal(t, map[string]any{ + "spec": 1, + "minecraft": "1.21.1", + "json": "/version.json", + "libraries": []any{}, + "processors": []any{ + mojmaps("client"), + mojmaps("server"), + map[string]any{"jar": "net.neoforged.installertools:binarypatcher:2.1.2", "args": []string{"--clean", "{MC_SRG}"}}, + }, + "data": map[string]any{ + "MOJMAPS": map[string]string{"server": "[net.minecraft:server:1.21.1-20240808.144430:mappings@txt]"}, + }, + }) + version := marshal(t, map[string]any{"id": "neoforge", "libraries": []any{ + library("org.example:nosum:1.0", r.URL+"/maven/a.jar", ""), + }}) + + dir := t.TempDir() + writeJar(t, filepath.Join(dir, "neoforge-installer.jar"), map[string]string{ + "install_profile.json": profile, + "version.json": version, + "data/": "", + "data/server.lzma": "patches", + offlineInstaller: "accepts offline", + "META-INF/MANIFEST.MF": "Manifest-Version: 1.0\r\nMain-Class: x.Y\r\n\r\n", + "META-INF/NEOFORGE.SF": "signature", + "META-INF/NEOFORGE.DSA": "signature", + }) + + versions := &fakeVersions{ + url: r.URL + "/server.jar", sha1: sha1Hex("vanilla"), + mappingsURL: r.URL + "/server.txt", mappingsSHA1: sha1Hex(sampleMappings), + } + + install, err := ForgeInstaller(context.Background(), client(), versions, dir, "neoforge-installer.jar", "NeoForge") + if err != nil { + t.Fatalf("ForgeInstaller: %v", err) + } + if install.Installer != "neoforge-installer-offline.jar" || !install.Offline { + t.Fatalf("install = %+v, want a repacked offline installer", install) + } + + mappings := "libraries/net/minecraft/server/1.21.1-20240808.144430/server-1.21.1-20240808.144430-mappings.txt" + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(mappings))); got != sampleMappings { + t.Errorf("the raw mappings were not put in place: %q", got) + } + if got := readFile(t, filepath.Join(dir, "minecraft_server.1.21.1.jar")); got != "vanilla" { + t.Errorf("vanilla server = %q", got) + } + + jar, err := OpenJar(filepath.Join(dir, install.Installer)) + if err != nil { + t.Fatal(err) + } + + var repacked struct { + Processors []forgeProcessor `json:"processors"` + } + data, _, _ := jar.Read(installProfile) + if err := json.Unmarshal(data, &repacked); err != nil { + t.Fatal(err) + } + if len(repacked.Processors) != 2 || repacked.Processors[0].Sides[0] != "client" || + repacked.Processors[1].arg("--clean") != "{MC_SRG}" { + t.Errorf("processors left: %+v", repacked.Processors) + } + + var repackedVersion struct { + ID string `json:"id"` + Libraries []forgeLibrary `json:"libraries"` + } + data, _, _ = jar.Read("version.json") + if err := json.Unmarshal(data, &repackedVersion); err != nil { + t.Fatal(err) + } + if repackedVersion.ID != "neoforge" || repackedVersion.Libraries[0].Downloads.Artifact.SHA1 != sha1Hex("aaaa") { + t.Errorf("version.json = %s", data) + } + + if patches, _, _ := jar.Read("data/server.lzma"); string(patches) != "patches" { + t.Errorf("data/server.lzma = %q", patches) + } + if jar.Has("META-INF/NEOFORGE.SF") || jar.Has("META-INF/NEOFORGE.DSA") || !jar.Has("META-INF/MANIFEST.MF") { + t.Error("the signature must go, the manifest must stay") + } + jar.Close() + + install.Remove() + if _, err := os.Stat(filepath.Join(dir, install.Installer)); !os.IsNotExist(err) { + t.Error("the repacked installer was not removed") + } + if _, err := os.Stat(filepath.Join(dir, "neoforge-installer.jar")); err != nil { + t.Error("the original installer is gone") + } +} + +func TestForgeInstallerWithoutOfflineModeIsNotRepacked(t *testing.T) { + r := newRepo(t, map[string]string{"/server.jar": "vanilla", "/server.txt": sampleMappings}) + + dir := t.TempDir() + writeJar(t, filepath.Join(dir, "forge-installer.jar"), map[string]string{ + "install_profile.json": marshal(t, map[string]any{ + "minecraft": "1.17.1", + "json": "/version.json", + "processors": []any{map[string]any{ + "args": []string{"--task", "DOWNLOAD_MOJMAPS", "--version", "1.17.1", "--side", "{SIDE}", "--output", "{MOJMAPS}"}, + }}, + "data": map[string]any{"MOJMAPS": map[string]string{"server": "[net.minecraft:server:1.17.1:mappings@txt]"}}, + }), + "version.json": `{"libraries": []}`, + }) + + versions := &fakeVersions{url: r.URL + "/server.jar", sha1: sha1Hex("vanilla"), + mappingsURL: r.URL + "/server.txt", mappingsSHA1: sha1Hex(sampleMappings)} + + install, err := ForgeInstaller(context.Background(), client(), versions, dir, "forge-installer.jar", "Forge") + if err != nil { + t.Fatal(err) + } + if install.Offline || install.Installer != "forge-installer.jar" { + t.Errorf("install = %+v, want the original installer, online", install) + } +} + +func TestLegacyForgeInstaller(t *testing.T) { + r := newRepo(t, map[string]string{ + "/server.jar": "vanilla", + "/forge/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar": "scala", + "/mc/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar": "wrapper", + "/mc/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar.sha1": sha1Hex("wrapper"), + }) + + saved := minecraftLibraries + minecraftLibraries = r.URL + "/mc/" + t.Cleanup(func() { minecraftLibraries = saved }) + + profile := marshal(t, map[string]any{ + "install": map[string]any{"minecraft": "1.7.10", "filePath": "forge-universal.jar"}, + "versionInfo": map[string]any{"libraries": []any{ + map[string]any{"name": "net.minecraftforge:forge:1.7.10-10.13.4.1614-1.7.10", "url": r.URL + "/forge/"}, + map[string]any{"name": "net.minecraft:launchwrapper:1.12", "serverreq": true}, + map[string]any{"name": "org.scala-lang:scala-library:2.11.1", "url": r.URL + "/forge/", "serverreq": true, + "checksums": []string{sha1Hex("packed"), sha1Hex("scala")}}, + map[string]any{"name": "org.lwjgl:lwjgl:2.9.1", "clientreq": true}, + }}, + }) + + dir := t.TempDir() + writeJar(t, filepath.Join(dir, "forge-installer.jar"), map[string]string{ + "install_profile.json": profile, + "forge-universal.jar": "forge", + offlineInstaller: "accepts offline", + }) + + versions := &fakeVersions{url: r.URL + "/server.jar", sha1: sha1Hex("vanilla")} + install, err := ForgeInstaller(context.Background(), client(), versions, dir, "forge-installer.jar", "Forge") + if err != nil { + t.Fatalf("ForgeInstaller: %v", err) + } + if !install.Offline || install.repacked { + t.Errorf("install = %+v", install) + } + + for rel, want := range map[string]string{ + "minecraft_server.1.7.10.jar": "vanilla", + "libraries/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar": "wrapper", + "libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar": "scala", + } { + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(rel))); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } + for _, rel := range []string{"libraries/org/lwjgl", "libraries/net/minecraftforge"} { + if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(rel))); !os.IsNotExist(err) { + t.Errorf("%s is not needed by the server", rel) + } + } +} + +func TestSignatureFile(t *testing.T) { + for name, want := range map[string]bool{ + "META-INF/FORGE.SF": true, + "META-INF/forge.rsa": true, + "META-INF/X.EC": true, + "META-INF/SIG-X": true, + "META-INF/MANIFEST.MF": false, + "META-INF/sub/X.SF": false, + "X.SF": false, + } { + if got := signatureFile(name); got != want { + t.Errorf("signatureFile(%q) = %v", name, got) + } + } +} diff --git a/internal/preseed/jar.go b/internal/preseed/jar.go new file mode 100644 index 0000000..781337f --- /dev/null +++ b/internal/preseed/jar.go @@ -0,0 +1,288 @@ +package preseed + +import ( + "archive/zip" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +// maxEntrySize bounds the metadata read from a jar +const maxEntrySize = 64 << 20 + +// Jar is an opened jar or zip +type Jar struct { + reader *zip.ReadCloser + files map[string]*zip.File +} + +// OpenJar opens the jar at path +func OpenJar(path string) (*Jar, error) { + reader, err := zip.OpenReader(path) + if err != nil { + return nil, fmt.Errorf("failed to open %s: %w", path, err) + } + + files := make(map[string]*zip.File, len(reader.File)) + for _, f := range reader.File { + files[f.Name] = f + } + + return &Jar{reader: reader, files: files}, nil +} + +// Close closes the jar +func (j *Jar) Close() error { + return j.reader.Close() +} + +// Has tells whether the jar holds the file name +func (j *Jar) Has(name string) bool { + _, ok := j.files[name] + return ok +} + +// Read returns the contents of the file name; ok is false when the jar does +// not hold it +func (j *Jar) Read(name string) (data []byte, ok bool, err error) { + f, found := j.files[name] + if !found { + return nil, false, nil + } + + rc, err := f.Open() + if err != nil { + return nil, true, fmt.Errorf("failed to read %s: %w", name, err) + } + defer rc.Close() + + data, err = io.ReadAll(io.LimitReader(rc, maxEntrySize+1)) + if err != nil { + return nil, true, fmt.Errorf("failed to read %s: %w", name, err) + } + if len(data) > maxEntrySize { + return nil, true, fmt.Errorf("%s is too large", name) + } + + return data, true, nil +} + +// Extract writes the file name to dest unless dest already holds it, checking +// it against its SHA-256 +func (j *Jar) Extract(name, dest, sha256Sum string) error { + if utils.VerifySHA256(dest, sha256Sum) == nil { + return nil + } + + f, found := j.files[name] + if !found { + return fmt.Errorf("%s is missing", name) + } + + rc, err := f.Open() + if err != nil { + return fmt.Errorf("failed to read %s: %w", name, err) + } + defer rc.Close() + + if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil { + return fmt.Errorf("failed to create %s: %w", filepath.Dir(dest), err) + } + + part := dest + ".part" + out, err := os.Create(part) + if err != nil { + return fmt.Errorf("failed to write %s: %w", dest, err) + } + defer os.Remove(part) + + hash := sha256.New() + _, err = io.Copy(io.MultiWriter(out, hash), rc) + if closeErr := out.Close(); err == nil { + err = closeErr + } + if err != nil { + return fmt.Errorf("failed to extract %s: %w", name, err) + } + + if got := hex.EncodeToString(hash.Sum(nil)); !strings.EqualFold(got, sha256Sum) { + return fmt.Errorf("%s has SHA-256 %s, want %s", name, got, sha256Sum) + } + + if err := os.Rename(part, dest); err != nil { + return fmt.Errorf("failed to write %s: %w", dest, err) + } + + return nil +} + +// lines splits text metadata into trimmed, non-empty lines +func lines(data []byte) []string { + raw := strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n") + + result := make([]string, 0, len(raw)) + for _, line := range raw { + if line = strings.TrimSpace(line); line != "" { + result = append(result, line) + } + } + + return result +} + +// Manifest reads the main attributes of the jar's META-INF/MANIFEST.MF +func (j *Jar) Manifest() (map[string]string, error) { + data, ok, err := j.Read("META-INF/MANIFEST.MF") + if err != nil || !ok { + return nil, err + } + + return parseManifest(data), nil +} + +// parseManifest reads the main section of a manifest, joining continuation +// lines +func parseManifest(data []byte) map[string]string { + attributes := make(map[string]string) + + var name, value string + flush := func() { + if name != "" { + attributes[name] = value + } + name, value = "", "" + } + + for _, line := range strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n") { + line = strings.TrimSuffix(line, "\r") + switch { + case line == "": + flush() + return attributes + case line[0] == ' ': + value += line[1:] + default: + flush() + if k, v, ok := strings.Cut(line, ": "); ok { + name, value = k, v + } + } + } + flush() + + return attributes +} + +// manifestLine writes one attribute the way java.util.jar.Manifest does: no +// line longer than 72 bytes, continued on lines that start with a space +func manifestLine(b *strings.Builder, name, value string) { + line := name + ": " + value + limit := 72 + for len(line) > limit { + b.WriteString(line[:limit]) + b.WriteString("\r\n ") + line = line[limit:] + limit = 71 + } + b.WriteString(line) + b.WriteString("\r\n") +} + +// WriteLaunchJar writes a jar that holds only a manifest with the given main +// attributes (Manifest-Version comes first) and the extra files. The jar is +// written next to path and renamed into place. +func WriteLaunchJar(path string, attributes [][2]string, extra map[string]string) error { + var manifest strings.Builder + manifestLine(&manifest, "Manifest-Version", "1.0") + for _, attr := range attributes { + manifestLine(&manifest, attr[0], attr[1]) + } + manifest.WriteString("\r\n") + + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return fmt.Errorf("failed to create %s: %w", filepath.Dir(path), err) + } + + tmp := path + ".tmp" + if err := writeZip(tmp, append([][2]string{{"META-INF/MANIFEST.MF", manifest.String()}}, sortedEntries(extra)...)); err != nil { + os.Remove(tmp) + return err + } + + if err := os.Rename(tmp, path); err != nil { + os.Remove(tmp) + return fmt.Errorf("failed to write %s: %w", path, err) + } + + return nil +} + +func sortedEntries(files map[string]string) [][2]string { + names := make([]string, 0, len(files)) + for name := range files { + names = append(names, name) + } + sort.Strings(names) + + entries := make([][2]string, 0, len(names)) + for _, name := range names { + entries = append(entries, [2]string{name, files[name]}) + } + return entries +} + +func writeZip(path string, entries [][2]string) error { + f, err := os.Create(path) + if err != nil { + return fmt.Errorf("failed to create %s: %w", path, err) + } + defer f.Close() + + zw := zip.NewWriter(f) + for _, entry := range entries { + w, err := zw.Create(entry[0]) + if err != nil { + return fmt.Errorf("failed to write %s: %w", path, err) + } + if _, err := io.WriteString(w, entry[1]); err != nil { + return fmt.Errorf("failed to write %s: %w", path, err) + } + } + if err := zw.Close(); err != nil { + return fmt.Errorf("failed to write %s: %w", path, err) + } + + return f.Close() +} + +// classPathComplete tells whether the jar at path exists and every Class-Path +// entry of its manifest is in place, which is how the Fabric server launcher +// decides that an install is complete +func classPathComplete(path string) bool { + jar, err := OpenJar(path) + if err != nil { + return false + } + defer jar.Close() + + manifest, err := jar.Manifest() + if err != nil || manifest["Main-Class"] == "" { + return false + } + + base := filepath.Dir(path) + for _, entry := range strings.Fields(manifest["Class-Path"]) { + if _, err := os.Stat(filepath.Join(base, filepath.FromSlash(entry))); err != nil { + return false + } + } + + return true +} diff --git a/internal/preseed/loader.go b/internal/preseed/loader.go new file mode 100644 index 0000000..97ed206 --- /dev/null +++ b/internal/preseed/loader.go @@ -0,0 +1,256 @@ +package preseed + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +var ( + fabricMetaURL = "https://meta.fabricmc.net" + quiltMetaURL = "https://meta.quiltmc.org" +) + +const ( + // fabricDataDir is where the Fabric server launcher keeps its install + fabricDataDir = ".fabric/server" + + // fabricDefaultLauncher starts loaders whose manifest names no main class + fabricDefaultLauncher = "net.fabricmc.loader.launch.server.FabricServerLauncher" +) + +// loaderProfile is the server profile Fabric and Quilt meta publish for a +// game and loader version +type loaderProfile struct { + MainClass string `json:"mainClass"` + LauncherMainClass string `json:"launcherMainClass"` + Libraries []struct { + Name string `json:"name"` + URL string `json:"url"` + SHA512 string `json:"sha512"` + SHA256 string `json:"sha256"` + SHA1 string `json:"sha1"` + MD5 string `json:"md5"` + } `json:"libraries"` +} + +func fetchProfile(ctx context.Context, client *utils.HTTPClient, url string) (*loaderProfile, error) { + data, err := client.Get(ctx, url) + if err != nil { + return nil, fmt.Errorf("failed to fetch the loader profile: %w", err) + } + + var profile loaderProfile + if err := json.Unmarshal(data, &profile); err != nil { + return nil, fmt.Errorf("failed to parse the loader profile: %w", err) + } + if len(profile.Libraries) == 0 { + return nil, fmt.Errorf("the loader profile %s lists no libraries", url) + } + + return &profile, nil +} + +func profileURL(base, format, game, loader string) string { + return base + fmt.Sprintf(format, url.PathEscape(game), url.PathEscape(loader)) +} + +// Fabric prepares what the Fabric server launcher installs on its first +// start: the vanilla server, the loader's libraries and the launch jar that +// lists them. The launcher finds them all in place and installs nothing. +// Loaders up to 0.12.5 have their libraries shaded into the launch jar +// instead; for them only the vanilla server is prepared. +func Fabric(ctx context.Context, client *utils.HTTPClient, versions Versions, dir, game, loader string) error { + serverJar := fabricDataDir + "/" + game + "-server.jar" + if err := ensureVanilla(ctx, client, versions, dir, game, serverJar); err != nil { + return err + } + + if versionAtMost(loader, "0.12.5") { + return nil + } + + launchJar := filepath.Join(dir, filepath.FromSlash( + fmt.Sprintf("%s/fabric-loader-server-%s-minecraft-%s.jar", fabricDataDir, loader, game))) + if classPathComplete(launchJar) { + return nil + } + + profile, err := fetchProfile(ctx, client, + profileURL(fabricMetaURL, "/v2/versions/loader/%s/%s/server/json", game, loader)) + if err != nil { + return err + } + + files := make([]File, 0, len(profile.Libraries)) + classPath := make([]string, 0, len(profile.Libraries)) + loaderJar := "" + + for _, lib := range profile.Libraries { + libPath, err := MavenPath(lib.Name) + if err != nil { + return err + } + + file := File{ + Path: "libraries/" + libPath, + URLs: []string{strings.TrimRight(lib.URL, "/") + "/" + libPath}, + SHA512: lib.SHA512, SHA256: lib.SHA256, SHA1: lib.SHA1, MD5: lib.MD5, + } + if file.SHA512 == "" && file.SHA256 == "" && file.SHA1 == "" && file.MD5 == "" { + file.Sidecar = "sha1" + } + files = append(files, file) + classPath = append(classPath, "../../"+file.Path) + + if strings.HasPrefix(lib.Name, "net.fabricmc:fabric-loader:") { + loaderJar = file.Path + } + } + + if err := Ensure(ctx, client, dir, "Fabric", files); err != nil { + return err + } + + mainClass := fabricDefaultLauncher + if loaderJar != "" { + if manifestClass := jarMainClass(filepath.Join(dir, filepath.FromSlash(loaderJar))); manifestClass != "" { + mainClass = manifestClass + } + } + + return WriteLaunchJar(launchJar, + [][2]string{{"Main-Class", mainClass}, {"Class-Path", strings.Join(classPath, " ")}}, + map[string]string{"fabric-server-launch.properties": "launch.mainClass=" + profile.MainClass + "\n"}) +} + +// Quilt installs a Quilt server the way `quilt-installer install server` +// does: the vanilla server as server.jar, the loader's libraries and a launch +// jar, named launcher here, that lists them +func Quilt(ctx context.Context, client *utils.HTTPClient, versions Versions, dir, game, loader, launcher string) error { + if err := ensureVanilla(ctx, client, versions, dir, game, "server.jar"); err != nil { + return err + } + + profile, err := fetchProfile(ctx, client, + profileURL(quiltMetaURL, "/v3/versions/loader/%s/%s/server/json", game, loader)) + if err != nil { + return err + } + if profile.LauncherMainClass == "" { + return fmt.Errorf("the Quilt profile for %s %s names no launcher", game, loader) + } + + files := make([]File, 0, len(profile.Libraries)) + classPath := make([]string, 0, len(profile.Libraries)) + + for _, lib := range profile.Libraries { + // The installer ignores classifiers + parts := strings.SplitN(lib.Name, ":", 4) + if len(parts) < 3 { + return fmt.Errorf("malformed library %q in the Quilt profile", lib.Name) + } + libPath, err := MavenPath(strings.Join(parts[:3], ":")) + if err != nil { + return err + } + + files = append(files, File{ + Path: "libraries/" + libPath, + URLs: []string{strings.TrimRight(lib.URL, "/") + "/" + libPath}, + SHA1: lib.SHA1, + Sidecar: "sha1", + }) + classPath = append(classPath, "libraries/"+libPath) + } + + if err := Ensure(ctx, client, dir, "Quilt", files); err != nil { + return err + } + + sort.Strings(classPath) + + launcherPath, err := Resolve(dir, launcher) + if err != nil { + return err + } + + return WriteLaunchJar(launcherPath, + [][2]string{{"Main-Class", profile.LauncherMainClass}, {"Class-Path", strings.Join(classPath, " ")}}, nil) +} + +// ensureVanilla puts the vanilla server at rel unless a file is there; the +// launchers do not check it either +func ensureVanilla(ctx context.Context, client *utils.HTTPClient, versions Versions, dir, game, rel string) error { + dest, err := Resolve(dir, rel) + if err != nil { + return err + } + if _, err := os.Stat(dest); err == nil { + return nil + } + + vanilla, err := VanillaServer(ctx, versions, game, rel) + if err != nil { + return err + } + + return Ensure(ctx, client, dir, "the vanilla server", []File{vanilla}) +} + +func jarMainClass(jarPath string) string { + jar, err := OpenJar(jarPath) + if err != nil { + return "" + } + defer jar.Close() + + manifest, err := jar.Manifest() + if err != nil { + return "" + } + + return manifest["Main-Class"] +} + +// versionAtMost compares dotted numeric versions, ignoring anything after +// the numbers (0.12.5+build.1 is 0.12.5) +func versionAtMost(version, limit string) bool { + a, b := versionNumbers(version), versionNumbers(limit) + for i := range max(len(a), len(b)) { + var x, y int + if i < len(a) { + x = a[i] + } + if i < len(b) { + y = b[i] + } + if x != y { + return x < y + } + } + return true +} + +func versionNumbers(version string) []int { + version, _, _ = strings.Cut(version, "+") + version, _, _ = strings.Cut(version, "-") + + var numbers []int + for part := range strings.SplitSeq(version, ".") { + n, err := strconv.Atoi(part) + if err != nil { + break + } + numbers = append(numbers, n) + } + return numbers +} diff --git a/internal/preseed/loader_test.go b/internal/preseed/loader_test.go new file mode 100644 index 0000000..4bfef21 --- /dev/null +++ b/internal/preseed/loader_test.go @@ -0,0 +1,247 @@ +package preseed + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/gameap/minecraft-runner/pkg/api/mojang" +) + +// fakeVersions serves the vanilla server and the mappings of every version +// from one URL each +type fakeVersions struct { + url, sha1 string + mappingsURL, mappingsSHA1 string + calls int +} + +func (f *fakeVersions) GetVersion(_ context.Context, id string) (*mojang.VersionDetail, error) { + f.calls++ + detail := &mojang.VersionDetail{ID: id} + detail.Downloads.Server = mojang.Download{URL: f.url, SHA1: f.sha1} + detail.Downloads.ServerMappings = mojang.Download{URL: f.mappingsURL, SHA1: f.mappingsSHA1} + return detail, nil +} + +func jarBytes(t *testing.T, entries map[string]string) string { + t.Helper() + + path := filepath.Join(t.TempDir(), "x.jar") + writeJar(t, path, entries) + return readFile(t, path) +} + +func TestManifestLinesAreJavaReadable(t *testing.T) { + long := make([]string, 0, 30) + for i := range 30 { + long = append(long, fmt.Sprintf("../../libraries/org/example/lib%d/1.0/lib%d-1.0.jar", i, i)) + } + + path := filepath.Join(t.TempDir(), "launch.jar") + err := WriteLaunchJar(path, [][2]string{{"Main-Class", "a.B"}, {"Class-Path", strings.Join(long, " ")}}, + map[string]string{"x.properties": "k=v\n"}) + if err != nil { + t.Fatal(err) + } + + jar, err := OpenJar(path) + if err != nil { + t.Fatal(err) + } + defer jar.Close() + + raw, _, _ := jar.Read("META-INF/MANIFEST.MF") + if !strings.HasPrefix(string(raw), "Manifest-Version: 1.0\r\n") || !strings.HasSuffix(string(raw), "\r\n\r\n") { + t.Errorf("manifest = %q", raw) + } + for _, line := range strings.Split(string(raw), "\r\n") { + if len(line) > 72 { + t.Errorf("line of %d bytes: %q", len(line), line) + } + } + + manifest, err := jar.Manifest() + if err != nil { + t.Fatal(err) + } + if manifest["Main-Class"] != "a.B" || manifest["Class-Path"] != strings.Join(long, " ") { + t.Errorf("manifest read back as %v", manifest) + } + if data, ok, _ := jar.Read("x.properties"); !ok || string(data) != "k=v\n" { + t.Errorf("x.properties = %q, %v", data, ok) + } +} + +func TestVersionAtMost(t *testing.T) { + for _, tt := range []struct { + version, limit string + want bool + }{ + {"0.12.5", "0.12.5", true}, + {"0.12.4", "0.12.5", true}, + {"0.12.6", "0.12.5", false}, + {"0.16.10", "0.12.5", false}, + {"0.12", "0.12.5", true}, + {"0.11.7+build.1", "0.12.5", true}, + {"1.0.0", "0.12.5", false}, + } { + if got := versionAtMost(tt.version, tt.limit); got != tt.want { + t.Errorf("versionAtMost(%q, %q) = %v", tt.version, tt.limit, got) + } + } +} + +func TestFabric(t *testing.T) { + loaderJar := jarBytes(t, map[string]string{ + "META-INF/MANIFEST.MF": "Manifest-Version: 1.0\r\nMain-Class: net.fabricmc.loader.impl.launch.server.FabricServerLauncher\r\n\r\n", + }) + + files := map[string]string{ + "/server.jar": "vanilla", + "/maven/net/fabricmc/fabric-loader/0.16.10/fabric-loader-0.16.10.jar": loaderJar, + "/maven/org/ow2/asm/asm/9.7.1/asm-9.7.1.jar": "asm", + "/maven/org/ow2/asm/asm/9.7.1/asm-9.7.1.jar.sha1": sha1Hex("asm"), + } + r := newRepo(t, files) + + profile, _ := json.Marshal(map[string]any{ + "mainClass": "net.fabricmc.loader.impl.launch.knot.KnotServer", + "libraries": []map[string]string{ + {"name": "org.ow2.asm:asm:9.7.1", "url": r.URL + "/maven/"}, + {"name": "net.fabricmc:fabric-loader:0.16.10", "url": r.URL + "/maven/", "sha256": sha256Hex(loaderJar)}, + }, + }) + r.mu.Lock() + r.files["/v2/versions/loader/1.21.4/0.16.10/server/json"] = string(profile) + r.mu.Unlock() + + saved := fabricMetaURL + fabricMetaURL = r.URL + t.Cleanup(func() { fabricMetaURL = saved }) + + versions := &fakeVersions{url: r.URL + "/server.jar", sha1: sha1Hex("vanilla")} + dir := t.TempDir() + + if err := Fabric(context.Background(), client(), versions, dir, "1.21.4", "0.16.10"); err != nil { + t.Fatalf("Fabric: %v", err) + } + + if got := readFile(t, filepath.Join(dir, ".fabric", "server", "1.21.4-server.jar")); got != "vanilla" { + t.Errorf("vanilla server = %q", got) + } + + launch := filepath.Join(dir, ".fabric", "server", "fabric-loader-server-0.16.10-minecraft-1.21.4.jar") + jar, err := OpenJar(launch) + if err != nil { + t.Fatal(err) + } + manifest, _ := jar.Manifest() + properties, _, _ := jar.Read("fabric-server-launch.properties") + jar.Close() + + if manifest["Main-Class"] != "net.fabricmc.loader.impl.launch.server.FabricServerLauncher" { + t.Errorf("Main-Class = %q", manifest["Main-Class"]) + } + wantClassPath := "../../libraries/org/ow2/asm/asm/9.7.1/asm-9.7.1.jar " + + "../../libraries/net/fabricmc/fabric-loader/0.16.10/fabric-loader-0.16.10.jar" + if manifest["Class-Path"] != wantClassPath { + t.Errorf("Class-Path = %q", manifest["Class-Path"]) + } + if string(properties) != "launch.mainClass=net.fabricmc.loader.impl.launch.knot.KnotServer\n" { + t.Errorf("fabric-server-launch.properties = %q", properties) + } + + before := r.requests() + if err := Fabric(context.Background(), client(), versions, dir, "1.21.4", "0.16.10"); err != nil { + t.Fatal(err) + } + if r.requests() != before || versions.calls != 1 { + t.Errorf("a prepared server cost %d requests and %d version lookups", r.requests()-before, versions.calls-1) + } + + // A library that went missing makes the launcher reinstall, so it is put back + os.Remove(filepath.Join(dir, "libraries", "org", "ow2", "asm", "asm", "9.7.1", "asm-9.7.1.jar")) + if err := Fabric(context.Background(), client(), versions, dir, "1.21.4", "0.16.10"); err != nil { + t.Fatal(err) + } + if !classPathComplete(launch) { + t.Error("the missing library was not restored") + } +} + +func TestFabricShadedLoadersGetTheVanillaServerOnly(t *testing.T) { + r := newRepo(t, map[string]string{"/server.jar": "vanilla"}) + versions := &fakeVersions{url: r.URL + "/server.jar", sha1: sha1Hex("vanilla")} + dir := t.TempDir() + + if err := Fabric(context.Background(), client(), versions, dir, "1.16.5", "0.12.5"); err != nil { + t.Fatalf("Fabric: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, ".fabric", "server", "1.16.5-server.jar")); err != nil { + t.Error(err) + } + if _, err := os.Stat(filepath.Join(dir, "libraries")); !os.IsNotExist(err) { + t.Error("the launcher shades libraries of 0.12.5 itself") + } +} + +func TestQuilt(t *testing.T) { + files := map[string]string{ + "/server.jar": "vanilla", + "/quilt/org/quiltmc/quilt-loader/0.29.2/quilt-loader-0.29.2.jar": "loader", + "/quilt/org/quiltmc/quilt-loader/0.29.2/quilt-loader-0.29.2.jar.sha1": sha1Hex("loader"), + "/fabric/net/fabricmc/intermediary/1.21.1/intermediary-1.21.1.jar": "intermediary", + } + r := newRepo(t, files) + + profile, _ := json.Marshal(map[string]any{ + "mainClass": "org.quiltmc.loader.impl.launch.knot.KnotServer", + "launcherMainClass": "org.quiltmc.loader.impl.launch.server.QuiltServerLauncher", + "libraries": []map[string]string{ + {"name": "org.quiltmc:quilt-loader:0.29.2", "url": r.URL + "/quilt/"}, + {"name": "net.fabricmc:intermediary:1.21.1:v2", "url": r.URL + "/fabric/"}, + }, + }) + r.mu.Lock() + r.files["/v3/versions/loader/1.21.1/0.29.2/server/json"] = string(profile) + r.mu.Unlock() + + saved := quiltMetaURL + quiltMetaURL = r.URL + t.Cleanup(func() { quiltMetaURL = saved }) + + dir := t.TempDir() + versions := &fakeVersions{url: r.URL + "/server.jar", sha1: sha1Hex("vanilla")} + + if err := Quilt(context.Background(), client(), versions, dir, "1.21.1", "0.29.2", "quilt-server-launch-1.21.1-0.29.2.jar"); err != nil { + t.Fatalf("Quilt: %v", err) + } + + if got := readFile(t, filepath.Join(dir, "server.jar")); got != "vanilla" { + t.Errorf("server.jar = %q", got) + } + + jar, err := OpenJar(filepath.Join(dir, "quilt-server-launch-1.21.1-0.29.2.jar")) + if err != nil { + t.Fatal(err) + } + manifest, _ := jar.Manifest() + jar.Close() + + if manifest["Main-Class"] != "org.quiltmc.loader.impl.launch.server.QuiltServerLauncher" { + t.Errorf("Main-Class = %q", manifest["Main-Class"]) + } + want := "libraries/net/fabricmc/intermediary/1.21.1/intermediary-1.21.1.jar " + + "libraries/org/quiltmc/quilt-loader/0.29.2/quilt-loader-0.29.2.jar" + if manifest["Class-Path"] != want { + t.Errorf("Class-Path = %q", manifest["Class-Path"]) + } + if !classPathComplete(filepath.Join(dir, "quilt-server-launch-1.21.1-0.29.2.jar")) { + t.Error("the launcher lists files that are not there") + } +} diff --git a/internal/preseed/maven.go b/internal/preseed/maven.go new file mode 100644 index 0000000..ce505d9 --- /dev/null +++ b/internal/preseed/maven.go @@ -0,0 +1,43 @@ +package preseed + +import ( + "fmt" + "strings" +) + +// MavenPath maps a Maven coordinate, group:artifact:version[:classifier][@ext], +// onto its path in a repository +func MavenPath(coord string) (string, error) { + ext := "jar" + if at := strings.LastIndexByte(coord, '@'); at >= 0 { + coord, ext = coord[:at], coord[at+1:] + } + + parts := strings.Split(coord, ":") + if len(parts) < 3 || len(parts) > 4 || ext == "" { + return "", fmt.Errorf("malformed Maven coordinate %q", coord) + } + for _, part := range append(parts, ext) { + if part == "" || part == "." || part == ".." || strings.ContainsAny(part, `/\`) { + return "", fmt.Errorf("malformed Maven coordinate %q", coord) + } + } + + group, artifact, version := parts[0], parts[1], parts[2] + + file := artifact + "-" + version + if len(parts) == 4 { + file += "-" + parts[3] + } + + return strings.ReplaceAll(group, ".", "/") + "/" + artifact + "/" + version + "/" + file + "." + ext, nil +} + +// repositoryURLs joins path to each repository +func repositoryURLs(repositories []string, path string) []string { + urls := make([]string, 0, len(repositories)) + for _, repo := range repositories { + urls = append(urls, strings.TrimRight(repo, "/")+"/"+path) + } + return urls +} diff --git a/internal/preseed/modules.go b/internal/preseed/modules.go new file mode 100644 index 0000000..1d3d673 --- /dev/null +++ b/internal/preseed/modules.go @@ -0,0 +1,63 @@ +package preseed + +import ( + "context" + "errors" + "fmt" + "os" + "path" + "path/filepath" + "strings" + + "github.com/goccy/go-yaml" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +// ProxyModules puts into modules/ the modules BungeeCord and Waterfall would +// download on start. Once modules.yml exists only the modules it lists are +// prepared, so a module the owner removed is not brought back. +func ProxyModules(ctx context.Context, client *utils.HTTPClient, dir string, modules []File) error { + listed, err := listedModules(filepath.Join(dir, "modules.yml")) + if err != nil { + return err + } + + files := make([]File, 0, len(modules)) + for _, m := range modules { + name := strings.TrimSuffix(path.Base(m.Path), ".jar") + if listed == nil || listed[name] { + files = append(files, m) + } + } + + return Ensure(ctx, client, dir, "the proxy modules", files) +} + +// listedModules reads the jenkins:// modules of modules.yml; nil means the file +// is not there yet +func listedModules(file string) (map[string]bool, error) { + data, err := os.ReadFile(file) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("failed to read %s: %w", file, err) + } + + var config struct { + Modules []string `yaml:"modules"` + } + if err := yaml.Unmarshal(data, &config); err != nil { + return nil, fmt.Errorf("failed to parse %s: %w", file, err) + } + + listed := make(map[string]bool, len(config.Modules)) + for _, module := range config.Modules { + if name, ok := strings.CutPrefix(strings.TrimSpace(module), "jenkins://"); ok { + listed[name] = true + } + } + + return listed, nil +} diff --git a/internal/preseed/mohist.go b/internal/preseed/mohist.go new file mode 100644 index 0000000..61a20ac --- /dev/null +++ b/internal/preseed/mohist.go @@ -0,0 +1,258 @@ +package preseed + +import ( + "context" + "encoding/json" + "fmt" + "regexp" + "slices" + "strings" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +// mohistRepositories serve the libraries Mohist lists in libraries.txt and +// mohist_libraries.txt, in the order Mohist tries them +var mohistRepositories = []string{"https://maven.mohistmc.com/", "https://mohistmc.github.io/maven/"} + +// bannerRepositories are the Maven repositories Banner's installer knows, +// with Maven Central for what Mohist's repositories proxy +var bannerRepositories = []string{ + "https://maven.mohistmc.com/libraries/", + "https://mohistmc.github.io/maven/libraries/", + "https://repo.spongepowered.org/maven/", + "https://maven.fabricmc.net/", + "https://libraries.minecraft.net/", + "https://repo1.maven.org/maven2/", + "https://maven.izzel.io/releases/", +} + +// vanillaLibrary matches the vanilla servers in Mohist's library lists +var vanillaLibrary = regexp.MustCompile(`(?:^|/)minecraft_server\.([^/]+)\.jar$|/net/minecraft/server/([^/]+)/server-([^/]+)\.jar$`) + +// Mohist prepares what a MohistMC server (Mohist, Banner, Cauldron) at +// jarPath downloads on its first start. Mohist 1.12.2 and the builds with an +// installer.txt carry their libraries inside the jar and download nothing. +func Mohist(ctx context.Context, client *utils.HTTPClient, versions Versions, dir, jarPath string) error { + jar, err := OpenJar(jarPath) + if err != nil { + return err + } + defer jar.Close() + + if jar.Has("installer.json") && jar.Has("fabric.mod.json") { + return banner(ctx, client, versions, dir, jar) + } + + for _, list := range []string{"libraries.txt", "mohist_libraries.txt"} { + if jar.Has(list) { + return mohistLibraries(ctx, client, versions, dir, jar, list) + } + } + + return nil +} + +// mohistLibraries handles the "path|md5[|size]" lists. Mohist copies the +// libraries it carries under META-INF/ itself; the others are downloaded. +func mohistLibraries( + ctx context.Context, client *utils.HTTPClient, versions Versions, dir string, jar *Jar, list string, +) error { + data, _, err := jar.Read(list) + if err != nil { + return err + } + + var files []File + for _, line := range lines(data) { + parts := strings.Split(line, "|") + if len(parts) < 2 || !strings.HasPrefix(parts[0], "libraries/") { + return fmt.Errorf("malformed line %q in %s", line, list) + } + + if jar.Has("META-INF/" + parts[0]) { + continue + } + + file := File{Path: parts[0], URLs: repositoryURLs(mohistRepositories, parts[0]), MD5: parts[1]} + if err := addMojangSource(ctx, versions, dir, &file); err != nil { + return err + } + files = append(files, file) + } + + return Ensure(ctx, client, dir, "Mohist", files) +} + +// addMojangSource lets a missing vanilla server come from Mojang: Mohist's +// repositories lost some of them, Mohist 1.16.5's among them +func addMojangSource(ctx context.Context, versions Versions, dir string, file *File) error { + version := vanillaVersion(file.Path) + if version == "" { + return nil + } + + dest, err := Resolve(dir, file.Path) + if err != nil { + return err + } + if present(dest, *file) { + return nil + } + + server, err := VanillaServer(ctx, versions, version, file.Path) + if err != nil { + fmt.Printf("[WARNING] %v\n", err) + return nil + } + file.URLs = append(file.URLs, server.URLs...) + + return nil +} + +// vanillaVersion tells which vanilla server a library path holds, if any +func vanillaVersion(path string) string { + match := vanillaLibrary.FindStringSubmatch(path) + if match == nil || match[2] != match[3] { + return "" + } + + return match[1] + match[2] +} + +type bannerInstall struct { + Installer struct { + Minecraft string `json:"minecraft"` + FabricLoader string `json:"fabricLoader"` + FabricLoaderHash string `json:"fabricLoaderHash"` + } `json:"installer"` + Libraries map[string]string `json:"libraries"` + FabricExtra map[string]string `json:"fabricExtra"` +} + +// banner prepares what Banner's installer checks before it runs: its +// libraries, the Fabric loader with the libraries the loader lists and the +// vanilla server. Missing any of them, it downloads Mojang's version manifest. +func banner(ctx context.Context, client *utils.HTTPClient, versions Versions, dir string, jar *Jar) error { + data, _, err := jar.Read("installer.json") + if err != nil { + return err + } + + var install bannerInstall + if err := json.Unmarshal(data, &install); err != nil { + return fmt.Errorf("failed to parse Banner's installer.json: %w", err) + } + game, loader := install.Installer.Minecraft, install.Installer.FabricLoader + if game == "" || loader == "" { + return fmt.Errorf("banner's installer.json names no Minecraft or Fabric version") + } + + libraries := make(map[string]string, len(install.Libraries)+len(install.FabricExtra)+1) + for coord, sum := range install.Libraries { + libraries[coord] = sum + } + for coord, sum := range install.FabricExtra { + libraries[coord] = sum + } + loaderCoord := "net.fabricmc:fabric-loader:" + loader + libraries[loaderCoord] = install.Installer.FabricLoaderHash + + files := make([]File, 0, len(libraries)+1) + for _, coord := range slices.Sorted(func(yield func(string) bool) { + for coord := range libraries { + if !yield(coord) { + return + } + } + }) { + libPath, err := MavenPath(coord) + if err != nil { + return err + } + files = append(files, File{Path: "libraries/" + libPath, URLs: repositoryURLs(bannerRepositories, libPath), SHA1: libraries[coord]}) + } + + // The server Banner carries replaces the vanilla one + serverJar := fmt.Sprintf("libraries/net/minecraft/server/%[1]s/server-%[1]s.jar", game) + if !jar.Has("META-INF/jars/server-" + game + ".jar") { + if exists, err := pathExists(dir, serverJar); err != nil { + return err + } else if !exists { + server, err := VanillaServer(ctx, versions, game, serverJar) + if err != nil { + return err + } + files = append(files, server) + } + } + + if err := Ensure(ctx, client, dir, "Banner", files); err != nil { + return err + } + + loaderPath, _ := MavenPath(loaderCoord) + loaderLibraries, err := fabricInstallerLibraries(dir, "libraries/"+loaderPath) + if err != nil { + return err + } + + return Ensure(ctx, client, dir, "Fabric", loaderLibraries) +} + +// fabricInstallerLibraries lists the libraries of the fabric-installer.json +// a Fabric loader jar carries +func fabricInstallerLibraries(dir, loaderJar string) ([]File, error) { + loaderPath, err := Resolve(dir, loaderJar) + if err != nil { + return nil, err + } + + jar, err := OpenJar(loaderPath) + if err != nil { + return nil, err + } + defer jar.Close() + + data, ok, err := jar.Read("fabric-installer.json") + if err != nil { + return nil, err + } + if !ok { + return nil, fmt.Errorf("%s has no fabric-installer.json", loaderJar) + } + + var installer struct { + Libraries map[string][]struct { + Name string `json:"name"` + URL string `json:"url"` + SHA1 string `json:"sha1"` + } `json:"libraries"` + } + if err := json.Unmarshal(data, &installer); err != nil { + return nil, fmt.Errorf("failed to parse the fabric-installer.json of %s: %w", loaderJar, err) + } + + var files []File + for _, side := range []string{"common", "server"} { + for _, lib := range installer.Libraries[side] { + libPath, err := MavenPath(lib.Name) + if err != nil { + return nil, err + } + + urls := repositoryURLs(bannerRepositories, libPath) + if lib.URL != "" { + urls = append([]string{strings.TrimRight(lib.URL, "/") + "/" + libPath}, urls...) + } + + file := File{Path: "libraries/" + libPath, URLs: urls, SHA1: lib.SHA1} + if file.SHA1 == "" { + file.Sidecar = "sha1" + } + files = append(files, file) + } + } + + return files, nil +} diff --git a/internal/preseed/mohist_test.go b/internal/preseed/mohist_test.go new file mode 100644 index 0000000..eda1218 --- /dev/null +++ b/internal/preseed/mohist_test.go @@ -0,0 +1,189 @@ +package preseed + +import ( + "context" + "os" + "path/filepath" + "testing" +) + +func useRepositories(t *testing.T, target *[]string, repos ...string) { + t.Helper() + + saved := *target + *target = repos + t.Cleanup(func() { *target = saved }) +} + +func TestMohistLibraries(t *testing.T) { + r := newRepo(t, map[string]string{ + "/github/libraries/org/example/b/1.0/b-1.0.jar": "bbbb", + "/mojang/server.jar": "vanilla", + "/maven/libraries/org/example/broken/1.0/broken-1.0.jar": "corrupt", + "/github/libraries/org/example/broken/1.0/broken-1.0.jar": "fixed", + }) + useRepositories(t, &mohistRepositories, r.URL+"/maven/", r.URL+"/github/") + + dir := t.TempDir() + jarPath := filepath.Join(dir, "mohist-1.16.5-362.jar") + writeJar(t, jarPath, map[string]string{ + "libraries.txt": "libraries/org/example/a/1.0/a-1.0.jar|" + md5Hex("aaaa") + "|4\n" + + "libraries/org/example/b/1.0/b-1.0.jar|" + md5Hex("bbbb") + "|4\r\n" + + "libraries/minecraft_server.1.16.5.jar|" + md5Hex("vanilla") + "|7\n" + + "libraries/org/example/broken/1.0/broken-1.0.jar|" + md5Hex("fixed") + "|5\n", + "META-INF/libraries/org/example/a/1.0/a-1.0.jar": "aaaa", + }) + + versions := &fakeVersions{url: r.URL + "/mojang/server.jar", sha1: sha1Hex("vanilla")} + if err := Mohist(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatalf("Mohist: %v", err) + } + if versions.calls != 1 { + t.Errorf("%d vanilla lookups, want 1", versions.calls) + } + + for rel, want := range map[string]string{ + "libraries/org/example/b/1.0/b-1.0.jar": "bbbb", + "libraries/minecraft_server.1.16.5.jar": "vanilla", + "libraries/org/example/broken/1.0/broken-1.0.jar": "fixed", + } { + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(rel))); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } + if _, err := os.Stat(filepath.Join(dir, "libraries", "org", "example", "a")); !os.IsNotExist(err) { + t.Error("a library the jar carries was downloaded") + } + + if err := Mohist(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatal(err) + } + if versions.calls != 1 { + t.Error("the vanilla server was looked up again although it is in place") + } +} + +func TestVanillaVersion(t *testing.T) { + for path, want := range map[string]string{ + "libraries/minecraft_server.1.16.5.jar": "1.16.5", + "libraries/net/minecraft/1.12.2/minecraft_server.1.12.2.jar": "1.12.2", + "libraries/net/minecraft/server/1.7.10/server-1.7.10.jar": "1.7.10", + "libraries/net/minecraft/server/1.16.5-20210115/server-1.16.5-20210115-extra.jar": "", + "libraries/org/eclipse/jetty/server-9.4.jar": "", + } { + if got := vanillaVersion(path); got != want { + t.Errorf("%s: version %q, want %q", path, got, want) + } + } +} + +func TestMohistCarryingEverythingDownloadsNothing(t *testing.T) { + r := newRepo(t, nil) + useRepositories(t, &mohistRepositories, r.URL+"/") + + dir := t.TempDir() + jarPath := filepath.Join(dir, "mohist.jar") + writeJar(t, jarPath, map[string]string{ + "mohist_libraries.txt": "libraries/net/minecraft/1.12.2/minecraft_server.1.12.2.jar|" + md5Hex("vanilla") + "\n", + "META-INF/libraries/net/minecraft/1.12.2/minecraft_server.1.12.2.jar": "vanilla", + "installer.txt": "com/example/x.jar|abc|1\n", + }) + + if err := Mohist(context.Background(), client(), &fakeVersions{}, dir, jarPath); err != nil { + t.Fatal(err) + } + if r.requests() != 0 { + t.Errorf("%d requests for a self-contained jar", r.requests()) + } +} + +func TestBanner(t *testing.T) { + r := newRepo(t, map[string]string{ + "/server.jar": "vanilla", + "/mohist/org/yaml/snakeyaml/2.2/snakeyaml-2.2.jar": "yaml", + "/sponge/net/fabricmc/intermediary/1.21.1/intermediary-1.21.1.jar": "intermediary", + "/fabric/org/ow2/asm/asm/9.8/asm-9.8.jar": "asm", + "/fabric/net/fabricmc/sponge-mixin/0.15.5/sponge-mixin-0.15.5.jar": "mixin", + "/fabric/net/fabricmc/sponge-mixin/0.15.5/sponge-mixin-0.15.5.jar.sha1": sha1Hex("mixin"), + }) + + loaderJar := jarBytes(t, map[string]string{ + "fabric-installer.json": `{"libraries": { + "common": [{"name": "org.ow2.asm:asm:9.8", "url": "` + r.URL + `/fabric/", "sha1": "` + sha1Hex("asm") + `"}], + "server": [{"name": "net.fabricmc:sponge-mixin:0.15.5", "url": "` + r.URL + `/fabric/"}], + "client": [{"name": "org.lwjgl:lwjgl:3.3.3", "url": "` + r.URL + `/fabric/"}] + }}`, + }) + r.mu.Lock() + r.files["/sponge/net/fabricmc/fabric-loader/0.16.14/fabric-loader-0.16.14.jar"] = loaderJar + r.mu.Unlock() + loaderSum := sha1Hex(loaderJar) + + useRepositories(t, &bannerRepositories, r.URL+"/mohist/", r.URL+"/sponge/") + + installJSON := `{ + "installer": {"minecraft": "1.21.1", "fabricLoader": "0.16.14", "fabricLoaderHash": "` + loaderSum + `"}, + "libraries": {"org.yaml:snakeyaml:2.2": "` + sha1Hex("yaml") + `"}, + "fabricExtra": {"net.fabricmc:intermediary:1.21.1": "` + sha1Hex("intermediary") + `"} + }` + + dir := t.TempDir() + jarPath := filepath.Join(dir, "banner-1.21.1-170.jar") + writeJar(t, jarPath, map[string]string{"installer.json": installJSON, "fabric.mod.json": "{}"}) + + versions := &fakeVersions{url: r.URL + "/server.jar", sha1: sha1Hex("vanilla")} + if err := Mohist(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatalf("Banner: %v", err) + } + + for rel, want := range map[string]string{ + "libraries/org/yaml/snakeyaml/2.2/snakeyaml-2.2.jar": "yaml", + "libraries/net/fabricmc/intermediary/1.21.1/intermediary-1.21.1.jar": "intermediary", + "libraries/org/ow2/asm/asm/9.8/asm-9.8.jar": "asm", + "libraries/net/fabricmc/sponge-mixin/0.15.5/sponge-mixin-0.15.5.jar": "mixin", + "libraries/net/minecraft/server/1.21.1/server-1.21.1.jar": "vanilla", + } { + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(rel))); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } + if _, err := os.Stat(filepath.Join(dir, "libraries", "org", "lwjgl")); !os.IsNotExist(err) { + t.Error("client libraries are not needed") + } + + before := r.requests() + if err := Mohist(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatal(err) + } + if r.requests() != before { + t.Errorf("a prepared Banner cost %d requests", r.requests()-before) + } +} + +func TestBannerCarryingItsServer(t *testing.T) { + r := newRepo(t, map[string]string{}) + useRepositories(t, &bannerRepositories, r.URL+"/") + + loaderJar := jarBytes(t, map[string]string{"fabric-installer.json": `{"libraries": {}}`}) + r.files["/net/fabricmc/fabric-loader/0.16.14/fabric-loader-0.16.14.jar"] = loaderJar + + dir := t.TempDir() + jarPath := filepath.Join(dir, "banner.jar") + writeJar(t, jarPath, map[string]string{ + "installer.json": `{"installer": {"minecraft": "1.20.1", "fabricLoader": "0.16.14", "fabricLoaderHash": "` + + sha1Hex(loaderJar) + `"}, "libraries": {}}`, + "fabric.mod.json": "{}", + "META-INF/jars/server-1.20.1.jar": "banner's server", + }) + + versions := &fakeVersions{} + if err := Mohist(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatal(err) + } + if versions.calls != 0 { + t.Error("the vanilla server was looked up although Banner carries its own") + } + if _, err := os.Stat(filepath.Join(dir, "libraries", "net", "minecraft")); !os.IsNotExist(err) { + t.Error("Banner extracts its server itself") + } +} diff --git a/internal/preseed/mojmaps.go b/internal/preseed/mojmaps.go new file mode 100644 index 0000000..b9b2c74 --- /dev/null +++ b/internal/preseed/mojmaps.go @@ -0,0 +1,335 @@ +package preseed + +import ( + "bufio" + "bytes" + "crypto/sha1" + "encoding/hex" + "fmt" + "io" + "maps" + "regexp" + "slices" + "sort" + "strconv" + "strings" + "unicode/utf16" +) + +// SanitizeMappings converts Mojang's ProGuard mappings into the TSRG file +// that DOWNLOAD_MOJMAPS --sanitize of Forge's installertools writes, and +// returns it when its SHA-1 is wantSHA1. It follows SrgUtils (IMappingFile.load, +// then write as TSRG) byte for byte; SrgUtils releases order members +// differently, so every known ordering is tried. +func SanitizeMappings(r io.Reader, wantSHA1 string) ([]byte, bool, error) { + m, err := parseMappings(r) + if err != nil { + return nil, false, err + } + + for _, order := range []memberOrder{srgUtilsLegacyOrder, srgUtilsOrder} { + out := m.tsrg(order) + if sum := sha1.Sum(out); strings.EqualFold(hex.EncodeToString(sum[:]), wantSHA1) { + return out, true, nil + } + } + + return nil, false, nil +} + +func parseMappings(r io.Reader) (*pgMappings, error) { + m := &pgMappings{classes: make(map[string]*pgClass)} + + scanner := bufio.NewScanner(r) + scanner.Buffer(make([]byte, 0, 64<<10), 16<<20) + scanner.Split(scanJavaLines) + + var cls *pgClass + for scanner.Scan() { + line := stripMappingComment(scanner.Text()) + if line == "" { + continue + } + + var err error + if cls, err = m.parse(cls, strings.ReplaceAll(line, ".", "/")); err != nil { + return nil, err + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("failed to read the mappings: %w", err) + } + + return m, nil +} + +type pgClass struct { + original, mapped string + fields map[string]pgMember + methods map[string]pgMember +} + +// pgMember is a field or method; seq is the order of its first appearance, +// which a later duplicate keeps, as in a Java HashMap +type pgMember struct { + original, desc, mapped string + seq int +} + +type pgMappings struct { + classes map[string]*pgClass +} + +func (m *pgMappings) parse(cls *pgClass, line string) (*pgClass, error) { + switch { + case !strings.HasPrefix(line, " ") && strings.HasSuffix(line, ":"): + parts := strings.Split(line, " -> ") + if len(parts) < 2 { + return nil, fmt.Errorf("malformed mappings line %q", line) + } + cls = &pgClass{ + original: parts[0], + mapped: strings.TrimSuffix(parts[1], ":"), + fields: make(map[string]pgMember), + methods: make(map[string]pgMember), + } + m.classes[cls.original] = cls + return cls, nil + + case cls == nil: + return nil, fmt.Errorf("mappings line %q precedes any class", line) + + case strings.Contains(line, "(") && strings.Contains(line, ")"): + method, err := parseMethod(strings.TrimSpace(line)) + if err != nil { + return nil, err + } + addMember(cls.methods, method.original+method.desc, method) + return cls, nil + + default: + parts := strings.Split(strings.TrimSpace(line), " ") + if len(parts) < 4 { + return nil, fmt.Errorf("malformed mappings line %q", line) + } + addMember(cls.fields, parts[1], pgMember{original: parts[1], desc: typeDescriptor(parts[0]), mapped: parts[3]}) + return cls, nil + } +} + +func addMember(members map[string]pgMember, key string, member pgMember) { + member.seq = len(members) + if old, ok := members[key]; ok { + member.seq = old.seq + } + members[key] = member +} + +// parseMethod reads "[start:end:]ret name(args)[:a:b] -> obf" +func parseMethod(line string) (pgMember, error) { + if i := strings.IndexByte(line, ':'); i != -1 { + j := strings.IndexByte(line[i+1:], ':') + if j == -1 { + return pgMember{}, fmt.Errorf("malformed mappings line %q", line) + } + for _, n := range []string{line[:i], line[i+1 : i+1+j]} { + if _, err := strconv.Atoi(n); err != nil { + return pgMember{}, fmt.Errorf("malformed mappings line %q", line) + } + } + line = line[i+1+j+1:] + } + + _, obf, ok := strings.Cut(line, " -> ") + space := strings.IndexByte(line, ' ') + open, closing := strings.IndexByte(line, '('), strings.IndexByte(line, ')') + if !ok || space == -1 || open < space || closing < open { + return pgMember{}, fmt.Errorf("malformed mappings line %q", line) + } + obf, _, _ = strings.Cut(obf, " -> ") + + var desc strings.Builder + desc.WriteByte('(') + for arg := range strings.SplitSeq(line[open+1:closing], ",") { + if arg == "" { + break + } + desc.WriteString(typeDescriptor(arg)) + } + desc.WriteByte(')') + desc.WriteString(typeDescriptor(line[:space])) + + return pgMember{original: line[space+1 : open], desc: desc.String(), mapped: obf}, nil +} + +func typeDescriptor(t string) string { + if elem, ok := strings.CutSuffix(t, "[]"); ok { + return "[" + typeDescriptor(elem) + } + + switch t { + case "int": + return "I" + case "void": + return "V" + case "boolean": + return "Z" + case "byte": + return "B" + case "char": + return "C" + case "short": + return "S" + case "double": + return "D" + case "float": + return "F" + case "long": + return "J" + } + + return "L" + t + ";" +} + +var classInDescriptor = regexp.MustCompile(`L([^;]+);`) + +func (m *pgMappings) remapClass(name string) string { + if cls, ok := m.classes[name]; ok { + return cls.mapped + } + if i := strings.LastIndexByte(name, '$'); i != -1 { + return m.remapClass(name[:i]) + "$" + name[i+1:] + } + return name +} + +func (m *pgMappings) remapDescriptor(desc string) string { + return classInDescriptor.ReplaceAllStringFunc(desc, func(match string) string { + return "L" + m.remapClass(match[1:len(match)-1]) + ";" + }) +} + +// memberOrder sorts the fields and the methods of a class in place +type memberOrder func(m *pgMappings, fields, methods []pgMember) + +// srgUtilsLegacyOrder is SrgUtils before 2026: members sorted by name alone, +// overloads left in the iteration order of the HashMap that holds them +func srgUtilsLegacyOrder(_ *pgMappings, fields, methods []pgMember) { + sort.SliceStable(fields, func(i, j int) bool { return fields[i].original < fields[j].original }) + + sort.Slice(methods, func(i, j int) bool { return methods[i].seq < methods[j].seq }) + buckets := javaHashMapCapacity(len(methods)) - 1 + bucket := func(method pgMember) int32 { return javaHashSpread(method.original+method.desc) & buckets } + sort.SliceStable(methods, func(i, j int) bool { return bucket(methods[i]) < bucket(methods[j]) }) + + sort.SliceStable(methods, func(i, j int) bool { return methods[i].original < methods[j].original }) +} + +// srgUtilsOrder is SrgUtils since 2026: fields by obfuscated name and type, +// methods by name and descriptor +func srgUtilsOrder(m *pgMappings, fields, methods []pgMember) { + sort.Slice(fields, func(i, j int) bool { + if fields[i].mapped != fields[j].mapped { + return fields[i].mapped < fields[j].mapped + } + return m.remapDescriptor(fields[i].desc) < m.remapDescriptor(fields[j].desc) + }) + + sort.Slice(methods, func(i, j int) bool { + if methods[i].original != methods[j].original { + return methods[i].original < methods[j].original + } + return methods[i].desc < methods[j].desc + }) +} + +func (m *pgMappings) tsrg(order memberOrder) []byte { + classes := make([]*pgClass, 0, len(m.classes)) + for _, cls := range m.classes { + classes = append(classes, cls) + } + sort.Slice(classes, func(i, j int) bool { return classes[i].original < classes[j].original }) + + var out bytes.Buffer + for _, cls := range classes { + fields := slices.Collect(maps.Values(cls.fields)) + methods := slices.Collect(maps.Values(cls.methods)) + order(m, fields, methods) + + out.WriteString(cls.original + " " + cls.mapped + "\n") + for _, field := range fields { + out.WriteString("\t" + field.original + " " + field.mapped + "\n") + } + for _, method := range methods { + out.WriteString("\t" + method.original + " " + method.desc + " " + method.mapped + "\n") + } + } + + return out.Bytes() +} + +// javaHashMapCapacity is the table size of a java.util.HashMap that got n +// entries one by one +func javaHashMapCapacity(n int) int32 { + capacity := int32(16) + for n > int(capacity)*3/4 { + capacity *= 2 + } + return capacity +} + +// javaHashSpread is String.hashCode as HashMap spreads it over the buckets +func javaHashSpread(s string) int32 { + var h int32 + for _, unit := range utf16.Encode([]rune(s)) { + h = 31*h + int32(unit) + } + return h ^ int32(uint32(h)>>16) +} + +// stripMappingComment mirrors SrgUtils' InternalUtils.stripComment, quirks +// included: the character before '#' is dropped and one leading space stays +func stripMappingComment(line string) string { + i := strings.IndexByte(line, '#') + if i == 0 { + return "" + } + if i != -1 { + line = line[:i-1] + } + + end := len(line) + for end > 1 && line[end-1] == ' ' { + end-- + } + return line[:end] +} + +// scanJavaLines splits lines the way BufferedReader.readLine does: on \n, +// \r or \r\n +func scanJavaLines(data []byte, atEOF bool) (advance int, token []byte, err error) { + if atEOF && len(data) == 0 { + return 0, nil, nil + } + + if i := bytes.IndexAny(data, "\r\n"); i != -1 { + if data[i] == '\n' { + return i + 1, data[:i], nil + } + if i+1 < len(data) { + if data[i+1] == '\n' { + return i + 2, data[:i], nil + } + return i + 1, data[:i], nil + } + if atEOF { + return i + 1, data[:i], nil + } + return 0, nil, nil + } + + if atEOF { + return len(data), data, nil + } + return 0, nil, nil +} diff --git a/internal/preseed/mojmaps_test.go b/internal/preseed/mojmaps_test.go new file mode 100644 index 0000000..ddd0500 --- /dev/null +++ b/internal/preseed/mojmaps_test.go @@ -0,0 +1,123 @@ +package preseed + +import ( + "bufio" + "reflect" + "strings" + "testing" +) + +// The mappings use both line endings and carry the comments Mojang puts in +const sampleMappings = "# (c) 2020 Microsoft Corporation.\r\n" + + "net.example.Thing -> a:\r\n" + + "# {\"fileName\":\"Thing.java\",\"id\":\"sourceFile\"}\n" + + " java.lang.String name -> b\n" + + " int[] counts -> a\n" + + " net.example.Thing$Inner inner -> c # trailing comment\n" + + " 1:2:java.lang.Object get(int) -> a\n" + + " 3:4:java.lang.Object get(long) -> a\n" + + " 5:5:java.lang.Object get() -> b\n" + + " 6:6:java.lang.Object get(java.lang.String):10:11 -> c\n" + + " 7:7:void () -> \n" + + " 8:8:java.lang.Object get(int) -> a\n" + + "\n" + + "net.example.Thing$Inner -> a$a:\n" + + " boolean flag -> a\n" + + "net.example.Another -> b:" + +// Overloads follow the buckets of a 16-slot java.util.HashMap: get() is in +// bucket 1, get(String) in 4, get(long) in 6, get(int) in 7 +const sampleLegacyTSRG = "net/example/Another b\n" + + "net/example/Thing a\n" + + "\tcounts a\n" + + "\tinner c\n" + + "\tname b\n" + + "\t ()V \n" + + "\tget ()Ljava/lang/Object; b\n" + + "\tget (Ljava/lang/String;)Ljava/lang/Object; c\n" + + "\tget (J)Ljava/lang/Object; a\n" + + "\tget (I)Ljava/lang/Object; a\n" + + "net/example/Thing$Inner a$a\n" + + "\tflag a\n" + +const sampleTSRG = "net/example/Another b\n" + + "net/example/Thing a\n" + + "\tcounts a\n" + + "\tname b\n" + + "\tinner c\n" + + "\t ()V \n" + + "\tget ()Ljava/lang/Object; b\n" + + "\tget (I)Ljava/lang/Object; a\n" + + "\tget (J)Ljava/lang/Object; a\n" + + "\tget (Ljava/lang/String;)Ljava/lang/Object; c\n" + + "net/example/Thing$Inner a$a\n" + + "\tflag a\n" + +func TestSanitizeMappings(t *testing.T) { + for name, want := range map[string]string{"legacy": sampleLegacyTSRG, "current": sampleTSRG} { + got, ok, err := SanitizeMappings(strings.NewReader(sampleMappings), sha1Hex(want)) + if err != nil { + t.Fatal(err) + } + if !ok || string(got) != want { + t.Errorf("%s ordering: matched %v, got\n%s", name, ok, got) + } + } + + if _, ok, _ := SanitizeMappings(strings.NewReader(sampleMappings), sha1Hex("other")); ok { + t.Error("a checksum no ordering meets was matched") + } +} + +func TestSanitizeMappingsRejectsGarbage(t *testing.T) { + for _, input := range []string{ + " int orphan -> a\n", + "a.B -> c:\n int x\n", + "a.B -> c:\n x:1:void f() -> a\n", + } { + if _, _, err := SanitizeMappings(strings.NewReader(input), "x"); err == nil { + t.Errorf("%q was accepted", input) + } + } +} + +func TestJavaHash(t *testing.T) { + if got := javaHashSpread("hello"); got != 99162322^(99162322>>16) { + t.Errorf("hello spreads to %d", got) + } + if javaHashSpread("Aa") != javaHashSpread("BB") { + t.Error("String.hashCode collisions must collide") + } + for n, want := range map[int]int32{0: 16, 12: 16, 13: 32, 24: 32, 25: 64} { + if got := javaHashMapCapacity(n); got != want { + t.Errorf("capacity for %d entries = %d, want %d", n, got, want) + } + } +} + +func TestStripMappingComment(t *testing.T) { + for in, want := range map[string]string{ + "# header": "", + "a -> b: # x": "a -> b:", + " int x -> a # y": " int x -> a", + " # indented": " ", + "plain": "plain", + } { + if got := stripMappingComment(in); got != want { + t.Errorf("stripMappingComment(%q) = %q, want %q", in, got, want) + } + } +} + +func TestScanJavaLines(t *testing.T) { + scanner := bufio.NewScanner(strings.NewReader("a\r\nb\rc\n\nd\r")) + scanner.Split(scanJavaLines) + + var got []string + for scanner.Scan() { + got = append(got, scanner.Text()) + } + if want := []string{"a", "b", "c", "", "d"}; !reflect.DeepEqual(got, want) { + t.Errorf("lines = %q, want %q", got, want) + } +} diff --git a/internal/preseed/paperclip.go b/internal/preseed/paperclip.go new file mode 100644 index 0000000..a6b7008 --- /dev/null +++ b/internal/preseed/paperclip.go @@ -0,0 +1,317 @@ +package preseed + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/goccy/go-yaml" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +// quantumLeaperRepositories are the repositories QuantumLeaper (Leaf's +// launcher) downloads libraries from; Maven Central replaces the Google mirror +// it uses by default +var quantumLeaperRepositories = []string{ + "https://repo1.maven.org/maven2/", + "https://repo.papermc.io/repository/maven-public/", + "https://maven.leafmc.one/snapshots/", +} + +// quantumLeaperDefaultMirror is the Maven Central mirror QuantumLeaper uses +// unless config/leaf-loader.yml names others +const quantumLeaperDefaultMirror = "https://maven-central.storage-download.googleapis.com/maven2/" + +// quantumLeaperConfig is QuantumLeaper's config/leaf-loader.yml with its +// defaults. Without the file the first start writes it and exits. +const quantumLeaperConfig = `maven-central-mirrors: +- ` + quantumLeaperDefaultMirror + ` +download-retries: 2 +auto-update: + enabled: false + channel: stable +` + +// Paperclip prepares a server started through Paperclip or QuantumLeaper +// (Paper, Folia, Purpur, Pufferfish, Leaf): the vanilla server the launcher +// patches and, for QuantumLeaper, the libraries it would download. A jar of +// another kind is left alone. +func Paperclip(ctx context.Context, client *utils.HTTPClient, dir, jarPath string) error { + jar, err := OpenJar(jarPath) + if err != nil { + return err + } + defer jar.Close() + + switch { + case jar.Has("META-INF/download-context"): + return paperclip3(ctx, client, dir, jar) + case jar.Has("patch.properties"): + data, _, err := jar.Read("patch.properties") + if err != nil { + return err + } + return legacyPaperclip(ctx, client, dir, parseProperties(data)) + case jar.Has("patch.json"): + data, _, err := jar.Read("patch.json") + if err != nil { + return err + } + var patch map[string]string + if err := json.Unmarshal(data, &patch); err != nil { + return fmt.Errorf("failed to parse patch.json: %w", err) + } + return legacyPaperclip(ctx, client, dir, patch) + } + + return nil +} + +// paperclip3 handles Paperclip 3 and QuantumLeaper: download-context names the +// vanilla jar, libraries.list the libraries, which are bundled in the jar, +// taken from the vanilla jar, patched or (QuantumLeaper only) downloaded +func paperclip3(ctx context.Context, client *utils.HTTPClient, dir string, jar *Jar) error { + data, _, err := jar.Read("META-INF/download-context") + if err != nil { + return err + } + + fields := strings.Split(strings.TrimSpace(string(data)), "\t") + if len(fields) != 3 { + return fmt.Errorf("malformed download-context: %q", data) + } + + vanilla := File{Path: "cache/" + fields[2], URLs: mojangURLs(fields[1]), SHA256: fields[0]} + if err := Ensure(ctx, client, dir, "the vanilla server", []File{vanilla}); err != nil { + return err + } + + repositories := quantumLeaperRepositories + quantumLeaper := jar.Has("META-INF/leaper.properties") + if quantumLeaper { + if err := writeIfMissing(filepath.Join(dir, "config", "leaf-loader.yml"), quantumLeaperConfig); err != nil { + return err + } + if repositories, err = quantumLeaperMirrors(dir); err != nil { + return err + } + } + + libraries, err := downloadedLibraries(jar, filepath.Join(dir, filepath.FromSlash(vanilla.Path)), repositories) + if err != nil { + return err + } + if len(libraries) == 0 { + return nil + } + if !quantumLeaper { + return fmt.Errorf("%d libraries are neither bundled nor in the vanilla server, the first is %s", + len(libraries), libraries[0].Path) + } + + return Ensure(ctx, client, dir, "libraries", libraries) +} + +// quantumLeaperMirrors puts the Maven Central mirrors of +// config/leaf-loader.yml before the built-in repositories. The default mirror +// is left out: Maven Central serves the same files, and GameAP's mirror stands +// in for it. +func quantumLeaperMirrors(dir string) ([]string, error) { + data, err := os.ReadFile(filepath.Join(dir, "config", "leaf-loader.yml")) + if errors.Is(err, os.ErrNotExist) { + return quantumLeaperRepositories, nil + } + if err != nil { + return nil, fmt.Errorf("failed to read config/leaf-loader.yml: %w", err) + } + + var config struct { + Mirrors []string `yaml:"maven-central-mirrors"` + } + if err := yaml.Unmarshal(data, &config); err != nil { + return nil, fmt.Errorf("failed to parse config/leaf-loader.yml: %w", err) + } + + repositories := make([]string, 0, len(config.Mirrors)+len(quantumLeaperRepositories)) + for _, mirror := range config.Mirrors { + mirror = strings.TrimRight(strings.TrimSpace(mirror), "/") + "/" + if mirror == "/" || mirror == quantumLeaperDefaultMirror || slices.Contains(repositories, mirror) { + continue + } + repositories = append(repositories, mirror) + } + + return append(repositories, quantumLeaperRepositories...), nil +} + +// downloadedLibraries lists the libraries.list entries that the launcher +// finds neither in its own jar nor in the vanilla jar and does not patch, with +// their URLs in repositories +func downloadedLibraries(jar *Jar, vanillaPath string, repositories []string) ([]File, error) { + data, ok, err := jar.Read("META-INF/libraries.list") + if err != nil || !ok { + return nil, err + } + + patched := make(map[string]bool) + if patches, _, err := jar.Read("META-INF/patches.list"); err != nil { + return nil, err + } else { + for _, line := range lines(patches) { + if fields := strings.Split(line, "\t"); len(fields) == 7 && fields[0] == "libraries" { + patched[fields[6]] = true + } + } + } + + vanilla, err := OpenJar(vanillaPath) + if err != nil { + return nil, err + } + defer vanilla.Close() + + var files []File + for _, line := range lines(data) { + fields := strings.Split(line, "\t") + if len(fields) != 3 { + return nil, fmt.Errorf("malformed libraries.list entry: %q", line) + } + + path := fields[2] + bundled := "META-INF/libraries/" + path + if patched[path] || jar.Has(bundled) || vanilla.Has(bundled) { + continue + } + + urls := repositoryURLs(repositories, path) + if snapshot := snapshotPath(path); snapshot != "" { + urls = append(urls, repositoryURLs(repositories, snapshot)...) + } + + files = append(files, File{Path: "libraries/" + path, URLs: urls, SHA256: fields[0]}) + } + + return files, nil +} + +// snapshotPath maps a timestamped snapshot, .../1.0-20250101.120000-3/x.jar, +// onto its -SNAPSHOT directory, as QuantumLeaper does +func snapshotPath(path string) string { + fileStart := strings.LastIndexByte(path, '/') + if fileStart <= 0 { + return "" + } + dirStart := strings.LastIndexByte(path[:fileStart], '/') + if dirStart < 0 { + return "" + } + + version := path[dirStart+1 : fileStart] + buildDash := strings.LastIndexByte(version, '-') + if buildDash < 0 { + return "" + } + stampDash := strings.LastIndexByte(version[:buildDash], '-') + if stampDash <= 0 || buildDash-stampDash != 16 || version[stampDash+9] != '.' { + return "" + } + + return path[:dirStart+1] + version[:stampDash] + "-SNAPSHOT" + path[fileStart:] +} + +// legacyPaperclip handles Paperclip 1 and 2 (Paper up to 1.17.1, Purpur up +// to 1.16.5), which cache the vanilla jar as cache/mojang_.jar and +// skip it once cache/patched_.jar is in place +func legacyPaperclip(ctx context.Context, client *utils.HTTPClient, dir string, patch map[string]string) error { + version, source, original := patch["version"], patch["sourceUrl"], patch["originalHash"] + if version == "" || source == "" || original == "" { + return fmt.Errorf("incomplete Paperclip patch data: %v", patch) + } + + if patched := patch["patchedHash"]; patched != "" { + dest, err := Resolve(dir, "cache/patched_"+version+".jar") + if err != nil { + return err + } + if present(dest, File{SHA256: patched}) { + return nil + } + } + + vanilla := File{Path: "cache/mojang_" + version + ".jar", URLs: mojangURLs(source), SHA256: strings.ToLower(original)} + + return Ensure(ctx, client, dir, "the vanilla server", []File{vanilla}) +} + +// mojangURLs adds piston-data for files addressed by their SHA-1 on Mojang's +// older launcher.mojang.com +func mojangURLs(raw string) []string { + u, err := url.Parse(raw) + if err != nil || u.Host != "launcher.mojang.com" || !strings.HasPrefix(u.Path, "/v1/objects/") { + return []string{raw} + } + + alternative := *u + alternative.Host = "piston-data.mojang.com" + + return []string{raw, alternative.String()} +} + +// parseProperties reads the subset of Java properties Paperclip writes +func parseProperties(data []byte) map[string]string { + result := make(map[string]string) + + for _, line := range lines(data) { + if line[0] == '#' || line[0] == '!' { + continue + } + + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + + result[strings.TrimSpace(unescapeProperty(key))] = strings.TrimSpace(unescapeProperty(value)) + } + + return result +} + +func unescapeProperty(s string) string { + var b strings.Builder + escaped := false + + for _, r := range s { + if escaped || r != '\\' { + b.WriteRune(r) + escaped = false + continue + } + escaped = true + } + + return b.String() +} + +func writeIfMissing(path, content string) error { + if _, err := os.Stat(path); err == nil { + return nil + } + + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return fmt.Errorf("failed to create %s: %w", filepath.Dir(path), err) + } + + if err := os.WriteFile(path, []byte(content), 0644); err != nil { + return fmt.Errorf("failed to write %s: %w", path, err) + } + + return nil +} diff --git a/internal/preseed/preseed_test.go b/internal/preseed/preseed_test.go new file mode 100644 index 0000000..c69f4a6 --- /dev/null +++ b/internal/preseed/preseed_test.go @@ -0,0 +1,469 @@ +package preseed + +import ( + "archive/zip" + "context" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "sync" + "testing" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +func TestMain(m *testing.M) { + utils.SetMirrors(nil) + os.Exit(m.Run()) +} + +func sha256Hex(s string) string { + sum := sha256.Sum256([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +func sha1Hex(s string) string { + sum := sha1.Sum([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +func md5Hex(s string) string { + sum := md5.Sum([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +// repo is a fake download server that counts requests per path +type repo struct { + *httptest.Server + mu sync.Mutex + files map[string]string + hits map[string]int +} + +func newRepo(t *testing.T, files map[string]string) *repo { + t.Helper() + + r := &repo{files: files, hits: map[string]int{}} + r.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + r.mu.Lock() + r.hits[req.URL.Path]++ + body, ok := r.files[req.URL.Path] + r.mu.Unlock() + + if !ok { + http.NotFound(w, req) + return + } + fmt.Fprint(w, body) + })) + t.Cleanup(r.Close) + + return r +} + +func (r *repo) requests() int { + r.mu.Lock() + defer r.mu.Unlock() + + n := 0 + for _, hits := range r.hits { + n += hits + } + return n +} + +func writeJar(t *testing.T, path string, entries map[string]string) { + t.Helper() + + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + t.Fatal(err) + } + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + + zw := zip.NewWriter(f) + names := make([]string, 0, len(entries)) + for name := range entries { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + w, err := zw.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write([]byte(entries[name])); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } +} + +func readFile(t *testing.T, path string) string { + t.Helper() + + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(data) +} + +func client() *utils.HTTPClient { + return utils.NewHTTPClient(false) +} + +func TestMavenPath(t *testing.T) { + for coord, want := range map[string]string{ + "net.fabricmc:fabric-loader:0.16.10": "net/fabricmc/fabric-loader/0.16.10/fabric-loader-0.16.10.jar", + "net.minecraftforge:forge:1.20.1-47.4.10:server": "net/minecraftforge/forge/1.20.1-47.4.10/forge-1.20.1-47.4.10-server.jar", + "de.oceanlabs.mcp:mcp_config:1.20.1-20230612@zip": "de/oceanlabs/mcp/mcp_config/1.20.1-20230612/mcp_config-1.20.1-20230612.zip", + "net.minecraft:server:1.20.1:mappings@txt": "net/minecraft/server/1.20.1/server-1.20.1-mappings.txt", + } { + if got, err := MavenPath(coord); err != nil || got != want { + t.Errorf("MavenPath(%q) = %q, %v; want %q", coord, got, err, want) + } + } + + for _, coord := range []string{"a:b", "a:b:c:d:e", "a:..:1", "a:b/c:1", "a:b:1@", ":b:1"} { + if got, err := MavenPath(coord); err == nil { + t.Errorf("MavenPath(%q) = %q, want an error", coord, got) + } + } +} + +func TestResolveStaysInsideTheDirectory(t *testing.T) { + dir := t.TempDir() + + if got, err := Resolve(dir, "libraries/a/b.jar"); err != nil || got != filepath.Join(dir, "libraries", "a", "b.jar") { + t.Errorf("Resolve = %q, %v", got, err) + } + + for _, rel := range []string{"", ".", "..", "../x", "a/../../x", "/etc/passwd", `a\b`, "C:/x"} { + if got, err := Resolve(dir, rel); err == nil { + t.Errorf("Resolve(%q) = %q, want an error", rel, got) + } + } +} + +func TestSnapshotPath(t *testing.T) { + for path, want := range map[string]string{ + "org/x/lib/1.0-20250101.120000-3/lib-1.0-20250101.120000-3.jar": "org/x/lib/1.0-SNAPSHOT/lib-1.0-20250101.120000-3.jar", + "org/x/lib/1.0/lib-1.0.jar": "", + "org/x/lib/1.0-SNAPSHOT/lib-1.0-SNAPSHOT.jar": "", + "lib.jar": "", + } { + if got := snapshotPath(path); got != want { + t.Errorf("snapshotPath(%q) = %q, want %q", path, got, want) + } + } +} + +func TestEnsure(t *testing.T) { + r := newRepo(t, map[string]string{ + "/good/a.jar": "a", + "/bad/b.jar": "tampered", + "/good/b.jar": "b", + "/side/c.jar": "c", + "/side/c.jar.sha1": sha1Hex("c") + " c.jar\n", + "/plain/d.jar": "d", + }) + dir := t.TempDir() + + files := []File{ + {Path: "libs/a.jar", URLs: []string{r.URL + "/good/a.jar"}, SHA256: sha256Hex("a")}, + {Path: "libs/b.jar", URLs: []string{r.URL + "/missing/b.jar", r.URL + "/bad/b.jar", r.URL + "/good/b.jar"}, MD5: md5Hex("b")}, + {Path: "libs/c.jar", URLs: []string{r.URL + "/side/c.jar"}, Sidecar: "sha1"}, + {Path: "libs/d.jar", URLs: []string{r.URL + "/plain/d.jar"}, Sidecar: "sha1"}, + } + + if err := Ensure(context.Background(), client(), dir, "test", files); err != nil { + t.Fatalf("Ensure: %v", err) + } + + for name, want := range map[string]string{"a.jar": "a", "b.jar": "b", "c.jar": "c", "d.jar": "d"} { + if got := readFile(t, filepath.Join(dir, "libs", name)); got != want { + t.Errorf("%s = %q, want %q", name, got, want) + } + } + if matches, _ := filepath.Glob(filepath.Join(dir, "libs", "*.part*")); len(matches) != 0 { + t.Errorf("leftovers: %v", matches) + } + + before := r.requests() + if err := Ensure(context.Background(), client(), dir, "test", files); err != nil { + t.Fatalf("second Ensure: %v", err) + } + if r.requests() != before { + t.Errorf("a prepared directory cost %d more requests", r.requests()-before) + } + + // A file that went bad is fetched again + os.WriteFile(filepath.Join(dir, "libs", "a.jar"), []byte("rotten"), 0644) + if err := Ensure(context.Background(), client(), dir, "test", files); err != nil { + t.Fatal(err) + } + if got := readFile(t, filepath.Join(dir, "libs", "a.jar")); got != "a" { + t.Errorf("a.jar = %q after repair", got) + } +} + +func TestEnsureReportsCancellation(t *testing.T) { + r := newRepo(t, map[string]string{"/x.jar": "x"}) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + files := make([]File, 0, 20) + for i := range 20 { + files = append(files, File{Path: fmt.Sprintf("libs/%d.jar", i), URLs: []string{r.URL + "/x.jar"}, SHA1: sha1Hex("x")}) + } + + if err := Ensure(ctx, client(), t.TempDir(), "test", files); !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want the cancellation", err) + } +} + +func TestEnsureFailsOnMismatch(t *testing.T) { + r := newRepo(t, map[string]string{"/x.jar": "tampered"}) + dir := t.TempDir() + + err := Ensure(context.Background(), client(), dir, "test", []File{ + {Path: "x.jar", URLs: []string{r.URL + "/x.jar"}, SHA1: sha1Hex("x")}, + }) + if err == nil || !strings.Contains(err.Error(), "x.jar") { + t.Fatalf("err = %v, want a mismatch naming x.jar", err) + } + if _, statErr := os.Stat(filepath.Join(dir, "x.jar")); !os.IsNotExist(statErr) { + t.Error("a file that failed its checksum must not be left in place") + } +} + +func TestPaperclip3(t *testing.T) { + vanilla := map[string]string{"META-INF/libraries/com/mojang/brigadier/1.0/brigadier-1.0.jar": "brigadier"} + vanillaPath := filepath.Join(t.TempDir(), "vanilla.jar") + writeJar(t, vanillaPath, vanilla) + vanillaBytes := readFile(t, vanillaPath) + + r := newRepo(t, map[string]string{ + "/v1/objects/abc/server.jar": vanillaBytes, + "/maven2/org/x/needed/1.0/needed-1.0.jar": "needed", + "/maven2/org/x/needed2/1.0/needed2-1.0.jar": "needed2", + "/maven2/org/x/bundled/1.0/bundled-1.0.jar": "never", + "/maven2/com/mojang/brigadier/1.0/brigadier-1.0.jar": "never", + }) + saved := quantumLeaperRepositories + quantumLeaperRepositories = []string{r.URL + "/maven2/"} + t.Cleanup(func() { quantumLeaperRepositories = saved }) + + libraries := strings.Join([]string{ + sha256Hex("needed") + "\torg.x:needed:1.0\torg/x/needed/1.0/needed-1.0.jar", + sha256Hex("bundled") + "\torg.x:bundled:1.0\torg/x/bundled/1.0/bundled-1.0.jar", + sha256Hex("brigadier") + "\tcom.mojang:brigadier:1.0\tcom/mojang/brigadier/1.0/brigadier-1.0.jar", + sha256Hex("patched") + "\torg.x:patched:2.0\torg/x/patched/2.0/patched-2.0.jar", + sha256Hex("needed2") + "\torg.x:needed2:1.0\torg/x/needed2/1.0/needed2-1.0.jar", + }, "\n") + downloadContext := sha256Hex(vanillaBytes) + "\t" + r.URL + "/v1/objects/abc/server.jar\tmojang_26.3.jar" + + t.Run("QuantumLeaper", func(t *testing.T) { + dir := t.TempDir() + jarPath := filepath.Join(dir, "leaf-26.3-22.jar") + writeJar(t, jarPath, map[string]string{ + "META-INF/download-context": downloadContext, + "META-INF/leaper.properties": "update-api-type=BIBLIOTHEK\n", + "META-INF/libraries.list": libraries, + "META-INF/libraries/org/x/bundled/1.0/bundled-1.0.jar": "bundled", + "META-INF/patches.list": "libraries\ta\tb\tc\torg/x/patched/1.0/patched-1.0.jar\torg/x/patched/2.0/patched-1.0.jar.patch\torg/x/patched/2.0/patched-2.0.jar", + }) + + if err := Paperclip(context.Background(), client(), dir, jarPath); err != nil { + t.Fatalf("Paperclip: %v", err) + } + + if got := readFile(t, filepath.Join(dir, "cache", "mojang_26.3.jar")); got != vanillaBytes { + t.Error("the vanilla jar was not cached") + } + for path, want := range map[string]string{ + "libraries/org/x/needed/1.0/needed-1.0.jar": "needed", + "libraries/org/x/needed2/1.0/needed2-1.0.jar": "needed2", + } { + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(path))); got != want { + t.Errorf("%s = %q", path, got) + } + } + for _, path := range []string{"libraries/org/x/bundled", "libraries/com/mojang", "libraries/org/x/patched"} { + if _, err := os.Stat(filepath.Join(dir, filepath.FromSlash(path))); !os.IsNotExist(err) { + t.Errorf("%s must be left to the launcher", path) + } + } + if got := readFile(t, filepath.Join(dir, "config", "leaf-loader.yml")); got != quantumLeaperConfig { + t.Errorf("leaf-loader.yml = %q", got) + } + + before := r.requests() + if err := Paperclip(context.Background(), client(), dir, jarPath); err != nil { + t.Fatal(err) + } + if r.requests() != before { + t.Error("a prepared server must cost no requests") + } + }) + + t.Run("QuantumLeaper with its own Maven Central mirror", func(t *testing.T) { + dir := t.TempDir() + r.mu.Lock() + r.files["/custom/org/x/needed/1.0/needed-1.0.jar"] = "needed" + builtIn := r.hits["/maven2/org/x/needed/1.0/needed-1.0.jar"] + r.mu.Unlock() + config := "maven-central-mirrors:\n- " + r.URL + "/custom\n- " + quantumLeaperDefaultMirror + "\ndownload-retries: 2\n" + if err := writeIfMissing(filepath.Join(dir, "config", "leaf-loader.yml"), config); err != nil { + t.Fatal(err) + } + jarPath := filepath.Join(dir, "leaf-26.3-22.jar") + writeJar(t, jarPath, map[string]string{ + "META-INF/download-context": downloadContext, + "META-INF/leaper.properties": "update-api-type=BIBLIOTHEK\n", + "META-INF/libraries.list": libraries, + "META-INF/libraries/org/x/bundled/1.0/bundled-1.0.jar": "bundled", + "META-INF/patches.list": "libraries\ta\tb\tc\torg/x/patched/1.0/patched-1.0.jar\torg/x/patched/2.0/patched-1.0.jar.patch\torg/x/patched/2.0/patched-2.0.jar", + }) + + if err := Paperclip(context.Background(), client(), dir, jarPath); err != nil { + t.Fatalf("Paperclip: %v", err) + } + + if got := readFile(t, filepath.Join(dir, "libraries", "org", "x", "needed", "1.0", "needed-1.0.jar")); got != "needed" { + t.Errorf("needed-1.0.jar = %q", got) + } + if r.hits["/custom/org/x/needed/1.0/needed-1.0.jar"] != 1 || r.hits["/maven2/org/x/needed/1.0/needed-1.0.jar"] != builtIn { + t.Error("the configured mirror must be asked before the built-in repositories") + } + if got := readFile(t, filepath.Join(dir, "libraries", "org", "x", "needed2", "1.0", "needed2-1.0.jar")); got != "needed2" { + t.Errorf("needed2-1.0.jar = %q, the built-in repositories must stay the fallback", got) + } + + repositories, err := quantumLeaperMirrors(dir) + if err != nil { + t.Fatal(err) + } + want := append([]string{r.URL + "/custom/"}, quantumLeaperRepositories...) + if !reflect.DeepEqual(repositories, want) { + t.Errorf("repositories = %v, want %v", repositories, want) + } + }) + + t.Run("Paperclip 3 bundles every library", func(t *testing.T) { + dir := t.TempDir() + jarPath := filepath.Join(dir, "paper.jar") + writeJar(t, jarPath, map[string]string{ + "META-INF/download-context": downloadContext, + "META-INF/libraries.list": sha256Hex("brigadier") + + "\tcom.mojang:brigadier:1.0\tcom/mojang/brigadier/1.0/brigadier-1.0.jar", + }) + + if err := Paperclip(context.Background(), client(), dir, jarPath); err != nil { + t.Fatalf("Paperclip: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "config", "leaf-loader.yml")); !os.IsNotExist(err) { + t.Error("leaf-loader.yml is QuantumLeaper's only") + } + }) +} + +func TestLegacyPaperclip(t *testing.T) { + r := newRepo(t, map[string]string{"/v1/objects/5faf/server.jar": "vanilla-1.8.8"}) + + properties := fmt.Sprintf("#comment\nversion=1.8.8\npatchedHash=%s\nsourceUrl=%s\noriginalHash=%s\npatch=paperMC.patch\n", + strings.ToUpper(sha256Hex("patched")), + strings.ReplaceAll(r.URL, ":", `\:`)+"/v1/objects/5faf/server.jar", + strings.ToUpper(sha256Hex("vanilla-1.8.8"))) + + dir := t.TempDir() + jarPath := filepath.Join(dir, "paper-1.8.8-445.jar") + writeJar(t, jarPath, map[string]string{"patch.properties": properties}) + + if err := Paperclip(context.Background(), client(), dir, jarPath); err != nil { + t.Fatalf("Paperclip: %v", err) + } + if got := readFile(t, filepath.Join(dir, "cache", "mojang_1.8.8.jar")); got != "vanilla-1.8.8" { + t.Errorf("mojang_1.8.8.jar = %q", got) + } + + // Once patched the vanilla jar is not needed any more + other := t.TempDir() + os.MkdirAll(filepath.Join(other, "cache"), 0755) + os.WriteFile(filepath.Join(other, "cache", "patched_1.8.8.jar"), []byte("patched"), 0644) + before := r.requests() + if err := Paperclip(context.Background(), client(), other, jarPath); err != nil { + t.Fatal(err) + } + if r.requests() != before { + t.Error("a patched server must not fetch the vanilla jar") + } +} + +func TestPaperclipIgnoresOtherJars(t *testing.T) { + dir := t.TempDir() + jarPath := filepath.Join(dir, "velocity.jar") + writeJar(t, jarPath, map[string]string{"META-INF/MANIFEST.MF": "Manifest-Version: 1.0\n"}) + + if err := Paperclip(context.Background(), client(), dir, jarPath); err != nil { + t.Errorf("Paperclip: %v", err) + } +} + +func TestMojangURLs(t *testing.T) { + got := mojangURLs("https://launcher.mojang.com/v1/objects/5faf/server.jar") + want := []string{ + "https://launcher.mojang.com/v1/objects/5faf/server.jar", + "https://piston-data.mojang.com/v1/objects/5faf/server.jar", + } + if !reflect.DeepEqual(got, want) { + t.Errorf("mojangURLs = %v", got) + } +} + +func TestProxyModules(t *testing.T) { + r := newRepo(t, map[string]string{"/cmd_alert.jar": "alert", "/cmd_kick.jar": "kick"}) + modules := []File{ + {Path: "modules/cmd_alert.jar", URLs: []string{r.URL + "/cmd_alert.jar"}, SHA256: sha256Hex("alert")}, + {Path: "modules/cmd_kick.jar", URLs: []string{r.URL + "/cmd_kick.jar"}, SHA256: sha256Hex("kick")}, + } + + t.Run("a new proxy gets every module", func(t *testing.T) { + dir := t.TempDir() + if err := ProxyModules(context.Background(), client(), dir, modules); err != nil { + t.Fatal(err) + } + for _, name := range []string{"cmd_alert.jar", "cmd_kick.jar"} { + if _, err := os.Stat(filepath.Join(dir, "modules", name)); err != nil { + t.Errorf("%s: %v", name, err) + } + } + }) + + t.Run("modules.yml decides", func(t *testing.T) { + dir := t.TempDir() + os.WriteFile(filepath.Join(dir, "modules.yml"), []byte("modules:\n- jenkins://cmd_alert\nversion: 3\n"), 0644) + if err := ProxyModules(context.Background(), client(), dir, modules); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "modules", "cmd_kick.jar")); !os.IsNotExist(err) { + t.Error("a module removed from modules.yml must stay removed") + } + }) +} diff --git a/internal/preseed/sponge.go b/internal/preseed/sponge.go new file mode 100644 index 0000000..0751306 --- /dev/null +++ b/internal/preseed/sponge.go @@ -0,0 +1,250 @@ +package preseed + +import ( + "context" + "encoding/json" + "fmt" + "path" + "slices" + "strings" + + "github.com/gameap/minecraft-runner/internal/utils" +) + +// spongeRepositories serve the libraries SpongeVanilla lists. Its installer +// finds them through the search of Sponge's Nexus, which hands out +// maven-public download links. +var spongeRepositories = []string{ + "https://repo.spongepowered.org/repository/maven-public/", + "https://repo1.maven.org/maven2/", +} + +type spongeLibraries struct { + Dependencies map[string][]struct { + Group string `json:"group"` + Module string `json:"module"` + Version string `json:"version"` + SHA512 string `json:"sha512"` + MD5 string `json:"md5"` + } `json:"dependencies"` +} + +// Sponge prepares what the installer of the SpongeVanilla jar at jarPath +// downloads: its libraries, the vanilla server and, up to Minecraft 1.21.11, +// Mojang's mappings. +// +// The installer reads Mojang's version manifest on every start and, when it +// cannot, carries on with the server it finds: from 26.1 the one extracted +// here, in 1.16.5 the one it remapped on an earlier start. 1.18.2 to 1.21.11 +// pick the server before remapping, which does not start, so they need Mojang. +func Sponge(ctx context.Context, client *utils.HTTPClient, versions Versions, dir, jarPath string) error { + jar, err := OpenJar(jarPath) + if err != nil { + return err + } + defer jar.Close() + + files, err := spongeLibraryFiles(jar) + if err != nil || files == nil { + return err + } + + game, err := spongeMinecraftVersion(jar) + if err != nil { + return err + } + + minecraftDir := "libraries/net/minecraft/" + game + "/" + bundled := !versionAtMost(game, "1.17.1") + server := minecraftDir + "minecraft_server.jar" + if bundled { + server = minecraftDir + "minecraft_server-bundle.jar" + } + mappings := "" + if versionAtMost(game, "1.21.11") { + mappings = "libraries/net/minecraft/mappings/" + game + "/server.txt" + } + + vanilla, err := spongeVanillaFiles(ctx, versions, dir, game, server, mappings, bundled) + if err != nil { + return err + } + + if err := Ensure(ctx, client, dir, "SpongeVanilla", append(files, vanilla...)); err != nil { + return err + } + + if !bundled { + return nil + } + + return extractBundledServer(dir, server, minecraftDir+"minecraft_server.jar") +} + +// spongeLibraryFiles lists the libraries of sponge-libraries.json (SHA-512) +// or of the older libraries.json (MD5); nil when the jar has neither +func spongeLibraryFiles(jar *Jar) ([]File, error) { + name := "sponge-libraries.json" + data, ok, err := jar.Read(name) + if err == nil && !ok { + name = "libraries.json" + data, ok, err = jar.Read(name) + } + if err != nil || !ok { + return nil, err + } + + var libraries spongeLibraries + if err := json.Unmarshal(data, &libraries); err != nil { + return nil, fmt.Errorf("failed to parse %s: %w", name, err) + } + + files := []File{} + seen := make(map[string]bool) + for _, collection := range slices.Sorted(func(yield func(string) bool) { + for key := range libraries.Dependencies { + if !yield(key) { + return + } + } + }) { + for _, dep := range libraries.Dependencies[collection] { + if dep.Group == "" || dep.Module == "" || dep.Version == "" || dep.SHA512 == "" && dep.MD5 == "" { + return nil, fmt.Errorf("incomplete library %s:%s:%s in %s", dep.Group, dep.Module, dep.Version, name) + } + + libPath := path.Join(strings.ReplaceAll(dep.Group, ".", "/"), dep.Module, dep.Version, + dep.Module+"-"+dep.Version+".jar") + if seen[libPath] { + continue + } + seen[libPath] = true + + files = append(files, File{ + Path: "libraries/" + libPath, + URLs: repositoryURLs(spongeRepositories, libPath), + SHA512: dep.SHA512, + MD5: dep.MD5, + }) + } + } + + return files, nil +} + +// spongeMinecraftVersion reads the Minecraft version from the build's +// Implementation-Version, such as 1.21.4-14.0.1-RC2773 +func spongeMinecraftVersion(jar *Jar) (string, error) { + manifest, err := jar.Manifest() + if err != nil { + return "", err + } + + game, _, _ := strings.Cut(manifest["Implementation-Version"], "-") + if game == "" || strings.ContainsAny(game, `/\`) || game == "." || game == ".." { + return "", fmt.Errorf("the SpongeVanilla jar names no Minecraft version") + } + + return game, nil +} + +// spongeVanillaFiles describes the vanilla server and the mappings that are +// not in place yet. What is in place the installer checks itself, so Mojang +// is not asked on every start. A bundle, which is extracted next, also has to +// open: one that was cut short is fetched again. +func spongeVanillaFiles( + ctx context.Context, versions Versions, dir, game, server, mappings string, bundled bool, +) ([]File, error) { + var missing []string + for _, rel := range []string{server, mappings} { + if rel == "" { + continue + } + ready, err := pathExists(dir, rel) + if err != nil { + return nil, err + } + if ready && bundled && rel == server { + ready = opensAsJar(dir, rel) + } + if !ready { + missing = append(missing, rel) + } + } + if len(missing) == 0 { + return nil, nil + } + + detail, err := versions.GetVersion(ctx, game) + if err != nil { + return nil, fmt.Errorf("failed to look up Minecraft %s: %w", game, err) + } + + var files []File + for _, rel := range missing { + download := detail.Downloads.Server + if rel == mappings { + download = detail.Downloads.ServerMappings + } + if download.URL == "" { + return nil, fmt.Errorf("minecraft %s has no download for %s", game, path.Base(rel)) + } + + files = append(files, File{Path: rel, URLs: mojangURLs(download.URL), SHA1: download.SHA1}) + } + + return files, nil +} + +func opensAsJar(dir, rel string) bool { + path, err := Resolve(dir, rel) + if err != nil { + return false + } + + jar, err := OpenJar(path) + if err != nil { + return false + } + + return jar.Close() == nil +} + +// extractBundledServer extracts the server from Mojang's bundle the way the +// installer does, to where it looks when Mojang is out of reach +func extractBundledServer(dir, bundle, server string) error { + bundlePath, err := Resolve(dir, bundle) + if err != nil { + return err + } + serverPath, err := Resolve(dir, server) + if err != nil { + return err + } + + jar, err := OpenJar(bundlePath) + if err != nil { + return err + } + defer jar.Close() + + data, ok, err := jar.Read("META-INF/versions.list") + if err != nil { + return err + } + if !ok { + return nil + } + + entries := lines(data) + if len(entries) == 0 { + return fmt.Errorf("%s lists no server", bundle) + } + + fields := strings.Split(entries[0], "\t") + if len(fields) != 3 { + return fmt.Errorf("malformed line %q in the versions.list of %s", entries[0], bundle) + } + + return jar.Extract("META-INF/versions/"+fields[2], serverPath, fields[0]) +} diff --git a/internal/preseed/sponge_test.go b/internal/preseed/sponge_test.go new file mode 100644 index 0000000..e7f1b0d --- /dev/null +++ b/internal/preseed/sponge_test.go @@ -0,0 +1,192 @@ +package preseed + +import ( + "context" + "crypto/sha512" + "encoding/hex" + "os" + "path/filepath" + "testing" +) + +func sha512Hex(s string) string { + sum := sha512.Sum512([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +func spongeJar(t *testing.T, dir, version, librariesFile, libraries string) string { + t.Helper() + + jarPath := filepath.Join(dir, "spongevanilla-"+version+"-universal.jar") + writeJar(t, jarPath, map[string]string{ + "META-INF/MANIFEST.MF": "Manifest-Version: 1.0\r\nImplementation-Version: " + version + "\r\n\r\n", + librariesFile: libraries, + }) + + return jarPath +} + +func TestSpongeBundledWithMappings(t *testing.T) { + bundle := jarBytes(t, map[string]string{ + "META-INF/versions.list": sha256Hex("server") + "\t1.21.4\t1.21.4/server-1.21.4.jar\n", + "META-INF/versions/1.21.4/server-1.21.4.jar": "server", + }) + r := newRepo(t, map[string]string{ + "/mojang/bundle.jar": bundle, + "/mojang/mappings.txt": "mappings", + "/public/com/lmax/disruptor/3.4.4/disruptor-3.4.4.jar": "disruptor", + "/central/org/ow2/asm/asm-tree/9.7/asm-tree-9.7.jar": "asm-tree", + "/public/org/ow2/asm/asm-tree/9.7/asm-tree-9.7.jar": "corrupt", + "/public/com/google/guava/guava/33.0.0-jre/guava-33.0.0-jre.jar": "guava", + }) + useRepositories(t, &spongeRepositories, r.URL+"/public/", r.URL+"/central/") + + dir := t.TempDir() + jarPath := spongeJar(t, dir, "1.21.4-14.0.1-RC2773", "sponge-libraries.json", `{"dependencies": { + "bootstrap": [ + {"group": "com.lmax", "module": "disruptor", "version": "3.4.4", "sha512": "`+sha512Hex("disruptor")+`"}, + {"group": "org.ow2.asm", "module": "asm-tree", "version": "9.7", "sha512": "`+sha512Hex("asm-tree")+`"} + ], + "main": [ + {"group": "com.google.guava", "module": "guava", "version": "33.0.0-jre", "sha512": "`+sha512Hex("guava")+`"}, + {"group": "com.lmax", "module": "disruptor", "version": "3.4.4", "sha512": "`+sha512Hex("disruptor")+`"} + ] + }}`) + + versions := &fakeVersions{ + url: r.URL + "/mojang/bundle.jar", sha1: sha1Hex(bundle), + mappingsURL: r.URL + "/mojang/mappings.txt", mappingsSHA1: sha1Hex("mappings"), + } + if err := Sponge(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatalf("Sponge: %v", err) + } + + for rel, want := range map[string]string{ + "libraries/com/lmax/disruptor/3.4.4/disruptor-3.4.4.jar": "disruptor", + "libraries/org/ow2/asm/asm-tree/9.7/asm-tree-9.7.jar": "asm-tree", + "libraries/com/google/guava/guava/33.0.0-jre/guava-33.0.0-jre.jar": "guava", + "libraries/net/minecraft/1.21.4/minecraft_server-bundle.jar": bundle, + "libraries/net/minecraft/1.21.4/minecraft_server.jar": "server", + "libraries/net/minecraft/mappings/1.21.4/server.txt": "mappings", + } { + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(rel))); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } + + before := r.requests() + if err := Sponge(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatal(err) + } + if r.requests() != before || versions.calls != 1 { + t.Errorf("a prepared server cost %d requests and %d lookups", r.requests()-before, versions.calls-1) + } +} + +func TestSpongeWithoutMappings(t *testing.T) { + bundle := jarBytes(t, map[string]string{ + "META-INF/versions.list": sha256Hex("server") + "\t26.1.2\t26.1.2/server-26.1.2.jar\n", + "META-INF/versions/26.1.2/server-26.1.2.jar": "server", + }) + r := newRepo(t, map[string]string{"/mojang/bundle.jar": bundle}) + + dir := t.TempDir() + jarPath := spongeJar(t, dir, "26.1.2-19.0.0-RC2789", "sponge-libraries.json", `{"dependencies": {}}`) + + versions := &fakeVersions{url: r.URL + "/mojang/bundle.jar", sha1: sha1Hex(bundle)} + if err := Sponge(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatalf("Sponge: %v", err) + } + + if got := readFile(t, filepath.Join(dir, "libraries", "net", "minecraft", "26.1.2", "minecraft_server.jar")); got != "server" { + t.Errorf("extracted server = %q", got) + } + if _, err := os.Stat(filepath.Join(dir, "libraries", "net", "minecraft", "mappings")); !os.IsNotExist(err) { + t.Error("mappings were prepared for an unobfuscated version") + } +} + +func TestSpongeRepairsATruncatedBundle(t *testing.T) { + bundle := jarBytes(t, map[string]string{ + "META-INF/versions.list": sha256Hex("server") + "\t26.1.2\t26.1.2/server-26.1.2.jar\n", + "META-INF/versions/26.1.2/server-26.1.2.jar": "server", + }) + r := newRepo(t, map[string]string{"/mojang/bundle.jar": bundle}) + + dir := t.TempDir() + jarPath := spongeJar(t, dir, "26.1.2-19.0.0-RC2789", "sponge-libraries.json", `{"dependencies": {}}`) + versions := &fakeVersions{url: r.URL + "/mojang/bundle.jar", sha1: sha1Hex(bundle)} + if err := Sponge(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatalf("Sponge: %v", err) + } + + bundlePath := filepath.Join(dir, "libraries", "net", "minecraft", "26.1.2", "minecraft_server-bundle.jar") + if err := os.WriteFile(bundlePath, []byte(bundle[:len(bundle)/2]), 0644); err != nil { + t.Fatal(err) + } + + if err := Sponge(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatalf("Sponge with a truncated bundle: %v", err) + } + if readFile(t, bundlePath) != bundle { + t.Error("the truncated bundle was not fetched again") + } + if versions.calls != 2 { + t.Errorf("%d lookups, want 2", versions.calls) + } +} + +func TestSpongeUnbundledWithMD5(t *testing.T) { + r := newRepo(t, map[string]string{ + "/mojang/server.jar": "vanilla", + "/mojang/mappings.txt": "mappings", + "/public/cpw/mods/modlauncher/8.1.3/modlauncher-8.1.3.jar": "modlauncher", + }) + useRepositories(t, &spongeRepositories, r.URL+"/public/") + + dir := t.TempDir() + jarPath := spongeJar(t, dir, "1.16.5-8.2.1-RC2708", "libraries.json", `{"dependencies": {"bootstrap": [ + {"group": "cpw.mods", "module": "modlauncher", "version": "8.1.3", "md5": "`+md5Hex("modlauncher")+`"} + ]}}`) + + versions := &fakeVersions{ + url: r.URL + "/mojang/server.jar", sha1: sha1Hex("vanilla"), + mappingsURL: r.URL + "/mojang/mappings.txt", mappingsSHA1: sha1Hex("mappings"), + } + if err := Sponge(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatalf("Sponge: %v", err) + } + + for rel, want := range map[string]string{ + "libraries/cpw/mods/modlauncher/8.1.3/modlauncher-8.1.3.jar": "modlauncher", + "libraries/net/minecraft/1.16.5/minecraft_server.jar": "vanilla", + "libraries/net/minecraft/mappings/1.16.5/server.txt": "mappings", + } { + if got := readFile(t, filepath.Join(dir, filepath.FromSlash(rel))); got != want { + t.Errorf("%s = %q, want %q", rel, got, want) + } + } +} + +func TestSpongeWithoutInstaller(t *testing.T) { + dir := t.TempDir() + jarPath := filepath.Join(dir, "spongevanilla-1.12.2-7.4.7.jar") + writeJar(t, jarPath, map[string]string{"META-INF/MANIFEST.MF": "Manifest-Version: 1.0\r\n\r\n"}) + + versions := &fakeVersions{} + if err := Sponge(context.Background(), client(), versions, dir, jarPath); err != nil { + t.Fatal(err) + } + if versions.calls != 0 { + t.Error("a jar without an installer needs nothing") + } +} + +func TestSpongeRejectsBadVersion(t *testing.T) { + dir := t.TempDir() + jarPath := spongeJar(t, dir, "../x", "sponge-libraries.json", `{"dependencies": {}}`) + + if err := Sponge(context.Background(), client(), &fakeVersions{}, dir, jarPath); err == nil { + t.Fatal("a version naming a path was accepted") + } +} diff --git a/internal/preseed/vanilla.go b/internal/preseed/vanilla.go new file mode 100644 index 0000000..8e6a89d --- /dev/null +++ b/internal/preseed/vanilla.go @@ -0,0 +1,28 @@ +package preseed + +import ( + "context" + "fmt" + + "github.com/gameap/minecraft-runner/pkg/api/mojang" +) + +// Versions looks up the files of a Minecraft version +type Versions interface { + GetVersion(ctx context.Context, id string) (*mojang.VersionDetail, error) +} + +// VanillaServer describes the vanilla server of version, to be stored at path +func VanillaServer(ctx context.Context, versions Versions, version, path string) (File, error) { + detail, err := versions.GetVersion(ctx, version) + if err != nil { + return File{}, fmt.Errorf("failed to look up the vanilla server %s: %w", version, err) + } + + server := detail.Downloads.Server + if server.URL == "" { + return File{}, fmt.Errorf("minecraft %s has no server download", version) + } + + return File{Path: path, URLs: mojangURLs(server.URL), SHA1: server.SHA1}, nil +} diff --git a/internal/providers/bungeecord.go b/internal/providers/bungeecord.go index beb2068..c8abe83 100644 --- a/internal/providers/bungeecord.go +++ b/internal/providers/bungeecord.go @@ -3,7 +3,11 @@ package providers import ( "context" "fmt" + "path" "strconv" + "strings" + + "github.com/gameap/minecraft-runner/internal/preseed" "github.com/gameap/minecraft-runner/pkg/api/jenkins" ) @@ -103,9 +107,46 @@ func (p *BungeecordProvider) GetServerJar(ctx context.Context, _, modVersion str URL: downloadURL, Filename: fmt.Sprintf("BungeeCord-%d.jar", build.Number), RequiresInstall: false, + Extras: p.modules(ctx, build), }, nil } +// modules lists the modules a build published separately. Builds up to #2107 +// download them on start from Jenkins; later builds bundle them. +func (p *BungeecordProvider) modules(ctx context.Context, build *jenkins.BuildInfo) []preseed.File { + var modules []preseed.File + for _, artifact := range build.Artifacts { + if !strings.HasPrefix(artifact.RelativePath, "module/") || !strings.HasSuffix(artifact.RelativePath, ".jar") { + continue + } + modules = append(modules, preseed.File{ + Path: "modules/" + path.Base(artifact.RelativePath), + URLs: []string{p.client.GetArtifactURL(build.Number, artifact.RelativePath)}, + }) + } + + if len(modules) == 0 { + return nil + } + + // Without checksums a module from an older build would pass for current + fingerprints, err := p.client.GetFingerprints(ctx, build.Number) + if err != nil { + fmt.Printf("[WARNING] Could not get the checksums of the BungeeCord modules: %v\n", err) + return modules + } + for i := range modules { + modules[i].MD5 = fingerprints["net.md-5:"+path.Base(modules[i].Path)] + } + + return modules +} + +// Prepare puts in place the modules the proxy would download on start +func (p *BungeecordProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return prepareModules(ctx, dir, jar) +} + // PostDownload handles post-download steps (none for Bungeecord) func (p *BungeecordProvider) PostDownload(_ context.Context, _ string, _ *ServerJar, _ string) error { return nil diff --git a/internal/providers/cauldron.go b/internal/providers/cauldron.go index 89f6e92..27b42d7 100644 --- a/internal/providers/cauldron.go +++ b/internal/providers/cauldron.go @@ -79,6 +79,11 @@ func (p *CauldronProvider) PostDownload(ctx context.Context, dir string, jar *Se return p.mohist.PostDownload(ctx, dir, jar, javaPath) } +// Prepare puts in place the libraries the server would download on start +func (p *CauldronProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return p.mohist.Prepare(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *CauldronProvider) GetRecommendedJavaVersion(_ context.Context, _ string) int { return 8 diff --git a/internal/providers/craftbukkit.go b/internal/providers/craftbukkit.go index dba5723..ff4a6b1 100644 --- a/internal/providers/craftbukkit.go +++ b/internal/providers/craftbukkit.go @@ -60,6 +60,11 @@ func (p *CraftBukkitProvider) PostDownload(_ context.Context, _ string, _ *Serve return nil } +// Prepare prepares the Paper server served instead +func (p *CraftBukkitProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return p.paper.Prepare(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *CraftBukkitProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/providers/fabric.go b/internal/providers/fabric.go index 019e081..6321bd3 100644 --- a/internal/providers/fabric.go +++ b/internal/providers/fabric.go @@ -4,7 +4,10 @@ import ( "context" "fmt" + "github.com/gameap/minecraft-runner/internal/preseed" + "github.com/gameap/minecraft-runner/internal/utils" "github.com/gameap/minecraft-runner/pkg/api/fabric" + "github.com/gameap/minecraft-runner/pkg/api/mojang" ) // FabricProvider provides Fabric server downloads @@ -130,6 +133,12 @@ func (p *FabricProvider) PostDownload(_ context.Context, _ string, _ *ServerJar, return nil } +// Prepare puts in place what the Fabric server launcher would install on its +// first start: the vanilla server, the libraries and the launch jar +func (p *FabricProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return preseed.Fabric(ctx, utils.NewHTTPClient(false), mojang.NewClient(), dir, jar.Version, jar.ModVersion) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *FabricProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/providers/fill.go b/internal/providers/fill.go index 1baf9b4..3bc86e6 100644 --- a/internal/providers/fill.go +++ b/internal/providers/fill.go @@ -3,7 +3,11 @@ package providers import ( "context" "fmt" + "sort" "strconv" + "strings" + + "github.com/gameap/minecraft-runner/internal/preseed" "github.com/gameap/minecraft-runner/pkg/api/paper" ) @@ -170,14 +174,47 @@ func (p *FillProvider) GetServerJar(ctx context.Context, version, modVersion str URL: download.URL, SHA256: download.Checksums.SHA256, Filename: download.Name, + Extras: fillModules(build), }, nil } +// fillModules lists the modules Waterfall would download on start +func fillModules(build *paper.BuildInfo) []preseed.File { + var modules []preseed.File + for key, download := range build.Downloads { + name, ok := strings.CutPrefix(key, "module:") + if !ok { + continue + } + modules = append(modules, preseed.File{ + Path: "modules/" + name + ".jar", + URLs: []string{download.URL}, + SHA256: download.Checksums.SHA256, + }) + } + + sort.Slice(modules, func(i, j int) bool { return modules[i].Path < modules[j].Path }) + + return modules +} + // PostDownload handles post-download steps (none for Fill projects) func (p *FillProvider) PostDownload(_ context.Context, _ string, _ *ServerJar, _ string) error { return nil } +// Prepare puts in place what the server downloads on start: the vanilla +// server Paper and Folia patch, the modules of Waterfall +func (p *FillProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + switch p.project { + case "paper", "folia": + return preparePaperclip(ctx, dir, jar) + case "waterfall": + return prepareModules(ctx, dir, jar) + } + return nil +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *FillProvider) GetRecommendedJavaVersion(ctx context.Context, version string) int { return p.javaVersion(ctx, version) diff --git a/internal/providers/forge.go b/internal/providers/forge.go index 42b7579..be21b4c 100644 --- a/internal/providers/forge.go +++ b/internal/providers/forge.go @@ -166,7 +166,7 @@ func (p *ForgeProvider) ResolveLaunch(dir string, jar *ServerJar) *LaunchTarget func (p *ForgeProvider) PostDownload(ctx context.Context, dir string, jar *ServerJar, javaPath string) error { fmt.Println("Running Forge installer...") - if err := runInstaller(ctx, javaPath, dir, jar.Filename, "--installServer"); err != nil { + if err := installForge(ctx, javaPath, dir, jar.Filename, "Forge"); err != nil { return installerError("Forge", err) } diff --git a/internal/providers/leaf.go b/internal/providers/leaf.go index a487a3b..9e98006 100644 --- a/internal/providers/leaf.go +++ b/internal/providers/leaf.go @@ -159,6 +159,11 @@ func (p *LeafProvider) PostDownload(_ context.Context, _ string, _ *ServerJar, _ return nil } +// Prepare puts the vanilla server the launcher patches in place +func (p *LeafProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return preparePaperclip(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *LeafProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/providers/mohist.go b/internal/providers/mohist.go index ca8aa9b..5d55cdd 100644 --- a/internal/providers/mohist.go +++ b/internal/providers/mohist.go @@ -168,6 +168,11 @@ func (p *MohistProvider) PostDownload(_ context.Context, _ string, _ *ServerJar, return nil } +// Prepare puts in place the libraries the server would download on start +func (p *MohistProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return prepareMohist(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *MohistProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/providers/neoforge.go b/internal/providers/neoforge.go index fbdcf28..2f64f7f 100644 --- a/internal/providers/neoforge.go +++ b/internal/providers/neoforge.go @@ -171,7 +171,7 @@ func (p *NeoForgeProvider) ResolveLaunch(dir string, jar *ServerJar) *LaunchTarg func (p *NeoForgeProvider) PostDownload(ctx context.Context, dir string, jar *ServerJar, javaPath string) error { fmt.Println("Running NeoForge installer...") - if err := runInstaller(ctx, javaPath, dir, jar.Filename, "--installServer"); err != nil { + if err := installForge(ctx, javaPath, dir, jar.Filename, "NeoForge"); err != nil { return installerError("NeoForge", err) } diff --git a/internal/providers/prepare.go b/internal/providers/prepare.go new file mode 100644 index 0000000..7f9ea17 --- /dev/null +++ b/internal/providers/prepare.go @@ -0,0 +1,55 @@ +package providers + +import ( + "context" + "fmt" + "path/filepath" + + "github.com/gameap/minecraft-runner/internal/preseed" + "github.com/gameap/minecraft-runner/internal/utils" + "github.com/gameap/minecraft-runner/pkg/api/mojang" +) + +// prepareModules puts the modules of BungeeCord and Waterfall in place +func prepareModules(ctx context.Context, dir string, jar *ServerJar) error { + if len(jar.Extras) == 0 { + return nil + } + return preseed.ProxyModules(ctx, utils.NewHTTPClient(false), dir, jar.Extras) +} + +// preparePaperclip prepares a server started through Paperclip or QuantumLeaper +func preparePaperclip(ctx context.Context, dir string, jar *ServerJar) error { + return preseed.Paperclip(ctx, utils.NewHTTPClient(false), dir, filepath.Join(dir, jar.Filename)) +} + +// prepareMohist prepares a Mohist, Banner or Cauldron server +func prepareMohist(ctx context.Context, dir string, jar *ServerJar) error { + return preseed.Mohist(ctx, utils.NewHTTPClient(false), mojang.NewClient(), dir, filepath.Join(dir, jar.Filename)) +} + +// prepareSponge prepares a SpongeVanilla server +func prepareSponge(ctx context.Context, dir string, jar *ServerJar) error { + return preseed.Sponge(ctx, utils.NewHTTPClient(false), mojang.NewClient(), dir, filepath.Join(dir, jar.Filename)) +} + +// installForge runs a Forge or NeoForge installer. What it would download is +// put in place first, so it runs offline. When that is not possible, or the +// offline run fails, the original installer runs and downloads on its own. +func installForge(ctx context.Context, javaPath, dir, installer, name string) error { + install, err := preseed.ForgeInstaller(ctx, utils.NewHTTPClient(false), mojang.NewClient(), dir, installer, name) + if err != nil { + fmt.Printf("[WARNING] Could not prepare the %s installer, it downloads its files itself: %v\n", name, err) + } + + if install != nil && install.Offline { + err := runInstaller(ctx, javaPath, dir, install.Installer, "--offline", "--installServer") + install.Remove() + if err == nil || ctx.Err() != nil { + return err + } + fmt.Printf("[WARNING] The offline %s install failed (%v), running the installer online\n", name, err) + } + + return runInstaller(ctx, javaPath, dir, installer, "--installServer") +} diff --git a/internal/providers/provider.go b/internal/providers/provider.go index 0d04a09..8b8985b 100644 --- a/internal/providers/provider.go +++ b/internal/providers/provider.go @@ -5,6 +5,8 @@ import ( "fmt" "sort" "time" + + "github.com/gameap/minecraft-runner/internal/preseed" ) // ServerJar contains information about a downloadable server JAR @@ -18,6 +20,10 @@ type ServerJar struct { Filename string // Suggested filename RequiresInstall bool // True if post-download installation is needed (e.g., Forge) ServerArgs []string // Program arguments; empty means the runner default + + // Extras are further files the server downloads on its own, known when + // the JAR is resolved; see Preparer + Extras []preseed.File } // LaunchTarget describes how an installed server is started. @@ -68,6 +74,15 @@ type LaunchResolver interface { ResolveLaunch(dir string, jar *ServerJar) *LaunchTarget } +// Preparer is implemented by providers whose server downloads more files on +// its own: the vanilla server it patches, libraries, modules. Prepare puts +// them into dir beforehand through mcrun's downloads, which check checksums +// and fall back to the mirrors, so the server needs no network. It runs before +// every start and costs no requests once the files are in place. +type Preparer interface { + Prepare(ctx context.Context, dir string, jar *ServerJar) error +} + // ProxyProvider is implemented by proxy servers, which have neither an EULA // nor a server.properties type ProxyProvider interface { diff --git a/internal/providers/pufferfish.go b/internal/providers/pufferfish.go index 5d117d7..f262c9f 100644 --- a/internal/providers/pufferfish.go +++ b/internal/providers/pufferfish.go @@ -261,6 +261,11 @@ func (p *PufferfishProvider) PostDownload(_ context.Context, _ string, _ *Server return nil } +// Prepare puts the vanilla server the launcher patches in place +func (p *PufferfishProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return preparePaperclip(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *PufferfishProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/providers/purpur.go b/internal/providers/purpur.go index a1d9f02..25de974 100644 --- a/internal/providers/purpur.go +++ b/internal/providers/purpur.go @@ -141,6 +141,11 @@ func (p *PurpurProvider) PostDownload(_ context.Context, _ string, _ *ServerJar, return nil } +// Prepare puts the vanilla server the launcher patches in place +func (p *PurpurProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return preparePaperclip(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *PurpurProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/providers/quilt.go b/internal/providers/quilt.go index f231e33..df56d85 100644 --- a/internal/providers/quilt.go +++ b/internal/providers/quilt.go @@ -6,17 +6,15 @@ import ( "os" "path/filepath" + "github.com/gameap/minecraft-runner/internal/preseed" + "github.com/gameap/minecraft-runner/internal/utils" + "github.com/gameap/minecraft-runner/pkg/api/mojang" "github.com/gameap/minecraft-runner/pkg/api/quilt" ) -const ( - // quiltLauncher is the launcher JAR the Quilt installer writes. It carries - // no version, and the vanilla server.jar next to it belongs to whichever - // Minecraft version was installed last. - quiltLauncher = "quilt-server-launch.jar" - - quiltServerJar = "server.jar" -) +// quiltServerJar is the vanilla server the Quilt launcher starts. It belongs +// to whichever Minecraft version was installed last. +const quiltServerJar = "server.jar" // QuiltProvider provides Quilt server downloads type QuiltProvider struct { @@ -95,8 +93,9 @@ func (p *QuiltProvider) GetLatestVersion(ctx context.Context) (*VersionInfo, err return nil, fmt.Errorf("no stable versions available") } -// GetServerJar returns download info for a specific version. The download is -// the Quilt installer; ModVersion is the loader it will install. +// GetServerJar returns what to install for a specific version. mcrun installs +// Quilt itself, so there is nothing to download up front; ModVersion is the +// loader. func (p *QuiltProvider) GetServerJar(ctx context.Context, mcVersion, modVersion string) (*ServerJar, error) { loaderVersion := modVersion if loaderVersion == "" { @@ -107,24 +106,14 @@ func (p *QuiltProvider) GetServerJar(ctx context.Context, mcVersion, modVersion loaderVersion = loader.Version } - installer, err := p.client.GetLatestInstaller(ctx) - if err != nil { - return nil, fmt.Errorf("failed to get installer version: %w", err) - } - - checksum, err := p.client.GetInstallerSHA256(ctx, installer) - if err != nil { - return nil, err - } - - return &ServerJar{ + jar := &ServerJar{ Version: mcVersion, ModVersion: loaderVersion, - URL: installer.URL, - SHA256: checksum, - Filename: fmt.Sprintf("quilt-installer-%s.jar", installer.Version), RequiresInstall: true, - }, nil + } + jar.Filename = quiltVersionedLauncher(jar) + + return jar, nil } // ResolveLaunch finds the launcher of an installed Quilt version @@ -140,31 +129,25 @@ func (p *QuiltProvider) ResolveLaunch(dir string, jar *ServerJar) *LaunchTarget return &LaunchTarget{Jar: launcher} } -// PostDownload runs the Quilt installer and gives the launcher a versioned -// name, which is what lets ResolveLaunch tell the installed version. Launchers -// of other versions are removed: they would start against the server.jar that -// was just replaced. -func (p *QuiltProvider) PostDownload(ctx context.Context, dir string, jar *ServerJar, javaPath string) error { - fmt.Println("Running Quilt installer...") - - err := runInstaller(ctx, javaPath, dir, jar.Filename, - "install", "server", jar.Version, jar.ModVersion, "--install-dir=.", "--download-server") - if err != nil { - return installerError("Quilt", err) - } +// PostDownload installs Quilt the way its installer would, with the +// launcher under a versioned name, which is what lets ResolveLaunch tell the +// installed version. The Quilt installer is not used: it downloads everything +// again on each run and knows nothing of the mirrors. Launchers of other +// versions are removed: they would start against the server.jar that is +// replaced. +func (p *QuiltProvider) PostDownload(ctx context.Context, dir string, jar *ServerJar, _ string) error { + fmt.Println("Installing Quilt...") - stale, _ := filepath.Glob(filepath.Join(dir, "quilt-server-launch-*.jar")) + stale, _ := filepath.Glob(filepath.Join(dir, "quilt-server-launch*.jar")) for _, launcher := range stale { os.Remove(launcher) } - if err := os.Rename(filepath.Join(dir, quiltLauncher), filepath.Join(dir, quiltVersionedLauncher(jar))); err != nil { - return fmt.Errorf("failed to rename the Quilt launcher: %w", err) - } - - removeInstaller(dir, jar.Filename) + // Another Minecraft version needs another vanilla server + os.Remove(filepath.Join(dir, quiltServerJar)) - return nil + return preseed.Quilt(ctx, utils.NewHTTPClient(false), mojang.NewClient(), dir, + jar.Version, jar.ModVersion, quiltVersionedLauncher(jar)) } func quiltVersionedLauncher(jar *ServerJar) string { diff --git a/internal/providers/spigot.go b/internal/providers/spigot.go index 1dfc77b..c23af67 100644 --- a/internal/providers/spigot.go +++ b/internal/providers/spigot.go @@ -60,6 +60,11 @@ func (p *SpigotProvider) PostDownload(_ context.Context, _ string, _ *ServerJar, return nil } +// Prepare prepares the Paper server served instead +func (p *SpigotProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return p.paper.Prepare(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *SpigotProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/providers/sponge.go b/internal/providers/sponge.go index 2b74266..b093428 100644 --- a/internal/providers/sponge.go +++ b/internal/providers/sponge.go @@ -164,6 +164,12 @@ func (p *SpongeVanillaProvider) PostDownload(_ context.Context, _ string, _ *Ser return nil } +// Prepare puts in place the libraries and the vanilla server the installer +// would download on start +func (p *SpongeVanillaProvider) Prepare(ctx context.Context, dir string, jar *ServerJar) error { + return prepareSponge(ctx, dir, jar) +} + // GetRecommendedJavaVersion returns the recommended Java version func (p *SpongeVanillaProvider) GetRecommendedJavaVersion(ctx context.Context, mcVersion string) int { return GetRecommendedJavaVersion(ctx, mcVersion) diff --git a/internal/server/downloader.go b/internal/server/downloader.go index cf0e743..0a5936e 100644 --- a/internal/server/downloader.go +++ b/internal/server/downloader.go @@ -33,13 +33,21 @@ func NewDownloader(registry *providers.Registry) *Downloader { } } -// Download resolves and downloads a server JAR +// Download resolves and downloads a server JAR. A server without a file of its +// own to download, such as Quilt, is installed instead. func (d *Downloader) Download(ctx context.Context, opts DownloadOptions) (*providers.ServerJar, error) { jar, err := d.Resolve(ctx, opts) if err != nil { return nil, err } + if jar.URL == "" { + if err := d.install(ctx, opts, jar); err != nil { + return nil, err + } + return jar, nil + } + if err := d.Fetch(ctx, opts.Directory, jar, opts.Force); err != nil { return nil, err } @@ -47,6 +55,36 @@ func (d *Downloader) Download(ctx context.Context, opts DownloadOptions) (*provi return jar, nil } +// install has the provider build a server that has no file of its own to +// download, unless that version is installed already. Such providers install +// without Java. +func (d *Downloader) install(ctx context.Context, opts DownloadOptions, jar *providers.ServerJar) error { + provider, err := d.registry.Get(opts.Mod) + if err != nil { + return fmt.Errorf("unknown server type '%s': %w", opts.Mod, err) + } + + key := installKey(provider.Name(), jar.Version, jar.ModVersion) + if resolver, ok := provider.(providers.LaunchResolver); ok && !opts.Force && !installUnfinished(opts.Directory, key) { + if target := resolver.ResolveLaunch(opts.Directory, jar); target != nil { + fmt.Printf("Server already installed: %s\n", target.Jar) + return nil + } + } + + if err := os.MkdirAll(opts.Directory, 0755); err != nil { + return fmt.Errorf("failed to create directory: %w", err) + } + if err := startInstall(opts.Directory, key); err != nil { + return err + } + if err := provider.PostDownload(ctx, opts.Directory, jar, ""); err != nil { + return fmt.Errorf("failed to install: %w", err) + } + + return finishInstall(opts.Directory, key) +} + // Resolve asks the provider which file serves the requested version. It is the // only step that needs the provider's API. func (d *Downloader) Resolve(ctx context.Context, opts DownloadOptions) (*providers.ServerJar, error) { @@ -73,8 +111,13 @@ func (d *Downloader) Resolve(ctx context.Context, opts DownloadOptions) (*provid return jar, nil } -// Fetch downloads a resolved JAR into the directory unless a verified copy is already there +// Fetch downloads a resolved JAR into the directory unless a verified copy is +// already there. A server without a URL is installed by its provider alone. func (d *Downloader) Fetch(ctx context.Context, directory string, jar *providers.ServerJar, force bool) error { + if jar.URL == "" { + return nil + } + targetPath := filepath.Join(directory, jar.Filename) if !force && d.IsDownloaded(directory, jar) { diff --git a/internal/server/runner.go b/internal/server/runner.go index 115e747..ae9aa19 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -70,6 +70,7 @@ type installation struct { version string launch providers.LaunchTarget serverArgs []string + jar *providers.ServerJar } // NewRunner creates a new server runner @@ -143,11 +144,19 @@ func (r *Runner) prepare( return nil, nil, ctx.Err() } - inst, err := r.installedFallback(opts, resolveErr) + inst, err := r.installedFallback(provider.Name(), opts, resolveErr) if err != nil { return nil, nil, err } + // What a previous run prepared is most likely still there + if err := r.prepareFiles(ctx, provider, opts.Directory, inst.jar); err != nil { + if ctx.Err() != nil { + return nil, nil, ctx.Err() + } + fmt.Printf("[WARNING] %v\n", err) + } + javaInst, err := r.findJava(ctx, opts, provider, inst.version) if err != nil { return nil, nil, fmt.Errorf("failed to find Java: %w", err) @@ -166,10 +175,15 @@ func (r *Runner) prepare( return nil, nil, err } + if err := r.prepareFiles(ctx, provider, opts.Directory, jar); err != nil { + return nil, nil, err + } + inst := &installation{ version: jar.Version, launch: *launch, serverArgs: jar.ServerArgs, + jar: jar, } r.recordInstall(opts, jar, inst) @@ -177,12 +191,17 @@ func (r *Runner) prepare( return inst, javaInst, nil } -// install downloads and installs the server unless that exact version is already in place +// install downloads and installs the server unless that exact version is +// already in place. What an installer that did not finish left behind does +// not count as installed. func (r *Runner) install( ctx context.Context, provider providers.Provider, jar *providers.ServerJar, javaPath, directory string, ) (*providers.LaunchTarget, error) { - if target := r.resolveLaunch(provider, directory, jar); target != nil { - return target, nil + key := installKey(provider.Name(), jar.Version, jar.ModVersion) + if !installUnfinished(directory, key) { + if target := r.resolveLaunch(provider, directory, jar); target != nil { + return target, nil + } } if err := r.downloader.Fetch(ctx, directory, jar, false); err != nil { @@ -190,10 +209,16 @@ func (r *Runner) install( } if jar.RequiresInstall { + if err := startInstall(directory, key); err != nil { + return nil, err + } if err := provider.PostDownload(ctx, directory, jar, javaPath); err != nil { return nil, fmt.Errorf("post-download failed: %w", err) } } + if err := finishInstall(directory, key); err != nil { + return nil, err + } target := r.resolveLaunch(provider, directory, jar) if target == nil { @@ -204,6 +229,22 @@ func (r *Runner) install( return target, nil } +// prepareFiles puts in place what the server would download on start +func (r *Runner) prepareFiles( + ctx context.Context, provider providers.Provider, directory string, jar *providers.ServerJar, +) error { + preparer, ok := provider.(providers.Preparer) + if !ok || jar == nil { + return nil + } + + if err := preparer.Prepare(ctx, directory, jar); err != nil { + return fmt.Errorf("failed to prepare the %s server: %w", provider.Name(), err) + } + + return nil +} + func (r *Runner) resolveLaunch( provider providers.Provider, directory string, jar *providers.ServerJar, ) *providers.LaunchTarget { @@ -218,10 +259,11 @@ func (r *Runner) resolveLaunch( return &providers.LaunchTarget{Jar: jar.Filename} } -// installedFallback starts the server a previous run installed when the -// provider's API cannot tell which file serves the request. Servers that are -// already on disk must not go down together with a download API. -func (r *Runner) installedFallback(opts RunOptions, cause error) (*installation, error) { +// installedFallback starts the server a previous run installed with the +// provider named provider when its API cannot tell which file serves the +// request. Servers that are already on disk must not go down together with a +// download API. +func (r *Runner) installedFallback(provider string, opts RunOptions, cause error) (*installation, error) { failure := fmt.Errorf("failed to resolve server: %w", cause) state, err := LoadState(opts.Directory) @@ -232,6 +274,9 @@ func (r *Runner) installedFallback(opts RunOptions, cause error) (*installation, if !state.Matches(opts.Mod, opts.Version, opts.ModVersion) || !launchFilesExist(opts.Directory, state.Launch) { return nil, failure } + if installUnfinished(opts.Directory, installKey(provider, state.Version, state.ModVersion)) { + return nil, fmt.Errorf("%w; the last install did not finish", failure) + } fmt.Printf("[WARNING] Could not resolve the %s server to run: %v\n", opts.Mod, cause) fmt.Printf(" Starting the installed %s %s instead\n\n", state.Mod, state.Version) @@ -240,6 +285,7 @@ func (r *Runner) installedFallback(opts RunOptions, cause error) (*installation, version: state.Version, launch: state.Launch, serverArgs: state.ServerArgs, + jar: &providers.ServerJar{Version: state.Version, ModVersion: state.ModVersion, Filename: state.File}, }, nil } diff --git a/internal/server/runner_test.go b/internal/server/runner_test.go index fd38ebd..766f213 100644 --- a/internal/server/runner_test.go +++ b/internal/server/runner_test.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "reflect" + "runtime" "testing" "github.com/gameap/minecraft-runner/internal/config" @@ -21,6 +22,7 @@ type fakeProvider struct { resolveErr error launch *providers.LaunchTarget installs []string + installErr error installCalls int } @@ -61,7 +63,7 @@ func (p *fakeProvider) PostDownload(_ context.Context, dir string, _ *providers. return err } } - return nil + return p.installErr } func (p *fakeProvider) GetRecommendedJavaVersion(context.Context, string) int { return 21 } @@ -287,6 +289,78 @@ func TestInstall(t *testing.T) { } }) + t.Run("a failed installer run is repeated", func(t *testing.T) { + dir := t.TempDir() + argFile := "libraries/net/minecraftforge/forge/1.20.1-47.4.10/unix_args.txt" + writeFile(t, dir, "forge-installer.jar") + + provider := &fakeInstallerProvider{fakeProvider{ + name: "forge", + jar: &providers.ServerJar{ + Version: "1.20.1", ModVersion: "47.4.10", Filename: "forge-installer.jar", RequiresInstall: true, + }, + launch: &providers.LaunchTarget{ArgFiles: []string{argFile}}, + installs: []string{argFile}, + installErr: errors.New("processor failed"), + }} + runner := newTestRunner(provider) + + if _, err := runner.install(context.Background(), provider, provider.jar, "java", dir); err == nil { + t.Fatal("expected the installer error") + } + + provider.installErr = nil + if _, err := runner.install(context.Background(), provider, provider.jar, "java", dir); err != nil { + t.Fatalf("second install: %v", err) + } + if provider.installCalls != 2 { + t.Errorf("installer ran %d times, want 2", provider.installCalls) + } + if installUnfinished(dir, installKey("forge", "1.20.1", "47.4.10")) { + t.Error("a finished install is still marked unfinished") + } + if _, err := os.Stat(filepath.Join(dir, installMarkerName)); !os.IsNotExist(err) { + t.Error("the install marker must be gone once nothing is unfinished") + } + }) + + t.Run("another install does not clear the mark of an unfinished one", func(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "forge-installer.jar") + + forge := func(modVersion string, installErr error) *fakeInstallerProvider { + argFile := "libraries/net/minecraftforge/forge/1.20.1-" + modVersion + "/unix_args.txt" + return &fakeInstallerProvider{fakeProvider{ + name: "forge", + jar: &providers.ServerJar{ + Version: "1.20.1", ModVersion: modVersion, Filename: "forge-installer.jar", RequiresInstall: true, + }, + launch: &providers.LaunchTarget{ArgFiles: []string{argFile}}, + installs: []string{argFile}, + installErr: installErr, + }} + } + interrupted := forge("47.4.10", errors.New("processor failed")) + other := forge("47.4.0", nil) + runner := newTestRunner(interrupted) + + if _, err := runner.install(context.Background(), interrupted, interrupted.jar, "java", dir); err == nil { + t.Fatal("expected the installer error") + } + if _, err := runner.install(context.Background(), other, other.jar, "java", dir); err != nil { + t.Fatalf("install of another version: %v", err) + } + + interrupted.installErr = nil + if _, err := runner.install(context.Background(), interrupted, interrupted.jar, "java", dir); err != nil { + t.Fatalf("second install: %v", err) + } + if interrupted.installCalls != 2 { + t.Errorf("the interrupted install ran %d times, want 2: its leftovers were taken for an installation", + interrupted.installCalls) + } + }) + t.Run("an installer that leaves nothing to launch is an error", func(t *testing.T) { dir := t.TempDir() writeFile(t, dir, "forge-installer.jar") @@ -331,7 +405,7 @@ func TestInstalledFallback(t *testing.T) { {Mod: "paper", Version: "1.21.8", Directory: dir}, {Mod: "paper", Version: "1.21.8", ModVersion: "60", Directory: dir}, } { - inst, err := runner.installedFallback(opts, cause) + inst, err := runner.installedFallback("paper", opts, cause) if err != nil { t.Fatalf("installedFallback(%+v): %v", opts, err) } @@ -349,7 +423,7 @@ func TestInstalledFallback(t *testing.T) { {Mod: "paper", Version: "1.21.10", Directory: dir}, {Mod: "paper", Version: "1.21.8", ModVersion: "61", Directory: dir}, } { - if _, err := runner.installedFallback(opts, cause); !errors.Is(err, cause) { + if _, err := runner.installedFallback("paper", opts, cause); !errors.Is(err, cause) { t.Errorf("installedFallback(%+v) err = %v, want the resolve error", opts, err) } } @@ -359,15 +433,37 @@ func TestInstalledFallback(t *testing.T) { dir, runner := setup(t) os.Remove(filepath.Join(dir, "paper-1.21.8-60.jar")) - if _, err := runner.installedFallback(RunOptions{Mod: "paper", Directory: dir}, cause); !errors.Is(err, cause) { + if _, err := runner.installedFallback("paper", RunOptions{Mod: "paper", Directory: dir}, cause); !errors.Is(err, cause) { t.Errorf("err = %v, want the resolve error", err) } }) + t.Run("an install that did not finish is not started", func(t *testing.T) { + dir, runner := setup(t) + if err := startInstall(dir, installKey("paper", "1.21.8", "60")); err != nil { + t.Fatal(err) + } + + if _, err := runner.installedFallback("paper", RunOptions{Mod: "paper", Directory: dir}, cause); !errors.Is(err, cause) { + t.Errorf("err = %v, want the resolve error", err) + } + }) + + t.Run("an unfinished install of another version does not matter", func(t *testing.T) { + dir, runner := setup(t) + if err := startInstall(dir, installKey("paper", "1.21.10", "")); err != nil { + t.Fatal(err) + } + + if _, err := runner.installedFallback("paper", RunOptions{Mod: "paper", Directory: dir}, cause); err != nil { + t.Errorf("installedFallback: %v", err) + } + }) + t.Run("no state at all", func(t *testing.T) { runner := newTestRunner(&fakeProvider{name: "paper", resolveErr: cause}) - if _, err := runner.installedFallback(RunOptions{Mod: "paper", Directory: t.TempDir()}, cause); !errors.Is(err, cause) { + if _, err := runner.installedFallback("paper", RunOptions{Mod: "paper", Directory: t.TempDir()}, cause); !errors.Is(err, cause) { t.Errorf("err = %v, want the resolve error", err) } }) @@ -462,3 +558,107 @@ func TestLoadStateMissing(t *testing.T) { t.Errorf("LoadState() = %v, %v; want nil, nil", state, err) } } + +func TestFailedMarkerRewriteKeepsTheUnfinishedInstalls(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a directory the test cannot write to") + } + + dir := t.TempDir() + first, second := installKey("forge", "1.20.1", "47.4.0"), installKey("forge", "1.21.1", "52.1.0") + for _, key := range []string{first, second} { + if err := startInstall(dir, key); err != nil { + t.Fatal(err) + } + } + + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(dir, 0o755) }) + + if err := startInstall(dir, installKey("neoforge", "1.21.1", "21.1.251")); err == nil { + t.Error("startInstall() succeeded in a read-only directory") + } + if err := finishInstall(dir, first); err == nil { + t.Error("finishInstall() succeeded in a read-only directory") + } + + if got, err := unfinishedInstalls(dir); err != nil || !reflect.DeepEqual(got, []string{first, second}) { + t.Errorf("unfinishedInstalls() = %q, %v; want %q", got, err, []string{first, second}) + } +} + +func TestUnreadableMarkerIsNotReplaced(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("needs a file the test cannot read") + } + + dir := t.TempDir() + first := installKey("forge", "1.20.1", "47.4.0") + if err := startInstall(dir, first); err != nil { + t.Fatal(err) + } + + marker := filepath.Join(dir, installMarkerName) + if err := os.Chmod(marker, 0); err != nil { + t.Fatal(err) + } + + if err := startInstall(dir, installKey("forge", "1.21.1", "52.1.0")); err == nil { + t.Error("startInstall() succeeded with an unreadable marker") + } + if err := finishInstall(dir, first); err == nil { + t.Error("finishInstall() succeeded with an unreadable marker") + } + if !installUnfinished(dir, installKey("forge", "1.21.1", "52.1.0")) { + t.Error("an unreadable marker counts as a finished install") + } + + if err := os.Chmod(marker, 0o644); err != nil { + t.Fatal(err) + } + if got, err := unfinishedInstalls(dir); err != nil || !reflect.DeepEqual(got, []string{first}) { + t.Errorf("unfinishedInstalls() = %q, %v; want %q", got, err, []string{first}) + } +} + +func TestDownloadInstallsAServerWithoutAFileOfItsOwn(t *testing.T) { + dir := t.TempDir() + launcher := "quilt-server-launch-1.21.1-0.29.0.jar" + provider := &fakeInstallerProvider{fakeProvider{ + name: "quilt", + jar: &providers.ServerJar{ + Version: "1.21.1", ModVersion: "0.29.0", Filename: launcher, RequiresInstall: true, + }, + launch: &providers.LaunchTarget{Jar: launcher}, + installs: []string{launcher}, + }} + registry := providers.NewRegistry() + registry.Register(provider) + downloader := NewDownloader(registry) + opts := DownloadOptions{Version: "1.21.1", Mod: "quilt", Directory: dir} + + for range 2 { + if _, err := downloader.Download(context.Background(), opts); err != nil { + t.Fatalf("Download: %v", err) + } + } + if _, err := os.Stat(filepath.Join(dir, launcher)); err != nil { + t.Errorf("the server was not installed: %v", err) + } + if provider.installCalls != 1 { + t.Errorf("installed %d times, want 1", provider.installCalls) + } + if installUnfinished(dir, installKey("quilt", "1.21.1", "0.29.0")) { + t.Error("a finished install is still marked unfinished") + } + + opts.Force = true + if _, err := downloader.Download(context.Background(), opts); err != nil { + t.Fatalf("forced Download: %v", err) + } + if provider.installCalls != 2 { + t.Errorf("a forced download installed %d times in all, want 2", provider.installCalls) + } +} diff --git a/internal/server/state.go b/internal/server/state.go index a75696c..02003a4 100644 --- a/internal/server/state.go +++ b/internal/server/state.go @@ -6,12 +6,21 @@ import ( "fmt" "os" "path/filepath" + "slices" + "strings" "time" "github.com/gameap/minecraft-runner/internal/providers" ) -const stateFileName = ".mcrun-state.json" +const ( + stateFileName = ".mcrun-state.json" + + // installMarkerName is kept in the server directory while an installer + // runs. A failed installer can leave files behind that look launchable, + // such as Forge's argument file written before its processors failed. + installMarkerName = ".mcrun-installing" +) // State records the server mcrun last installed into a directory. It lets a // server start while the provider's API is unreachable and tells which JAR a @@ -52,23 +61,29 @@ func (s *State) Save(directory string) error { return fmt.Errorf("failed to encode %s: %w", stateFileName, err) } - tmp, err := os.CreateTemp(directory, stateFileName+".*.tmp") + return replaceFile(directory, stateFileName, append(data, '\n')) +} + +// replaceFile writes name in directory through a temporary file: a write that +// fails or is interrupted leaves the previous content in place +func replaceFile(directory, name string, data []byte) error { + tmp, err := os.CreateTemp(directory, name+".*.tmp") if err != nil { - return fmt.Errorf("failed to create temporary state file: %w", err) + return fmt.Errorf("failed to create temporary file for %s: %w", name, err) } tmpName := tmp.Name() defer os.Remove(tmpName) - if _, err := tmp.Write(append(data, '\n')); err != nil { + if _, err := tmp.Write(data); err != nil { tmp.Close() - return fmt.Errorf("failed to write %s: %w", stateFileName, err) + return fmt.Errorf("failed to write %s: %w", name, err) } if err := tmp.Close(); err != nil { - return fmt.Errorf("failed to close %s: %w", stateFileName, err) + return fmt.Errorf("failed to close %s: %w", name, err) } - if err := os.Rename(tmpName, filepath.Join(directory, stateFileName)); err != nil { - return fmt.Errorf("failed to move %s into place: %w", stateFileName, err) + if err := os.Rename(tmpName, filepath.Join(directory, name)); err != nil { + return fmt.Errorf("failed to move %s into place: %w", name, err) } return nil @@ -109,3 +124,73 @@ func launchFilesExist(directory string, target providers.LaunchTarget) bool { return true } + +// installKey names one installation in the install marker, which holds a line +// for every installer run in the directory that did not finish +func installKey(provider, version, modVersion string) string { + return strings.TrimSpace(provider + " " + version + " " + modVersion) +} + +func unfinishedInstalls(directory string) ([]string, error) { + data, err := os.ReadFile(filepath.Join(directory, installMarkerName)) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("failed to read %s: %w", installMarkerName, err) + } + + var keys []string + for _, line := range strings.Split(string(data), "\n") { + if line = strings.TrimSpace(line); line != "" { + keys = append(keys, line) + } + } + + return keys, nil +} + +// installUnfinished tells whether the installer run for key in directory did +// not finish. A marker that cannot be read may hold key, so it counts as +// unfinished; recording the install then fails with the read error. +func installUnfinished(directory, key string) bool { + keys, err := unfinishedInstalls(directory) + return err != nil || slices.Contains(keys, key) +} + +// startInstall marks the installer run for key as not finished yet +func startInstall(directory, key string) error { + keys, err := unfinishedInstalls(directory) + if err != nil { + return err + } + if slices.Contains(keys, key) { + return nil + } + + return replaceFile(directory, installMarkerName, []byte(strings.Join(append(keys, key), "\n")+"\n")) +} + +// finishInstall clears the mark of the installer run for key. The marks of +// other installs that did not finish stay, so their leftovers are not taken +// for an installation. +func finishInstall(directory, key string) error { + keys, err := unfinishedInstalls(directory) + if err != nil { + return err + } + if !slices.Contains(keys, key) { + return nil + } + + path := filepath.Join(directory, installMarkerName) + rest := slices.DeleteFunc(keys, func(k string) bool { return k == key }) + if len(rest) == 0 { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("failed to remove %s: %w", installMarkerName, err) + } + return nil + } + + return replaceFile(directory, installMarkerName, []byte(strings.Join(rest, "\n")+"\n")) +} diff --git a/internal/utils/download.go b/internal/utils/download.go index a876b40..12742ce 100644 --- a/internal/utils/download.go +++ b/internal/utils/download.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "net" "net/http" "os" "path/filepath" @@ -23,6 +24,10 @@ const ( // stallTimeout aborts a download that stopped delivering data stallTimeout = 60 * time.Second + + // dialTimeout bounds connecting, so an unreachable host is left for a + // mirror quickly + dialTimeout = 10 * time.Second ) // userAgent identifies mcrun to the download APIs. PaperMC asks for a @@ -50,6 +55,7 @@ type HTTPClient struct { func NewHTTPClient(showProgress bool) *HTTPClient { transport := http.DefaultTransport.(*http.Transport).Clone() transport.ResponseHeaderTimeout = headerTimeout + transport.DialContext = (&net.Dialer{Timeout: dialTimeout, KeepAlive: 30 * time.Second}).DialContext return &HTTPClient{ client: &http.Client{Transport: transport}, @@ -71,10 +77,13 @@ func (e *StatusError) Error() string { } // doWithRetry performs a GET request, retrying network errors, 5xx and 429 -func (c *HTTPClient) doWithRetry(ctx context.Context, url string) (*http.Response, error) { +// up to retries times. With fastFail a host that cannot be reached at all is +// not retried and a broken exchange is retried once, because a mirror is +// waiting to take over. +func (c *HTTPClient) doWithRetry(ctx context.Context, url string, retries int, fastFail bool) (*http.Response, error) { var lastErr error - for attempt := 0; attempt <= c.retryMax; attempt++ { + for attempt := 0; attempt <= retries; attempt++ { if attempt > 0 { backoff := c.retryWaitMin * time.Duration(1< c.retryWaitMax { @@ -100,6 +109,9 @@ func (c *HTTPClient) doWithRetry(ctx context.Context, url string) (*http.Respons return nil, ctx.Err() } lastErr = err + if fastFail && (isConnectError(err) || attempt >= 1) { + break + } continue } @@ -112,37 +124,55 @@ func (c *HTTPClient) doWithRetry(ctx context.Context, url string) (*http.Respons return resp, nil } - return nil, fmt.Errorf("request failed after %d retries: %w", c.retryMax, lastErr) + return nil, fmt.Errorf("request failed: %w", lastErr) } -// Get performs a GET request and returns the response body +// Get performs a GET request and returns the response body. The upstream and +// each mirror get requestTimeout of their own; an answer that breaks off is +// asked from the next mirror. func (c *HTTPClient) Get(ctx context.Context, url string) ([]byte, error) { - ctx, cancel := context.WithTimeout(ctx, requestTimeout) - defer cancel() + from := upstreamSource + for { + data, source, err := c.get(ctx, url, from) + + next, retry := retryAfterBreak(ctx, url, source, err) + if !retry { + return data, err + } + from = next + } +} - resp, err := c.doWithRetry(ctx, url) +func (c *HTTPClient) get(ctx context.Context, url string, from int) ([]byte, int, error) { + resp, source, err := c.fetch(ctx, url, requestTimeout, from) if err != nil { - return nil, fmt.Errorf("request failed: %w", err) + return nil, source, fmt.Errorf("request failed: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, &StatusError{StatusCode: resp.StatusCode, URL: url} + return nil, source, &StatusError{StatusCode: resp.StatusCode, URL: url} } - return io.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) + if err != nil { + if ctx.Err() != nil { + return nil, source, ctx.Err() + } + return nil, source, fmt.Errorf("failed to read response: %w: %w", errBrokenBody, err) + } + + return data, source, nil } -// DownloadFile downloads a file to the specified path with progress bar +// DownloadFile downloads a file to the specified path with progress bar. A +// download that breaks off midway is started over through the next mirror. func (c *HTTPClient) DownloadFile(ctx context.Context, url string, destPath string) (err error) { dir := filepath.Dir(destPath) if err := os.MkdirAll(dir, 0755); err != nil { return fmt.Errorf("failed to create directory: %w", err) } - ctx, cancel := context.WithCancelCause(ctx) - defer cancel(nil) - tmpPath := destPath + ".tmp" file, err := os.Create(tmpPath) if err != nil { @@ -155,14 +185,61 @@ func (c *HTTPClient) DownloadFile(ctx context.Context, url string, destPath stri } }() - resp, err := c.doWithRetry(ctx, url) + from := upstreamSource + for { + var source int + source, err = c.downloadTo(ctx, url, destPath, file, from) + + next, retry := retryAfterBreak(ctx, url, source, err) + if !retry { + break + } + + if _, err = file.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("failed to rewind file: %w", err) + } + if err = file.Truncate(0); err != nil { + return fmt.Errorf("failed to truncate file: %w", err) + } + from = next + } if err != nil { - return fmt.Errorf("download failed: %w", err) + return err + } + + if err = file.Close(); err != nil { + return fmt.Errorf("failed to close file: %w", err) + } + + if err = os.Rename(tmpPath, destPath); err != nil { + return fmt.Errorf("failed to rename file: %w", err) + } + + return nil +} + +// errBrokenBody marks a download that failed while the body was arriving +var errBrokenBody = errors.New("download broke off") + +func isBrokenBody(err error) bool { + return errors.Is(err, errBrokenBody) +} + +// downloadTo writes one response into file +func (c *HTTPClient) downloadTo( + parent context.Context, url, destPath string, file *os.File, from int, +) (source int, err error) { + ctx, cancel := context.WithCancelCause(parent) + defer cancel(nil) + + resp, source, err := c.fetch(ctx, url, 0, from) + if err != nil { + return source, fmt.Errorf("download failed: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return &StatusError{StatusCode: resp.StatusCode, URL: url} + return source, &StatusError{StatusCode: resp.StatusCode, URL: url} } var writer io.Writer = file @@ -188,27 +265,23 @@ func (c *HTTPClient) DownloadFile(ctx context.Context, url string, destPath stri if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) { err = cause } - return fmt.Errorf("failed to write file: %w", err) + if parent.Err() != nil { + return source, fmt.Errorf("failed to write file: %w", err) + } + return source, fmt.Errorf("failed to write file: %w: %w", errBrokenBody, err) } // Not every provider publishes a checksum, and a broken mirror may well // answer 200 with an empty or cut-off body if written == 0 { - return fmt.Errorf("the server sent an empty file for %s", url) + return source, fmt.Errorf("the server sent an empty file for %s", url) } if resp.ContentLength > 0 && written != resp.ContentLength { - return fmt.Errorf("incomplete download of %s: got %d of %d bytes", url, written, resp.ContentLength) - } - - if err = file.Close(); err != nil { - return fmt.Errorf("failed to close file: %w", err) + return source, fmt.Errorf("%w: incomplete download of %s: got %d of %d bytes", + errBrokenBody, url, written, resp.ContentLength) } - if err = os.Rename(tmpPath, destPath); err != nil { - return fmt.Errorf("failed to rename file: %w", err) - } - - return nil + return source, nil } // FileExists checks if a file exists at the given path diff --git a/internal/utils/hash.go b/internal/utils/hash.go index b4d7cc0..91fa2d4 100644 --- a/internal/utils/hash.go +++ b/internal/utils/hash.go @@ -4,6 +4,7 @@ import ( "crypto/md5" "crypto/sha1" "crypto/sha256" + "crypto/sha512" "encoding/hex" "fmt" "hash" @@ -32,6 +33,11 @@ func CalculateSHA1(filePath string) (string, error) { return calculateHash(sha1.New(), filePath) } +// VerifySHA512 verifies that a file matches the expected SHA512 hash +func VerifySHA512(filePath string, expectedHash string) error { + return verifyHash("SHA512", sha512.New(), filePath, expectedHash) +} + // VerifyMD5 verifies that a file matches the expected MD5 hash func VerifyMD5(filePath string, expectedHash string) error { return verifyHash("MD5", md5.New(), filePath, expectedHash) diff --git a/internal/utils/mirror.go b/internal/utils/mirror.go new file mode 100644 index 0000000..2a591d9 --- /dev/null +++ b/internal/utils/mirror.go @@ -0,0 +1,352 @@ +package utils + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// defaultMirrors are GameAP's mirrors of everything mcrun downloads. They are +// asked only when the upstream itself cannot be reached. +var defaultMirrors = []string{"https://mirror.gameap.ru"} + +// mirrorCacheHeader is set by the mirror on every answer it got from or for +// the upstream, which tells an upstream 404 from a path it does not mirror +const mirrorCacheHeader = "X-Mirror-Cache" + +// mirrorAttempts is how often each mirror is tried +const mirrorAttempts = 2 + +// upstreamSource is the source of an answer that came from the upstream +// itself rather than from a mirror +const upstreamSource = -1 + +var ( + mirrorsMu sync.RWMutex + mirrors = defaultMirrors + + // downHosts remembers the upstreams that could not be reached during this + // run, so later requests to them go to the mirrors without waiting again + downHosts sync.Map + + // warnedHosts makes the fallback warning appear once per host + warnedHosts sync.Map +) + +// SetMirrors replaces the mirror list; an empty list disables the fallback +func SetMirrors(list []string) { + cleaned := make([]string, 0, len(list)) + for _, m := range list { + m = strings.TrimRight(strings.TrimSpace(m), "/") + if m == "" { + continue + } + if u, err := url.Parse(m); err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + fmt.Printf("[WARNING] Ignoring mirror %q: not an http(s) URL\n", m) + continue + } + cleaned = append(cleaned, m) + } + + mirrorsMu.Lock() + mirrors = cleaned + mirrorsMu.Unlock() +} + +// ConfigureMirrors applies the MCRUN_MIRRORS environment variable: a comma +// separated list of mirror URLs, or "off". Unset keeps GameAP's mirrors. +func ConfigureMirrors(env string, set bool) { + if !set { + return + } + + if strings.EqualFold(strings.TrimSpace(env), "off") { + SetMirrors(nil) + return + } + + SetMirrors(strings.Split(env, ",")) +} + +func currentMirrors() []string { + mirrorsMu.RLock() + defer mirrorsMu.RUnlock() + + return mirrors +} + +// canMirror tells whether raw can be asked from a mirror at all +func canMirror(raw string) bool { + if len(currentMirrors()) == 0 { + return false + } + _, ok := mirrorURL("", raw) + return ok +} + +// mirrorURL maps an upstream URL onto a mirror: https://host/path?q becomes +// /host/path?q. It reports false for URLs that cannot be mirrored. +func mirrorURL(base, raw string) (string, bool) { + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + return "", false + } + + for _, m := range currentMirrors() { + if strings.HasPrefix(raw, m+"/") { + return "", false + } + } + + mirrored := base + "/" + u.Host + u.EscapedPath() + if u.RawQuery != "" { + mirrored += "?" + u.RawQuery + } + + return mirrored, true +} + +// isConnectError reports a failure to reach the host at all: name +// resolution or connecting, as opposed to a broken exchange with a host that +// answered +func isConnectError(err error) bool { + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) { + return true + } + + var opErr *net.OpError + + return errors.As(err, &opErr) && opErr.Op == "dial" +} + +// blockedStatus is an answer of a host that refuses to serve this client +// rather than one that lacks the file +func blockedStatus(code int) bool { + return code == http.StatusForbidden || code == http.StatusUnavailableForLegalReasons +} + +func hostOf(raw string) string { + if u, err := url.Parse(raw); err == nil { + return u.Host + } + return "" +} + +func isHostDown(raw string) bool { + _, down := downHosts.Load(hostOf(raw)) + return down +} + +func markHostDown(raw string) { + if host := hostOf(raw); host != "" { + downHosts.Store(host, struct{}{}) + } +} + +// warnOnce prints a warning about host once per run +func warnOnce(host, format string, args ...any) { + if _, warned := warnedHosts.LoadOrStore(host, struct{}{}); warned { + return + } + + fmt.Printf("[WARNING] "+format+"\n", args...) +} + +// retryAfterBreak tells where to ask again after err: an answer that broke off +// midway is asked from the mirror after the source that sent it, while there +// is one. An upstream that broke off gets the rest of this run's requests +// sent to the mirrors. +func retryAfterBreak(ctx context.Context, raw string, source int, err error) (int, bool) { + if err == nil || ctx.Err() != nil || !isBrokenBody(err) || !canMirror(raw) { + return 0, false + } + + mirrorList := currentMirrors() + next := source + 1 + if next >= len(mirrorList) { + return 0, false + } + + if source == upstreamSource { + host := hostOf(raw) + warnOnce(host, "Download from %s broke off (%v), retrying through a mirror", host, err) + markHostDown(raw) + } else { + fmt.Printf("[WARNING] Download of %s through %s broke off (%v), trying the next mirror\n", + raw, mirrorList[source], err) + } + + return next, true +} + +func warnFallback(raw string, cause error, mirror string) { + host := hostOf(raw) + warnOnce(host, "%s is unreachable (%v), downloading through %s", host, cause, mirror) +} + +// fetch performs a GET: first from the upstream, then, when the upstream +// cannot be reached, from each mirror. A host already found unreachable in +// this run goes to the mirrors first and gets its own chance only when they +// fail. From the index of a mirror on, only that mirror and the ones after it +// are asked. budget bounds each request phase (0: no bound); the response body +// keeps its phase's deadline until it is closed. source is upstreamSource or +// the index of the mirror that answered. +func (c *HTTPClient) fetch( + ctx context.Context, raw string, budget time.Duration, from int, +) (resp *http.Response, source int, err error) { + mirrorOnly := from != upstreamSource + + var mirrorList []string + if canMirror(raw) { + mirrorList = currentMirrors() + } + + if mirrorOnly && from >= len(mirrorList) { + return nil, upstreamSource, errors.New("no mirror to retry through") + } + if len(mirrorList) == 0 { + resp, err = c.phase(ctx, budget, func(ctx context.Context) (*http.Response, error) { + return c.doWithRetry(ctx, raw, c.retryMax, false) + }) + return resp, upstreamSource, err + } + + skipDirect := mirrorOnly || isHostDown(raw) + + var directErr error + if skipDirect { + directErr = fmt.Errorf("%s was unreachable earlier in this run", hostOf(raw)) + } else { + resp, err = c.direct(ctx, raw, budget) + if err == nil || ctx.Err() != nil || !shouldFallback(err) { + return resp, upstreamSource, err + } + markHostDown(raw) + directErr = err + } + + first := max(from, 0) + resp, answered, failures, err := c.viaMirrors(ctx, raw, mirrorList[first:], budget, directErr) + if resp != nil || err != nil { + return resp, first + answered, err + } + if ctx.Err() != nil { + return nil, upstreamSource, ctx.Err() + } + + if skipDirect && !mirrorOnly { + resp, err = c.direct(ctx, raw, budget) + return resp, upstreamSource, err + } + + return nil, upstreamSource, fmt.Errorf("%w; mirrors failed too: %s", directErr, strings.Join(failures, "; ")) +} + +// direct asks the upstream. A host that cannot be reached at all is not +// asked again, the mirrors are; a broken exchange gets one more try. +func (c *HTTPClient) direct(ctx context.Context, raw string, budget time.Duration) (*http.Response, error) { + resp, err := c.phase(ctx, budget, func(ctx context.Context) (*http.Response, error) { + return c.doWithRetry(ctx, raw, c.retryMax, true) + }) + if err != nil { + return nil, err + } + + if blockedStatus(resp.StatusCode) { + resp.Body.Close() + return nil, &StatusError{StatusCode: resp.StatusCode, URL: raw} + } + + return resp, nil +} + +// shouldFallback tells the failures a mirror can help with: the host was +// unreachable, kept failing, or refused this client +func shouldFallback(err error) bool { + var statusErr *StatusError + if errors.As(err, &statusErr) { + return statusErr.StatusCode >= 500 || statusErr.StatusCode == http.StatusTooManyRequests || + blockedStatus(statusErr.StatusCode) + } + return true +} + +// viaMirrors asks each mirror in turn. It returns the first good answer, or +// a 404 error when a mirror reports that the upstream has no such file, with +// the index of that mirror, or neither, with what went wrong on each mirror. +func (c *HTTPClient) viaMirrors( + ctx context.Context, raw string, mirrorList []string, budget time.Duration, directErr error, +) (*http.Response, int, []string, error) { + failures := make([]string, 0, len(mirrorList)) + + for i, base := range mirrorList { + target, _ := mirrorURL(base, raw) + + resp, err := c.phase(ctx, budget, func(ctx context.Context) (*http.Response, error) { + return c.doWithRetry(ctx, target, mirrorAttempts-1, true) + }) + if err != nil { + if ctx.Err() != nil { + return nil, 0, nil, nil + } + failures = append(failures, fmt.Sprintf("%s: %v", base, err)) + continue + } + + switch { + case resp.StatusCode == http.StatusOK: + warnFallback(raw, directErr, base) + return resp, i, nil, nil + case resp.StatusCode == http.StatusNotFound && resp.Header.Get(mirrorCacheHeader) != "": + resp.Body.Close() + warnFallback(raw, directErr, base) + return nil, i, nil, &StatusError{StatusCode: resp.StatusCode, URL: raw} + default: + resp.Body.Close() + failures = append(failures, fmt.Sprintf("%s: status %d", base, resp.StatusCode)) + } + } + + return nil, 0, failures, nil +} + +// phase runs one request phase under its own deadline. The deadline stays +// with the response body and ends when the body is closed. +func (c *HTTPClient) phase( + ctx context.Context, budget time.Duration, do func(context.Context) (*http.Response, error), +) (*http.Response, error) { + if budget <= 0 { + return do(ctx) + } + + ctx, cancel := context.WithTimeout(ctx, budget) + + resp, err := do(ctx) + if err != nil { + cancel() + return nil, err + } + + resp.Body = &cancelOnClose{ReadCloser: resp.Body, cancel: cancel} + + return resp, nil +} + +type cancelOnClose struct { + io.ReadCloser + cancel context.CancelFunc +} + +func (c *cancelOnClose) Close() error { + err := c.ReadCloser.Close() + c.cancel() + return err +} diff --git a/internal/utils/mirror_test.go b/internal/utils/mirror_test.go new file mode 100644 index 0000000..239ad53 --- /dev/null +++ b/internal/utils/mirror_test.go @@ -0,0 +1,434 @@ +package utils + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" +) + +// No test may reach GameAP's real mirrors +func TestMain(m *testing.M) { + SetMirrors(nil) + os.Exit(m.Run()) +} + +// useMirrors installs mirrors for one test and forgets the hosts earlier tests +// found unreachable +func useMirrors(t *testing.T, list ...string) { + t.Helper() + + reset := func() { + downHosts.Clear() + warnedHosts.Clear() + } + + reset() + SetMirrors(list) + t.Cleanup(func() { + SetMirrors(nil) + reset() + }) +} + +// counted serves handler and counts the requests it gets +type counted struct { + *httptest.Server + calls atomic.Int32 +} + +func newCounted(t *testing.T, handler http.HandlerFunc) *counted { + t.Helper() + + c := &counted{} + c.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.calls.Add(1) + handler(w, r) + })) + t.Cleanup(c.Close) + + return c +} + +// mirrorOf serves body for every request of upstream's host, the way +// gameap-mirror does +func mirrorOf(t *testing.T, body string) *counted { + t.Helper() + + return newCounted(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(mirrorCacheHeader, "MISS") + fmt.Fprint(w, body) + }) +} + +func status(code int) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(code) + } +} + +func closedPortURL(t *testing.T) string { + t.Helper() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + ln.Close() + + return "http://" + addr +} + +func TestMirrorURL(t *testing.T) { + useMirrors(t, "https://mirror.example") + + for raw, want := range map[string]string{ + "https://meta.fabricmc.net/v2/versions/game": "https://m/meta.fabricmc.net/v2/versions/game", + "https://ci.pufferfish.host/api/json?tree=jobs[name]": "https://m/ci.pufferfish.host/api/json?tree=jobs[name]", + "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.13%2B9/jre.tar.gz": "https://m/github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.13%2B9/jre.tar.gz", + } { + if got, ok := mirrorURL("https://m", raw); !ok || got != want { + t.Errorf("mirrorURL(%s) = %q, %v, want %q", raw, got, ok, want) + } + } + + for _, raw := range []string{"ftp://host/file", "/relative/path", "https://mirror.example/meta.fabricmc.net/x"} { + if got, ok := mirrorURL("https://m", raw); ok { + t.Errorf("mirrorURL(%s) = %q, must not be mirrored", raw, got) + } + } +} + +func TestConfigureMirrors(t *testing.T) { + useMirrors(t, defaultMirrors...) + + ConfigureMirrors("", false) + if got := currentMirrors(); !reflect.DeepEqual(got, defaultMirrors) { + t.Errorf("unset: %v, want the defaults", got) + } + + ConfigureMirrors(" https://a.example/ , ftp://b.example,http://c.example:8437", true) + if got, want := currentMirrors(), []string{"https://a.example", "http://c.example:8437"}; !reflect.DeepEqual(got, want) { + t.Errorf("list: %v, want %v", got, want) + } + + ConfigureMirrors("OFF", true) + if got := currentMirrors(); len(got) != 0 { + t.Errorf("off: %v, want none", got) + } +} + +func TestGetFallsBackWhenUpstreamIsUnreachable(t *testing.T) { + mirror := mirrorOf(t, "from-mirror") + useMirrors(t, mirror.URL) + + upstream := closedPortURL(t) + + for range 2 { + data, err := newFastClient().Get(context.Background(), upstream+"/v2/versions/game?x=1") + if err != nil || string(data) != "from-mirror" { + t.Fatalf("Get = %q, %v", data, err) + } + } + + if mirror.calls.Load() != 2 { + t.Errorf("mirror got %d requests, want 2", mirror.calls.Load()) + } +} + +func TestGetSendsTheUpstreamPathAndQueryToTheMirror(t *testing.T) { + var got string + mirror := newCounted(t, func(w http.ResponseWriter, r *http.Request) { + got = r.URL.RequestURI() + fmt.Fprint(w, "ok") + }) + useMirrors(t, mirror.URL+"/") + + upstream := closedPortURL(t) + if _, err := newFastClient().Get(context.Background(), upstream+"/api/json?tree=jobs%5Bname%5D"); err != nil { + t.Fatal(err) + } + + if want := "/" + strings.TrimPrefix(upstream, "http://") + "/api/json?tree=jobs%5Bname%5D"; got != want { + t.Errorf("mirror asked for %q, want %q", got, want) + } +} + +func TestGetFallsBackAfterServerErrors(t *testing.T) { + upstream := newCounted(t, status(http.StatusServiceUnavailable)) + mirror := mirrorOf(t, "from-mirror") + useMirrors(t, mirror.URL) + + client := newFastClient() + + data, err := client.Get(context.Background(), upstream.URL+"/file") + if err != nil || string(data) != "from-mirror" { + t.Fatalf("Get = %q, %v", data, err) + } + if want := int32(client.retryMax + 1); upstream.calls.Load() != want { + t.Errorf("upstream got %d requests, want %d", upstream.calls.Load(), want) + } + + // The host failed once in this run, the next request goes to the mirror + if _, err := client.Get(context.Background(), upstream.URL+"/other"); err != nil { + t.Fatal(err) + } + if want := int32(client.retryMax + 1); upstream.calls.Load() != want { + t.Errorf("upstream got %d requests, want still %d", upstream.calls.Load(), want) + } +} + +func TestGetFallsBackWhenBlocked(t *testing.T) { + upstream := newCounted(t, status(http.StatusForbidden)) + mirror := mirrorOf(t, "from-mirror") + useMirrors(t, mirror.URL) + + data, err := newFastClient().Get(context.Background(), upstream.URL+"/file") + if err != nil || string(data) != "from-mirror" { + t.Fatalf("Get = %q, %v", data, err) + } + if upstream.calls.Load() != 1 { + t.Errorf("upstream got %d requests, want 1", upstream.calls.Load()) + } +} + +func TestGetDoesNotFallBackOnNotFound(t *testing.T) { + upstream := newCounted(t, status(http.StatusNotFound)) + mirror := mirrorOf(t, "from-mirror") + useMirrors(t, mirror.URL) + + _, err := newFastClient().Get(context.Background(), upstream.URL+"/file") + + var statusErr *StatusError + if !errors.As(err, &statusErr) || statusErr.StatusCode != http.StatusNotFound { + t.Errorf("err = %v, want a 404 StatusError", err) + } + if mirror.calls.Load() != 0 { + t.Errorf("mirror got %d requests, want none", mirror.calls.Load()) + } +} + +func TestGetTriesTheNextMirror(t *testing.T) { + notMirrored := newCounted(t, status(http.StatusNotFound)) + failing := newCounted(t, status(http.StatusBadGateway)) + good := mirrorOf(t, "from-third") + useMirrors(t, notMirrored.URL, failing.URL, good.URL) + + data, err := newFastClient().Get(context.Background(), closedPortURL(t)+"/file") + if err != nil || string(data) != "from-third" { + t.Fatalf("Get = %q, %v", data, err) + } + if notMirrored.calls.Load() != 1 || failing.calls.Load() != mirrorAttempts { + t.Errorf("mirrors got %d and %d requests, want 1 and %d", + notMirrored.calls.Load(), failing.calls.Load(), mirrorAttempts) + } +} + +func TestGetTrustsTheMirrorsNotFound(t *testing.T) { + missing := newCounted(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(mirrorCacheHeader, "MISS") + w.WriteHeader(http.StatusNotFound) + }) + second := mirrorOf(t, "never") + useMirrors(t, missing.URL, second.URL) + + _, err := newFastClient().Get(context.Background(), closedPortURL(t)+"/file") + + var statusErr *StatusError + if !errors.As(err, &statusErr) || statusErr.StatusCode != http.StatusNotFound { + t.Errorf("err = %v, want a 404 StatusError", err) + } + if second.calls.Load() != 0 { + t.Error("the upstream has no such file, no other mirror is asked") + } +} + +func TestGetReportsTheUpstreamErrorWhenMirrorsFail(t *testing.T) { + upstream := newCounted(t, status(http.StatusServiceUnavailable)) + mirror := newCounted(t, status(http.StatusNotFound)) + useMirrors(t, mirror.URL) + + _, err := newFastClient().Get(context.Background(), upstream.URL+"/file") + + var statusErr *StatusError + if !errors.As(err, &statusErr) || statusErr.StatusCode != http.StatusServiceUnavailable { + t.Errorf("err = %v, want the upstream's 503", err) + } + if err == nil || !strings.Contains(err.Error(), "mirrors failed too") { + t.Errorf("err = %v, want the mirror failures mentioned", err) + } +} + +func TestGetRetriesADownHostWhenMirrorsFail(t *testing.T) { + var healthy atomic.Bool + upstream := newCounted(t, func(w http.ResponseWriter, r *http.Request) { + if !healthy.Load() { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + fmt.Fprint(w, "upstream-back") + }) + mirror := newCounted(t, status(http.StatusBadGateway)) + useMirrors(t, mirror.URL) + + client := newFastClient() + if _, err := client.Get(context.Background(), upstream.URL+"/file"); err == nil { + t.Fatal("expected an error while everything is down") + } + + healthy.Store(true) + + data, err := client.Get(context.Background(), upstream.URL+"/file") + if err != nil || string(data) != "upstream-back" { + t.Errorf("Get = %q, %v", data, err) + } +} + +func TestGetDoesNotFallBackWhenCancelled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + upstream := newCounted(t, func(w http.ResponseWriter, r *http.Request) { + cancel() + <-r.Context().Done() + }) + mirror := mirrorOf(t, "from-mirror") + useMirrors(t, mirror.URL) + + if _, err := newFastClient().Get(ctx, upstream.URL+"/file"); !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if mirror.calls.Load() != 0 { + t.Errorf("mirror got %d requests, want none", mirror.calls.Load()) + } +} + +// breaksOff sends the headers and part of body, then drops the connection +func breaksOff(body string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.WriteHeader(http.StatusOK) + io.WriteString(w, body[:len(body)/2]) + w.(http.Flusher).Flush() + panic(http.ErrAbortHandler) + } +} + +func TestGetRefetchesABrokenBodyThroughTheMirror(t *testing.T) { + upstream := newCounted(t, breaksOff(`{"versions":[]}`)) + mirror := mirrorOf(t, `{"versions":[]}`) + useMirrors(t, mirror.URL) + + data, err := newFastClient().Get(context.Background(), upstream.URL+"/versions") + if err != nil || string(data) != `{"versions":[]}` { + t.Fatalf("Get = %q, %v", data, err) + } +} + +func TestDownloadFileRestartsABrokenDownloadThroughTheMirror(t *testing.T) { + upstream := newCounted(t, breaksOff("0123456789")) + mirror := mirrorOf(t, "0123456789") + useMirrors(t, mirror.URL) + + dest := filepath.Join(t.TempDir(), "server.jar") + if err := newFastClient().DownloadFile(context.Background(), upstream.URL+"/server.jar", dest); err != nil { + t.Fatalf("DownloadFile: %v", err) + } + + data, err := os.ReadFile(dest) + if err != nil || string(data) != "0123456789" { + t.Errorf("file = %q, %v", data, err) + } + if upstream.calls.Load() != 1 || mirror.calls.Load() != 1 { + t.Errorf("upstream and mirror got %d and %d requests, want 1 and 1", upstream.calls.Load(), mirror.calls.Load()) + } +} + +func TestGetMovesOnFromAMirrorThatBreaksOff(t *testing.T) { + broken := newCounted(t, breaksOff(`{"versions":[]}`)) + mirror := mirrorOf(t, `{"versions":[]}`) + useMirrors(t, broken.URL, mirror.URL) + + data, err := newFastClient().Get(context.Background(), closedPortURL(t)+"/versions") + if err != nil || string(data) != `{"versions":[]}` { + t.Fatalf("Get = %q, %v", data, err) + } + if broken.calls.Load() != 1 || mirror.calls.Load() != 1 { + t.Errorf("mirrors got %d and %d requests, want 1 and 1", broken.calls.Load(), mirror.calls.Load()) + } +} + +func TestDownloadFileMovesOnFromAMirrorThatBreaksOff(t *testing.T) { + upstream := newCounted(t, breaksOff("0123456789")) + broken := newCounted(t, breaksOff("0123456789")) + mirror := mirrorOf(t, "0123456789") + useMirrors(t, broken.URL, mirror.URL) + + dest := filepath.Join(t.TempDir(), "server.jar") + if err := newFastClient().DownloadFile(context.Background(), upstream.URL+"/server.jar", dest); err != nil { + t.Fatalf("DownloadFile: %v", err) + } + + if data, _ := os.ReadFile(dest); string(data) != "0123456789" { + t.Errorf("file = %q", data) + } + calls := []int32{upstream.calls.Load(), broken.calls.Load(), mirror.calls.Load()} + if calls[0] != 1 || calls[1] != 1 || calls[2] != 1 { + t.Errorf("upstream and mirrors got %v requests, want one each", calls) + } +} + +func TestDownloadFileGivesUpWhenEveryMirrorBreaksOff(t *testing.T) { + upstream := newCounted(t, breaksOff("0123456789")) + first := newCounted(t, breaksOff("0123456789")) + second := newCounted(t, breaksOff("0123456789")) + useMirrors(t, first.URL, second.URL) + + dest := filepath.Join(t.TempDir(), "server.jar") + if err := newFastClient().DownloadFile(context.Background(), upstream.URL+"/server.jar", dest); err == nil { + t.Fatal("expected an error") + } + + calls := []int32{upstream.calls.Load(), first.calls.Load(), second.calls.Load()} + if calls[0] != 1 || calls[1] != 1 || calls[2] != 1 { + t.Errorf("upstream and mirrors got %v requests, want one each", calls) + } + if _, err := os.Stat(dest + ".tmp"); !os.IsNotExist(err) { + t.Error("the temporary file must be gone") + } +} + +func TestDownloadFileFallsBackWhenUpstreamIsUnreachable(t *testing.T) { + mirror := mirrorOf(t, "jar-content") + useMirrors(t, mirror.URL) + + dest := filepath.Join(t.TempDir(), "server.jar") + if err := newFastClient().DownloadFile(context.Background(), closedPortURL(t)+"/server.jar", dest); err != nil { + t.Fatalf("DownloadFile: %v", err) + } + + if data, _ := os.ReadFile(dest); string(data) != "jar-content" { + t.Errorf("file = %q", data) + } +} + +func TestBrokenDownloadWithoutMirrorsFails(t *testing.T) { + upstream := newCounted(t, breaksOff("0123456789")) + + dest := filepath.Join(t.TempDir(), "server.jar") + err := newFastClient().DownloadFile(context.Background(), upstream.URL+"/server.jar", dest) + if err == nil { + t.Fatal("expected an error") + } + if _, statErr := os.Stat(dest + ".tmp"); !os.IsNotExist(statErr) { + t.Error("the temporary file must be gone") + } +} diff --git a/pkg/api/jenkins/client.go b/pkg/api/jenkins/client.go index ef15080..42412b0 100644 --- a/pkg/api/jenkins/client.go +++ b/pkg/api/jenkins/client.go @@ -138,6 +138,29 @@ func (c *Client) GetLastSuccessfulBuild(ctx context.Context) (*BuildInfo, error) return &build, nil } +// GetFingerprints returns the MD5 of the files a build produced, keyed by +// their Maven-style name, e.g. net.md-5:cmd_alert.jar +func (c *Client) GetFingerprints(ctx context.Context, number int) (map[string]string, error) { + var response struct { + Fingerprint []struct { + FileName string `json:"fileName"` + Hash string `json:"hash"` + } `json:"fingerprint"` + } + + url := fmt.Sprintf("%s/%d/api/json?tree=fingerprint%%5BfileName,hash%%5D", c.baseURL, number) + if err := c.get(ctx, url, &response); err != nil { + return nil, fmt.Errorf("failed to fetch build fingerprints: %w", err) + } + + result := make(map[string]string, len(response.Fingerprint)) + for _, f := range response.Fingerprint { + result[f.FileName] = f.Hash + } + + return result, nil +} + // GetArtifactURL constructs the download URL for an artifact func (c *Client) GetArtifactURL(buildNumber int, relativePath string) string { return fmt.Sprintf("%s/%d/artifact/%s", c.baseURL, buildNumber, relativePath) diff --git a/pkg/api/mojang/client.go b/pkg/api/mojang/client.go index 12afea6..bc6055a 100644 --- a/pkg/api/mojang/client.go +++ b/pkg/api/mojang/client.go @@ -57,20 +57,20 @@ type Version struct { ReleaseTime time.Time `json:"releaseTime"` } +// Download is one file of a version +type Download struct { + SHA1 string `json:"sha1"` + Size int64 `json:"size"` + URL string `json:"url"` +} + // VersionDetail contains detailed information about a specific version type VersionDetail struct { ID string `json:"id"` Downloads struct { - Server struct { - SHA1 string `json:"sha1"` - Size int64 `json:"size"` - URL string `json:"url"` - } `json:"server"` - Client struct { - SHA1 string `json:"sha1"` - Size int64 `json:"size"` - URL string `json:"url"` - } `json:"client"` + Server Download `json:"server"` + ServerMappings Download `json:"server_mappings"` + Client Download `json:"client"` } `json:"downloads"` JavaVersion struct { Component string `json:"component"` @@ -108,6 +108,21 @@ func (c *Client) GetVersionDetail(ctx context.Context, versionURL string) (*Vers return &detail, nil } +// GetVersion fetches the details of the version id +func (c *Client) GetVersion(ctx context.Context, id string) (*VersionDetail, error) { + manifest, err := c.GetVersionManifest(ctx) + if err != nil { + return nil, err + } + + version := manifest.FindVersion(id) + if version == nil { + return nil, fmt.Errorf("minecraft version %s not found", id) + } + + return c.GetVersionDetail(ctx, version.URL) +} + // FindVersion finds a version by ID in the manifest func (m *VersionManifest) FindVersion(id string) *Version { for _, v := range m.Versions {