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