Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
38 changes: 30 additions & 8 deletions app/resources/server/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (s *DB) Upsert(ctx context.Context, e All) error {

svr, err = s.client.Server.
FindUnique(db.Server.IP.Equals(e.IP)).
Update(
Update(append([]db.ServerSetParam{
db.Server.IP.Set(e.IP),
db.Server.Hn.Set(e.Core.Hostname),
db.Server.Pc.Set(db.BigInt(e.Core.Players)),
Expand All @@ -68,7 +68,7 @@ func (s *DB) Upsert(ctx context.Context, e All) error {
db.Server.Banner.SetOptional(e.Banner),
db.Server.Active.Set(e.Active),
db.Server.LastActive.Set(time.Now()),
).Exec(ctx)
}, extraParams(e.Extra)...)...).Exec(ctx)
if errors.Is(err, db.ErrNotFound) {
if !e.Active {
// don't store inactive servers that don't exist.
Expand All @@ -84,12 +84,14 @@ func (s *DB) Upsert(ctx context.Context, e All) error {
db.Server.Pa.Set(e.Core.Password),
db.Server.Vn.Set(e.Core.Version),
db.Server.Active.Set(e.Active),
db.Server.Omp.Set(e.Core.IsOmp),
db.Server.Pending.Set(true),
db.Server.Domain.SetOptional(e.Domain),
db.Server.Description.SetOptional(e.Description),
db.Server.Banner.SetOptional(e.Banner),
db.Server.LastActive.Set(time.Now()),
append([]db.ServerSetParam{
db.Server.Omp.Set(e.Core.IsOmp),
db.Server.Pending.Set(true),
db.Server.Domain.SetOptional(e.Domain),
db.Server.Description.SetOptional(e.Description),
db.Server.Banner.SetOptional(e.Banner),
db.Server.LastActive.Set(time.Now()),
}, extraParams(e.Extra)...)...,
).Exec(ctx); err != nil {
return errors.Wrapf(err, "failed to create '%v'", e)
}
Expand Down Expand Up @@ -121,6 +123,26 @@ func (s *DB) Upsert(ctx context.Context, e All) error {
return nil
}

// extraParams writes the open.mp extra info when this query got it. Without it
// (a SA-MP server, or the extra query failed) the stored values are left alone.
func extraParams(extra *Extra) []db.ServerSetParam {
if extra == nil {
return nil
}
optional := func(value string) *string {
if value == "" {
return nil
}
return &value
}
return []db.ServerSetParam{
db.Server.Discord.SetOptional(optional(extra.Discord)),
db.Server.BannerLight.SetOptional(optional(extra.BannerLight)),
db.Server.BannerDark.SetOptional(optional(extra.BannerDark)),
db.Server.Logo.SetOptional(optional(extra.Logo)),
}
}

func (s *DB) GetByID(ctx context.Context, id string) (*All, error) {
r, err := s.client.Server.FindUnique(db.Server.ID.Equals(id)).Exec(ctx)
if err != nil {
Expand Down
32 changes: 32 additions & 0 deletions app/resources/server/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,23 @@ type All struct {
Rules map[string]string `json:"ru,omitempty"`
Description *string `json:"description"`
Banner *string `json:"banner"`
Extra *Extra `json:"extra,omitempty"`
Active bool `json:"active"`
Pending bool `json:"pending"`
LastUpdated time.Time `json:"lastUpdated"`
LastActive *time.Time `json:"lastActive"`
}

// Extra holds what an open.mp server publishes about itself beyond the SA:MP
// query: the same Discord link, banners and logo the launcher shows. Empty
// strings mean the server didn't set that field.
type Extra struct {
Discord string `json:"discord,omitempty"`
BannerLight string `json:"bannerLight,omitempty"`
BannerDark string `json:"bannerDark,omitempty"`
Logo string `json:"logo,omitempty"`
}

// Essential stores the standard SA:MP 'info' query fields necessary for server
// lists. The json keys are short to cut down on network traffic since these are
// the objects returned to a listing request which could contain hundreds of
Expand Down Expand Up @@ -105,13 +116,34 @@ func dbToAPI(r db.ServerModel) *All {
Rules: transformRules(r.Ru()),
Description: r.InnerServer.Description,
Banner: r.InnerServer.Banner,
Extra: extraFromDB(r),
Active: r.Active,
Pending: r.Pending,
LastUpdated: r.UpdatedAt,
LastActive: r.InnerServer.LastActive,
}
}

func extraFromDB(r db.ServerModel) *Extra {
e := Extra{
Discord: valueOr(r.InnerServer.Discord),
BannerLight: valueOr(r.InnerServer.BannerLight),
BannerDark: valueOr(r.InnerServer.BannerDark),
Logo: valueOr(r.InnerServer.Logo),
}
if e == (Extra{}) {
return nil
}
return &e
}

func valueOr(s *string) string {
if s == nil {
return ""
}
return *s
}

func dbToAPISlice(r []db.ServerModel) []All {
result := []All{}
for _, s := range r {
Expand Down
138 changes: 138 additions & 0 deletions app/services/queryer/extrainfo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package queryer

import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"time"
)

// ExtraInfo is what an open.mp server returns to the 'o' query: the Discord
// invite, banners and logo set in its config.json. The launcher reads the same
// packet (src-tauri/src/query.rs in the launcher repo). Empty fields were not set.
type ExtraInfo struct {
Discord string
BannerLight string
BannerDark string
Logo string
}

// Limits the launcher applies to each field.
const (
maxDiscordLength = 50
maxURLLength = 160
)

var errExtraInfoMalformed = errors.New("malformed extra info packet")

// QueryExtraInfo sends the open.mp 'o' query to address. Only open.mp servers
// answer it; SA-MP servers ignore it and the call times out.
func QueryExtraInfo(ctx context.Context, address string) (ExtraInfo, error) {
host, portText, err := net.SplitHostPort(address)
if err != nil {
return ExtraInfo{}, err
}
port, err := strconv.ParseUint(portText, 10, 16)
if err != nil {
return ExtraInfo{}, fmt.Errorf("invalid port %q: %w", portText, err)
}

ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host)
if err != nil || len(ips) == 0 {
return ExtraInfo{}, fmt.Errorf("could not resolve %q: %w", host, err)
}
ip := ips[0].To4()

ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()

var d net.Dialer
conn, err := d.DialContext(ctx, "udp4", net.JoinHostPort(ip.String(), portText))
if err != nil {
return ExtraInfo{}, err
}
defer conn.Close()
if deadline, ok := ctx.Deadline(); ok {
_ = conn.SetDeadline(deadline)
}

request := make([]byte, 0, 11)
request = append(request, 'S', 'A', 'M', 'P')
request = append(request, ip...)
request = append(request, byte(port&0xFF), byte(port>>8&0xFF))
request = append(request, 'o')
if _, err := conn.Write(request); err != nil {
return ExtraInfo{}, err
}

buf := make([]byte, 2048)
n, err := conn.Read(buf)
if err != nil {
return ExtraInfo{}, err
}

return parseExtraInfo(buf[:n])
}

// parseExtraInfo reads the reply: the 11-byte query header, then the Discord
// link, light banner and dark banner, each a little-endian uint32 length
// followed by that many bytes, then an optional logo in the same form.
func parseExtraInfo(packet []byte) (ExtraInfo, error) {
if len(packet) < 11 || !bytes.Equal(packet[:4], []byte("SAMP")) || packet[10] != 'o' {
return ExtraInfo{}, errExtraInfoMalformed
}
r := bytes.NewReader(packet[11:])

readString := func(limit uint32) (string, error) {
var length uint32
if err := binary.Read(r, binary.LittleEndian, &length); err != nil {
return "", errExtraInfoMalformed
}
if length > limit || int(length) > r.Len() {
return "", errExtraInfoMalformed
}
value := make([]byte, length)
if _, err := r.Read(value); err != nil && length > 0 {
return "", errExtraInfoMalformed
}
return strings.TrimSpace(string(value)), nil
}

var info ExtraInfo
var err error
if info.Discord, err = readString(maxDiscordLength); err != nil {
return ExtraInfo{}, err
}
if info.BannerLight, err = readString(maxURLLength); err != nil {
return ExtraInfo{}, err
}
if info.BannerDark, err = readString(maxURLLength); err != nil {
return ExtraInfo{}, err
}
// Older open.mp versions stop before the logo.
if r.Len() > 4 {
if info.Logo, err = readString(maxURLLength); err != nil {
return ExtraInfo{}, err
}
}

info.BannerLight = webURL(info.BannerLight)
info.BannerDark = webURL(info.BannerDark)
info.Logo = webURL(info.Logo)
return info, nil
}

// webURL keeps only absolute http(s) addresses, since these end up in <img src>.
func webURL(value string) string {
u, err := url.Parse(value)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return ""
}
return u.String()
}
85 changes: 85 additions & 0 deletions app/services/queryer/extrainfo_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package queryer

import (
"encoding/binary"
"testing"
)

// appendLength adds a little-endian uint32 (binary.LittleEndian.AppendUint32
// needs Go 1.19, and CI runs 1.17).
func appendLength(p []byte, n int) []byte {
var b [4]byte
binary.LittleEndian.PutUint32(b[:], uint32(n))
return append(p, b[:]...)
}

func packetWith(fields ...string) []byte {
p := []byte{'S', 'A', 'M', 'P', 127, 0, 0, 1, 0x61, 0x1e, 'o'}
for _, f := range fields {
p = appendLength(p, len(f))
p = append(p, f...)
}
return p
}

func TestParseExtraInfo(t *testing.T) {
info, err := parseExtraInfo(packetWith(
"discord.gg/example",
"https://example.com/light.png",
"https://example.com/dark.png",
"https://example.com/logo.png",
))
if err != nil {
t.Fatal(err)
}
want := ExtraInfo{
Discord: "discord.gg/example",
BannerLight: "https://example.com/light.png",
BannerDark: "https://example.com/dark.png",
Logo: "https://example.com/logo.png",
}
if info != want {
t.Fatalf("got %+v, want %+v", info, want)
}
}

func TestParseExtraInfoWithoutLogo(t *testing.T) {
info, err := parseExtraInfo(packetWith("", "https://example.com/light.png", ""))
if err != nil {
t.Fatal(err)
}
if info.BannerLight != "https://example.com/light.png" || info.Logo != "" || info.BannerDark != "" {
t.Fatalf("unexpected %+v", info)
}
}

func TestParseExtraInfoDropsNonWebURLs(t *testing.T) {
info, err := parseExtraInfo(packetWith("", "javascript:alert(1)", "example.com/dark.png", "data:image/png;base64,AAAA"))
if err != nil {
t.Fatal(err)
}
if info.BannerLight != "" || info.BannerDark != "" || info.Logo != "" {
t.Fatalf("non-web URLs kept: %+v", info)
}
}

func TestParseExtraInfoRejectsBadPackets(t *testing.T) {
tooLong := make([]byte, maxURLLength+1)
for i := range tooLong {
tooLong[i] = 'a'
}
truncated := packetWith("discord.gg/x")
truncated = appendLength(truncated, 40) // claims 40 bytes, has none

cases := map[string][]byte{
"short": []byte("SAMP"),
"wrong type": append(packetWith()[:10], 'r'),
"too long": packetWith("", string(tooLong), ""),
"truncated": truncated,
}
for name, p := range cases {
if _, err := parseExtraInfo(p); err == nil {
t.Errorf("%s: expected an error", name)
}
}
}
10 changes: 10 additions & 0 deletions app/services/queryer/queryer.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (

type Queryer interface {
Query(ctx context.Context, address string) (sampquery.Server, error)
// ExtraInfo asks an open.mp server for its Discord link, banners and logo.
ExtraInfo(ctx context.Context, address string) (ExtraInfo, error)
}

type SAMPQueryer struct{}
Expand All @@ -24,6 +26,10 @@ func (q *SAMPQueryer) Query(ctx context.Context, address string) (sampquery.Serv
return sampquery.GetServerInfo(ctx, address, true)
}

func (q *SAMPQueryer) ExtraInfo(ctx context.Context, address string) (ExtraInfo, error) {
return QueryExtraInfo(ctx, address)
}

// Mock for testing

type MockQueryer struct{}
Expand Down Expand Up @@ -66,3 +72,7 @@ func (q *MockQueryer) Query(ctx context.Context, address string) (sampquery.Serv
}
return sampquery.Server{}, errors.New("not found")
}

func (q *MockQueryer) ExtraInfo(ctx context.Context, address string) (ExtraInfo, error) {
return ExtraInfo{}, errors.New("not found")
}
13 changes: 13 additions & 0 deletions app/services/scraper/pooled.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ func (s *PooledScraper) Scrape(ctx context.Context, addresses []string) chan ser

result.Core.IP = result.IP

// Only open.mp servers answer the extra info query. A failed or
// timed-out query leaves Extra nil, which keeps the stored values.
if result.Active && result.Core.IsOmp {
if info, err := s.Q.ExtraInfo(c, addr); err == nil {
result.Extra = &server.Extra{
Discord: info.Discord,
BannerLight: info.BannerLight,
BannerDark: info.BannerDark,
Logo: info.Logo,
}
}
}

out <- result
}(a)
}
Expand Down
Loading