Your IP : 216.73.216.224


Current Path : /home/hotlineuser/mobius/hotline/
Upload File :
Current File : //home/hotlineuser/mobius/hotline/tracker.go

package hotline

import (
	"bufio"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"net"
	"slices"
	"strconv"
)

// TrackerRegistration represents the payload a Hotline server sends to a Tracker to register
type TrackerRegistration struct {
	Port        [2]byte // Server's listening TCP port number
	UserCount   int     // Number of users connected to this particular server
	TLSPort     [2]byte // TLSPort
	PassID      [4]byte // Random number generated by the server
	Name        string  // Server Name
	Description string  // Description of the server
	Password    string  // Tracker password, if required by tracker

	readOffset int // Internal offset to track read progress
}

// Read implements io.Reader to write tracker registration payload bytes to slice
func (tr *TrackerRegistration) Read(p []byte) (int, error) {
	userCount := make([]byte, 2)
	binary.BigEndian.PutUint16(userCount, uint16(tr.UserCount))

	buf := slices.Concat(
		[]byte{0x00, 0x01}, // Magic number, always 1
		tr.Port[:],
		userCount,
		tr.TLSPort[:],
		tr.PassID[:],
		[]byte{uint8(len(tr.Name))},
		[]byte(tr.Name),
		[]byte{uint8(len(tr.Description))},
		[]byte(tr.Description),
		[]byte{uint8(len(tr.Password))},
		[]byte(tr.Password),
	)

	return readFrom(p, &tr.readOffset, buf)
}

// Dialer interface to abstract the dialing operation
type Dialer interface {
	Dial(network, address string) (net.Conn, error)
}

// RealDialer is the real implementation of the Dialer interface
type RealDialer struct{}

func (d *RealDialer) Dial(network, address string) (net.Conn, error) {
	return net.Dial(network, address)
}

func register(dialer Dialer, tracker string, tr io.Reader) error {
	conn, err := dialer.Dial("udp", tracker)
	if err != nil {
		return fmt.Errorf("failed to dial tracker: %v", err)
	}
	defer func() { _ = conn.Close() }()

	if _, err := io.Copy(conn, tr); err != nil {
		return fmt.Errorf("failed to write to connection: %w", err)
	}

	return nil
}

// All string values use 8-bit ASCII character set encoding.
// Client Interface with Tracker
// After establishing a connection with tracker, the following information is sent:
// Description	Size	Data	Note
// Magic number	4	‘HTRK’
// Version	2	1 or 2	Old protocol (1) or new (2)

// TrackerHeader is sent in reply Reply received from the tracker starts with a header:
type TrackerHeader struct {
	Protocol [4]byte // "HTRK" 0x4854524B
	Version  [2]byte // Old protocol (1) or new (2)
}

// ServerInfoHeader represents a batch header in the tracker response.
// The tracker protocol splits large server lists into batches, with each batch
// preceded by its own ServerInfoHeader. The first header indicates the total
// number of servers across all batches, and each header (including the first)
// indicates how many servers are in the current batch.
//
// Example flow for 106 servers split into batches:
//  1. First ServerInfoHeader: SrvCount=106, BatchSize=97
//  2. Read 97 ServerRecords
//  3. Second ServerInfoHeader: SrvCount=106, BatchSize=9
//  4. Read 9 ServerRecords (total: 106)
type ServerInfoHeader struct {
	MsgType     [2]byte // Always has value of 1
	MsgDataSize [2]byte // Remaining size of request
	SrvCount    [2]byte // Total number of servers across all batches
	BatchSize   [2]byte // Number of servers in the current batch
}

// ServerRecord is a tracker listing for a single server
type ServerRecord struct {
	IPAddr          [4]byte
	Port            [2]byte
	NumUsers        [2]byte // Number of users connected to this particular server
	TLSPort         [2]byte
	NameSize        byte   // Length of Name string
	Name            []byte // Server Name
	DescriptionSize byte
	Description     []byte
}

