aboutsummaryrefslogtreecommitdiff
path: root/clients.go
blob: 15512c023668a49e3e30fd541864d07cf124a1ec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main

import (
	"log/slog"
	"net"
	"sync"
)

type Client struct {
	conn   *net.Conn
	UID    string
	Nick   string
	Ident  string
	Gecos  string
	Host   string
	Server Server
	State  ClientState
}

func (client *Client) Send(msg SMsg) error {
	return client.SendRaw(msg.ClientSerialize())
}

// Send failures are not returned; broken connections detected and severed on
// the next receive.
func (client *Client) SendRaw(s string) error {
	if client.conn == nil {
		panic("not implemented")
	}
	slog.Debug("send", "line", s, "conn", client.conn)
	_, err := (*client.conn).Write([]byte(s))
	if err != nil {
		// TODO: Should shut down the netFd instead but the stdlib
		// doesn't expose a way to do this.
		(*client.conn).Close()
	}
	return nil
}

func (client Client) ClientSource() string {
	// TODO: Edge cases where these aren't available
	return client.Nick + "!" + client.Ident + "@" + client.Host
}

func (client Client) ServerSource() string {
	return client.UID
}

func (client *Client) Teardown() {
	if client.conn != nil {
		(*client.conn).Close()
	}
	if !uidToClient.CompareAndDelete(client.UID, client) {
		slog.Error("uid inconsistent", "uid", client.UID, "client", client)
	}
	if !nickToClient.CompareAndDelete(client.Nick, client) {
		slog.Error("nick inconsistent", "nick", client.Nick, "client", client)
	}
}

func (client *Client) checkRegistration() {
	if client.State != ClientStatePreRegistration {
		slog.Error("spurious call to checkRegistration", "client", client)
		return // TODO: Return an error?
	}
	if client.Nick != "*" && client.Ident != "" {
		client.Send(MakeMsg(self, RPL_WELCOME, client.Nick, "Welcome"))
	}
}

type ClientState uint8

const (
	ClientStateRemote ClientState = iota
	ClientStatePreRegistration
	ClientStateRegistered
)

var uidToClient = sync.Map{}
var nickToClient = sync.Map{}