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