Source

GoIRCd / server.go

Full commit
  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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"crypto/tls"
	"encoding/hex"
	"fmt"
	"io"
	"net"

	"strconv"
	"time"
)

// ProtocolVersion is the current version of the server-to-server protocol.
const ProtocolVersion uint = 1

// SID is a unique ServerNode identifier.
type SID uint32

// SIDShift is the left-shift offset of the SID in a UID.
const SIDShift uint = 20

// MaxSID is the maximum valid SID.
const MaxSID SID = 0x9ff

func (id SID) String() string {
	return fmt.Sprintf("%03X", uint32(id))
}

// ParseSID returns the SID represented by 3 hexadecimal characters.
func ParseSID(s string) SID {
	var id SID
	fmt.Sscanf(s, "%03X", &id)
	return id
}

// NewUID creates a UID containing this SID.
func (sid SID) NewUID(id UID) UID {
	return UID(sid<<SIDShift) | id
}

// GetSID returns the SID portion of this UID.
func (id UID) GetSID() SID {
	return SID(id >> SIDShift)
}

// GenerateSID returns a server ID in the range 100 <= sid <= MaxSID.
func GenerateSID(name, desc string) SID {
	id := uint(0)

	for _, c := range name {
		id = id*5 + uint(c)
	}
	for _, c := range desc {
		id = id*5 + uint(c)
	}

	return SID((id % 0x8ff) + 0x100)
}

type RemoteSend struct {
	serverRoutes map[*DirectNode]bool
}

func (rs *RemoteSend) AddNode(node *ServerNode) {
	if rs.serverRoutes == nil {
		rs.Reset()
	}
	rs.serverRoutes[node.Route] = true
}

func (rs *RemoteSend) AddUser(user *User) {
	if user.IsLocal() {
		panic("Attempt to RemoteSend to local user")
	} else if rs.serverRoutes == nil {
		rs.Reset()
	}
	rs.serverRoutes[user.Server.Route] = true
}

func (rs *RemoteSend) Reset() {
	rs.serverRoutes = make(map[*DirectNode]bool)
}

func (rs *RemoteSend) Propagate(serv *Server, node *ServerNode,
	format string, args ...interface{}) {
	if rs.serverRoutes != nil && len(rs.serverRoutes) != 0 {
		for route := range rs.serverRoutes {
			if route != node.Route {
				route.Send(format, args...)
			}
		}
	}
}

func (rs *RemoteSend) Send(serv *Server, format string, args ...interface{}) {
	if rs.serverRoutes != nil && len(rs.serverRoutes) != 0 {
		for route := range rs.serverRoutes {
			route.Send(format, args...)
		}
	}
}

type ServerNode struct {
	Id SID

	Name        string
	Description string

	// Time the connection was established
	Connected time.Time

	// Configured ULine for this server or nil
	ULine *ULine

	// Servers connected to this node
	Nodes map[SID]*ServerNode

	// Clients connected to this node
	Users map[UID]*User

	// Whether we are directly connected to this node
	IsDirect bool

	// Directly connected node between us and this node, nil on root node
	Route *DirectNode

	// Path back to the root, nil on root node
	Return *ServerNode
}

// DirectNode.Messages constants
const (
	SQuit int = iota
	Linked
)

type DirectNode struct {
	Connection net.Conn

	Messages chan int
	Incoming chan string
	Outgoing chan string
	Errors   chan error

	// Whether we initiated the connection to the remote server
	Initiated bool

	// Whether the link negotiation has completed successfully
	IsLinked bool

	// Link block
	Link *Link

	// Data pertaining to link negotiation;
	// nil before "CAPAB START" is received and after Link is set
	Handshake *Handshake
}

func NewDirectNode(conn net.Conn, initiated bool) *DirectNode {
	return &DirectNode{Connection: conn, Initiated: initiated,
		Messages: make(chan int, 16),
		Incoming: make(chan string, 102400),
		Outgoing: make(chan string, 102400),
		Errors:   make(chan error, 16)}
}

type Handshake struct {
	IncomingVersion uint
	AcceptedModes   bool
	AcceptedModules bool
	CapabEnded      bool
	RecvChallenge   string
	SendChallenge   string
}

