source: code/trunk/user.go@ 428

Last change on this file since 428 was 423, checked in by contact, 5 years ago

Add message store abstraction

Introduce a messageStore type, which will allow for multiple
implementations (e.g. in the DB or in-memory instead of on-disk).

The message store is per-user so that we don't need to deal with locking
and it's easier to implement per-user limits.

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