1 | package soju
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "crypto/sha256"
|
---|
5 | "encoding/binary"
|
---|
6 | "encoding/hex"
|
---|
7 | "fmt"
|
---|
8 | "time"
|
---|
9 |
|
---|
10 | "gopkg.in/irc.v3"
|
---|
11 | )
|
---|
12 |
|
---|
13 | type event interface{}
|
---|
14 |
|
---|
15 | type eventUpstreamMessage struct {
|
---|
16 | msg *irc.Message
|
---|
17 | uc *upstreamConn
|
---|
18 | }
|
---|
19 |
|
---|
20 | type eventUpstreamConnectionError struct {
|
---|
21 | net *network
|
---|
22 | err error
|
---|
23 | }
|
---|
24 |
|
---|
25 | type eventUpstreamConnected struct {
|
---|
26 | uc *upstreamConn
|
---|
27 | }
|
---|
28 |
|
---|
29 | type eventUpstreamDisconnected struct {
|
---|
30 | uc *upstreamConn
|
---|
31 | }
|
---|
32 |
|
---|
33 | type eventUpstreamError struct {
|
---|
34 | uc *upstreamConn
|
---|
35 | err error
|
---|
36 | }
|
---|
37 |
|
---|
38 | type eventDownstreamMessage struct {
|
---|
39 | msg *irc.Message
|
---|
40 | dc *downstreamConn
|
---|
41 | }
|
---|
42 |
|
---|
43 | type eventDownstreamConnected struct {
|
---|
44 | dc *downstreamConn
|
---|
45 | }
|
---|
46 |
|
---|
47 | type eventDownstreamDisconnected struct {
|
---|
48 | dc *downstreamConn
|
---|
49 | }
|
---|
50 |
|
---|
51 | type eventChannelDetach struct {
|
---|
52 | uc *upstreamConn
|
---|
53 | name string
|
---|
54 | }
|
---|
55 |
|
---|
56 | type eventBroadcast struct {
|
---|
57 | msg *irc.Message
|
---|
58 | }
|
---|
59 |
|
---|
60 | type eventStop struct{}
|
---|
61 |
|
---|
62 | type deliveredClientMap map[string]string // client name -> msg ID
|
---|
63 |
|
---|
64 | type deliveredStore struct {
|
---|
65 | m deliveredCasemapMap
|
---|
66 | }
|
---|
67 |
|
---|
68 | func newDeliveredStore() deliveredStore {
|
---|
69 | return deliveredStore{deliveredCasemapMap{newCasemapMap(0)}}
|
---|
70 | }
|
---|
71 |
|
---|
72 | func (ds deliveredStore) HasTarget(target string) bool {
|
---|
73 | return ds.m.Value(target) != nil
|
---|
74 | }
|
---|
75 |
|
---|
76 | func (ds deliveredStore) LoadID(target, clientName string) string {
|
---|
77 | clients := ds.m.Value(target)
|
---|
78 | if clients == nil {
|
---|
79 | return ""
|
---|
80 | }
|
---|
81 | return clients[clientName]
|
---|
82 | }
|
---|
83 |
|
---|
84 | func (ds deliveredStore) StoreID(target, clientName, msgID string) {
|
---|
85 | clients := ds.m.Value(target)
|
---|
86 | if clients == nil {
|
---|
87 | clients = make(deliveredClientMap)
|
---|
88 | ds.m.SetValue(target, clients)
|
---|
89 | }
|
---|
90 | clients[clientName] = msgID
|
---|
91 | }
|
---|
92 |
|
---|
93 | func (ds deliveredStore) ForEachTarget(f func(target string)) {
|
---|
94 | for _, entry := range ds.m.innerMap {
|
---|
95 | f(entry.originalKey)
|
---|
96 | }
|
---|
97 | }
|
---|
98 |
|
---|
99 | func (ds deliveredStore) ForEachClient(f func(clientName string)) {
|
---|
100 | clients := make(map[string]struct{})
|
---|
101 | for _, entry := range ds.m.innerMap {
|
---|
102 | delivered := entry.value.(deliveredClientMap)
|
---|
103 | for clientName := range delivered {
|
---|
104 | clients[clientName] = struct{}{}
|
---|
105 | }
|
---|
106 | }
|
---|
107 |
|
---|
108 | for clientName := range clients {
|
---|
109 | f(clientName)
|
---|
110 | }
|
---|
111 | }
|
---|
112 |
|
---|
113 | type network struct {
|
---|
114 | Network
|
---|
115 | user *user
|
---|
116 | logger Logger
|
---|
117 | stopped chan struct{}
|
---|
118 |
|
---|
119 | conn *upstreamConn
|
---|
120 | channels channelCasemapMap
|
---|
121 | delivered deliveredStore
|
---|
122 | lastError error
|
---|
123 | casemap casemapping
|
---|
124 | }
|
---|
125 |
|
---|
126 | func newNetwork(user *user, record *Network, channels []Channel) *network {
|
---|
127 | logger := &prefixLogger{user.logger, fmt.Sprintf("network %q: ", record.GetName())}
|
---|
128 |
|
---|
129 | m := channelCasemapMap{newCasemapMap(0)}
|
---|
130 | for _, ch := range channels {
|
---|
131 | ch := ch
|
---|
132 | m.SetValue(ch.Name, &ch)
|
---|
133 | }
|
---|
134 |
|
---|
135 | return &network{
|
---|
136 | Network: *record,
|
---|
137 | user: user,
|
---|
138 | logger: logger,
|
---|
139 | stopped: make(chan struct{}),
|
---|
140 | channels: m,
|
---|
141 | delivered: newDeliveredStore(),
|
---|
142 | casemap: casemapRFC1459,
|
---|
143 | }
|
---|
144 | }
|
---|
145 |
|
---|
146 | func (net *network) forEachDownstream(f func(*downstreamConn)) {
|
---|
147 | net.user.forEachDownstream(func(dc *downstreamConn) {
|
---|
148 | if dc.network == nil && dc.caps["soju.im/bouncer-networks"] {
|
---|
149 | return
|
---|
150 | }
|
---|
151 | if dc.network != nil && dc.network != net {
|
---|
152 | return
|
---|
153 | }
|
---|
154 | f(dc)
|
---|
155 | })
|
---|
156 | }
|
---|
157 |
|
---|
158 | func (net *network) isStopped() bool {
|
---|
159 | select {
|
---|
160 | case <-net.stopped:
|
---|
161 | return true
|
---|
162 | default:
|
---|
163 | return false
|
---|
164 | }
|
---|
165 | }
|
---|
166 |
|
---|
167 | func userIdent(u *User) string {
|
---|
168 | // The ident is a string we will send to upstream servers in clear-text.
|
---|
169 | // For privacy reasons, make sure it doesn't expose any meaningful user
|
---|
170 | // metadata. We just use the base64-encoded hashed ID, so that people don't
|
---|
171 | // start relying on the string being an integer or following a pattern.
|
---|
172 | var b [64]byte
|
---|
173 | binary.LittleEndian.PutUint64(b[:], uint64(u.ID))
|
---|
174 | h := sha256.Sum256(b[:])
|
---|
175 | return hex.EncodeToString(h[:16])
|
---|
176 | }
|
---|
177 |
|
---|
178 | func (net *network) run() {
|
---|
179 | if !net.Enabled {
|
---|
180 | return
|
---|
181 | }
|
---|
182 |
|
---|
183 | var lastTry time.Time
|
---|
184 | for {
|
---|
185 | if net.isStopped() {
|
---|
186 | return
|
---|
187 | }
|
---|
188 |
|
---|
189 | if dur := time.Now().Sub(lastTry); dur < retryConnectDelay {
|
---|
190 | delay := retryConnectDelay - dur
|
---|
191 | net.logger.Printf("waiting %v before trying to reconnect to %q", delay.Truncate(time.Second), net.Addr)
|
---|
192 | time.Sleep(delay)
|
---|
193 | }
|
---|
194 | lastTry = time.Now()
|
---|
195 |
|
---|
196 | uc, err := connectToUpstream(net)
|
---|
197 | if err != nil {
|
---|
198 | net.logger.Printf("failed to connect to upstream server %q: %v", net.Addr, err)
|
---|
199 | net.user.events <- eventUpstreamConnectionError{net, fmt.Errorf("failed to connect: %v", err)}
|
---|
200 | continue
|
---|
201 | }
|
---|
202 |
|
---|
203 | if net.user.srv.Identd != nil {
|
---|
204 | net.user.srv.Identd.Store(uc.RemoteAddr().String(), uc.LocalAddr().String(), userIdent(&net.user.User))
|
---|
205 | }
|
---|
206 |
|
---|
207 | uc.register()
|
---|
208 | if err := uc.runUntilRegistered(); err != nil {
|
---|
209 | text := err.Error()
|
---|
210 | if regErr, ok := err.(registrationError); ok {
|
---|
211 | text = string(regErr)
|
---|
212 | }
|
---|
213 | uc.logger.Printf("failed to register: %v", text)
|
---|
214 | net.user.events <- eventUpstreamConnectionError{net, fmt.Errorf("failed to register: %v", text)}
|
---|
215 | uc.Close()
|
---|
216 | continue
|
---|
217 | }
|
---|
218 |
|
---|
219 | // TODO: this is racy with net.stopped. If the network is stopped
|
---|
220 | // before the user goroutine receives eventUpstreamConnected, the
|
---|
221 | // connection won't be closed.
|
---|
222 | net.user.events <- eventUpstreamConnected{uc}
|
---|
223 | if err := uc.readMessages(net.user.events); err != nil {
|
---|
224 | uc.logger.Printf("failed to handle messages: %v", err)
|
---|
225 | net.user.events <- eventUpstreamError{uc, fmt.Errorf("failed to handle messages: %v", err)}
|
---|
226 | }
|
---|
227 | uc.Close()
|
---|
228 | net.user.events <- eventUpstreamDisconnected{uc}
|
---|
229 |
|
---|
230 | if net.user.srv.Identd != nil {
|
---|
231 | net.user.srv.Identd.Delete(uc.RemoteAddr().String(), uc.LocalAddr().String())
|
---|
232 | }
|
---|
233 | }
|
---|
234 | }
|
---|
235 |
|
---|
236 | func (net *network) stop() {
|
---|
237 | if !net.isStopped() {
|
---|
238 | close(net.stopped)
|
---|
239 | }
|
---|
240 |
|
---|
241 | if net.conn != nil {
|
---|
242 | net.conn.Close()
|
---|
243 | }
|
---|
244 | }
|
---|
245 |
|
---|
246 | func (net *network) detach(ch *Channel) {
|
---|
247 | if ch.Detached {
|
---|
248 | return
|
---|
249 | }
|
---|
250 |
|
---|
251 | net.logger.Printf("detaching channel %q", ch.Name)
|
---|
252 |
|
---|
253 | ch.Detached = true
|
---|
254 |
|
---|
255 | if net.user.msgStore != nil {
|
---|
256 | nameCM := net.casemap(ch.Name)
|
---|
257 | lastID, err := net.user.msgStore.LastMsgID(net, nameCM, time.Now())
|
---|
258 | if err != nil {
|
---|
259 | net.logger.Printf("failed to get last message ID for channel %q: %v", ch.Name, err)
|
---|
260 | }
|
---|
261 | ch.DetachedInternalMsgID = lastID
|
---|
262 | }
|
---|
263 |
|
---|
264 | if net.conn != nil {
|
---|
265 | uch := net.conn.channels.Value(ch.Name)
|
---|
266 | if uch != nil {
|
---|
267 | uch.updateAutoDetach(0)
|
---|
268 | }
|
---|
269 | }
|
---|
270 |
|
---|
271 | net.forEachDownstream(func(dc *downstreamConn) {
|
---|
272 | dc.SendMessage(&irc.Message{
|
---|
273 | Prefix: dc.prefix(),
|
---|
274 | Command: "PART",
|
---|
275 | Params: []string{dc.marshalEntity(net, ch.Name), "Detach"},
|
---|
276 | })
|
---|
277 | })
|
---|
278 | }
|
---|
279 |
|
---|
280 | func (net *network) attach(ch *Channel) {
|
---|
281 | if !ch.Detached {
|
---|
282 | return
|
---|
283 | }
|
---|
284 |
|
---|
285 | net.logger.Printf("attaching channel %q", ch.Name)
|
---|
286 |
|
---|
287 | detachedMsgID := ch.DetachedInternalMsgID
|
---|
288 | ch.Detached = false
|
---|
289 | ch.DetachedInternalMsgID = ""
|
---|
290 |
|
---|
291 | var uch *upstreamChannel
|
---|
292 | if net.conn != nil {
|
---|
293 | uch = net.conn.channels.Value(ch.Name)
|
---|
294 |
|
---|
295 | net.conn.updateChannelAutoDetach(ch.Name)
|
---|
296 | }
|
---|
297 |
|
---|
298 | net.forEachDownstream(func(dc *downstreamConn) {
|
---|
299 | dc.SendMessage(&irc.Message{
|
---|
300 | Prefix: dc.prefix(),
|
---|
301 | Command: "JOIN",
|
---|
302 | Params: []string{dc.marshalEntity(net, ch.Name)},
|
---|
303 | })
|
---|
304 |
|
---|
305 | if uch != nil {
|
---|
306 | forwardChannel(dc, uch)
|
---|
307 | }
|
---|
308 |
|
---|
309 | if detachedMsgID != "" {
|
---|
310 | dc.sendTargetBacklog(net, ch.Name, detachedMsgID)
|
---|
311 | }
|
---|
312 | })
|
---|
313 | }
|
---|
314 |
|
---|
315 | func (net *network) deleteChannel(name string) error {
|
---|
316 | ch := net.channels.Value(name)
|
---|
317 | if ch == nil {
|
---|
318 | return fmt.Errorf("unknown channel %q", name)
|
---|
319 | }
|
---|
320 | if net.conn != nil {
|
---|
321 | uch := net.conn.channels.Value(ch.Name)
|
---|
322 | if uch != nil {
|
---|
323 | uch.updateAutoDetach(0)
|
---|
324 | }
|
---|
325 | }
|
---|
326 |
|
---|
327 | if err := net.user.srv.db.DeleteChannel(ch.ID); err != nil {
|
---|
328 | return err
|
---|
329 | }
|
---|
330 | net.channels.Delete(name)
|
---|
331 | return nil
|
---|
332 | }
|
---|
333 |
|
---|
334 | func (net *network) updateCasemapping(newCasemap casemapping) {
|
---|
335 | net.casemap = newCasemap
|
---|
336 | net.channels.SetCasemapping(newCasemap)
|
---|
337 | net.delivered.m.SetCasemapping(newCasemap)
|
---|
338 | if net.conn != nil {
|
---|
339 | net.conn.channels.SetCasemapping(newCasemap)
|
---|
340 | for _, entry := range net.conn.channels.innerMap {
|
---|
341 | uch := entry.value.(*upstreamChannel)
|
---|
342 | uch.Members.SetCasemapping(newCasemap)
|
---|
343 | }
|
---|
344 | }
|
---|
345 | }
|
---|
346 |
|
---|
347 | func (net *network) storeClientDeliveryReceipts(clientName string) {
|
---|
348 | if !net.user.hasPersistentMsgStore() {
|
---|
349 | return
|
---|
350 | }
|
---|
351 |
|
---|
352 | var receipts []DeliveryReceipt
|
---|
353 | net.delivered.ForEachTarget(func(target string) {
|
---|
354 | msgID := net.delivered.LoadID(target, clientName)
|
---|
355 | if msgID == "" {
|
---|
356 | return
|
---|
357 | }
|
---|
358 | receipts = append(receipts, DeliveryReceipt{
|
---|
359 | Target: target,
|
---|
360 | InternalMsgID: msgID,
|
---|
361 | })
|
---|
362 | })
|
---|
363 |
|
---|
364 | if err := net.user.srv.db.StoreClientDeliveryReceipts(net.ID, clientName, receipts); err != nil {
|
---|
365 | net.logger.Printf("failed to store delivery receipts for client %q: %v", clientName, err)
|
---|
366 | }
|
---|
367 | }
|
---|
368 |
|
---|
369 | func (net *network) isHighlight(msg *irc.Message) bool {
|
---|
370 | if msg.Command != "PRIVMSG" && msg.Command != "NOTICE" {
|
---|
371 | return false
|
---|
372 | }
|
---|
373 |
|
---|
374 | text := msg.Params[1]
|
---|
375 |
|
---|
376 | nick := net.Nick
|
---|
377 | if net.conn != nil {
|
---|
378 | nick = net.conn.nick
|
---|
379 | }
|
---|
380 |
|
---|
381 | // TODO: use case-mapping aware comparison here
|
---|
382 | return msg.Prefix.Name != nick && isHighlight(text, nick)
|
---|
383 | }
|
---|
384 |
|
---|
385 | func (net *network) detachedMessageNeedsRelay(ch *Channel, msg *irc.Message) bool {
|
---|
386 | highlight := net.isHighlight(msg)
|
---|
387 | return ch.RelayDetached == FilterMessage || ((ch.RelayDetached == FilterHighlight || ch.RelayDetached == FilterDefault) && highlight)
|
---|
388 | }
|
---|
389 |
|
---|
390 | type user struct {
|
---|
391 | User
|
---|
392 | srv *Server
|
---|
393 | logger Logger
|
---|
394 |
|
---|
395 | events chan event
|
---|
396 | done chan struct{}
|
---|
397 |
|
---|
398 | networks []*network
|
---|
399 | downstreamConns []*downstreamConn
|
---|
400 | msgStore messageStore
|
---|
401 |
|
---|
402 | // LIST commands in progress
|
---|
403 | pendingLISTs []pendingLIST
|
---|
404 | }
|
---|
405 |
|
---|
406 | type pendingLIST struct {
|
---|
407 | downstreamID uint64
|
---|
408 | // list of per-upstream LIST commands not yet sent or completed
|
---|
409 | pendingCommands map[int64]*irc.Message
|
---|
410 | }
|
---|
411 |
|
---|
412 | func newUser(srv *Server, record *User) *user {
|
---|
413 | logger := &prefixLogger{srv.Logger, fmt.Sprintf("user %q: ", record.Username)}
|
---|
414 |
|
---|
415 | var msgStore messageStore
|
---|
416 | if srv.LogPath != "" {
|
---|
417 | msgStore = newFSMessageStore(srv.LogPath, record.Username)
|
---|
418 | } else {
|
---|
419 | msgStore = newMemoryMessageStore()
|
---|
420 | }
|
---|
421 |
|
---|
422 | return &user{
|
---|
423 | User: *record,
|
---|
424 | srv: srv,
|
---|
425 | logger: logger,
|
---|
426 | events: make(chan event, 64),
|
---|
427 | done: make(chan struct{}),
|
---|
428 | msgStore: msgStore,
|
---|
429 | }
|
---|
430 | }
|
---|
431 |
|
---|
432 | func (u *user) forEachNetwork(f func(*network)) {
|
---|
433 | for _, network := range u.networks {
|
---|
434 | f(network)
|
---|
435 | }
|
---|
436 | }
|
---|
437 |
|
---|
438 | func (u *user) forEachUpstream(f func(uc *upstreamConn)) {
|
---|
439 | for _, network := range u.networks {
|
---|
440 | if network.conn == nil {
|
---|
441 | continue
|
---|
442 | }
|
---|
443 | f(network.conn)
|
---|
444 | }
|
---|
445 | }
|
---|
446 |
|
---|
447 | func (u *user) forEachDownstream(f func(dc *downstreamConn)) {
|
---|
448 | for _, dc := range u.downstreamConns {
|
---|
449 | f(dc)
|
---|
450 | }
|
---|
451 | }
|
---|
452 |
|
---|
453 | func (u *user) getNetwork(name string) *network {
|
---|
454 | for _, network := range u.networks {
|
---|
455 | if network.Addr == name {
|
---|
456 | return network
|
---|
457 | }
|
---|
458 | if network.Name != "" && network.Name == name {
|
---|
459 | return network
|
---|
460 | }
|
---|
461 | }
|
---|
462 | return nil
|
---|
463 | }
|
---|
464 |
|
---|
465 | func (u *user) getNetworkByID(id int64) *network {
|
---|
466 | for _, net := range u.networks {
|
---|
467 | if net.ID == id {
|
---|
468 | return net
|
---|
469 | }
|
---|
470 | }
|
---|
471 | return nil
|
---|
472 | }
|
---|
473 |
|
---|
474 | func (u *user) run() {
|
---|
475 | defer func() {
|
---|
476 | if u.msgStore != nil {
|
---|
477 | if err := u.msgStore.Close(); err != nil {
|
---|
478 | u.logger.Printf("failed to close message store for user %q: %v", u.Username, err)
|
---|
479 | }
|
---|
480 | }
|
---|
481 | close(u.done)
|
---|
482 | }()
|
---|
483 |
|
---|
484 | networks, err := u.srv.db.ListNetworks(u.ID)
|
---|
485 | if err != nil {
|
---|
486 | u.logger.Printf("failed to list networks for user %q: %v", u.Username, err)
|
---|
487 | return
|
---|
488 | }
|
---|
489 |
|
---|
490 | for _, record := range networks {
|
---|
491 | record := record
|
---|
492 | channels, err := u.srv.db.ListChannels(record.ID)
|
---|
493 | if err != nil {
|
---|
494 | u.logger.Printf("failed to list channels for user %q, network %q: %v", u.Username, record.GetName(), err)
|
---|
495 | continue
|
---|
496 | }
|
---|
497 |
|
---|
498 | network := newNetwork(u, &record, channels)
|
---|
499 | u.networks = append(u.networks, network)
|
---|
500 |
|
---|
501 | if u.hasPersistentMsgStore() {
|
---|
502 | receipts, err := u.srv.db.ListDeliveryReceipts(record.ID)
|
---|
503 | if err != nil {
|
---|
504 | u.logger.Printf("failed to load delivery receipts for user %q, network %q: %v", u.Username, network.GetName(), err)
|
---|
505 | return
|
---|
506 | }
|
---|
507 |
|
---|
508 | for _, rcpt := range receipts {
|
---|
509 | network.delivered.StoreID(rcpt.Target, rcpt.Client, rcpt.InternalMsgID)
|
---|
510 | }
|
---|
511 | }
|
---|
512 |
|
---|
513 | go network.run()
|
---|
514 | }
|
---|
515 |
|
---|
516 | for e := range u.events {
|
---|
517 | switch e := e.(type) {
|
---|
518 | case eventUpstreamConnected:
|
---|
519 | uc := e.uc
|
---|
520 |
|
---|
521 | uc.network.conn = uc
|
---|
522 |
|
---|
523 | uc.updateAway()
|
---|
524 |
|
---|
525 | netIDStr := fmt.Sprintf("%v", uc.network.ID)
|
---|
526 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
527 | dc.updateSupportedCaps()
|
---|
528 |
|
---|
529 | if !dc.caps["soju.im/bouncer-networks"] {
|
---|
530 | sendServiceNOTICE(dc, fmt.Sprintf("connected to %s", uc.network.GetName()))
|
---|
531 | }
|
---|
532 |
|
---|
533 | dc.updateNick()
|
---|
534 | dc.updateRealname()
|
---|
535 | })
|
---|
536 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
537 | if dc.caps["soju.im/bouncer-networks-notify"] {
|
---|
538 | dc.SendMessage(&irc.Message{
|
---|
539 | Prefix: dc.srv.prefix(),
|
---|
540 | Command: "BOUNCER",
|
---|
541 | Params: []string{"NETWORK", netIDStr, "state=connected"},
|
---|
542 | })
|
---|
543 | }
|
---|
544 | })
|
---|
545 | uc.network.lastError = nil
|
---|
546 | case eventUpstreamDisconnected:
|
---|
547 | u.handleUpstreamDisconnected(e.uc)
|
---|
548 | case eventUpstreamConnectionError:
|
---|
549 | net := e.net
|
---|
550 |
|
---|
551 | stopped := false
|
---|
552 | select {
|
---|
553 | case <-net.stopped:
|
---|
554 | stopped = true
|
---|
555 | default:
|
---|
556 | }
|
---|
557 |
|
---|
558 | if !stopped && (net.lastError == nil || net.lastError.Error() != e.err.Error()) {
|
---|
559 | net.forEachDownstream(func(dc *downstreamConn) {
|
---|
560 | sendServiceNOTICE(dc, fmt.Sprintf("failed connecting/registering to %s: %v", net.GetName(), e.err))
|
---|
561 | })
|
---|
562 | }
|
---|
563 | net.lastError = e.err
|
---|
564 | case eventUpstreamError:
|
---|
565 | uc := e.uc
|
---|
566 |
|
---|
567 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
568 | sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s: %v", uc.network.GetName(), e.err))
|
---|
569 | })
|
---|
570 | uc.network.lastError = e.err
|
---|
571 | case eventUpstreamMessage:
|
---|
572 | msg, uc := e.msg, e.uc
|
---|
573 | if uc.isClosed() {
|
---|
574 | uc.logger.Printf("ignoring message on closed connection: %v", msg)
|
---|
575 | break
|
---|
576 | }
|
---|
577 | if err := uc.handleMessage(msg); err != nil {
|
---|
578 | uc.logger.Printf("failed to handle message %q: %v", msg, err)
|
---|
579 | }
|
---|
580 | case eventChannelDetach:
|
---|
581 | uc, name := e.uc, e.name
|
---|
582 | c := uc.network.channels.Value(name)
|
---|
583 | if c == nil || c.Detached {
|
---|
584 | continue
|
---|
585 | }
|
---|
586 | uc.network.detach(c)
|
---|
587 | if err := uc.srv.db.StoreChannel(uc.network.ID, c); err != nil {
|
---|
588 | u.logger.Printf("failed to store updated detached channel %q: %v", c.Name, err)
|
---|
589 | }
|
---|
590 | case eventDownstreamConnected:
|
---|
591 | dc := e.dc
|
---|
592 |
|
---|
593 | if err := dc.welcome(); err != nil {
|
---|
594 | dc.logger.Printf("failed to handle new registered connection: %v", err)
|
---|
595 | break
|
---|
596 | }
|
---|
597 |
|
---|
598 | u.downstreamConns = append(u.downstreamConns, dc)
|
---|
599 |
|
---|
600 | dc.forEachNetwork(func(network *network) {
|
---|
601 | if network.lastError != nil {
|
---|
602 | sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s: %v", network.GetName(), network.lastError))
|
---|
603 | }
|
---|
604 | })
|
---|
605 |
|
---|
606 | u.forEachUpstream(func(uc *upstreamConn) {
|
---|
607 | uc.updateAway()
|
---|
608 | })
|
---|
609 | case eventDownstreamDisconnected:
|
---|
610 | dc := e.dc
|
---|
611 |
|
---|
612 | for i := range u.downstreamConns {
|
---|
613 | if u.downstreamConns[i] == dc {
|
---|
614 | u.downstreamConns = append(u.downstreamConns[:i], u.downstreamConns[i+1:]...)
|
---|
615 | break
|
---|
616 | }
|
---|
617 | }
|
---|
618 |
|
---|
619 | dc.forEachNetwork(func(net *network) {
|
---|
620 | net.storeClientDeliveryReceipts(dc.clientName)
|
---|
621 | })
|
---|
622 |
|
---|
623 | u.forEachUpstream(func(uc *upstreamConn) {
|
---|
624 | uc.updateAway()
|
---|
625 | })
|
---|
626 | case eventDownstreamMessage:
|
---|
627 | msg, dc := e.msg, e.dc
|
---|
628 | if dc.isClosed() {
|
---|
629 | dc.logger.Printf("ignoring message on closed connection: %v", msg)
|
---|
630 | break
|
---|
631 | }
|
---|
632 | err := dc.handleMessage(msg)
|
---|
633 | if ircErr, ok := err.(ircError); ok {
|
---|
634 | ircErr.Message.Prefix = dc.srv.prefix()
|
---|
635 | dc.SendMessage(ircErr.Message)
|
---|
636 | } else if err != nil {
|
---|
637 | dc.logger.Printf("failed to handle message %q: %v", msg, err)
|
---|
638 | dc.Close()
|
---|
639 | }
|
---|
640 | case eventBroadcast:
|
---|
641 | msg := e.msg
|
---|
642 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
643 | dc.SendMessage(msg)
|
---|
644 | })
|
---|
645 | case eventStop:
|
---|
646 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
647 | dc.Close()
|
---|
648 | })
|
---|
649 | for _, n := range u.networks {
|
---|
650 | n.stop()
|
---|
651 |
|
---|
652 | n.delivered.ForEachClient(func(clientName string) {
|
---|
653 | n.storeClientDeliveryReceipts(clientName)
|
---|
654 | })
|
---|
655 | }
|
---|
656 | return
|
---|
657 | default:
|
---|
658 | panic(fmt.Sprintf("received unknown event type: %T", e))
|
---|
659 | }
|
---|
660 | }
|
---|
661 | }
|
---|
662 |
|
---|
663 | func (u *user) handleUpstreamDisconnected(uc *upstreamConn) {
|
---|
664 | uc.network.conn = nil
|
---|
665 |
|
---|
666 | uc.endPendingLISTs(true)
|
---|
667 |
|
---|
668 | for _, entry := range uc.channels.innerMap {
|
---|
669 | uch := entry.value.(*upstreamChannel)
|
---|
670 | uch.updateAutoDetach(0)
|
---|
671 | }
|
---|
672 |
|
---|
673 | netIDStr := fmt.Sprintf("%v", uc.network.ID)
|
---|
674 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
675 | dc.updateSupportedCaps()
|
---|
676 | })
|
---|
677 |
|
---|
678 | // If the network has been removed, don't send a state change notification
|
---|
679 | found := false
|
---|
680 | for _, net := range u.networks {
|
---|
681 | if net == uc.network {
|
---|
682 | found = true
|
---|
683 | break
|
---|
684 | }
|
---|
685 | }
|
---|
686 | if !found {
|
---|
687 | return
|
---|
688 | }
|
---|
689 |
|
---|
690 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
691 | if dc.caps["soju.im/bouncer-networks-notify"] {
|
---|
692 | dc.SendMessage(&irc.Message{
|
---|
693 | Prefix: dc.srv.prefix(),
|
---|
694 | Command: "BOUNCER",
|
---|
695 | Params: []string{"NETWORK", netIDStr, "state=disconnected"},
|
---|
696 | })
|
---|
697 | }
|
---|
698 | })
|
---|
699 |
|
---|
700 | if uc.network.lastError == nil {
|
---|
701 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
702 | if !dc.caps["soju.im/bouncer-networks"] {
|
---|
703 | sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s", uc.network.GetName()))
|
---|
704 | }
|
---|
705 | })
|
---|
706 | }
|
---|
707 | }
|
---|
708 |
|
---|
709 | func (u *user) addNetwork(network *network) {
|
---|
710 | u.networks = append(u.networks, network)
|
---|
711 | go network.run()
|
---|
712 | }
|
---|
713 |
|
---|
714 | func (u *user) removeNetwork(network *network) {
|
---|
715 | network.stop()
|
---|
716 |
|
---|
717 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
718 | if dc.network != nil && dc.network == network {
|
---|
719 | dc.Close()
|
---|
720 | }
|
---|
721 | })
|
---|
722 |
|
---|
723 | for i, net := range u.networks {
|
---|
724 | if net == network {
|
---|
725 | u.networks = append(u.networks[:i], u.networks[i+1:]...)
|
---|
726 | return
|
---|
727 | }
|
---|
728 | }
|
---|
729 |
|
---|
730 | panic("tried to remove a non-existing network")
|
---|
731 | }
|
---|
732 |
|
---|
733 | func (u *user) checkNetwork(record *Network) error {
|
---|
734 | for _, net := range u.networks {
|
---|
735 | if net.GetName() == record.GetName() && net.ID != record.ID {
|
---|
736 | return fmt.Errorf("a network with the name %q already exists", record.GetName())
|
---|
737 | }
|
---|
738 | }
|
---|
739 | return nil
|
---|
740 | }
|
---|
741 |
|
---|
742 | func (u *user) createNetwork(record *Network) (*network, error) {
|
---|
743 | if record.ID != 0 {
|
---|
744 | panic("tried creating an already-existing network")
|
---|
745 | }
|
---|
746 |
|
---|
747 | if err := u.checkNetwork(record); err != nil {
|
---|
748 | return nil, err
|
---|
749 | }
|
---|
750 |
|
---|
751 | if u.srv.MaxUserNetworks >= 0 && len(u.networks) >= u.srv.MaxUserNetworks {
|
---|
752 | return nil, fmt.Errorf("maximum number of networks reached")
|
---|
753 | }
|
---|
754 |
|
---|
755 | network := newNetwork(u, record, nil)
|
---|
756 | err := u.srv.db.StoreNetwork(u.ID, &network.Network)
|
---|
757 | if err != nil {
|
---|
758 | return nil, err
|
---|
759 | }
|
---|
760 |
|
---|
761 | u.addNetwork(network)
|
---|
762 |
|
---|
763 | idStr := fmt.Sprintf("%v", network.ID)
|
---|
764 | attrs := getNetworkAttrs(network)
|
---|
765 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
766 | if dc.caps["soju.im/bouncer-networks-notify"] {
|
---|
767 | dc.SendMessage(&irc.Message{
|
---|
768 | Prefix: dc.srv.prefix(),
|
---|
769 | Command: "BOUNCER",
|
---|
770 | Params: []string{"NETWORK", idStr, attrs.String()},
|
---|
771 | })
|
---|
772 | }
|
---|
773 | })
|
---|
774 |
|
---|
775 | return network, nil
|
---|
776 | }
|
---|
777 |
|
---|
778 | func (u *user) updateNetwork(record *Network) (*network, error) {
|
---|
779 | if record.ID == 0 {
|
---|
780 | panic("tried updating a new network")
|
---|
781 | }
|
---|
782 |
|
---|
783 | // If the realname is reset to the default, just wipe the per-network
|
---|
784 | // setting
|
---|
785 | if record.Realname == u.Realname {
|
---|
786 | record.Realname = ""
|
---|
787 | }
|
---|
788 |
|
---|
789 | if err := u.checkNetwork(record); err != nil {
|
---|
790 | return nil, err
|
---|
791 | }
|
---|
792 |
|
---|
793 | network := u.getNetworkByID(record.ID)
|
---|
794 | if network == nil {
|
---|
795 | panic("tried updating a non-existing network")
|
---|
796 | }
|
---|
797 |
|
---|
798 | if err := u.srv.db.StoreNetwork(u.ID, record); err != nil {
|
---|
799 | return nil, err
|
---|
800 | }
|
---|
801 |
|
---|
802 | // Most network changes require us to re-connect to the upstream server
|
---|
803 |
|
---|
804 | channels := make([]Channel, 0, network.channels.Len())
|
---|
805 | for _, entry := range network.channels.innerMap {
|
---|
806 | ch := entry.value.(*Channel)
|
---|
807 | channels = append(channels, *ch)
|
---|
808 | }
|
---|
809 |
|
---|
810 | updatedNetwork := newNetwork(u, record, channels)
|
---|
811 |
|
---|
812 | // If we're currently connected, disconnect and perform the necessary
|
---|
813 | // bookkeeping
|
---|
814 | if network.conn != nil {
|
---|
815 | network.stop()
|
---|
816 | // Note: this will set network.conn to nil
|
---|
817 | u.handleUpstreamDisconnected(network.conn)
|
---|
818 | }
|
---|
819 |
|
---|
820 | // Patch downstream connections to use our fresh updated network
|
---|
821 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
822 | if dc.network != nil && dc.network == network {
|
---|
823 | dc.network = updatedNetwork
|
---|
824 | }
|
---|
825 | })
|
---|
826 |
|
---|
827 | // We need to remove the network after patching downstream connections,
|
---|
828 | // otherwise they'll get closed
|
---|
829 | u.removeNetwork(network)
|
---|
830 |
|
---|
831 | // This will re-connect to the upstream server
|
---|
832 | u.addNetwork(updatedNetwork)
|
---|
833 |
|
---|
834 | // TODO: only broadcast attributes that have changed
|
---|
835 | idStr := fmt.Sprintf("%v", updatedNetwork.ID)
|
---|
836 | attrs := getNetworkAttrs(updatedNetwork)
|
---|
837 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
838 | if dc.caps["soju.im/bouncer-networks-notify"] {
|
---|
839 | dc.SendMessage(&irc.Message{
|
---|
840 | Prefix: dc.srv.prefix(),
|
---|
841 | Command: "BOUNCER",
|
---|
842 | Params: []string{"NETWORK", idStr, attrs.String()},
|
---|
843 | })
|
---|
844 | }
|
---|
845 | })
|
---|
846 |
|
---|
847 | return updatedNetwork, nil
|
---|
848 | }
|
---|
849 |
|
---|
850 | func (u *user) deleteNetwork(id int64) error {
|
---|
851 | network := u.getNetworkByID(id)
|
---|
852 | if network == nil {
|
---|
853 | panic("tried deleting a non-existing network")
|
---|
854 | }
|
---|
855 |
|
---|
856 | if err := u.srv.db.DeleteNetwork(network.ID); err != nil {
|
---|
857 | return err
|
---|
858 | }
|
---|
859 |
|
---|
860 | u.removeNetwork(network)
|
---|
861 |
|
---|
862 | idStr := fmt.Sprintf("%v", network.ID)
|
---|
863 | u.forEachDownstream(func(dc *downstreamConn) {
|
---|
864 | if dc.caps["soju.im/bouncer-networks-notify"] {
|
---|
865 | dc.SendMessage(&irc.Message{
|
---|
866 | Prefix: dc.srv.prefix(),
|
---|
867 | Command: "BOUNCER",
|
---|
868 | Params: []string{"NETWORK", idStr, "*"},
|
---|
869 | })
|
---|
870 | }
|
---|
871 | })
|
---|
872 |
|
---|
873 | return nil
|
---|
874 | }
|
---|
875 |
|
---|
876 | func (u *user) updateUser(record *User) error {
|
---|
877 | if u.ID != record.ID {
|
---|
878 | panic("ID mismatch when updating user")
|
---|
879 | }
|
---|
880 |
|
---|
881 | realnameUpdated := u.Realname != record.Realname
|
---|
882 | if err := u.srv.db.StoreUser(record); err != nil {
|
---|
883 | return fmt.Errorf("failed to update user %q: %v", u.Username, err)
|
---|
884 | }
|
---|
885 | u.User = *record
|
---|
886 |
|
---|
887 | if realnameUpdated {
|
---|
888 | // Re-connect to networks which use the default realname
|
---|
889 | var needUpdate []Network
|
---|
890 | u.forEachNetwork(func(net *network) {
|
---|
891 | if net.Realname == "" {
|
---|
892 | needUpdate = append(needUpdate, net.Network)
|
---|
893 | }
|
---|
894 | })
|
---|
895 |
|
---|
896 | var netErr error
|
---|
897 | for _, net := range needUpdate {
|
---|
898 | if _, err := u.updateNetwork(&net); err != nil {
|
---|
899 | netErr = err
|
---|
900 | }
|
---|
901 | }
|
---|
902 | if netErr != nil {
|
---|
903 | return netErr
|
---|
904 | }
|
---|
905 | }
|
---|
906 |
|
---|
907 | return nil
|
---|
908 | }
|
---|
909 |
|
---|
910 | func (u *user) stop() {
|
---|
911 | u.events <- eventStop{}
|
---|
912 | <-u.done
|
---|
913 | }
|
---|
914 |
|
---|
915 | func (u *user) hasPersistentMsgStore() bool {
|
---|
916 | if u.msgStore == nil {
|
---|
917 | return false
|
---|
918 | }
|
---|
919 | _, isMem := u.msgStore.(*memoryMessageStore)
|
---|
920 | return !isMem
|
---|
921 | }
|
---|