func (node *ServerNode) AddNode(n *ServerNode) {
	if n.Route == nil {
		n.Route = node.Route
	}
	n.Return = node

	n.Nodes[node.Id] = node
	node.Nodes[n.Id] = n
}

func (node *ServerNode) RemoveNode(n *ServerNode) {
	delete(node.Nodes, n.Id)
	delete(n.Nodes, node.Id)
}

func (node *ServerNode) AddUser(user *User) {
	node.Users[user.Id] = user
}

func (node *ServerNode) StartCapab(version uint) {
	node.Route.Handshake.IncomingVersion = version
}

func (node *ServerNode) CapabEnd(serv *Server) {
	route := node.Route
	route.Handshake.CapabEnded = true
	if route.Initiated {
		serv.SendLink(node)
	} else {
		serv.SendCapab(node)
	}
}

func (node *ServerNode) IsLinked() bool {
	return !node.IsDirect || node.Route.IsLinked
}

func (node *ServerNode) IsULine() bool {
	return node.ULine != nil
}

func (node *ServerNode) Nearest() *ServerNode {
	if node.Return == nil {
		panic("Nearest called on root node")
	}

	res := node
	n := res.Return

	for n.Return != nil {
		res = n
		n = res.Return
	}

	return res
}

func (route *DirectNode) Split(reason string) {
	route.Send("ERROR :%s", reason)
	route.Send("")
	route.Messages <- SQuit
}

func (route *DirectNode) Send(format string, args ...interface{}) error {
	line := fmt.Sprintf(format, args...)
	select {
	case route.Outgoing <- line:
		break
	default:
		return SendQExceeded
	}
	return nil
}

// PurgeNode kills all Users belonging to the given ServerNode.
func (self *Server) PurgeNode(node *ServerNode) {
	for _, u := range node.Users {
		self.KillUser(u, "*.net *.split")
	}

	for _, n := range node.Nodes {
		// Purge all nodes on that side of the split, but don't recurse backward
		if node.Return != n {
			self.PurgeNode(n)
		}
	}

	if node.IsLinked() {
		delete(self.Servers, node.Id)
		delete(self.ServerNames, node.Name)
	} else {
		delete(self.UnknownServers, node)
	}
}

// SendNode delivers a message to the given ServerNode.
func (self *Server) SendNode(node *ServerNode, format string, args ...interface{}) {
	if err := node.Route.Send(format, args...); err != nil {
		self.SplitNode(node.Nearest(), err.Error())
	}
}

// Broadcast sends a message to all connected nodes.
func (self *Server) Broadcast(format string, args ...interface{}) {
	self.Propagate(self.Root, format, args...)
}

// Relay a message from a source to all remaining nodes.
func (self *Server) Propagate(source *ServerNode, format string, args ...interface{}) {
	route := source.Route
	for _, node := range self.Root.Nodes {
		if node.Route != route {
			self.SendNode(node, format, args...)
		}
	}
}

// SplitAllNodes causes a split on all connected nodes without issuing any
// messages to nodes (except to report the split reason) or clients.
// The server will be in a somewhat unclean state after this call: All server
// connections will be closed, but ServerNode and remote User structures
// will be left in an undefined state.
//
// Generally only useful in performing a complete shutdown of the server.
func (self *Server) SplitAllNodes(reason string) {
	for _, node := range self.Root.Nodes {
		node.Route.Split(reason)
	}
	for node := range self.UnknownServers {
		node.Route.Split(reason)
	}
}

// SplitNode causes a netsplit on the given node if it is directly connected
// or delivers an RSQUIT message to the node directly linked to given node.
func (self *Server) SplitNode(node *ServerNode, reason string) {
	if node == self.Root {
		panic("Attempt to split from root node")
	}

	if node.IsDirect {
		for _, handler := range ServerSplit {
			handler.(ServerSplitHandler).ServerSplit(self, node, reason)
		}

		node.Route.Split(reason)
		self.RemoveNode(node)
		self.Broadcast(":%s SQUIT %s :%s", self.Id, node.Id, reason)
		self.GlobalNotice('l', "Server %s split: %s", node.Name, reason)
	} else {
		self.SendNode(node, ":%s RSQUIT %s :%s", self.Id, node.Id, reason)
	}
}

