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