15 type ClientPrefs struct {
16 Username string `yaml:"Username"`
17 IconID int `yaml:"IconID"`
18 Tracker string `yaml:"Tracker"`
19 EnableBell bool `yaml:"EnableBell"`
22 func (cp *ClientPrefs) IconBytes() []byte {
23 iconBytes := make([]byte, 2)
24 binary.BigEndian.PutUint16(iconBytes, uint16(cp.IconID))
32 Handlers map[[2]byte]ClientHandler
33 activeTasks map[[4]byte]*Transaction
36 type ClientHandler func(context.Context, *Client, *Transaction) ([]Transaction, error)
38 func (c *Client) HandleFunc(tranType [2]byte, handler ClientHandler) {
39 c.Handlers[tranType] = handler
42 func NewClient(username string, logger *slog.Logger) *Client {
45 activeTasks: make(map[[4]byte]*Transaction),
46 Handlers: make(map[[2]byte]ClientHandler),
47 Pref: &ClientPrefs{Username: username},
53 type ClientTransaction struct {
55 Handler func(*Client, *Transaction) ([]Transaction, error)
58 func (ch ClientTransaction) Handle(cc *Client, t *Transaction) ([]Transaction, error) {
59 return ch.Handler(cc, t)
62 type ClientTHandler interface {
63 Handle(*Client, *Transaction) ([]Transaction, error)
66 // JoinServer connects to a Hotline server and completes the login flow
67 func (c *Client) Connect(address, login, passwd string) (err error) {
68 // Establish TCP connection to server
69 c.Connection, err = net.DialTimeout("tcp", address, 5*time.Second)
74 // Send handshake sequence
75 if err := c.Handshake(); err != nil {
79 // Authenticate (send TranLogin 107)
83 TranLogin, [2]byte{0, 0},
84 NewField(FieldUserName, []byte(c.Pref.Username)),
85 NewField(FieldUserIconID, c.Pref.IconBytes()),
86 NewField(FieldUserLogin, encodeString([]byte(login))),
87 NewField(FieldUserPassword, encodeString([]byte(passwd))),
91 return fmt.Errorf("error sending login transaction: %w", err)
94 // start keepalive go routine
95 go func() { _ = c.keepalive() }()
100 const keepaliveInterval = 300 * time.Second
102 func (c *Client) keepalive() error {
104 time.Sleep(keepaliveInterval)
105 _ = c.Send(NewTransaction(TranKeepAlive, [2]byte{}))
109 var ClientHandshake = []byte{
110 0x54, 0x52, 0x54, 0x50, // TRTP
111 0x48, 0x4f, 0x54, 0x4c, // HOTL
116 var ServerHandshake = []byte{
117 0x54, 0x52, 0x54, 0x50, // TRTP
118 0x00, 0x00, 0x00, 0x00, // ErrorCode
121 func (c *Client) Handshake() error {
122 // Protocol Type 4 ‘TRTP’ 0x54 52 54 50
123 // Sub-protocol Type 4 User defined
124 // Version 2 1 Currently 1
125 // Sub-version 2 User defined
126 if _, err := c.Connection.Write(ClientHandshake); err != nil {
127 return fmt.Errorf("handshake write err: %s", err)
130 replyBuf := make([]byte, 8)
131 _, err := c.Connection.Read(replyBuf)
136 if bytes.Equal(replyBuf, ServerHandshake) {
140 // In the case of an error, client and server close the connection.
141 return fmt.Errorf("handshake response err: %s", err)
144 func (c *Client) Send(t Transaction) error {
145 requestNum := binary.BigEndian.Uint16(t.Type[:])
147 // if transaction is NOT reply, add it to the list to transactions we're expecting a response for
149 c.activeTasks[t.ID] = &t
152 n, err := io.Copy(c.Connection, &t)
154 return fmt.Errorf("error sending transaction: %w", err)
157 c.Logger.Debug("Sent Transaction",
158 "IsReply", t.IsReply,
165 func (c *Client) HandleTransaction(ctx context.Context, t *Transaction) error {
166 var origT Transaction
168 origT = *c.activeTasks[t.ID]
172 if handler, ok := c.Handlers[t.Type]; ok {
174 "Received transaction",
175 "IsReply", t.IsReply,
178 outT, err := handler(ctx, c, t)
180 c.Logger.Error("error handling transaction", "err", err)
182 for _, t := range outT {
183 if err := c.Send(t); err != nil {
189 "Unimplemented transaction type",
190 "IsReply", t.IsReply,
198 func (c *Client) Disconnect() error {
199 return c.Connection.Close()
202 func (c *Client) HandleTransactions(ctx context.Context) error {
203 // Create a new scanner for parsing incoming bytes into transaction tokens
204 scanner := bufio.NewScanner(c.Connection)
205 scanner.Split(transactionScanner)
207 // Scan for new transactions and handle them as they come in.
209 // Make a new []byte slice and copy the scanner bytes to it. This is critical to avoid a data race as the
210 // scanner re-uses the buffer for subsequent scans.
211 buf := make([]byte, len(scanner.Bytes()))
212 copy(buf, scanner.Bytes())
215 _, err := t.Write(buf)
220 if err := c.HandleTransaction(ctx, &t); err != nil {
221 c.Logger.Error("Error handling transaction", "err", err)
225 if scanner.Err() == nil {