// RemoveNode removes a ServerNode and its clients from the network
func (self *Server) RemoveNode(node *ServerNode) {
	if node == self.Root {
		panic("Attempt to remove root node")
	}
	self.PurgeNode(node)
	node.Return.RemoveNode(node)

	delete(self.Servers, node.Id)
	delete(self.UnknownServers, node)
}

// SendServers sends SID messages on the given route, beginning with the given
// ServerNode's directly-connected nodes. An SID message is not sent for the
// given node itself.
func (self *Server) SendServers(route *DirectNode, node *ServerNode) {
	for _, n := range node.Nodes {
		if n != node.Return {
			route.Send(":%s SID %s %s :%s",
				node.Id, n.Name, n.Id, n.Description)
			if len(n.Nodes) > 1 {
				self.SendServers(route, n)
			}
		}
	}
}

// SendBurst sends appropriate messages to the given node to describe all data
// on this side of the network.
func (self *Server) SendBurst(node *ServerNode) {
	route := node.Route

	route.Send(":%s BURST %d", self.Id, time.Now())

	self.SendServers(route, self.Root)

	for _, user := range self.Users {
		host := user.Host
		hostMask := user.HostMask
		ipMask := user.IPMask
		vhost := user.VirtualHost

		if host == "" {
			host = NullField
		}
		if hostMask == "" {
			hostMask = NullField
		}
		if ipMask == "" {
			ipMask = NullField
		}
		if vhost == "" {
			vhost = NullField
		}

		route.Send(":%s UID %s %s %s %s %s %s %s %s %d %s %s :%s", user.Id.GetSID(),
			user.Id, user.Nick, user.Ident, user.IP, ipMask, host, hostMask,
			vhost, user.Connected, user.Modes.String(),
			user.ServerNotices.String(), user.RealName)

		if user.IsOper() {
			route.Send(":%s OPERTYPE :%s", user.Id, user.OperType.Name)
		}
	}

	for _, ch := range self.channels {
		var names string

		for u := range ch.Users {
			if names != "" {
				names += " "
			}

			if pfx := ch.GetPrefix(u); pfx != 0 {
				names += pfx.String() + u.Id.String()
			} else {
				names += u.Id.String()
			}
		}

		route.Send(":%s SJOIN %s %d %s :%s", self.Id,
			ch.Name, ch.Creation, ch.ModeString(false), names)

		if ch.TopicCreation != 0 {
			route.Send(":%s STOPIC %s %d %s %d :%s", self.Id,
				ch.Name, ch.Creation, ch.TopicSetter, ch.TopicCreation, ch.Topic)
		}
	}

	for typ, xlines := range self.XLines {
		if typ != 'K' {
			for _, x := range xlines {
				route.Send(":%s ADDLINE %c %s %s %d %d :%s", self.Id, typ,
					x.Mask(), x.Setter, x.Creation, x.Duration, x.Reason)
			}
		}
	}

	route.Send(":%s ENDBURST", self.Id)
}

// SendCapab sends CAPAB messages to the given node to negotiate a link.
func (self *Server) SendCapab(node *ServerNode) {
	route := node.Route

	challenge := GenerateSalt(20)
	route.Handshake.SendChallenge = challenge

	route.Send("CAPAB START %d", ProtocolVersion)
	route.Send("CAPAB CHALLENGE %s", challenge)
	route.Send("CAPAB MODES %s %s %s",
		self.prefixModes, self.channelModesTypes, self.userModes)
	route.Send("CAPAB MODULES :%s", ModuleString())
	route.Send("CAPAB CAPABILITIES :MAXNICK=%d MAXCHAN=%d MAXMODES=%d "+
		"MAXIDENT=%d MAXQUIT=%d MAXTOPIC=%d MAXKICK=%d MAXREALNAME=%d "+
		"MAXAWAY=%d MAXPART=%d",
		self.MaxNick, self.MaxChannelName, self.MaxModes, self.MaxIdent,
		self.MaxQuitReason, self.MaxTopic, self.MaxKickReason,
		self.MaxRealName, self.MaxAway, self.MaxPartReason)
	route.Send("CAPAB END")
}

// SendLink sends a LINK message to the given node to complete a link.
func (self *Server) SendLink(node *ServerNode) {
	route := node.Route

	passwd := HMACResponse(route.Link.SendPass, route.Handshake.RecvChallenge)

	route.Send("LINK %s %s %s :%s",
		self.ServerName, passwd, self.Id, self.Description)
}