func GetListing(conn io.ReadWriteCloser) ([]ServerRecord, error) {
	defer func() { _ = conn.Close() }()

	_, err := conn.Write(
		[]byte{
			0x48, 0x54, 0x52, 0x4B, // HTRK
			0x00, 0x01, // Version
		},
	)
	if err != nil {
		return nil, err
	}

	var th TrackerHeader
	if err := binary.Read(conn, binary.BigEndian, &th); err != nil {
		return nil, err
	}

	// Use a buffered reader so we can read both headers and server records from the same buffer
	reader := bufio.NewReader(conn)

	var info ServerInfoHeader
	if err := binary.Read(reader, binary.BigEndian, &info); err != nil {
		return nil, err
	}

	totalSrv := int(binary.BigEndian.Uint16(info.SrvCount[:]))
	batchSize := int(binary.BigEndian.Uint16(info.BatchSize[:]))

	servers := make([]ServerRecord, 0, totalSrv)
	serversInCurrentBatch := 0

	for len(servers) < totalSrv {
		// Check if we've read all servers in the current batch
		if serversInCurrentBatch == batchSize {
			// Read the next ServerInfoHeader for the next batch from the buffered reader
			if err := binary.Read(reader, binary.BigEndian, &info); err != nil {
				return nil, fmt.Errorf("failed to read next ServerInfoHeader after %d servers: %w", len(servers), err)
			}

			batchSize = int(binary.BigEndian.Uint16(info.BatchSize[:]))
			serversInCurrentBatch = 0
		}

		// Read a server record using our helper function
		srv, err := readServerRecord(reader)
		if err != nil {
			return nil, fmt.Errorf("failed to read server record %d: %w", len(servers)+1, err)
		}

		servers = append(servers, srv)
		serversInCurrentBatch++
	}

	return servers, nil
}

// readServerRecord reads a single ServerRecord from the reader
func readServerRecord(reader *bufio.Reader) (ServerRecord, error) {
	var srv ServerRecord

	// Read fixed header: IP (4) + Port (2) + NumUsers (2) + TLSPort (2) = 10 bytes
	header := make([]byte, 10)
	if _, err := io.ReadFull(reader, header); err != nil {
		return srv, fmt.Errorf("failed to read server header: %w", err)
	}

	copy(srv.IPAddr[:], header[0:4])
	copy(srv.Port[:], header[4:6])
	copy(srv.NumUsers[:], header[6:8])
	copy(srv.TLSPort[:], header[8:10])

	// Read name size
	nameSizeByte, err := reader.ReadByte()
	if err != nil {
		return srv, fmt.Errorf("failed to read name size: %w", err)
	}
	srv.NameSize = nameSizeByte

	// Read name
	srv.Name = make([]byte, srv.NameSize)
	if _, err := io.ReadFull(reader, srv.Name); err != nil {
		return srv, fmt.Errorf("failed to read name: %w", err)
	}

	// Read description size
	descSizeByte, err := reader.ReadByte()
	if err != nil {
		return srv, fmt.Errorf("failed to read description size: %w", err)
	}
	srv.DescriptionSize = descSizeByte

	// Read description
	srv.Description = make([]byte, srv.DescriptionSize)
	if _, err := io.ReadFull(reader, srv.Description); err != nil {
		return srv, fmt.Errorf("failed to read description: %w", err)
	}

	return srv, nil
}

// Write implements io.Writer for ServerRecord
func (s *ServerRecord) Write(b []byte) (n int, err error) {
	if len(b) < 12 {
		return 0, errors.New("too few bytes")
	}
	copy(s.IPAddr[:], b[0:4])
	copy(s.Port[:], b[4:6])
	copy(s.NumUsers[:], b[6:8])
	s.NameSize = b[10]
	nameLen := int(b[10])

	s.Name = b[11 : 11+nameLen]
	s.DescriptionSize = b[11+nameLen]
	s.Description = b[12+nameLen : 12+nameLen+int(s.DescriptionSize)]

	return 12 + nameLen + int(s.DescriptionSize), nil
}

func (s *ServerRecord) Addr() string {
	return fmt.Sprintf("%s:%s",
		net.IP(s.IPAddr[:]),
		strconv.Itoa(int(binary.BigEndian.Uint16(s.Port[:]))),
	)
}