-
Notifications
You must be signed in to change notification settings - Fork 14
/
server.go
477 lines (417 loc) · 10.5 KB
/
server.go
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package irckit
import (
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/sorcix/irc"
)
var ErrHandshakeFailed = errors.New("handshake failed")
var defaultVersion = "go-irckit"
const handshakeMsgTolerance = 20
// ID will normalize a name to be used as a unique identifier for comparison.
func ID(s string) string {
return strings.ToLower(s)
}
type Prefixer interface {
// Prefix returns a prefix configuration for the origin of the message.
Prefix() *irc.Prefix
}
type Server interface {
Prefixer
Publisher
// Name of the server (usually hostname).
Name() string
// Motd is the Message of the Day for the server.
Motd() []string
// Connect starts the handshake for a new user, blocks until it's completed or failed with an error.
Connect(*User) error
// Quit removes the user from all the channels and disconnects.
Quit(*User, string)
// HasUser returns an existing User with a given Nick.
HasUser(string) (*User, bool)
// RenameUser changes the Nick of a User if the new name is available.
// Returns whether the rename was was successful.
RenameUser(*User, string) bool
// Channel gets or creates a new channel with the given name.
Channel(string) Channel
// HasChannel returns an existing Channel with a given name.
HasChannel(string) (Channel, bool)
// UnlinkChannel removes the channel from the server's storage if it
// exists. Once removed, the server is free to create a fresh channel with
// the same ID. The server is not responsible for evicting members of an
// unlinked channel.
UnlinkChannel(Channel)
}
// ServerConfig produces a Server setup with configuration options.
type ServerConfig struct {
// Name is used as the prefix for the server.
Name string
// Version string of the server (default: go-irckit).
Version string
// Motd is the message of the day for the server, list of message lines where each line should be max 80 chars.
Motd []string
// InviteOnly prevents regular users from joining and making new channels.
InviteOnly bool
// MaxNickLen is the maximum length for a NICK value (default: 32)
MaxNickLen int
// Publisher to use. If nil, a new SyncPublisher will be used.
Publisher Publisher
// DiscardEmpty setting will start a goroutine to discard empty channels.
DiscardEmpty bool
// NewChannel overrides the constructor for a new Channel in a given Server and Name.
NewChannel func(s Server, name string) Channel
// Commands is the handler registry to use (default: DefaultCommands())
Commands Commands
}
func (c ServerConfig) Server() Server {
if c.Publisher == nil {
c.Publisher = SyncPublisher()
}
if c.NewChannel == nil {
c.NewChannel = NewChannel
}
if c.Commands == nil {
c.Commands = DefaultCommands()
}
if c.Version == "" {
c.Version = defaultVersion
}
if c.Name == "" {
c.Name = "go-irckit"
}
if c.MaxNickLen == 0 {
c.MaxNickLen = 32
}
srv := &server{
config: c,
users: map[string]*User{},
channels: map[string]Channel{},
created: time.Now(),
commands: c.Commands,
Publisher: c.Publisher,
}
if c.DiscardEmpty {
srv.channelEvents = make(chan Event, 1)
go srv.cleanupEmpty()
}
return srv
}
// NewServer creates a server.
func NewServer(name string) Server {
return ServerConfig{Name: name}.Server()
}
type server struct {
created time.Time
config ServerConfig
commands Commands
sync.RWMutex
count int
users map[string]*User
channels map[string]Channel
channelEvents chan Event
Publisher
}
func (s *server) Name() string {
return s.config.Name
}
func (s *server) Motd() []string {
return s.config.Motd
}
func (s *server) Close() error {
// TODO: Send notice or something?
// TODO: Clear channels?
s.Lock()
for _, u := range s.users {
u.Close()
}
s.Publisher.Close()
s.Unlock()
return nil
}
// Prefix returns the server's command prefix string.
func (s *server) Prefix() *irc.Prefix {
return &irc.Prefix{Name: s.config.Name}
}
// HasUser returns whether a given user is in the server.
func (s *server) HasUser(nick string) (*User, bool) {
s.RLock()
u, exists := s.users[ID(nick)]
s.RUnlock()
return u, exists
}
// Rename will attempt to rename the given user's Nick if it's available.
func (s *server) RenameUser(u *User, newNick string) bool {
if len(newNick) > s.config.MaxNickLen {
newNick = newNick[:s.config.MaxNickLen]
}
s.Lock()
if _, exists := s.users[ID(newNick)]; exists {
s.Unlock()
u.Encode(&irc.Message{
Prefix: s.Prefix(),
Command: irc.ERR_NICKNAMEINUSE,
Params: []string{newNick},
Trailing: "Nickname is already in use",
})
return false
}
delete(s.users, u.ID())
oldPrefix := u.Prefix()
u.Nick = newNick
s.users[u.ID()] = u
s.Unlock()
changeMsg := &irc.Message{
Prefix: oldPrefix,
Command: irc.NICK,
Params: []string{newNick},
}
u.Encode(changeMsg)
for _, other := range u.VisibleTo() {
other.Encode(changeMsg)
}
return true
}
// HasChannel returns whether a given channel already exists.
func (s *server) HasChannel(name string) (Channel, bool) {
s.RLock()
ch, exists := s.channels[ID(name)]
s.RUnlock()
return ch, exists
}
// Channel returns an existing or new channel with the give name.
func (s *server) Channel(name string) Channel {
s.Lock()
id := ID(name)
ch, ok := s.channels[id]
if !ok {
newFn := s.config.NewChannel
ch = newFn(s, name)
id = ch.ID()
s.channels[id] = ch
s.Unlock()
if s.config.DiscardEmpty {
ch.Subscribe(s.channelEvents)
}
s.Publish(&event{NewChanEvent, s, ch, nil, nil})
} else {
s.Unlock()
}
return ch
}
// cleanupEmpty receives Channel candidates for cleaning up and removes them if they're empty. (Blocking)
func (s *server) cleanupEmpty() {
for evt := range s.channelEvents {
if evt.Kind() != EmptyChanEvent {
continue
}
ch := evt.Channel()
s.Lock()
if s.channels[ch.ID()] != ch {
// Not the same channel anymore, already been replaced.
s.Unlock()
continue
}
if ch.Len() != 0 {
// Not empty.
s.Unlock()
continue
}
delete(s.channels, ch.ID())
s.Unlock()
}
}
// UnlinkChannel unlinks the channel from the server's storage, returns whether it existed.
func (s *server) UnlinkChannel(ch Channel) {
s.Lock()
chStored := s.channels[ch.ID()]
r := chStored == ch
if r {
delete(s.channels, ch.ID())
}
s.Unlock()
}
// Connect starts the handshake for a new User and returns when complete or failed.
func (s *server) Connect(u *User) error {
err := s.handshake(u)
if err != nil {
u.Close()
return err
}
go s.handle(u)
s.Publish(&event{ConnectEvent, s, nil, u, nil})
return nil
}
// Quit will remove the user from all channels and disconnect.
func (s *server) Quit(u *User, message string) {
go u.Close()
s.Lock()
delete(s.users, u.ID())
s.Unlock()
}
func (s *server) guestNick() string {
s.Lock()
defer s.Unlock()
s.count++
return fmt.Sprintf("Guest%d", s.count)
}
// Len returns the number of users connected to the server.
func (s *server) Len() int {
s.RLock()
defer s.RUnlock()
return len(s.users)
}
func (s *server) welcome(u *User) error {
err := u.Encode(
&irc.Message{
Prefix: s.Prefix(),
Command: irc.RPL_WELCOME,
Params: []string{u.Nick},
Trailing: fmt.Sprintf("Welcome! %s", u.Prefix()),
},
&irc.Message{
Prefix: s.Prefix(),
Command: irc.RPL_YOURHOST,
Params: []string{u.Nick},
Trailing: fmt.Sprintf("Your host is %s, running version %s", s.config.Name, s.config.Version),
},
&irc.Message{
Prefix: s.Prefix(),
Command: irc.RPL_CREATED,
Params: []string{u.Nick},
Trailing: fmt.Sprintf("This server was created %s", s.created.Format(time.UnixDate)),
},
&irc.Message{
Prefix: s.Prefix(),
Command: irc.RPL_MYINFO,
Params: []string{u.Nick},
Trailing: fmt.Sprintf("%s %s o o", s.config.Name, s.config.Version),
},
&irc.Message{
Prefix: s.Prefix(),
Command: irc.RPL_LUSERCLIENT,
Params: []string{u.Nick},
Trailing: fmt.Sprintf("There are %d users and 0 services on 1 servers", s.Len()),
},
)
if err != nil {
return err
}
// Always include motd, even if it's empty? Seems some clients expect it (libpurple?).
return CmdMotd(s, u, nil)
}
// names lists all names for a given channel
func (s *server) names(u *User, channels ...string) []*irc.Message {
// TODO: Support full list?
r := []*irc.Message{}
for _, channel := range channels {
ch, exists := s.HasChannel(channel)
if !exists {
continue
}
// FIXME: This needs to be broken up into multiple messages to fit <510 chars
msg := irc.Message{
Prefix: s.Prefix(),
Command: irc.RPL_NAMREPLY,
Params: []string{u.Nick, "=", channel},
Trailing: strings.Join(ch.Names(), " "),
}
r = append(r, &msg)
}
endParams := []string{u.Nick}
if len(channels) == 1 {
endParams = append(endParams, channels[0])
}
r = append(r, &irc.Message{
Prefix: s.Prefix(),
Params: endParams,
Command: irc.RPL_ENDOFNAMES,
Trailing: "End of /NAMES list.",
})
return r
}
func (s *server) handle(u *User) {
var partMsg string
defer s.Quit(u, partMsg)
for {
msg, err := u.Decode()
if err != nil {
logger.Errorf("handle decode error for %s: %s", u.ID(), err.Error())
return
}
if msg == nil {
// Ignore empty messages
continue
}
err = s.commands.Run(s, u, msg)
if err == ErrUnknownCommand {
// TODO: Emit event?
} else if err != nil {
logger.Errorf("handler error for %s: %s", u.ID(), err.Error())
return
}
}
}
func (s *server) add(u *User) (ok bool) {
s.Lock()
defer s.Unlock()
id := u.ID()
if _, exists := s.users[id]; exists {
return false
}
s.users[id] = u
return true
}
func (s *server) handshake(u *User) error {
// Assign host
u.Host = u.ResolveHost()
// Read messages until we filled in USER details.
for i := handshakeMsgTolerance; i > 0; i-- {
// Consume N messages then give up.
msg, err := u.Decode()
if err != nil {
return err
}
if msg == nil {
// Empty message, ignore.
continue
}
if len(msg.Params) < 1 {
u.Encode(&irc.Message{
Prefix: s.Prefix(),
Command: irc.ERR_NEEDMOREPARAMS,
Params: []string{msg.Command},
})
continue
}
switch msg.Command {
case irc.NICK:
u.Nick = msg.Params[0]
case irc.USER:
u.User = msg.Params[0]
u.Real = msg.Trailing
}
if u.Nick == "" || u.User == "" {
// Wait for both to be set before proceeding
continue
}
if len(u.Nick) > s.config.MaxNickLen {
u.Nick = u.Nick[:s.config.MaxNickLen]
}
ok := s.add(u)
if !ok {
u.Encode(
&irc.Message{
Prefix: s.Prefix(),
Command: irc.ERR_NICKNAMEINUSE,
Params: []string{u.Nick},
Trailing: "Nickname is already in use",
},
)
continue
}
return s.welcome(u)
}
return ErrHandshakeFailed
}