func (self *Server) BroadcastChannel(ch *Channel) {
	var names string

	for u := range ch.Users {
		if names != "" {
			names += " "
		}

		if pfx := ch.GetPrefix(u); pfx != 0 {
			names += pfx.String() + u.Id.String()
		} else {
			names += u.Id.String()
		}
	}

	self.Broadcast(":%s SJOIN %s %d %s :%s", self.Id,
		ch.Name, ch.Creation, ch.ModeString(false), names)
}

// BroadcastUser sends a UID message to all connected nodes to announce a new client.
func (self *Server) BroadcastUser(user *User) {
	host := user.Host
	if host == "" {
		host = NullField
	}

	vhost := user.VirtualHost
	if vhost == "" {
		vhost = NullField
	}

	// UID Nick Ident IP IPMask Host HostMask VHost ConnectTime Modes SNotices :Realname
	self.Broadcast(":%s UID %s %s %s %s %s %s %s %s %d %s %s :%s", self.Id,
		user.Id, user.Nick, user.Ident, user.IP, user.IPMask, host, user.HostMask,
		vhost, user.Connected, user.Modes.String(),
		user.ServerNotices.String(), user.RealName)
}

func HMACResponse(key, challenge string) string {
	hmac256 := hmac.New(sha256.New, []byte(key))
	hmac256.Write([]byte(challenge))

	return "HMAC-SHA256:" + hex.EncodeToString(hmac256.Sum(nil))
}

func (self *Server) NewRemoteUser(node *ServerNode, id UID,
	nick, ident, realName string, ip net.IP, ipMask, host, hostMask, vhost string,
	creation int64, modes, sNotices *Modes) *User {
	user := &User{Id: id, Type: UserRemote,
		Nick: nick, Ident: ident, RealName: realName, Host: host,
		HostMask: hostMask, VirtualHost: vhost, IP: ip, IPMask: ipMask,
		Server: node, Connected: time.Unix(creation, 0),
		Modes: *modes, ServerNotices: *sNotices}

	user.Init()

	return user
}

type ServerTree struct {
	Root           *ServerNode
	Users          map[UID]*User
	Servers        map[SID]*ServerNode
	ServerNames    map[string]*ServerNode
	UnknownServers map[*ServerNode]bool
}

func (t *ServerTree) Init(serv *Server) {
	root := NewRootNode(serv)
	t.Root = root
	t.Users = make(map[UID]*User)
	t.Servers = map[SID]*ServerNode{root.Id: root}
	t.ServerNames = map[string]*ServerNode{root.Name: root}
	t.UnknownServers = make(map[*ServerNode]bool)
}

func NewRootNode(serv *Server) *ServerNode {
	return &ServerNode{Id: serv.Id, Name: serv.ServerName,
		Description: serv.Description, Connected: serv.StartTime,
		Nodes: make(map[SID]*ServerNode), Users: serv.LocalUsers}
}

func (self *Server) NewIncomingServer(conn net.Conn) *ServerNode {
	addr := conn.RemoteAddr().(*net.TCPAddr)

	name := fmt.Sprintf("incoming from %s", addr.IP)

	node := &ServerNode{Name: name,
		Connected: time.Now(),
		Nodes:     make(map[SID]*ServerNode),
		Users:     make(map[UID]*User), IsDirect: true,
		Return: self.Root, Route: NewDirectNode(conn, false)}

	return node
}

func (self *Server) resolveOutgoingLink(node *ServerNode) error {
	var conn net.Conn

	link := node.Route.Link

	addr, err := net.ResolveTCPAddr("tcp",
		net.JoinHostPort(link.Host, strconv.Itoa(link.Port)))

	if err != nil {
		return err
	}

	if !link.Matches(addr.IP) {
		return fmt.Errorf("Remote address %s does not match allow mask %s",
			addr.IP, link.AllowMask)
	}

	conn, err = net.DialTCP("tcp", nil, addr)

	if err != nil {
		return err
	}

	if link.TLS {
		conn = tls.Client(conn, nil)
	}

	node.Connected = time.Now()
	node.Route.Connection = conn

	return nil
}

