source: code/trunk/user.go@ 452

Last change on this file since 452 was 451, checked in by contact, 4 years ago

Rename network.history to network.delivered

"History" is over-loaded with e.g. CHATHISTORY support.

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