diff --git a/classic/cmd/eqoaadmin/classic.go b/classic/cmd/eqoaadmin/classic.go new file mode 100644 index 0000000..dbc6413 --- /dev/null +++ b/classic/cmd/eqoaadmin/classic.go @@ -0,0 +1,369 @@ +package main + +// classic.go — "eqoaadmin classic": the game's own rewards back where the +// Heirloom shards' Ascended gear took their place, for a classic shard. +// +// tools/ascend_boss_loot.py pointed the tuned raid bosses' loot (their tables' +// rows, their own category-pool rows, what they hold) at "Ascended" copies of +// their gear (a tenth more of every stat, table itemascended: copy -> base), +// and tools/ascended_epics_20261111.py pointed the level 49 and 60 epic +// rewards (queststeps.choices and byclass: each option's "items" and +// "spells"; rewarditems) at Ascended items and spells (spellascended), their +// answers worded "The Ascended ". This points every such reference back +// at its base and takes "Ascended " out of those answers. A record named +// "Ascended " that those tables do not list (older Ascended boss gear, +// the Ascended spell scrolls of Zaoran Plateau's spell table) counts as a copy +// of the one record named "", where there is exactly one. An option worded +// "Ascended " whose ids name no record at all (the open database's +// Necromancer epic: its six abilities' ids were never made) is given the one +// record of that name. The Ascended records themselves stay (nothing gives +// them any more; a character holding one keeps it). A second run finds +// nothing to do. + +import ( + "database/sql" + "encoding/json" + "fmt" + "regexp" + "strconv" + "strings" +) + +// classicReport is what a run changed. +type classicReport struct { + LootRows, PoolRows, HeldRows int + QuestSteps, QuestItems, QuestSpells int + Answers, ByName int + BadJSON []string +} + +func (r classicReport) total() int { + return r.LootRows + r.PoolRows + r.HeldRows + r.QuestSteps +} + +func (r classicReport) String() string { + return fmt.Sprintf("loot table rows %d, loot pool rows %d, held items %d; quest steps %d (%d item and %d spell rewards, %d found by name, %d answers reworded)", + r.LootRows, r.PoolRows, r.HeldRows, r.QuestSteps, r.QuestItems, r.QuestSpells, r.ByName, r.Answers) +} + +// catalog is what the restore reads: the Ascended copies' bases, every +// record's id, and the records that are not Ascended copies by name. +type catalog struct { + items, spells map[int64]int64 // Ascended copy -> base + itemIDs, spellIDs map[int64]bool + itemByName, spellByName map[string][]int64 +} + +var ( + digitsRe = regexp.MustCompile(`\d+`) + objectRe = regexp.MustCompile(`\{[^{}]*\}`) + idListRe = regexp.MustCompile(`"(items|spells)"(\s*:\s*)"([^"\\]*)"`) + answerRe = regexp.MustCompile(`"answer"(\s*:\s*)"((?:[^"\\]|\\.)*)"`) +) + +// restoreList puts each id of an id list ("980043, 709300", "718029*2") that +// m knows back at its base, keeping everything else as written. +func restoreList(s string, m map[int64]int64) (string, int) { + n := 0 + out := digitsRe.ReplaceAllStringFunc(s, func(d string) string { + id, err := strconv.ParseInt(d, 10, 64) + if err != nil { + return d + } + if base, ok := m[id]; ok { + n++ + return strconv.FormatInt(base, 10) + } + return d + }) + return out, n +} + +// allMissing reports whether a list names ids and none of them is a record. +func allMissing(list string, known map[int64]bool) bool { + ids := digitsRe.FindAllString(list, -1) + if len(ids) == 0 || known == nil { + return false + } + for _, d := range ids { + if id, err := strconv.ParseInt(d, 10, 64); err == nil && known[id] { + return false + } + } + return true +} + +// unAscended is an answer's name without the Ascended wording: "The Ascended +// Judgement" is "Judgement", "Ascended Blood Vortex" is "Blood Vortex". +func unAscended(answer string) string { + name := strings.TrimSpace(strings.ReplaceAll(answer, "Ascended ", "")) + return strings.TrimSpace(strings.TrimPrefix(name, "The ")) +} + +// restoreObject does one option ({"answer":..., "items":..., "spells":...}, a +// byclass entry): its ids back at their bases, an Ascended-worded option whose +// ids name no record given the one record of its name, and, where anything +// changed, "Ascended " out of its answer. +func restoreObject(obj string, c *catalog) (out string, nItems, nSpells, nAnswers, nByName int) { + answer := "" + if p := answerRe.FindStringSubmatch(obj); p != nil { + answer = p[2] + } + ascendedWords := strings.Contains(answer, "Ascended ") + out = idListRe.ReplaceAllStringFunc(obj, func(kv string) string { + p := idListRe.FindStringSubmatch(kv) + m, known, byName := c.items, c.itemIDs, c.itemByName + if p[1] == "spells" { + m, known, byName = c.spells, c.spellIDs, c.spellByName + } + v, n := restoreList(p[3], m) + if n == 0 && ascendedWords && allMissing(v, known) { + if ids := byName[unAscended(answer)]; len(ids) == 1 { + v = strconv.FormatInt(ids[0], 10) + n = 1 + nByName++ + } + } + if p[1] == "spells" { + nSpells += n + } else { + nItems += n + } + return `"` + p[1] + `"` + p[2] + `"` + v + `"` + }) + if nItems+nSpells == 0 { + return obj, 0, 0, 0, 0 + } + if ascendedWords { + out = answerRe.ReplaceAllStringFunc(out, func(kv string) string { + p := answerRe.FindStringSubmatch(kv) + nAnswers++ + return `"answer"` + p[1] + `"` + strings.ReplaceAll(p[2], "Ascended ", "") + `"` + }) + } + return out, nItems, nSpells, nAnswers, nByName +} + +// restoreJSON does restoreObject on every innermost object of a quest step's +// choices or byclass JSON. The text is edited in place, so nothing else +// changes. +func restoreJSON(s string, c *catalog) (out string, nItems, nSpells, nAnswers, nByName int) { + out = objectRe.ReplaceAllStringFunc(s, func(obj string) string { + o, i, sp, a, b := restoreObject(obj, c) + nItems += i + nSpells += sp + nAnswers += a + nByName += b + return o + }) + return out, nItems, nSpells, nAnswers, nByName +} + +func tableHas(tx *sql.Tx, table, column string) bool { + rows, err := tx.Query(`SELECT name FROM pragma_table_info(?)`, table) + if err != nil { + return false + } + defer rows.Close() + for rows.Next() { + var name string + if rows.Scan(&name) == nil && strings.EqualFold(name, column) { + return true + } + } + return false +} + +// ascendedMap reads copy -> base from table (itemascended, spellascended), +// keeping only bases that exist in their own table. +func ascendedMap(tx *sql.Tx, table, idCol, baseTable, baseCol string) (map[int64]int64, error) { + m := map[int64]int64{} + if !tableHas(tx, table, "base") || !tableHas(tx, baseTable, baseCol) { + return m, nil + } + q := fmt.Sprintf(`SELECT a.%s, a.base FROM %s a JOIN %s b ON b.%s = a.base`, idCol, table, baseTable, baseCol) + rows, err := tx.Query(q) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var id, base int64 + if err := rows.Scan(&id, &base); err != nil { + return nil, err + } + m[id] = base + } + return m, rows.Err() +} + +// records reads a record table's ids and, of the records that are no +// Ascended copy, their names; then it adds to copies each record named +// "Ascended " that copies does not list, as a copy of the one record +// named "" (none, or two of that name: left out). +func records(tx *sql.Tx, table, idCol, nameCol string, copies map[int64]int64) (map[int64]bool, map[string][]int64, error) { + ids, byName := map[int64]bool{}, map[string][]int64{} + if !tableHas(tx, table, idCol) || !tableHas(tx, table, nameCol) { + return nil, nil, nil + } + rows, err := tx.Query(fmt.Sprintf(`SELECT %s, COALESCE(%s, '') FROM %s`, idCol, nameCol, table)) + if err != nil { + return nil, nil, err + } + defer rows.Close() + unlisted := map[int64]string{} + for rows.Next() { + var id int64 + var name string + if err := rows.Scan(&id, &name); err != nil { + return nil, nil, err + } + ids[id] = true + name = strings.TrimSpace(name) + _, listed := copies[id] + switch { + case strings.HasPrefix(name, "Ascended "): + if !listed { + unlisted[id] = strings.TrimSpace(strings.TrimPrefix(name, "Ascended ")) + } + case !listed && name != "": + byName[name] = append(byName[name], id) + } + } + if err := rows.Err(); err != nil { + return nil, nil, err + } + for id, name := range unlisted { + if bases := byName[name]; len(bases) == 1 { + copies[id] = bases[0] + } + } + return ids, byName, nil +} + +// repoint sets column back to its base in every row of table holding a copy. +func repoint(tx *sql.Tx, table, column string, m map[int64]int64) (int, error) { + if len(m) == 0 || !tableHas(tx, table, column) { + return 0, nil + } + rows, err := tx.Query(fmt.Sprintf(`SELECT rowid, %s FROM %s WHERE %s IS NOT NULL`, column, table, column)) + if err != nil { + return 0, err + } + type change struct{ rowid, base int64 } + var todo []change + for rows.Next() { + var rowid int64 + var id sql.NullInt64 + if err := rows.Scan(&rowid, &id); err != nil { + rows.Close() + return 0, err + } + if base, ok := m[id.Int64]; ok && id.Valid { + todo = append(todo, change{rowid, base}) + } + } + rows.Close() + for _, c := range todo { + if _, err := tx.Exec(fmt.Sprintf(`UPDATE %s SET %s = ? WHERE rowid = ?`, table, column), c.base, c.rowid); err != nil { + return 0, err + } + } + return len(todo), nil +} + +// restoreClassic does the whole change in one transaction; dry leaves the +// database as it was and only reports. +func restoreClassic(db *sql.DB, dry bool) (classicReport, error) { + var r classicReport + tx, err := db.Begin() + if err != nil { + return r, err + } + defer tx.Rollback() + + c := &catalog{} + if c.items, err = ascendedMap(tx, "itemascended", "patternid", "itempattern", "patternid"); err != nil { + return r, fmt.Errorf("itemascended: %w", err) + } + if c.spells, err = ascendedMap(tx, "spellascended", "spellid", "spellpattern", "spellid"); err != nil { + return r, fmt.Errorf("spellascended: %w", err) + } + if c.itemIDs, c.itemByName, err = records(tx, "itempattern", "patternid", "itemname", c.items); err != nil { + return r, fmt.Errorf("itempattern: %w", err) + } + if c.spellIDs, c.spellByName, err = records(tx, "spellpattern", "spellid", "spellname", c.spells); err != nil { + return r, fmt.Errorf("spellpattern: %w", err) + } + if r.LootRows, err = repoint(tx, "loottables", "patternid", c.items); err != nil { + return r, fmt.Errorf("loottables: %w", err) + } + if r.PoolRows, err = repoint(tx, "lootpool", "patternid", c.items); err != nil { + return r, fmt.Errorf("lootpool: %w", err) + } + if r.HeldRows, err = repoint(tx, "npcheld", "patternid", c.items); err != nil { + return r, fmt.Errorf("npcheld: %w", err) + } + + if tableHas(tx, "queststeps", "choices") && tableHas(tx, "queststeps", "byclass") && tableHas(tx, "queststeps", "rewarditems") { + rows, err := tx.Query(`SELECT rowid, questid, step, COALESCE(rewarditems, ''), COALESCE(choices, ''), COALESCE(byclass, '') FROM queststeps`) + if err != nil { + return r, fmt.Errorf("queststeps: %w", err) + } + type change struct { + rowid int64 + column string + value string + } + var todo []change + for rows.Next() { + var rowid, quest, step int64 + var rewards, choices, byclass string + if err := rows.Scan(&rowid, &quest, &step, &rewards, &choices, &byclass); err != nil { + rows.Close() + return r, err + } + newRewards, ni := restoreList(rewards, c.items) + newChoices, ci, cs, ca, cb := restoreJSON(choices, c) + newByclass, bi, bs, ba, bb := restoreJSON(byclass, c) + if ni+ci+cs+bi+bs == 0 { + continue + } + bad := false + for _, j := range []string{newChoices, newByclass} { + if j != "" && !json.Valid([]byte(j)) { + bad = true + } + } + if bad { + r.BadJSON = append(r.BadJSON, fmt.Sprintf("quest %d step %d", quest, step)) + continue + } + r.QuestSteps++ + r.QuestItems += ni + ci + bi + r.QuestSpells += cs + bs + r.Answers += ca + ba + r.ByName += cb + bb + // only the columns that changed are written (an empty one stays as it is) + if newRewards != rewards { + todo = append(todo, change{rowid, "rewarditems", newRewards}) + } + if newChoices != choices { + todo = append(todo, change{rowid, "choices", newChoices}) + } + if newByclass != byclass { + todo = append(todo, change{rowid, "byclass", newByclass}) + } + } + rows.Close() + for _, ch := range todo { + if _, err := tx.Exec(fmt.Sprintf(`UPDATE queststeps SET %s = ? WHERE rowid = ?`, ch.column), ch.value, ch.rowid); err != nil { + return r, fmt.Errorf("queststeps: %w", err) + } + } + } + if dry { + return r, nil + } + return r, tx.Commit() +} diff --git a/classic/cmd/eqoaadmin/classic_test.go b/classic/cmd/eqoaadmin/classic_test.go new file mode 100644 index 0000000..446c86f --- /dev/null +++ b/classic/cmd/eqoaadmin/classic_test.go @@ -0,0 +1,138 @@ +package main + +import ( + "database/sql" + "encoding/json" + "path/filepath" + "testing" +) + +func testCatalog() *catalog { + return &catalog{ + items: map[int64]int64{980103: 1103, 980044: 1044}, + spells: map[int64]int64{906800: 6800}, + itemIDs: map[int64]bool{1103: true, 1044: true, 980103: true, 980044: true}, + spellIDs: map[int64]bool{6800: true, 906800: true, 700571: true}, + itemByName: map[string][]int64{"Judgement": {1103}}, + spellByName: map[string][]int64{"Blood Vortex": {700571}, "Twin": {1, 2}}, + } +} + +func TestRestoreJSON(t *testing.T) { + c := testCatalog() + + in := `{"ask":"Which weapon do you take?","options":[{"answer":"The Ascended Judgement","says":"It is yours.","items":"980103"},{"answer":"Withering Wind and the Ascended Spear of Fate","says":"It is yours.","items":"980044","spells":"906800"}]}` + out, ni, ns, na, nb := restoreJSON(in, c) + want := `{"ask":"Which weapon do you take?","options":[{"answer":"The Judgement","says":"It is yours.","items":"1103"},{"answer":"Withering Wind and the Spear of Fate","says":"It is yours.","items":"1044","spells":"6800"}]}` + if out != want || ni != 2 || ns != 1 || na != 2 || nb != 0 { + t.Fatalf("got %s (%d items, %d spells, %d answers, %d by name)\nwant %s", out, ni, ns, na, nb, want) + } + if !json.Valid([]byte(out)) { + t.Fatal("not JSON any more") + } + + // an id of the other kind is not touched: a spell id under "items" stays + in = `{"0":{"items":"906800, 980103"},"1":{"items":"980044*2"}}` + out, ni, ns, _, _ = restoreJSON(in, c) + if out != `{"0":{"items":"906800, 1103"},"1":{"items":"1044*2"}}` || ni != 2 || ns != 0 { + t.Fatalf("byclass: got %s (%d, %d)", out, ni, ns) + } + + // nothing Ascended: left byte for byte, its answers too + in = `{"options":[{"answer":"An Ascended Path","items":"1103"}]}` + if out, ni, ns, na, nb = restoreJSON(in, c); out != in || ni+ns+na+nb != 0 { + t.Fatalf("untouched JSON changed: %s", out) + } + + // an Ascended-worded option whose id names no record: the record of its + // name; a name two records share, or an id that exists, is left + in = `{"options":[{"answer":"Ascended Blood Vortex","spells":"906608"},{"answer":"Ascended Twin","spells":"906609"},{"answer":"Ascended Blood Vortex","spells":"6800"}]}` + out, _, ns, na, nb = restoreJSON(in, c) + want = `{"options":[{"answer":"Blood Vortex","spells":"700571"},{"answer":"Ascended Twin","spells":"906609"},{"answer":"Ascended Blood Vortex","spells":"6800"}]}` + if out != want || ns != 1 || na != 1 || nb != 1 { + t.Fatalf("by name: got %s (%d spells, %d answers, %d by name)\nwant %s", out, ns, na, nb, want) + } + + if out, n := restoreList("980043, 709300", map[int64]int64{980043: 43}); out != "43, 709300" || n != 1 { + t.Fatalf("list: %s %d", out, n) + } +} + +func TestRestoreClassicDB(t *testing.T) { + db, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "t.db")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for _, s := range []string{ + `CREATE TABLE itempattern (patternid INTEGER PRIMARY KEY, itemname TEXT)`, + `CREATE TABLE spellpattern (spellid INTEGER PRIMARY KEY, spellname TEXT)`, + `CREATE TABLE itemascended (patternid INTEGER PRIMARY KEY, base INTEGER NOT NULL UNIQUE, made TEXT, source TEXT)`, + `CREATE TABLE spellascended (spellid INTEGER PRIMARY KEY, base INTEGER NOT NULL, made TEXT, source TEXT)`, + `CREATE TABLE loottables (id INTEGER PRIMARY KEY, tablename TEXT, patternid INTEGER, weight INTEGER)`, + `CREATE TABLE lootpool (id INTEGER PRIMARY KEY, npc_name TEXT, patternid INTEGER)`, + `CREATE TABLE npcheld (npc_name TEXT, hand INTEGER, patternid INTEGER)`, + `CREATE TABLE queststeps (questid INTEGER, step INTEGER, rewarditems TEXT, choices TEXT, byclass TEXT)`, + `INSERT INTO itempattern VALUES (1, 'Sword'), (2, 'Shield'), (980001, 'Ascended Sword'), (980002, 'Ascended Shield'), (980003, 'Ascended Ghost')`, + // named Ascended but not listed: a copy of the one record of its name; + // a name two records share is left + `INSERT INTO itempattern VALUES (5677, 'Grimblade'), (966003, 'Ascended Grimblade'), (7, 'Twin'), (8, 'Twin'), (966004, 'Ascended Twin')`, + `INSERT INTO spellpattern VALUES (10, 'Fireball'), (906001, 'Ascended Fireball'), (11, 'Blood Vortex'), (906002, 'Ascended Blood Vortex')`, + // 980003's base (3) does not exist: left alone + `INSERT INTO itemascended VALUES (980001, 1, '', ''), (980002, 2, '', ''), (980003, 3, '', '')`, + `INSERT INTO spellascended VALUES (906001, 10, '', ''), (906002, 11, '', '')`, + `INSERT INTO loottables (tablename, patternid, weight) VALUES ('lord nagafen', 980001, 5), ('lord nagafen', 2, 5), ('lord nagafen', 980003, 1), ('boss megaladon', 966003, 1), ('boss megaladon', 966004, 1)`, + `INSERT INTO lootpool (npc_name, patternid) VALUES ('lord nagafen', 980002)`, + `INSERT INTO npcheld VALUES ('vallon zek', 0, 980001)`, + `INSERT INTO queststeps VALUES (1, 2, '980001, 7', NULL, NULL)`, + `INSERT INTO queststeps VALUES (2, 1, '', '{"options":[{"answer":"The Ascended Sword","items":"980001","spells":"906001"}]}', NULL)`, + `INSERT INTO queststeps VALUES (3, 1, '', NULL, '{"0":{"items":"980002*2"}}')`, + // the Necromancer's case: an id no record has, the answer naming the spell + `INSERT INTO queststeps VALUES (4, 1, '', '{"options":[{"answer":"Ascended Blood Vortex","spells":"906608"}]}', NULL)`, + } { + if _, err := db.Exec(s); err != nil { + t.Fatalf("%s: %v", s, err) + } + } + + r, err := restoreClassic(db, true) + if err != nil || r.LootRows != 2 || r.PoolRows != 1 || r.HeldRows != 1 || r.QuestSteps != 4 { + t.Fatalf("dry run: %+v %v", r, err) + } + var id int64 + db.QueryRow(`SELECT patternid FROM npcheld`).Scan(&id) + if id != 980001 { + t.Fatal("the dry run wrote") + } + + r, err = restoreClassic(db, false) + if err != nil || r.QuestItems != 3 || r.QuestSpells != 2 || r.Answers != 2 || r.ByName != 1 { + t.Fatalf("run: %+v %v", r, err) + } + check := func(q, want string) { + t.Helper() + var got sql.NullString + if err := db.QueryRow(q).Scan(&got); err != nil { + t.Fatalf("%s: %v", q, err) + } + if got.String != want { + t.Fatalf("%s: got %q, want %q", q, got.String, want) + } + } + check(`SELECT group_concat(patternid, ',') FROM (SELECT patternid FROM loottables ORDER BY id)`, "1,2,980003,5677,966004") + check(`SELECT patternid FROM lootpool`, "2") + check(`SELECT patternid FROM npcheld`, "1") + check(`SELECT rewarditems FROM queststeps WHERE questid = 1`, "1, 7") + check(`SELECT choices FROM queststeps WHERE questid = 2`, `{"options":[{"answer":"The Sword","items":"1","spells":"10"}]}`) + check(`SELECT byclass FROM queststeps WHERE questid = 3`, `{"0":{"items":"2*2"}}`) + check(`SELECT choices FROM queststeps WHERE questid = 4`, `{"options":[{"answer":"Blood Vortex","spells":"11"}]}`) + var nulls int + db.QueryRow(`SELECT count(*) FROM queststeps WHERE (questid = 1 AND choices IS NULL AND byclass IS NULL) OR (questid = 3 AND choices IS NULL)`).Scan(&nulls) + if nulls != 2 { + t.Fatalf("an empty column was written (%d left NULL, want 2)", nulls) + } + + if r, err = restoreClassic(db, false); err != nil || r.total() != 0 { + t.Fatalf("a second run changed something: %+v %v", r, err) + } +} diff --git a/classic/cmd/eqoaadmin/main.go b/classic/cmd/eqoaadmin/main.go new file mode 100644 index 0000000..92ba968 --- /dev/null +++ b/classic/cmd/eqoaadmin/main.go @@ -0,0 +1,204 @@ +// Command eqoaadmin is a small account and backup tool for a server's +// database, for hosts with no sqlite3 shell (the Windows package's +// "Server Control" menu runs it). It writes beside a running server safely: +// the database is in WAL mode and every statement waits for its lock. +// +// eqoaadmin -db eqoa.db list +// eqoaadmin -db eqoa.db gm NAME [LEVEL] (LEVEL 2: admin, 1: GM, 0: player) +// eqoaadmin -db eqoa.db create NAME PASSWORD [LEVEL] +// eqoaadmin -db eqoa.db password NAME NEWPASSWORD +// eqoaadmin -db eqoa.db classic [-dry-run] (Ascended rewards back to the game's own: classic.go) +// eqoaadmin -db eqoa.db backup FILE (a consistent copy, VACUUM INTO) +package main + +import ( + "database/sql" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/eqoa/server/internal/auth" + "github.com/eqoa/server/internal/database" + _ "modernc.org/sqlite" +) + +func main() { + dbPath := flag.String("db", "eqoa.db", "the server's database") + cost := flag.Int("cost", 10, "bcrypt cost for new passwords (the server's auth.bcrypt_cost)") + flag.Usage = func() { + fmt.Fprintln(os.Stderr, `usage: eqoaadmin [-db eqoa.db] COMMAND + list accounts and their levels + gm NAME [LEVEL] set an account's level (2 admin, 1 GM, 0 player; default 2) + create NAME PASSWORD [LEVEL] make an account (default level 0) + password NAME NEWPASSWORD set an account's password + classic [-dry-run] the game's own raid loot and epic rewards in place of Ascended gear + backup FILE write a consistent copy of the database`) + } + flag.Parse() + args := flag.Args() + if len(args) == 0 { + flag.Usage() + os.Exit(2) + } + if _, err := os.Stat(*dbPath); err != nil { + fail("database %s: %v", *dbPath, err) + } + raw, err := sql.Open("sqlite", *dbPath+"?"+database.BusyTimeoutDSN) + if err != nil { + fail("open %s: %v", *dbPath, err) + } + defer raw.Close() + raw.SetMaxOpenConns(1) + db := &database.SQLiteDB{DB: raw} + accounts := database.NewSQLiteAccountStore(db) + + switch cmd := strings.ToLower(args[0]); cmd { + case "list": + rows, err := raw.Query(`SELECT username, COALESCE(acctlevel, 0), COALESCE(acctstatus, 0), + COALESCE(CAST(lastlogin AS TEXT), '') FROM accountinfo ORDER BY COALESCE(acctlevel, 0) DESC, username`) + if err != nil { + fail("list: %v", err) + } + defer rows.Close() + fmt.Printf("%-24s %-6s %-8s %s\n", "ACCOUNT", "LEVEL", "STATUS", "LAST LOGIN") + n := 0 + for rows.Next() { + var name, last string + var level, status int + if err := rows.Scan(&name, &level, &status, &last); err != nil { + fail("list: %v", err) + } + st := "active" + switch { + case status < 0: + st = "banned" + case status == 0: + st = "inactive" + } + fmt.Printf("%-24s %-6d %-8s %s\n", name, level, st, last) + n++ + } + fmt.Printf("%d account(s)\n", n) + + case "gm": + need(args, 2, "gm NAME [LEVEL]") + level := 2 + if len(args) > 2 { + level = atoi(args[2]) + } + a, err := accounts.GetByUsername(args[1]) + if err != nil { + fail("no account %q (log in with it once, or use create): %v", args[1], err) + } + if _, err := raw.Exec(`UPDATE accountinfo SET acctlevel = ? WHERE accountid = ?`, level, a.ID); err != nil { + fail("gm: %v", err) + } + fmt.Printf("%s is now level %d\n", a.Username, level) + + case "create": + need(args, 3, "create NAME PASSWORD [LEVEL]") + level := 0 + if len(args) > 3 { + level = atoi(args[3]) + } + if _, err := accounts.GetByUsername(args[1]); err == nil { + fail("account %q already exists", args[1]) + } else if !errors.Is(err, database.ErrAccountNotFound) { + fail("create: %v", err) + } + hash, err := auth.HashPassword(args[2], *cost) + if err != nil { + fail("hash: %v", err) + } + a, err := accounts.Create(args[1], hash) + if err != nil { + fail("create: %v", err) + } + if _, err := raw.Exec(`UPDATE accountinfo SET acctlevel = ? WHERE accountid = ?`, level, a.ID); err != nil { + fail("create: level: %v", err) + } + fmt.Printf("created %s (level %d)\n", a.Username, level) + + case "password": + need(args, 3, "password NAME NEWPASSWORD") + a, err := accounts.GetByUsername(args[1]) + if err != nil { + fail("no account %q: %v", args[1], err) + } + hash, err := auth.HashPassword(args[2], *cost) + if err != nil { + fail("hash: %v", err) + } + if err := accounts.UpdatePasswordHash(a.ID, hash); err != nil { + fail("password: %v", err) + } + fmt.Printf("password of %s changed\n", a.Username) + + case "classic": + dry := len(args) > 1 && (args[1] == "-dry-run" || args[1] == "--dry-run") + r, err := restoreClassic(raw, dry) + if err != nil { + fail("classic: %v", err) + } + for _, b := range r.BadJSON { + fmt.Printf("left as it was (its rewards would not read back): %s\n", b) + } + switch { + case r.total() == 0: + fmt.Println("classic rewards: nothing to restore (already classic)") + case dry: + fmt.Printf("classic rewards (dry run, nothing written): %s\n", r) + default: + fmt.Printf("classic rewards restored: %s\n", r) + } + + case "backup": + need(args, 2, "backup FILE") + out, err := filepath.Abs(args[1]) + if err != nil { + fail("backup: %v", err) + } + if _, err := os.Stat(out); err == nil { + fail("backup: %s already exists", out) + } + if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil { + fail("backup: %v", err) + } + if _, err := raw.Exec(`VACUUM INTO ?`, out); err != nil { + fail("backup: %v", err) + } + fi, _ := os.Stat(out) + size := int64(0) + if fi != nil { + size = fi.Size() + } + fmt.Printf("backup written: %s (%d MB)\n", out, size>>20) + + default: + flag.Usage() + os.Exit(2) + } +} + +func need(args []string, n int, usage string) { + if len(args) < n { + fail("usage: eqoaadmin %s", usage) + } +} + +func atoi(s string) int { + n, err := strconv.Atoi(s) + if err != nil || n < 0 || n > 9 { + fail("level %q: a number 0-9", s) + } + return n +} + +func fail(format string, args ...any) { + fmt.Fprintf(os.Stderr, "eqoaadmin: "+format+"\n", args...) + os.Exit(1) +} diff --git a/classic/cmd/eqoacheck/main.go b/classic/cmd/eqoacheck/main.go new file mode 100644 index 0000000..e66e3cd --- /dev/null +++ b/classic/cmd/eqoacheck/main.go @@ -0,0 +1,262 @@ +// Command eqoacheck walks the path a browser player's game takes, from the +// outside, and says what works: the site's pages, the patch files, and through +// the web relay's WebSockets the login server (a real login, when an account is +// given), the patch server's HTTP and the game server's first DRDP answer. +// +// eqoacheck -url https://play.example.org -server 203.0.113.10 [-user NAME -pass PASSWORD] +// +// The Windows package's installer runs it once everything is started. +package main + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/binary" + "errors" + "flag" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "os" + "strings" + "time" + + "github.com/coder/websocket" + "github.com/eqoa/pkg/pkg/buffer" + "github.com/eqoa/server/internal/network/tcp" + "github.com/eqoa/server/internal/protocol" +) + +func main() { + base := flag.String("url", "", "the site's address, e.g. https://play.example.org") + server := flag.String("server", "", "the game server's address as the server list names it (server.server_ip)") + user := flag.String("user", "", "an account to log in with (optional)") + pass := flag.String("pass", "", "its password") + insecure := flag.Bool("insecure", false, "accept any HTTPS certificate (a test)") + connect := flag.String("connect", "", "reach the site at this address instead of the one its name resolves to (e.g. 127.0.0.1 on the server itself; the certificate is still checked for the name)") + flag.Parse() + if *connect != "" { + http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + _, port, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + return (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, network, net.JoinHostPort(*connect, port)) + } + } + if *insecure { + http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + } + if *base == "" || *server == "" { + fmt.Fprintln(os.Stderr, "usage: eqoacheck -url https://HOST -server IP [-user NAME -pass PASSWORD]") + os.Exit(2) + } + site := strings.TrimRight(*base, "/") + ip, err := netip.ParseAddr(*server) + if err != nil || !ip.Is4() { + fmt.Fprintf(os.Stderr, "-server %q: an IPv4 address\n", *server) + os.Exit(2) + } + hc := &http.Client{Timeout: 20 * time.Second} + ws := "ws" + strings.TrimPrefix(site, "http") + "/eqoa/relay" + origin := site + + failed := 0 + step := func(name string, fn func() (string, error)) { + detail, err := fn() + if err != nil { + failed++ + fmt.Printf("FAIL %-34s %v\n", name, err) + return + } + fmt.Printf("OK %-34s %s\n", name, detail) + } + + step("players' page", func() (string, error) { return get(hc, site+"/", "") }) + step("browser game page", func() (string, error) { return get(hc, site+"/eqoa/play/", "main.js") }) + step("patch files (https)", func() (string, error) { + return get(hc, site+"/patch/eqoa/eqoa-frontierslive-update.xml.gz", "") + }) + step("relay -> login server", func() (string, error) { + return relayLogin(ws, origin, *insecure, ip, *user, *pass) + }) + step("relay -> patch server", func() (string, error) { return relayPatch(ws, origin, *insecure, ip) }) + step("relay -> game server (UDP)", func() (string, error) { return relayGame(ws, origin, *insecure, ip) }) + + if failed > 0 { + fmt.Printf("%d check(s) failed\n", failed) + os.Exit(1) + } + fmt.Println("all checks passed: browser players can reach the game") +} + +func get(hc *http.Client, url, want string) (string, error) { + r, err := hc.Get(url) + if err != nil { + return "", err + } + defer r.Body.Close() + body, _ := io.ReadAll(io.LimitReader(r.Body, 4<<20)) + if r.StatusCode != http.StatusOK { + return "", fmt.Errorf("HTTP %d", r.StatusCode) + } + if want != "" && !bytes.Contains(body, []byte(want)) { + return "", fmt.Errorf("the page does not mention %q", want) + } + return fmt.Sprintf("HTTP 200, %d bytes", len(body)), nil +} + +func dial(ctx context.Context, url, origin string, _ bool) (*websocket.Conn, error) { + // http.DefaultTransport carries -connect and -insecure + opts := &websocket.DialOptions{HTTPHeader: http.Header{"Origin": {origin}}, HTTPClient: &http.Client{Transport: http.DefaultTransport}} + c, _, err := websocket.Dial(ctx, url, opts) + if err != nil { + return nil, err + } + c.SetReadLimit(1 << 20) + typ, m, err := c.Read(ctx) + if err != nil { + c.CloseNow() + return nil, err + } + if typ != websocket.MessageText || !strings.HasPrefix(string(m), "ok ") { + c.CloseNow() + return nil, fmt.Errorf("relay said %q", m) + } + return c, nil +} + +// readN reads n bytes of a relayed TCP stream (its binary messages). +func readN(ctx context.Context, c *websocket.Conn, n int, have []byte) ([]byte, []byte, error) { + for len(have) < n { + typ, m, err := c.Read(ctx) + if err != nil { + return nil, nil, err + } + if typ == websocket.MessageBinary { + have = append(have, m...) + } + } + return have[:n], have[n:], nil +} + +func relayLogin(ws, origin string, insecure bool, ip netip.Addr, user, pass string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + c, err := dial(ctx, fmt.Sprintf("%s/tcp?host=%s&port=9735", ws, ip), origin, insecure) + if err != nil { + return "", err + } + defer c.CloseNow() + hello, rest, err := readN(ctx, c, 40, nil) + if err != nil { + return "", fmt.Errorf("no server hello: %w", err) + } + if op := binary.BigEndian.Uint32(hello[4:8]); op != 0x04 { + return "", fmt.Errorf("server hello opcode 0x%02X", op) + } + if user == "" { + return "server hello received (no account given: login not tried)", nil + } + packet := make([]byte, 148) + binary.BigEndian.PutUint32(packet[0:4], 148) + binary.BigEndian.PutUint32(packet[4:8], 0x24) + binary.BigEndian.PutUint32(packet[12:16], 2) + copy(packet[16:48], user) + field, err := tcp.EncryptPasswordField(pass) + if err != nil { + return "", err + } + copy(packet[48:80], field) + binary.BigEndian.PutUint32(packet[80:84], 1) + copy(packet[84:88], "EQOA") + if err := c.Write(ctx, websocket.MessageBinary, packet); err != nil { + return "", err + } + resp, _, err := readN(ctx, c, 168, rest) + if err != nil { + return "", fmt.Errorf("no login answer: %w", err) + } + if op := binary.BigEndian.Uint32(resp[4:8]); op != 0x25 { + return "", fmt.Errorf("login answer opcode 0x%02X", op) + } + if flagErr, status := binary.BigEndian.Uint32(resp[8:12]), binary.BigEndian.Uint32(resp[84:88]); flagErr != 0 || status != 3 { + return "", fmt.Errorf("login of %q refused (error %d, status %d)", user, flagErr, status) + } + return fmt.Sprintf("logged in as %s", user), nil +} + +func relayPatch(ws, origin string, insecure bool, ip netip.Addr) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + c, err := dial(ctx, fmt.Sprintf("%s/tcp?host=%s&port=7000", ws, ip), origin, insecure) + if err != nil { + return "", err + } + defer c.CloseNow() + req := fmt.Sprintf("GET /patch/eqoa/eqoa-frontierslive-update.xml.gz HTTP/1.0\r\nHost: %s\r\n\r\n", ip) + if err := c.Write(ctx, websocket.MessageBinary, []byte(req)); err != nil { + return "", err + } + head, _, err := readN(ctx, c, 12, nil) + if err != nil { + return "", fmt.Errorf("no answer: %w", err) + } + if !bytes.HasPrefix(head, []byte("HTTP/1.")) || !bytes.Contains(head, []byte(" 200")) { + return "", fmt.Errorf("answer %q", head) + } + return "HTTP 200", nil +} + +// relayGame sends the game server the first packet of a DRDP session (as +// cmd/testclient does) through the relay's UDP socket and waits for its answer. +func relayGame(ws, origin string, insecure bool, ip netip.Addr) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + c, err := dial(ctx, ws+"/udp", origin, insecure) + if err != nil { + return "", err + } + defer c.CloseNow() + const clientID, serverID, instance = 0x7384, 0xFFFE, 0x73FD6058 + buf := make([]byte, 0x530) + w := buffer.NewWriter(buf) + w.WriteUint16(clientID) + w.WriteUint16(serverID) + flags := uint64(protocol.SegmentFlagNewInstance) | uint64(protocol.SegmentFlagHasInstance) | uint64(protocol.SegmentFlagClientInitiated) + w.Write7BitEncodedUInt64(flags | 7) + w.WriteUint32(instance) + w.WriteByte(byte(protocol.BodyFlagSessionAck | protocol.BodyFlagRdpMessage)) + w.WriteUint32(instance) + w.WriteUint16(1) + packet := protocol.AppendCRC(w.Bytes()) + + to := netip.AddrPortFrom(ip, 10070) + a := to.Addr().As4() + msg := append([]byte{a[0], a[1], a[2], a[3], byte(to.Port() >> 8), byte(to.Port())}, packet...) + // sent twice, a moment apart, in case one datagram is lost (a cancelled + // read closes the WebSocket, so there is no resending after a timeout) + for try := 0; try < 2; try++ { + if err := c.Write(ctx, websocket.MessageBinary, msg); err != nil { + return "", err + } + time.Sleep(150 * time.Millisecond) + } + rctx, done := context.WithTimeout(ctx, 10*time.Second) + defer done() + for { + typ, m, err := c.Read(rctx) + if err != nil { + if rctx.Err() != nil { + return "", errors.New("no answer from the game server's UDP port in 10 s") + } + return "", err + } + if typ == websocket.MessageBinary && len(m) > 6 && bytes.Equal(m[:6], msg[:6]) { + return fmt.Sprintf("the game server answered (%d bytes)", len(m)-6), nil + } + } +} diff --git a/classic/cmd/eqoaservice/main.go b/classic/cmd/eqoaservice/main.go new file mode 100644 index 0000000..02a1299 --- /dev/null +++ b/classic/cmd/eqoaservice/main.go @@ -0,0 +1,385 @@ +//go:build windows + +// Command eqoaservice runs one of a Windows server's programs (the game +// server, the web relay, the web server) as a Windows service: started with +// the machine, started again if it stops on its own, its output kept in a log +// that is rolled over, and stopped GRACEFULLY. The game server saves every +// character when it is interrupted (main.go: SIGINT), and a Windows program +// can only be interrupted by a console control event from a process sharing +// its console, which a service has none of: this one makes a console, starts +// the program in a process group of its own on it, and sends that group +// CTRL_BREAK at a stop, killing it only if it has not ended in -stop-wait. +// +// eqoaservice install -name NAME -display TEXT [-desc TEXT] -dir DIR -log FILE [-stop-wait 60s] -- PROGRAM [ARGS...] +// eqoaservice remove -name NAME +// eqoaservice console -dir DIR -log FILE [-stop-after 30s] -- PROGRAM [ARGS...] (the same, in the foreground: a test) +// eqoaservice run ... (what the service manager runs; made by install) +package main + +import ( + "errors" + "flag" + "fmt" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strings" + "sync" + "syscall" + "time" + + "golang.org/x/sys/windows" + "golang.org/x/sys/windows/svc" + "golang.org/x/sys/windows/svc/mgr" +) + +// opts is what install, run and console share. +type opts struct { + name, display, desc string + dir, log string + stopWait, stopAfter time.Duration + argv []string +} + +func parse(cmd string, args []string) opts { + var o opts + fs := flag.NewFlagSet(cmd, flag.ExitOnError) + fs.StringVar(&o.name, "name", "", "the service's name") + fs.StringVar(&o.display, "display", "", "the service's display name") + fs.StringVar(&o.desc, "desc", "", "the service's description") + fs.StringVar(&o.dir, "dir", "", "the program's working folder") + fs.StringVar(&o.log, "log", "", "the log file the program's output goes to") + fs.DurationVar(&o.stopWait, "stop-wait", 60*time.Second, "how long a stop waits for the program to end by itself") + fs.DurationVar(&o.stopAfter, "stop-after", 0, "console: stop after this long (a test)") + _ = fs.Parse(args) + o.argv = fs.Args() + if len(o.argv) > 0 && o.argv[0] == "--" { + o.argv = o.argv[1:] + } + return o +} + +func main() { + if len(os.Args) < 2 { + usage() + } + cmd, rest := os.Args[1], os.Args[2:] + var err error + switch cmd { + case "install": + err = install(parse(cmd, rest)) + case "remove": + err = remove(parse(cmd, rest).name) + case "run": + o := parse(cmd, rest) + err = svc.Run(o.name, &service{o: o}) + case "console": + err = console(parse(cmd, rest)) + default: + usage() + } + if err != nil { + fmt.Fprintf(os.Stderr, "eqoaservice %s: %v\n", cmd, err) + os.Exit(1) + } +} + +func usage() { + fmt.Fprintln(os.Stderr, `usage: + eqoaservice install -name NAME -display TEXT [-desc TEXT] -dir DIR -log FILE [-stop-wait 60s] -- PROGRAM [ARGS...] + eqoaservice remove -name NAME + eqoaservice console -dir DIR -log FILE [-stop-after 30s] -- PROGRAM [ARGS...]`) + os.Exit(2) +} + +func check(o opts, needName bool) error { + if needName && o.name == "" { + return errors.New("-name is needed") + } + if o.dir == "" || o.log == "" || len(o.argv) == 0 { + return errors.New("-dir, -log and the program after -- are needed") + } + return nil +} + +// install registers the service: started with the machine, as LocalSystem, +// started again by the service manager if this wrapper itself should end. +func install(o opts) error { + if err := check(o, true); err != nil { + return err + } + self, err := os.Executable() + if err != nil { + return err + } + m, err := mgr.Connect() + if err != nil { + return fmt.Errorf("the service manager (run as administrator): %w", err) + } + defer m.Disconnect() + if s, err := m.OpenService(o.name); err == nil { + s.Close() + return fmt.Errorf("service %s already exists (remove it first)", o.name) + } + args := []string{"run", "-name", o.name, "-dir", o.dir, "-log", o.log, "-stop-wait", o.stopWait.String(), "--"} + args = append(args, o.argv...) + display := o.display + if display == "" { + display = o.name + } + s, err := m.CreateService(o.name, self, mgr.Config{ + DisplayName: display, + Description: o.desc, + StartType: mgr.StartAutomatic, + }, args...) + if err != nil { + return err + } + defer s.Close() + restart := mgr.RecoveryAction{Type: mgr.ServiceRestart, Delay: 10 * time.Second} + if err := s.SetRecoveryActions([]mgr.RecoveryAction{restart, restart, restart}, 24*60*60); err != nil { + return fmt.Errorf("recovery actions: %w", err) + } + fmt.Printf("service %s installed\n", o.name) + return nil +} + +// remove stops the service (gracefully, as a stop always is) and deletes it. +func remove(name string) error { + if name == "" { + return errors.New("-name is needed") + } + m, err := mgr.Connect() + if err != nil { + return fmt.Errorf("the service manager (run as administrator): %w", err) + } + defer m.Disconnect() + s, err := m.OpenService(name) + if err != nil { + fmt.Printf("service %s is not installed\n", name) + return nil + } + defer s.Close() + if st, err := s.Query(); err == nil && st.State != svc.Stopped { + if _, err := s.Control(svc.Stop); err == nil { + deadline := time.Now().Add(2 * time.Minute) + for time.Now().Before(deadline) { + if st, err := s.Query(); err != nil || st.State == svc.Stopped { + break + } + time.Sleep(500 * time.Millisecond) + } + } + } + if err := s.Delete(); err != nil { + return err + } + fmt.Printf("service %s removed\n", name) + return nil +} + +// service is the service manager's handler. +type service struct{ o opts } + +func (h *service) Execute(_ []string, r <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) { + const accepts = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPreShutdown + status <- svc.Status{State: svc.StartPending} + if err := check(h.o, false); err != nil { + return true, 1 + } + ensureConsole() + sup := newSupervisor(h.o) + go sup.loop() + status <- svc.Status{State: svc.Running, Accepts: accepts} + for c := range r { + switch c.Cmd { + case svc.Interrogate: + status <- c.CurrentStatus + case svc.Stop, svc.Shutdown, svc.PreShutdown: + wait := h.o.stopWait + status <- svc.Status{State: svc.StopPending, WaitHint: uint32((wait + 15*time.Second) / time.Millisecond)} + sup.stop(wait) + return false, 0 + } + } + return false, 0 +} + +// console runs the same supervisor in the foreground until Ctrl+C or +// -stop-after: how the graceful stop is tried without installing anything. +func console(o opts) error { + if err := check(o, false); err != nil { + return err + } + ensureConsole() + sup := newSupervisor(o) + go sup.loop() + interrupt := make(chan os.Signal, 1) + signal.Notify(interrupt, os.Interrupt) + var after <-chan time.Time + if o.stopAfter > 0 { + after = time.After(o.stopAfter) + } + select { + case <-interrupt: + case <-after: + } + fmt.Println("eqoaservice: stopping") + sup.stop(o.stopWait) + fmt.Println("eqoaservice: stopped") + return nil +} + +var ( + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + procAllocConsole = kernel32.NewProc("AllocConsole") + procGetConsoleWn = kernel32.NewProc("GetConsoleWindow") + user32 = windows.NewLazySystemDLL("user32.dll") + procShowWindow = user32.NewProc("ShowWindow") +) + +// ensureConsole gives this process a console if it has none (a service has +// none), hidden: the program shares it, and a console control event reaches +// it only through one. +func ensureConsole() { + if w, _, _ := procGetConsoleWn.Call(); w != 0 { + return + } + procAllocConsole.Call() + if w, _, _ := procGetConsoleWn.Call(); w != 0 { + procShowWindow.Call(w, 0) // SW_HIDE + } +} + +// supervisor keeps one program running. +type supervisor struct { + o opts + mu sync.Mutex + cmd *exec.Cmd + quit chan struct{} + done chan struct{} + closed bool +} + +func newSupervisor(o opts) *supervisor { + return &supervisor{o: o, quit: make(chan struct{}), done: make(chan struct{})} +} + +func (s *supervisor) loop() { + defer close(s.done) + backoff := 2 * time.Second + for { + select { + case <-s.quit: + return + default: + } + f, err := openLog(s.o.log) + if err != nil { + f = nil + } + note := func(format string, args ...any) { + if f != nil { + fmt.Fprintf(f, "=== %s eqoaservice: %s\n", time.Now().Format("2006-01-02 15:04:05"), fmt.Sprintf(format, args...)) + } + } + cmd := exec.Command(s.o.argv[0], s.o.argv[1:]...) + cmd.Dir = s.o.dir + if f != nil { + cmd.Stdout, cmd.Stderr = f, f + } + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: syscall.CREATE_NEW_PROCESS_GROUP} + note("starting %s", strings.Join(s.o.argv, " ")) + s.mu.Lock() + if s.closed { + s.mu.Unlock() + closeFile(f) + return + } + err = cmd.Start() + if err == nil { + s.cmd = cmd + } + s.mu.Unlock() + started := time.Now() + if err != nil { + note("could not start: %v", err) + } else { + err = cmd.Wait() + note("ended after %s: %v", time.Since(started).Round(time.Second), exitText(err)) + } + s.mu.Lock() + s.cmd = nil + s.mu.Unlock() + closeFile(f) + if time.Since(started) > 2*time.Minute { + backoff = 2 * time.Second + } else if backoff < time.Minute { + backoff *= 2 + } + select { + case <-s.quit: + return + case <-time.After(backoff): + } + } +} + +// stop ends the program gracefully (CTRL_BREAK to its process group), or +// kills it after wait, and keeps it from being started again. +func (s *supervisor) stop(wait time.Duration) { + s.mu.Lock() + if !s.closed { + s.closed = true + close(s.quit) + } + cmd := s.cmd + s.mu.Unlock() + if cmd != nil && cmd.Process != nil { + if err := windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(cmd.Process.Pid)); err != nil { + cmd.Process.Kill() + } + select { + case <-s.done: + return + case <-time.After(wait): + cmd.Process.Kill() + } + } + select { + case <-s.done: + case <-time.After(10 * time.Second): + } +} + +func exitText(err error) string { + if err == nil { + return "exit 0" + } + return err.Error() +} + +func closeFile(f *os.File) { + if f != nil { + f.Close() + } +} + +// openLog opens the log for appending, rolling it over first past 20 MB +// (log.1 ... log.3 kept). +func openLog(path string) (*os.File, error) { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return nil, err + } + if fi, err := os.Stat(path); err == nil && fi.Size() > 20<<20 { + ext := filepath.Ext(path) + base := strings.TrimSuffix(path, ext) + os.Remove(fmt.Sprintf("%s.3%s", base, ext)) + for i := 2; i >= 1; i-- { + os.Rename(fmt.Sprintf("%s.%d%s", base, i, ext), fmt.Sprintf("%s.%d%s", base, i+1, ext)) + } + os.Rename(path, fmt.Sprintf("%s.1%s", base, ext)) + } + return os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) +} diff --git a/classic/cmd/eqoaservice/main_other.go b/classic/cmd/eqoaservice/main_other.go new file mode 100644 index 0000000..2a5053a --- /dev/null +++ b/classic/cmd/eqoaservice/main_other.go @@ -0,0 +1,15 @@ +//go:build !windows + +// Command eqoaservice is the Windows service wrapper (main.go); elsewhere the +// system's own service manager (systemd: README) does its work. +package main + +import ( + "fmt" + "os" +) + +func main() { + fmt.Fprintln(os.Stderr, "eqoaservice runs on Windows only; use systemd (README, \"Run it\")") + os.Exit(1) +} diff --git a/upstream/cmd/gameserver/main.go b/classic/cmd/gameserver/main.go index 0492712..8f86935 100644 --- a/upstream/cmd/gameserver/main.go +++ b/classic/cmd/gameserver/main.go @@ -806,6 +806,11 @@ func main() { if cfg.World.VanillaUI { log.Printf("Vanilla UI: no quality-of-life additions (world.vanilla_ui)") } + // with it, the map, minimap and item links locked off (world.lock_map) + handlers.SetLockMap(cfg.World.LockMap) + if cfg.World.VanillaUI && cfg.World.LockMap { + log.Printf("Lock map: the map, minimap and item links are locked off (world.lock_map)") + } // [OG] characters: chosen when new, the game's own UI for their sessions, // drawn "[OG] Name" (handlers/ogaccount.go, database/ogchar.go) handlers.SetOGAccounts(cfg.World.OGAccounts) diff --git a/upstream/cmd/wsrelay/README.md b/classic/cmd/wsrelay/README.md index 4fd66ea..c1bbcc2 100644 --- a/upstream/cmd/wsrelay/README.md +++ b/classic/cmd/wsrelay/README.md @@ -50,6 +50,7 @@ entry is the client's to choose). From any other peer the headers are ignored. | `-tcp-idle` | `10m` | A TCP connection idle this long is closed. | | `-ping` | `30s` | WebSocket pings that notice a client gone silent (a browser answers them itself; the page never sees them). `0` turns them off. | | `-lookup` | off | Also serve `GET /client?port=N` on this address: the client address behind one of the relay's local ports (a UDP socket's or a TCP connection's), 404 for one it does not hold. For the game server's one-login rule (`auth.relay_lookup`). It names players' addresses: **loopback only**, never behind the public proxy. | +| `-via` | none | `PUBLIC=LOCAL`, repeatable: what the page sends to `PUBLIC` goes to `LOCAL`, and what `LOCAL` sends back is shown to the page as from `PUBLIC`. On the game server's own machine, `-via =127.0.0.1` keeps the relay's traffic on loopback, for a cloud VM behind 1:1 NAT whose public address is not on its network card. The allow lists still name `PUBLIC`. | | `-v` | off | Also log dropped datagrams and failed handshakes. | It logs one line per socket opened, refused and closed: the client, the target diff --git a/upstream/cmd/wsrelay/main.go b/classic/cmd/wsrelay/main.go index 0a9d222..ce49ef5 100644 --- a/upstream/cmd/wsrelay/main.go +++ b/classic/cmd/wsrelay/main.go @@ -12,6 +12,7 @@ import ( "fmt" "log" "net/http" + "net/netip" "os" "strings" "time" @@ -19,6 +20,21 @@ import ( "github.com/eqoa/server/internal/wsrelay" ) +// parseVia reads -via's PUBLIC=LOCAL pairs (both IPv4 addresses). +func parseVia(pairs []string) (map[netip.Addr]netip.Addr, error) { + via := map[netip.Addr]netip.Addr{} + for _, p := range pairs { + from, to, ok := strings.Cut(p, "=") + a, aerr := netip.ParseAddr(strings.TrimSpace(from)) + b, berr := netip.ParseAddr(strings.TrimSpace(to)) + if !ok || aerr != nil || berr != nil || !a.Is4() || !b.Is4() { + return nil, fmt.Errorf("-via %q: want PUBLIC=LOCAL, two IPv4 addresses (203.0.113.10=127.0.0.1)", p) + } + via[a] = b + } + return via, nil +} + // list is a flag that may repeat and may hold commas. type list []string @@ -34,7 +50,8 @@ func (l *list) Set(v string) error { } func main() { - var allowUDP, allowTCP, origins list + var allowUDP, allowTCP, origins, viaPairs list + flag.Var(&viaPairs, "via", "PUBLIC=LOCAL: what the page sends to PUBLIC goes to LOCAL (e.g. the server's own public address=127.0.0.1, for a host behind NAT); repeatable") listen := flag.String("listen", "127.0.0.1:8790", "address to serve on (behind a TLS proxy: keep it on loopback)") flag.Var(&allowUDP, "allow-udp", "HOST:PORT or HOST:LO-HI the relay may send datagrams to and take them from (repeatable, comma-separated)") flag.Var(&allowTCP, "allow-tcp", "HOST:PORT or HOST:LO-HI the relay may connect to (repeatable, comma-separated)") @@ -63,6 +80,10 @@ func main() { flag.Usage() os.Exit(2) } + via, err := parseVia(viaPairs) + if err != nil { + log.Fatal(err) + } p := *ping if p == 0 { p = -1 @@ -76,7 +97,11 @@ func main() { TCPIdle: *tcpIdle, Ping: p, Verbose: *verbose, + Via: via, }) + for from, to := range via { + log.Printf("wsrelay: %s reached via %s", from, to) + } o := "any origin" if len(origins) > 0 { o = "origins " + origins.String() diff --git a/upstream/config.yaml.example b/classic/config.yaml.example index df0912c..0e94687 100644 --- a/upstream/config.yaml.example +++ b/classic/config.yaml.example @@ -101,6 +101,11 @@ world: # the map, minimap and item links off. Off unless set. # vanilla_ui: true + # With vanilla_ui: the map, minimap and item links LOCKED off for every + # player (handlers/vanillaui.go, QoLLocked), not just off by default. Off + # unless set. + # lock_map: true + # [OG] characters (handlers/ogaccount.go, database/ogchar.go; the Vanilla # Test shard, the owner 2026-11-18, a character's since 2026-11-19): a new # character chooses [OG] (vanilla's create page, else the game's question box diff --git a/upstream/internal/config/config.go b/classic/internal/config/config.go index 91d4a52..e75e784 100644 --- a/upstream/internal/config/config.go +++ b/classic/internal/config/config.go @@ -725,6 +725,12 @@ type WorldConfig struct { // Unset or false: everything as before. VanillaUI bool `yaml:"vanilla_ui"` + // LockMap, with VanillaUI, LOCKS the map, the minimap and item links off + // for every vanilla client (handlers/vanillaui.go: QoLLocked), where + // VanillaUI alone only starts them off. For a classic shard with no + // minimap at all. Unset or false: as before. + LockMap bool `yaml:"lock_map"` + // OGAccounts turns [OG] characters on (handlers/ogaccount.go; the owner, // 2026-11-18, for the Vanilla Test server: "[OG] tag shows players you // opt-out of the QoL changes to EQOA and only use the most basic upgrades diff --git a/upstream/internal/handlers/vanillaui.go b/classic/internal/handlers/vanillaui.go index 3b63180..1e7e324 100644 --- a/upstream/internal/handlers/vanillaui.go +++ b/classic/internal/handlers/vanillaui.go @@ -51,6 +51,14 @@ func SetVanillaUI(on bool) { vanillaUI.Store(on) } // VanillaUI reports world.vanilla_ui. func VanillaUI() bool { return vanillaUI.Load() } +// lockMap is world.lock_map: with world.vanilla_ui, the map, the minimap and +// item links LOCKED off (QoLLocked) for every session, where vanilla_ui alone +// only starts them off. Off unless set. +var lockMap atomic.Bool + +// SetLockMap turns world.lock_map on or off. +func SetLockMap(on bool) { lockMap.Store(on) } + // QoLOn is whether this server gives its quality-of-life additions: not // world.vanilla_ui. func QoLOn() bool { return !vanillaUI.Load() } @@ -122,6 +130,9 @@ func vanillaUIBits(sess *session.Session) uint32 { case sess.OG(): return QoLOGOff case VanillaUI(): + if lockMap.Load() { + return QoLAllOff | QoLLocked + } return QoLAllOff } return 0 diff --git a/upstream/internal/handlers/vanillaui_test.go b/classic/internal/handlers/vanillaui_test.go index 17daafc..54485da 100644 --- a/upstream/internal/handlers/vanillaui_test.go +++ b/classic/internal/handlers/vanillaui_test.go @@ -213,3 +213,33 @@ func TestVanillaUIConIsTheGames(t *testing.T) { t.Fatalf("a target box offer went with vanilla_ui: %d messages", len(got)) } } + +// world.lock_map: with world.vanilla_ui, a client that answered the bug report +// offer is sent QoLAllOff and QoLLocked (the map, minimap and item links locked +// off, no row turning them on), never the [OG] character's no-mouse and +// no-touch; without vanilla_ui it sends nothing, as before. +func TestLockMapLocksTheMap(t *testing.T) { + _, h, _, as, _ := bugWorld(t) + yes := []byte{1, 0, 0, 0} + SetLockMap(true) + t.Cleanup(func() { SetLockMap(false) }) + + as.Queue().GetPending() + h.handleBugReportOffer(as, incoming(protocol.OpcodeBugReportOffer, yes)) + if got := vanillaUISent(as); len(got) != 0 { + t.Fatalf("lock_map without vanilla_ui: sent % x", got) + } + + vanillaUISwitch(t) + as.Queue().GetPending() + h.handleBugReportOffer(as, incoming(protocol.OpcodeBugReportOffer, yes)) + want := binary.LittleEndian.AppendUint16(nil, uint16(protocol.OpcodeVanillaUI)) + want = append(want, 1) + want = binary.LittleEndian.AppendUint32(want, QoLAllOff|QoLLocked) + if got := vanillaUISent(as); len(got) != 1 || !bytes.Equal(got[0], want) { + t.Fatalf("sent % x, want one % x", got, want) + } + if bits := vanillaUIBits(as); bits&(QoLNoMouse|QoLNoTouch) != 0 { + t.Fatalf("bits %#x: lock_map took the mouse or touch away", bits) + } +} diff --git a/upstream/internal/wsrelay/relay.go b/classic/internal/wsrelay/relay.go index 9916401..505c601 100644 --- a/upstream/internal/wsrelay/relay.go +++ b/classic/internal/wsrelay/relay.go @@ -58,11 +58,39 @@ type Config struct { // silent (a browser answers them itself). 0: 30 s; negative: none. Ping time.Duration Verbose bool + // Via reaches an address through another: what the page addresses to a + // key goes to its value, and what the value sends back is shown to the + // page as from the key. For a relay on the game server's own machine, + // {public address: 127.0.0.1} keeps its traffic on loopback, where a + // cloud VM behind 1:1 NAT (its public address not on its network card) + // may never get a datagram to its own public address back. The allow + // lists name the addresses the page uses (the keys). Empty: none. + Via map[netip.Addr]netip.Addr // Logf receives one line per socket opened, refused and closed (nil: // log.Printf). Logf func(format string, args ...any) } +// through is where traffic the page addresses to a goes (Config.Via). +func (r *Relay) through(a netip.Addr) netip.Addr { + if v, ok := r.cfg.Via[a.Unmap()]; ok { + return v + } + return a.Unmap() +} + +// shownAs is the address the page is told a datagram came from: the key whose +// Via value sent it, else the address itself. +func (r *Relay) shownAs(a netip.Addr) netip.Addr { + a = a.Unmap() + for k, v := range r.cfg.Via { + if v == a { + return k + } + } + return a +} + // Relay is an http.Handler serving the protocol above. type Relay struct { cfg Config @@ -410,7 +438,7 @@ func (r *Relay) udp(ctx context.Context, cancel context.CancelFunc, c *websocket } local := "127.0.0.1" if toward.IsValid() { - local = localToward(toward) + local = localToward(r.through(toward)) } if err := r.write(ctx, c, websocket.MessageText, []byte(fmt.Sprintf("ok %s %d", local, port))); err != nil { return @@ -437,6 +465,7 @@ func (r *Relay) udp(ctx context.Context, cancel context.CancelFunc, c *websocket if err != nil { return } + from = netip.AddrPortFrom(r.shownAs(from.Addr()), from.Port()) if !r.cfg.AllowUDP.Allows(from.Addr(), from.Port()) { dropped.Add(1) r.vlogf("wsrelay: udp client=%s port=%d: dropped a datagram from %s", ip, port, from) @@ -470,7 +499,7 @@ func (r *Relay) udp(ctx context.Context, cancel context.CancelFunc, c *websocket continue } act.touch() - if _, werr := conn.WriteToUDPAddrPort(m[6:], to); werr != nil { + if _, werr := conn.WriteToUDPAddrPort(m[6:], netip.AddrPortFrom(r.through(to.Addr()), to.Port())); werr != nil { r.vlogf("wsrelay: udp client=%s port=%d: send to %s: %v", ip, port, to, werr) continue } @@ -499,7 +528,7 @@ func (r *Relay) tcp(ctx context.Context, cancel context.CancelFunc, c *websocket return } dctx, done := context.WithTimeout(ctx, r.cfg.ConnectTimeout) - conn, err := (&net.Dialer{}).DialContext(dctx, "tcp4", target) + conn, err := (&net.Dialer{}).DialContext(dctx, "tcp4", net.JoinHostPort(r.through(addr).String(), portStr)) done() if err != nil { refuse(fmt.Sprintf("%s: %v", target, err)) diff --git a/upstream/internal/wsrelay/relay_test.go b/classic/internal/wsrelay/relay_test.go index e2d12f5..b3696a7 100644 --- a/upstream/internal/wsrelay/relay_test.go +++ b/classic/internal/wsrelay/relay_test.go @@ -599,3 +599,49 @@ func TestClientOfNamesThePage(t *testing.T) { time.Sleep(20 * time.Millisecond) } } + +// Via: the page addresses the server's public address, the relay reaches it +// on loopback, and the page sees the public address on what comes back; the +// greeting names the relay's own address toward loopback, which is what the +// server sees. A TCP connection to the public address is made to loopback +// too. Without Via the public address is not reached at all. +func TestViaKeepsTrafficLocal(t *testing.T) { + echo := newUDPPeer(t, true) + public := netip.MustParseAddr("203.0.113.7") + shown := netip.AddrPortFrom(public, echo.addr().Port()) + ln := tcpServer(t, echoServe) + via := map[netip.Addr]netip.Addr{public: netip.MustParseAddr("127.0.0.1")} + _, srv, _ := newRelay(t, Config{ + AllowUDP: allow(t, shown.String()), + AllowTCP: allow(t, fmt.Sprintf("203.0.113.7:%d", lnPort(ln))), + Via: via, + }) + + c := dialOK(t, srv, "/udp") + okPort(t, readText(t, c), "127.0.0.1") + send(t, c, websocket.MessageBinary, dgram(shown, "hello")) + typ, m, err := read(t, c, 5*time.Second) + if err != nil || typ != websocket.MessageBinary { + t.Fatalf("no echo through via: %v %v", typ, err) + } + if !bytes.Equal(m[:6], header(shown)) || string(m[6:]) != "hello" { + t.Fatalf("echo %x, want header %x (the public address) + hello", m, header(shown)) + } + + tc := dialOK(t, srv, fmt.Sprintf("/tcp?host=203.0.113.7&port=%d", lnPort(ln))) + okPort(t, readText(t, tc), "127.0.0.1") + send(t, tc, websocket.MessageBinary, []byte("abc")) + if _, m, err := read(t, tc, 5*time.Second); err != nil || string(m) != "abc" { + t.Fatalf("tcp through via: %q %v", m, err) + } + + // negative control: without Via the datagram goes to the public address, + // which nothing answers here + _, plain, _ := newRelay(t, Config{AllowUDP: allow(t, shown.String())}) + c2 := dialOK(t, plain, "/udp") + readText(t, c2) + send(t, c2, websocket.MessageBinary, dgram(shown, "lost")) + if _, m, err := read(t, c2, 500*time.Millisecond); err == nil { + t.Fatalf("without via an answer came back: %q", m) + } +}