func (self *Server) NewOutgoingServer(link *Link) *ServerNode {
	route := NewDirectNode(nil, true)
	route.Link = link

	name := "outgoing to " + link.Host

	node := &ServerNode{Name: name,
		Nodes:    make(map[SID]*ServerNode),
		Users:    make(map[UID]*User),
		IsDirect: true, Return: self.Root, Route: route}

	return node
}

func (self *Server) NewServerNode(id SID, name, desc string) *ServerNode {
	node := &ServerNode{Id: id, Name: name, Description: desc,
		Connected: time.Now(),
		Nodes:     make(map[SID]*ServerNode),
		Users:     make(map[UID]*User)}

	self.Servers[id] = node
	self.ServerNames[name] = node

	node.ULine = self.ULines[name]

	return node
}

func (self *Server) GetServer(id SID) *ServerNode {
	return self.Servers[id]
}

func (self *Server) GetServerByName(name string) *ServerNode {
	return self.ServerNames[name]
}

func (self *Server) GetUserById(id UID) *User {
	return self.Users[id]
}

func (self *Server) CheckServer(node *ServerNode) bool {
	return self.Servers[node.Id] == node || self.UnknownServers[node]
}

func (self *Server) HandleServerMessage(node *ServerNode, tokens Tokens,
	line string, err error) {
	if !self.CheckServer(node) {
		return
	}

	if err != nil {
		if err == io.EOF {
			self.SplitNode(node, "Connection closed")
		} else {
			self.SplitNode(node, err.Error())
		}
		return
	}

	self.Log(Debug, "Incoming line <- %s: %#v\n", node.Id, line)

	var sSource *ServerNode
	var uSource *User

	if tokens[0][0] == ':' {
		if !node.IsLinked() {
			self.SplitNode(node, "Sourced message before LINK")
			return
		}

		source := tokens[0][1:]
		tokens = tokens[1:]

		if len(tokens) == 0 {
			self.SplitNode(node.Nearest(), "Invalid message")
			return
		}

		sid := ParseSID(source)
		sSource = self.GetServer(sid)
		if sSource == nil {
			self.SplitNode(node.Nearest(), "Invalid SID")
			return
		}

		if len(source) == 8 {
			uid := ParseUID(source)
			uSource = self.GetUserById(uid)
			if uSource == nil {
				self.SplitNode(node.Nearest(), "Invalid UID")
				return
			}
		}
	} else {
		sSource = node
	}

	name := tokens[0]

	if scmd := GetServerCommand(name); scmd != nil {
		err := scmd.Execute(self, sSource, uSource, tokens[1:])

		if err == Propagate {
			self.Propagate(node, "%s", line)
		} else if err != nil {
			self.SplitNode(node.Nearest(), err.Error())
		}
	} else if uSource != nil {
		if cmd := GetCommand(name); cmd != nil {
			if err := cmd.Execute(self, uSource, tokens[1:]); err != nil {
				self.SendError(uSource, err)
			}
		} else {
			self.SplitNode(node.Nearest(), "Unknown command: "+name)
		}
	} else {
		self.SplitNode(node.Nearest(), "Unknown command: "+name)
	}
}

func (self *Server) RecvServerMessage(node *ServerNode, tokens Tokens, line string) {
	self.serverMessages <- &ServerMessage{Node: node, Tokens: tokens, Line: line}
}

func (self *Server) ReportServerError(node *ServerNode, err error) {
	if opErr, ok := err.(*net.OpError); ok {
		err = opErr.Err
	}

	self.serverMessages <- &ServerMessage{Node: node, Error: err}
}

func (self *Server) RegisterServer(node *ServerNode, id SID, name, desc string, link *Link) {
	node.Id = id
	node.Name = name
	node.Description = desc

	route := node.Route
	route.Link = link
	route.IsLinked = true

	if !node.Route.Initiated {
		self.SendLink(node)
	}

	route.Handshake = nil

	self.SendBurst(node)

	self.ServerNotice('l', "Server %s linked successfully", node.Name)
	self.Propagate(node, ":%s SID %s %s :%s", self.Id, name, id, desc)

	delete(self.UnknownServers, node)
	self.Servers[id] = node
	self.ServerNames[name] = node
	self.Root.AddNode(node)

	node.ULine = self.ULines[name]

	for _, handler := range ServerLink {
		handler.(ServerLinkHandler).ServerLink(self, node)
	}
}

