source: code/trunk/user.go@ 440

Last change on this file since 440 was 439, checked in by contact, 4 years ago

Turn messageStore into an interface

This allows for other implementations that aren't based on a filesystem.

File size: 14.0 KB
RevLine 
[101]1package soju
2
3import (
[385]4 "crypto/sha256"
5 "encoding/binary"
[395]6 "encoding/hex"
[218]7 "fmt"
[101]8 "time"
[103]9
10 "gopkg.in/irc.v3"
[101]11)
12
[165]13type event interface{}
14
15type eventUpstreamMessage struct {
[103]16 msg *irc.Message
17 uc *upstreamConn
18}
19
[218]20type eventUpstreamConnectionError struct {
21 net *network
22 err error
23}
24
[196]25type eventUpstreamConnected struct {
26 uc *upstreamConn
27}
28
[179]29type eventUpstreamDisconnected struct {
30 uc *upstreamConn
31}
32
[218]33type eventUpstreamError struct {
34 uc *upstreamConn
35 err error
36}
37
[165]38type eventDownstreamMessage struct {
[103]39 msg *irc.Message
40 dc *downstreamConn
41}
42
[166]43type eventDownstreamConnected struct {
44 dc *downstreamConn
45}
46
[167]47type eventDownstreamDisconnected struct {
48 dc *downstreamConn
49}
50
[435]51type eventChannelDetach struct {
52 uc *upstreamConn
53 name string
54}
55
[376]56type eventStop struct{}
57
[253]58type networkHistory struct {
[409]59 clients map[string]string // indexed by client name
[253]60}
61
[101]62type network struct {
63 Network
[202]64 user *user
65 stopped chan struct{}
[131]66
[253]67 conn *upstreamConn
[267]68 channels map[string]*Channel
[253]69 history map[string]*networkHistory // indexed by entity
70 offlineClients map[string]struct{} // indexed by client name
71 lastError error
[101]72}
73
[267]74func newNetwork(user *user, record *Network, channels []Channel) *network {
75 m := make(map[string]*Channel, len(channels))
76 for _, ch := range channels {
[283]77 ch := ch
[267]78 m[ch.Name] = &ch
79 }
80
[101]81 return &network{
[253]82 Network: *record,
83 user: user,
84 stopped: make(chan struct{}),
[267]85 channels: m,
[253]86 history: make(map[string]*networkHistory),
87 offlineClients: make(map[string]struct{}),
[101]88 }
89}
90
[218]91func (net *network) forEachDownstream(f func(*downstreamConn)) {
92 net.user.forEachDownstream(func(dc *downstreamConn) {
93 if dc.network != nil && dc.network != net {
94 return
95 }
96 f(dc)
97 })
98}
99
[311]100func (net *network) isStopped() bool {
101 select {
102 case <-net.stopped:
103 return true
104 default:
105 return false
106 }
107}
108
[385]109func userIdent(u *User) string {
110 // The ident is a string we will send to upstream servers in clear-text.
111 // For privacy reasons, make sure it doesn't expose any meaningful user
112 // metadata. We just use the base64-encoded hashed ID, so that people don't
113 // start relying on the string being an integer or following a pattern.
114 var b [64]byte
115 binary.LittleEndian.PutUint64(b[:], uint64(u.ID))
116 h := sha256.Sum256(b[:])
[395]117 return hex.EncodeToString(h[:16])
[385]118}
119
[101]120func (net *network) run() {
121 var lastTry time.Time
122 for {
[311]123 if net.isStopped() {
[202]124 return
125 }
126
[398]127 if dur := time.Now().Sub(lastTry); dur < retryConnectDelay {
128 delay := retryConnectDelay - dur
[101]129 net.user.srv.Logger.Printf("waiting %v before trying to reconnect to %q", delay.Truncate(time.Second), net.Addr)
130 time.Sleep(delay)
131 }
132 lastTry = time.Now()
133
134 uc, err := connectToUpstream(net)
135 if err != nil {
136 net.user.srv.Logger.Printf("failed to connect to upstream server %q: %v", net.Addr, err)
[218]137 net.user.events <- eventUpstreamConnectionError{net, fmt.Errorf("failed to connect: %v", err)}
[101]138 continue
139 }
140
[385]141 if net.user.srv.Identd != nil {
142 net.user.srv.Identd.Store(uc.RemoteAddr().String(), uc.LocalAddr().String(), userIdent(&net.user.User))
143 }
144
[101]145 uc.register()
[197]146 if err := uc.runUntilRegistered(); err != nil {
[399]147 text := err.Error()
148 if regErr, ok := err.(registrationError); ok {
149 text = string(regErr)
150 }
151 uc.logger.Printf("failed to register: %v", text)
152 net.user.events <- eventUpstreamConnectionError{net, fmt.Errorf("failed to register: %v", text)}
[197]153 uc.Close()
154 continue
155 }
[101]156
[311]157 // TODO: this is racy with net.stopped. If the network is stopped
158 // before the user goroutine receives eventUpstreamConnected, the
159 // connection won't be closed.
[196]160 net.user.events <- eventUpstreamConnected{uc}
[165]161 if err := uc.readMessages(net.user.events); err != nil {
[101]162 uc.logger.Printf("failed to handle messages: %v", err)
[218]163 net.user.events <- eventUpstreamError{uc, fmt.Errorf("failed to handle messages: %v", err)}
[101]164 }
165 uc.Close()
[179]166 net.user.events <- eventUpstreamDisconnected{uc}
[385]167
168 if net.user.srv.Identd != nil {
169 net.user.srv.Identd.Delete(uc.RemoteAddr().String(), uc.LocalAddr().String())
170 }
[101]171 }
172}
173
[309]174func (net *network) stop() {
[311]175 if !net.isStopped() {
[202]176 close(net.stopped)
177 }
178
[279]179 if net.conn != nil {
180 net.conn.Close()
[202]181 }
182}
183
[435]184func (net *network) detach(ch *Channel) {
185 if ch.Detached {
186 return
[267]187 }
[435]188 ch.Detached = true
189 net.user.srv.Logger.Printf("network %q: detaching channel %q", net.GetName(), ch.Name)
190
191 if net.conn != nil {
192 if uch, ok := net.conn.channels[ch.Name]; ok {
193 uch.updateAutoDetach(0)
194 }
[222]195 }
[284]196
[435]197 net.forEachDownstream(func(dc *downstreamConn) {
198 net.offlineClients[dc.clientName] = struct{}{}
[284]199
[435]200 dc.SendMessage(&irc.Message{
201 Prefix: dc.prefix(),
202 Command: "PART",
203 Params: []string{dc.marshalEntity(net, ch.Name), "Detach"},
204 })
205 })
206}
[284]207
[435]208func (net *network) attach(ch *Channel) {
209 if !ch.Detached {
210 return
211 }
212 ch.Detached = false
213 net.user.srv.Logger.Printf("network %q: attaching channel %q", net.GetName(), ch.Name)
[284]214
[435]215 var uch *upstreamChannel
216 if net.conn != nil {
217 uch = net.conn.channels[ch.Name]
[284]218
[435]219 net.conn.updateChannelAutoDetach(ch.Name)
220 }
[284]221
[435]222 net.forEachDownstream(func(dc *downstreamConn) {
223 dc.SendMessage(&irc.Message{
224 Prefix: dc.prefix(),
225 Command: "JOIN",
226 Params: []string{dc.marshalEntity(net, ch.Name)},
227 })
228
229 if uch != nil {
230 forwardChannel(dc, uch)
[284]231 }
232
[435]233 if net.history[ch.Name] != nil {
234 dc.sendNetworkHistory(net)
235 }
236 })
[222]237}
238
239func (net *network) deleteChannel(name string) error {
[416]240 ch, ok := net.channels[name]
241 if !ok {
242 return fmt.Errorf("unknown channel %q", name)
243 }
[435]244 if net.conn != nil {
245 if uch, ok := net.conn.channels[ch.Name]; ok {
246 uch.updateAutoDetach(0)
247 }
248 }
249
[416]250 if err := net.user.srv.db.DeleteChannel(ch.ID); err != nil {
[267]251 return err
252 }
253 delete(net.channels, name)
254 return nil
[222]255}
256
[101]257type user struct {
258 User
259 srv *Server
260
[165]261 events chan event
[377]262 done chan struct{}
[103]263
[101]264 networks []*network
265 downstreamConns []*downstreamConn
[439]266 msgStore messageStore
[177]267
268 // LIST commands in progress
[179]269 pendingLISTs []pendingLIST
[101]270}
271
[177]272type pendingLIST struct {
273 downstreamID uint64
274 // list of per-upstream LIST commands not yet sent or completed
275 pendingCommands map[int64]*irc.Message
276}
277
[101]278func newUser(srv *Server, record *User) *user {
[439]279 var msgStore messageStore
[423]280 if srv.LogPath != "" {
[439]281 msgStore = newFSMessageStore(srv.LogPath, record.Username)
[423]282 }
283
[101]284 return &user{
[423]285 User: *record,
286 srv: srv,
287 events: make(chan event, 64),
288 done: make(chan struct{}),
289 msgStore: msgStore,
[101]290 }
291}
292
293func (u *user) forEachNetwork(f func(*network)) {
294 for _, network := range u.networks {
295 f(network)
296 }
297}
298
299func (u *user) forEachUpstream(f func(uc *upstreamConn)) {
300 for _, network := range u.networks {
[279]301 if network.conn == nil {
[101]302 continue
303 }
[279]304 f(network.conn)
[101]305 }
306}
307
308func (u *user) forEachDownstream(f func(dc *downstreamConn)) {
309 for _, dc := range u.downstreamConns {
310 f(dc)
311 }
312}
313
314func (u *user) getNetwork(name string) *network {
315 for _, network := range u.networks {
316 if network.Addr == name {
317 return network
318 }
[201]319 if network.Name != "" && network.Name == name {
320 return network
321 }
[101]322 }
323 return nil
324}
325
[313]326func (u *user) getNetworkByID(id int64) *network {
327 for _, net := range u.networks {
328 if net.ID == id {
329 return net
330 }
331 }
332 return nil
333}
334
[101]335func (u *user) run() {
[423]336 defer func() {
337 if u.msgStore != nil {
338 if err := u.msgStore.Close(); err != nil {
339 u.srv.Logger.Printf("failed to close message store for user %q: %v", u.Username, err)
340 }
341 }
342 close(u.done)
343 }()
[377]344
[421]345 networks, err := u.srv.db.ListNetworks(u.ID)
[101]346 if err != nil {
347 u.srv.Logger.Printf("failed to list networks for user %q: %v", u.Username, err)
348 return
349 }
350
351 for _, record := range networks {
[283]352 record := record
[267]353 channels, err := u.srv.db.ListChannels(record.ID)
354 if err != nil {
355 u.srv.Logger.Printf("failed to list channels for user %q, network %q: %v", u.Username, record.GetName(), err)
[359]356 continue
[267]357 }
358
359 network := newNetwork(u, &record, channels)
[101]360 u.networks = append(u.networks, network)
361
362 go network.run()
363 }
[103]364
[165]365 for e := range u.events {
366 switch e := e.(type) {
[196]367 case eventUpstreamConnected:
[198]368 uc := e.uc
[199]369
370 uc.network.conn = uc
371
[198]372 uc.updateAway()
[218]373
374 uc.forEachDownstream(func(dc *downstreamConn) {
[276]375 dc.updateSupportedCaps()
[223]376 sendServiceNOTICE(dc, fmt.Sprintf("connected to %s", uc.network.GetName()))
[296]377
378 dc.updateNick()
[218]379 })
380 uc.network.lastError = nil
[179]381 case eventUpstreamDisconnected:
[313]382 u.handleUpstreamDisconnected(e.uc)
383 case eventUpstreamConnectionError:
384 net := e.net
[199]385
[313]386 stopped := false
387 select {
388 case <-net.stopped:
389 stopped = true
390 default:
[179]391 }
[199]392
[313]393 if !stopped && (net.lastError == nil || net.lastError.Error() != e.err.Error()) {
[218]394 net.forEachDownstream(func(dc *downstreamConn) {
[223]395 sendServiceNOTICE(dc, fmt.Sprintf("failed connecting/registering to %s: %v", net.GetName(), e.err))
[218]396 })
397 }
398 net.lastError = e.err
399 case eventUpstreamError:
400 uc := e.uc
401
402 uc.forEachDownstream(func(dc *downstreamConn) {
[223]403 sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s: %v", uc.network.GetName(), e.err))
[218]404 })
405 uc.network.lastError = e.err
[165]406 case eventUpstreamMessage:
407 msg, uc := e.msg, e.uc
[175]408 if uc.isClosed() {
[133]409 uc.logger.Printf("ignoring message on closed connection: %v", msg)
410 break
411 }
[103]412 if err := uc.handleMessage(msg); err != nil {
413 uc.logger.Printf("failed to handle message %q: %v", msg, err)
414 }
[435]415 case eventChannelDetach:
416 uc, name := e.uc, e.name
417 c, ok := uc.network.channels[name]
418 if !ok || c.Detached {
419 continue
420 }
421 uc.network.detach(c)
422 if err := uc.srv.db.StoreChannel(uc.network.ID, c); err != nil {
423 u.srv.Logger.Printf("failed to store updated detached channel %q: %v", c.Name, err)
424 }
[166]425 case eventDownstreamConnected:
426 dc := e.dc
[168]427
428 if err := dc.welcome(); err != nil {
429 dc.logger.Printf("failed to handle new registered connection: %v", err)
430 break
431 }
432
[166]433 u.downstreamConns = append(u.downstreamConns, dc)
[198]434
435 u.forEachUpstream(func(uc *upstreamConn) {
436 uc.updateAway()
437 })
[167]438 case eventDownstreamDisconnected:
439 dc := e.dc
[204]440
[167]441 for i := range u.downstreamConns {
442 if u.downstreamConns[i] == dc {
443 u.downstreamConns = append(u.downstreamConns[:i], u.downstreamConns[i+1:]...)
444 break
445 }
446 }
[198]447
[253]448 // Save history if we're the last client with this name
449 skipHistory := make(map[*network]bool)
450 u.forEachDownstream(func(conn *downstreamConn) {
451 if dc.clientName == conn.clientName {
452 skipHistory[conn.network] = true
453 }
454 })
455
456 dc.forEachNetwork(func(net *network) {
457 if skipHistory[net] || skipHistory[nil] {
458 return
459 }
460
461 net.offlineClients[dc.clientName] = struct{}{}
462 })
463
[198]464 u.forEachUpstream(func(uc *upstreamConn) {
465 uc.updateAway()
466 })
[165]467 case eventDownstreamMessage:
468 msg, dc := e.msg, e.dc
[133]469 if dc.isClosed() {
470 dc.logger.Printf("ignoring message on closed connection: %v", msg)
471 break
472 }
[103]473 err := dc.handleMessage(msg)
474 if ircErr, ok := err.(ircError); ok {
475 ircErr.Message.Prefix = dc.srv.prefix()
476 dc.SendMessage(ircErr.Message)
477 } else if err != nil {
478 dc.logger.Printf("failed to handle message %q: %v", msg, err)
479 dc.Close()
480 }
[376]481 case eventStop:
482 u.forEachDownstream(func(dc *downstreamConn) {
483 dc.Close()
484 })
485 for _, n := range u.networks {
486 n.stop()
487 }
488 return
[165]489 default:
490 u.srv.Logger.Printf("received unknown event type: %T", e)
[103]491 }
492 }
[101]493}
494
[313]495func (u *user) handleUpstreamDisconnected(uc *upstreamConn) {
496 uc.network.conn = nil
497
498 uc.endPendingLISTs(true)
499
[435]500 for _, uch := range uc.channels {
501 uch.updateAutoDetach(0)
502 }
503
[313]504 uc.forEachDownstream(func(dc *downstreamConn) {
505 dc.updateSupportedCaps()
506 })
507
508 if uc.network.lastError == nil {
509 uc.forEachDownstream(func(dc *downstreamConn) {
510 sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s", uc.network.GetName()))
511 })
512 }
513}
514
515func (u *user) addNetwork(network *network) {
516 u.networks = append(u.networks, network)
517 go network.run()
518}
519
520func (u *user) removeNetwork(network *network) {
521 network.stop()
522
523 u.forEachDownstream(func(dc *downstreamConn) {
524 if dc.network != nil && dc.network == network {
525 dc.Close()
526 }
527 })
528
529 for i, net := range u.networks {
530 if net == network {
531 u.networks = append(u.networks[:i], u.networks[i+1:]...)
532 return
533 }
534 }
535
536 panic("tried to remove a non-existing network")
537}
538
539func (u *user) createNetwork(record *Network) (*network, error) {
540 if record.ID != 0 {
[144]541 panic("tried creating an already-existing network")
542 }
543
[313]544 network := newNetwork(u, record, nil)
[421]545 err := u.srv.db.StoreNetwork(u.ID, &network.Network)
[101]546 if err != nil {
547 return nil, err
548 }
[144]549
[313]550 u.addNetwork(network)
[144]551
[101]552 return network, nil
553}
[202]554
[313]555func (u *user) updateNetwork(record *Network) (*network, error) {
556 if record.ID == 0 {
557 panic("tried updating a new network")
558 }
[202]559
[313]560 network := u.getNetworkByID(record.ID)
561 if network == nil {
562 panic("tried updating a non-existing network")
563 }
564
[421]565 if err := u.srv.db.StoreNetwork(u.ID, record); err != nil {
[313]566 return nil, err
567 }
568
569 // Most network changes require us to re-connect to the upstream server
570
571 channels := make([]Channel, 0, len(network.channels))
572 for _, ch := range network.channels {
573 channels = append(channels, *ch)
574 }
575
576 updatedNetwork := newNetwork(u, record, channels)
577
578 // If we're currently connected, disconnect and perform the necessary
579 // bookkeeping
580 if network.conn != nil {
581 network.stop()
582 // Note: this will set network.conn to nil
583 u.handleUpstreamDisconnected(network.conn)
584 }
585
586 // Patch downstream connections to use our fresh updated network
587 u.forEachDownstream(func(dc *downstreamConn) {
588 if dc.network != nil && dc.network == network {
589 dc.network = updatedNetwork
[202]590 }
[313]591 })
[202]592
[313]593 // We need to remove the network after patching downstream connections,
594 // otherwise they'll get closed
595 u.removeNetwork(network)
[202]596
[313]597 // This will re-connect to the upstream server
598 u.addNetwork(updatedNetwork)
599
600 return updatedNetwork, nil
601}
602
603func (u *user) deleteNetwork(id int64) error {
604 network := u.getNetworkByID(id)
605 if network == nil {
606 panic("tried deleting a non-existing network")
[202]607 }
608
[313]609 if err := u.srv.db.DeleteNetwork(network.ID); err != nil {
610 return err
611 }
612
613 u.removeNetwork(network)
614 return nil
[202]615}
[252]616
617func (u *user) updatePassword(hashed string) error {
618 u.User.Password = hashed
[324]619 return u.srv.db.StoreUser(&u.User)
[252]620}
[376]621
622func (u *user) stop() {
623 u.events <- eventStop{}
[377]624 <-u.done
[376]625}
Note: See TracBrowser for help on using the repository browser.