func (self *Server) AddUser(user *User) {
	self.Users[user.Id] = user
	self.UserNicks[IRCToLower(user.Nick)] = user
	self.AddClone(user)

	if numUsers := len(self.Users); numUsers > self.MaxGlobalUsers {
		self.MaxGlobalUsers = numUsers
	}
}

func (self *Server) NickCollision(a, b *User) {
	aTime, bTime := a.Connected, b.Connected

	if aTime.Equal(bTime) {
		self.SetNick(a, a.Id.String())
		self.SetNick(b, b.Id.String())
	} else {
		// Reverse behavior if ident and IP match
		isGhost := a.Ident == b.Ident && a.IP.Equal(b.IP)

		if isGhost == aTime.Before(bTime) {
			self.SetNick(a, a.Id.String())
		} else {
			self.SetNick(b, b.Id.String())
		}
	}
}

func (self *Server) ServerLoop(node *ServerNode) {
	var loopId string

	if node.Route.Initiated {
		loopId = node.Route.Link.Name
	} else {
		loopId = node.Route.Connection.RemoteAddr().String()
	}

	self.Log(Debug, "Goroutine spawned: Server loop for %s", loopId)

	defer func() {
		self.Log(Debug, "Goroutine exit: Server loop for %s", loopId)
		defer self.RoutineExit()
	}()

	// First, we need to open the connection
	if node.Route.Initiated {
		if err := self.resolveOutgoingLink(node); err != nil {
			self.ReportServerError(node, err)
			return
		}
	}

	self.RoutineStart()
	go self.serverRead(node)
	self.RoutineStart()
	go self.serverWrite(node)

	now := time.Now().UnixNano()
	nextPing := now + 10*1000000000
	pingTimeout := true

	route := node.Route

	node.Route.Handshake = new(Handshake)

	if route.Initiated {
		self.SendCapab(node)
	}

	for {
		select {
		case msg := <-route.Messages:
			switch msg {
			case SQuit:
				return
			case Linked:
				nextPing = now + route.Link.Timeout*1000000000
				pingTimeout = false
			}
		case line := <-route.Incoming:
			if line != "" {
				tokens := Tokenize(line, true, 15)

				if len(tokens) == 0 {
					panic("Zero length tokens after parsing: " + line)
				}

				self.RecvServerMessage(node, tokens, line)

				now = time.Now().UnixNano()

				if route.Link != nil {
					nextPing = now + route.Link.Timeout*1000000000
					pingTimeout = false
				}
				continue
			}
		case err := <-route.Errors:
			self.ReportServerError(node, err)
		case <-time.After(time.Duration(nextPing - now)):
			if pingTimeout {
				self.ReportServerError(node, PingTimeout)
				return
			} else {
				route.Send(":%s PING %s", self.Id, node.Id)
				nextPing += route.Link.Timeout * 1000000000
				pingTimeout = true
			}
		}

		now = time.Now().UnixNano()
	}
}

func (self *Server) serverRead(node *ServerNode) {
	defer self.RoutineExit()

	var buf [1 << 20]byte
	off := 0

	for {
		n, err := node.Route.Connection.Read(buf[off:])

		off += n

		for {
			end := bytes.IndexByte(buf[:off], '\n')

			if end == -1 {
				break
			}

			next := end + 1

			if end != 0 && buf[end-1] == '\r' {
				end--
			}

			line := string(buf[:end])
			copy(buf[:], buf[next:])
			off -= next

			node.Route.Incoming <- line
		}

		if err != nil {
			node.Route.Errors <- err
			break
		}
	}
}

func (self *Server) serverWrite(node *ServerNode) {
	defer self.RoutineExit()

	for {
		line := <-node.Route.Outgoing

		if line == "" {
			node.Route.Connection.Close()
			return
		}

		self.Log(Debug, "Outgoing line -> %s: %#v\n", node.Id, line)

		buf := []byte(line + "\r\n")
		off := 0

		for off < len(buf) {
			n, err := node.Route.Connection.Write(buf[off:])

			off += n

			if err != nil {
				node.Route.Errors <- err
				return
			}
		}
	}
}