1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
|
package soju
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"math/big"
"net"
"sort"
"strings"
"sync/atomic"
"time"
"codeberg.org/emersion/soju/xirc"
"github.com/SherClockHolmes/webpush-go"
"gopkg.in/irc.v4"
"codeberg.org/emersion/soju/database"
"codeberg.org/emersion/soju/msgstore"
)
type UserUpdateFunc func(record *database.User) error
type event interface{}
type eventUpstreamMessage struct {
msg *irc.Message
uc *upstreamConn
}
type eventUpstreamConnectionError struct {
net *network
err error
}
type eventUpstreamConnected struct {
uc *upstreamConn
}
type eventUpstreamDisconnected struct {
uc *upstreamConn
}
type eventUpstreamError struct {
uc *upstreamConn
err error
}
type eventDownstreamMessage struct {
msg *irc.Message
dc *downstreamConn
}
type eventDownstreamConnected struct {
dc *downstreamConn
}
type eventDownstreamDisconnected struct {
dc *downstreamConn
}
type eventChannelDetach struct {
uc *upstreamConn
name string
}
type eventBroadcast struct {
msg *irc.Message
}
type eventStop struct{}
type eventUserUpdate struct {
password *string
admin *bool
enabled *bool
maxNetworks *int
done chan error
}
type eventTryRegainNick struct {
uc *upstreamConn
nick string
}
type eventUserRun struct {
params []string
ch chan userRunMsg
}
type deliveredClientMap map[string]string // client name -> msg ID
type deliveredStore struct {
m xirc.CaseMappingMap[deliveredClientMap]
}
func newDeliveredStore(cm xirc.CaseMapping) deliveredStore {
return deliveredStore{xirc.NewCaseMappingMap[deliveredClientMap](cm)}
}
func (ds deliveredStore) Empty() bool {
return ds.m.Len() == 0
}
func (ds deliveredStore) HasTarget(target string) bool {
return ds.m.Get(target) != nil
}
func (ds deliveredStore) LoadID(target, clientName string) string {
clients := ds.m.Get(target)
if clients == nil {
return ""
}
return clients[clientName]
}
func (ds deliveredStore) StoreID(target, clientName, msgID string) {
clients := ds.m.Get(target)
if clients == nil {
clients = make(deliveredClientMap)
ds.m.Set(target, clients)
}
clients[clientName] = msgID
}
func (ds deliveredStore) ForEachTarget(f func(target string)) {
ds.m.ForEach(func(name string, _ deliveredClientMap) {
f(name)
})
}
func (ds deliveredStore) ForEachClient(f func(clientName string)) {
clients := make(map[string]struct{})
ds.m.ForEach(func(name string, delivered deliveredClientMap) {
for clientName := range delivered {
clients[clientName] = struct{}{}
}
})
for clientName := range clients {
f(clientName)
}
}
type network struct {
database.Network
user *user
logger Logger
stopped chan struct{}
conn *upstreamConn
channels xirc.CaseMappingMap[*database.Channel]
delivered deliveredStore
pushTargets xirc.CaseMappingMap[time.Time]
lastError error
casemap xirc.CaseMapping
}
func newNetwork(user *user, record *database.Network, channels []database.Channel) *network {
logger := &prefixLogger{user.logger, fmt.Sprintf("network %q: ", record.GetName())}
// Initialize maps with the most strict case-mapping to avoid collisions:
// we don't know which case-mapping will be used by the upstream server yet
cm := xirc.CaseMappingASCII
m := xirc.NewCaseMappingMap[*database.Channel](cm)
for _, ch := range channels {
ch := ch
m.Set(ch.Name, &ch)
}
return &network{
Network: *record,
user: user,
logger: logger,
stopped: make(chan struct{}),
channels: m,
delivered: newDeliveredStore(cm),
pushTargets: xirc.NewCaseMappingMap[time.Time](cm),
casemap: stdCaseMapping,
}
}
func (net *network) forEachDownstream(f func(*downstreamConn)) {
for _, dc := range net.user.downstreamConns {
if dc.network != net {
continue
}
f(dc)
}
}
func (net *network) isStopped() bool {
select {
case <-net.stopped:
return true
default:
return false
}
}
func (net *network) equalCasemap(a, b string) bool {
return net.casemap(a) == net.casemap(b)
}
func userIdent(u *database.User) string {
// The ident is a string we will send to upstream servers in clear-text.
// For privacy reasons, make sure it doesn't expose any meaningful user
// metadata. We just use the base64-encoded hashed ID, so that people don't
// start relying on the string being an integer or following a pattern.
var b [64]byte
binary.LittleEndian.PutUint64(b[:], uint64(u.ID))
h := sha256.Sum256(b[:])
return hex.EncodeToString(h[:16])
}
func (net *network) runConn(ctx context.Context) error {
net.user.srv.metrics.upstreams.Add(1)
defer net.user.srv.metrics.upstreams.Add(-1)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
done := ctx.Done() // This must not be subject to timeout
ctx, cancelTimeout := context.WithTimeout(ctx, time.Minute)
defer cancelTimeout()
uc, err := connectToUpstream(ctx, net)
if err != nil {
return fmt.Errorf("failed to connect: %w", err)
}
defer uc.Close()
// The context is cancelled by the caller when the network is stopped.
go func() {
<-done
uc.Close()
}()
if net.user.srv.Identd != nil {
net.user.srv.Identd.Store(uc.RemoteAddr().String(), uc.LocalAddr().String(), userIdent(&net.user.User))
defer net.user.srv.Identd.Delete(uc.RemoteAddr().String(), uc.LocalAddr().String())
}
// TODO: this is racy, we're not running in the user goroutine yet
// uc.register accesses user/network DB records
uc.register(ctx)
if err := uc.runUntilRegistered(ctx); err != nil {
return fmt.Errorf("failed to register: %w", err)
}
net.user.events <- eventUpstreamConnected{uc}
defer func() {
net.user.events <- eventUpstreamDisconnected{uc}
}()
if err := uc.readMessages(net.user.events); err != nil {
return fmt.Errorf("failed to handle messages: %w", err)
}
return nil
}
func (net *network) run() {
if !net.user.Enabled || !net.Enabled {
return
}
ctx, cancel := context.WithCancel(context.TODO())
go func() {
<-net.stopped
cancel()
}()
var lastTry time.Time
backoff := newBackoffer(retryConnectMinDelay, retryConnectMaxDelay, retryConnectJitter)
for {
if net.isStopped() {
return
}
delay := backoff.Next() - time.Now().Sub(lastTry)
if delay > 0 {
net.logger.Printf("waiting %v before trying to reconnect to %q", delay.Truncate(time.Second), net.Addr)
time.Sleep(delay)
}
lastTry = time.Now()
if err := net.runConn(ctx); err != nil {
text := err.Error()
temp := true
var regErr registrationError
if errors.As(err, ®Err) {
text = "failed to register: " + regErr.Reason()
temp = regErr.Temporary()
}
net.logger.Printf("connection error to %q: %v", net.Addr, text)
net.user.events <- eventUpstreamConnectionError{net, fmt.Errorf("connection error: %v", err)}
net.user.srv.metrics.upstreamConnectErrorsTotal.Inc()
if !temp {
return
}
} else {
backoff.Reset()
}
}
}
func (net *network) stop() {
if !net.isStopped() {
close(net.stopped)
}
}
func (net *network) detach(ch *database.Channel) {
if ch.Detached {
return
}
net.logger.Printf("detaching channel %q", ch.Name)
ch.Detached = true
if net.user.msgStore != nil {
nameCM := net.casemap(ch.Name)
lastID, err := net.user.msgStore.LastMsgID(&net.Network, nameCM, time.Now())
if err != nil {
net.logger.Printf("failed to get last message ID for channel %q: %v", ch.Name, err)
}
ch.DetachedInternalMsgID = lastID
}
if net.conn != nil {
uch := net.conn.channels.Get(ch.Name)
if uch != nil {
uch.updateAutoDetach(0)
}
}
net.forEachDownstream(func(dc *downstreamConn) {
dc.SendMessage(context.TODO(), &irc.Message{
Prefix: dc.prefix(),
Command: "PART",
Params: []string{ch.Name, "Detach"},
})
})
}
func (net *network) attach(ctx context.Context, ch *database.Channel) {
if !ch.Detached {
return
}
net.logger.Printf("attaching channel %q", ch.Name)
detachedMsgID := ch.DetachedInternalMsgID
ch.Detached = false
ch.DetachedInternalMsgID = ""
var uch *upstreamChannel
if net.conn != nil {
uch = net.conn.channels.Get(ch.Name)
net.conn.updateChannelAutoDetach(ch.Name)
}
net.forEachDownstream(func(dc *downstreamConn) {
dc.SendMessage(ctx, &irc.Message{
Prefix: dc.prefix(),
Command: "JOIN",
Params: []string{ch.Name},
})
if uch != nil {
forwardChannel(ctx, dc, uch)
}
if detachedMsgID != "" {
dc.sendTargetBacklog(ctx, net, ch.Name, detachedMsgID)
}
})
}
func (net *network) deleteChannel(ctx context.Context, name string) error {
ch := net.channels.Get(name)
if ch == nil {
return fmt.Errorf("unknown channel %q", name)
}
if net.conn != nil {
uch := net.conn.channels.Get(ch.Name)
if uch != nil {
uch.updateAutoDetach(0)
}
}
if err := net.user.srv.db.DeleteChannel(ctx, ch.ID); err != nil {
return err
}
net.channels.Del(name)
return nil
}
func (net *network) updateCasemapping(newCasemap xirc.CaseMapping) {
net.casemap = newCasemap
net.channels.SetCaseMapping(newCasemap)
net.delivered.m.SetCaseMapping(newCasemap)
net.pushTargets.SetCaseMapping(newCasemap)
if uc := net.conn; uc != nil {
uc.channels.SetCaseMapping(newCasemap)
uc.channels.ForEach(func(_ string, uch *upstreamChannel) {
uch.Members.SetCaseMapping(newCasemap)
})
uc.users.SetCaseMapping(newCasemap)
uc.monitored.SetCaseMapping(newCasemap)
}
net.forEachDownstream(func(dc *downstreamConn) {
dc.updateCasemapping()
})
}
func (net *network) storeClientDeliveryReceipts(ctx context.Context, clientName string) {
if !net.user.hasPersistentMsgStore() {
return
}
var receipts []database.DeliveryReceipt
net.delivered.ForEachTarget(func(target string) {
msgID := net.delivered.LoadID(target, clientName)
if msgID == "" {
return
}
receipts = append(receipts, database.DeliveryReceipt{
Target: target,
InternalMsgID: msgID,
})
})
if err := net.user.srv.db.StoreClientDeliveryReceipts(ctx, net.ID, clientName, receipts); err != nil {
net.logger.Printf("failed to store delivery receipts for client %q: %v", clientName, err)
}
}
func (net *network) isHighlight(msg *irc.Message) bool {
if msg.Command != "PRIVMSG" && msg.Command != "NOTICE" {
return false
}
text := msg.Params[1]
nick := database.GetNick(&net.user.User, &net.Network)
if net.conn != nil {
nick = net.conn.nick
}
// TODO: use case-mapping aware comparison here
return msg.Prefix.Name != nick && isHighlight(text, nick)
}
func (net *network) detachedMessageNeedsRelay(ch *database.Channel, msg *irc.Message) bool {
highlight := net.isHighlight(msg)
return ch.RelayDetached == database.FilterMessage || ((ch.RelayDetached == database.FilterHighlight || ch.RelayDetached == database.FilterDefault) && highlight)
}
func (net *network) autoSaveSASLPlain(ctx context.Context, username, password string) {
// User may have e.g. EXTERNAL mechanism configured. We do not want to
// automatically erase the key pair or any other credentials.
if net.SASL.Mechanism != "" && net.SASL.Mechanism != "PLAIN" {
return
}
net.logger.Printf("auto-saving SASL PLAIN credentials with username %q", username)
net.SASL.Mechanism = "PLAIN"
net.SASL.Plain.Username = username
net.SASL.Plain.Password = password
if err := net.user.srv.db.StoreNetwork(ctx, net.user.ID, &net.Network); err != nil {
net.logger.Printf("failed to save SASL PLAIN credentials: %v", err)
}
}
// broadcastWebPush broadcasts a Web Push message for the given IRC message.
//
// Broadcasting the message to all Web Push endpoints might take a while, so
// callers should call this function in a new goroutine.
func (net *network) broadcastWebPush(msg *irc.Message) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
subs, err := net.user.srv.db.ListWebPushSubscriptions(ctx, net.user.ID, net.ID)
if err != nil {
net.logger.Printf("failed to list Web push subscriptions: %v", err)
return
}
for _, sub := range subs {
err := net.user.srv.sendWebPush(ctx, &webpush.Subscription{
Endpoint: sub.Endpoint,
Keys: webpush.Keys{
Auth: sub.Keys.Auth,
P256dh: sub.Keys.P256DH,
},
}, sub.Keys.VAPID, msg)
if err == errWebPushSubscriptionExpired {
if err := net.user.srv.db.DeleteWebPushSubscription(ctx, sub.ID); err != nil {
net.logger.Printf("failed to delete expired Web Push subscription %q: %v", sub.Endpoint, err)
} else {
net.logger.Debugf("deleted expired Web Push subscription %q", sub.Endpoint)
}
} else if err != nil {
net.logger.Printf("failed to send Web push notification to endpoint %q: %v", sub.Endpoint, err)
// If it failed for any reason and is old, delete it
if time.Since(sub.UpdatedAt) > webpushPruneSubscriptionDelay {
if err := net.user.srv.db.DeleteWebPushSubscription(ctx, sub.ID); err != nil {
net.logger.Printf("failed to delete pruned Web Push subscription %q: %v", sub.Endpoint, err)
} else {
net.logger.Printf("deleted pruned Web Push subscription %q", sub.Endpoint)
}
}
}
}
}
type user struct {
database.User
srv *Server
logger Logger
events chan event
done chan struct{}
numDownstreamConns atomic.Int64
networks []*network
downstreamConns []*downstreamConn
msgStore msgstore.Store
}
func newUser(srv *Server, record *database.User) *user {
logger := &prefixLogger{srv.Logger, fmt.Sprintf("user %q: ", record.Username)}
var msgStore msgstore.Store
switch srv.Config().MsgStoreDriver {
case "fs":
msgStore = msgstore.NewFSStore(srv.Config().MsgStorePath, record)
case "db":
msgStore = msgstore.NewDBStore(srv.db)
case "memory":
msgStore = msgstore.NewMemoryStore()
}
return &user{
User: *record,
srv: srv,
logger: logger,
events: make(chan event, 64),
done: make(chan struct{}),
msgStore: msgStore,
}
}
func (u *user) forEachUpstream(f func(uc *upstreamConn)) {
for _, network := range u.networks {
if network.conn == nil {
continue
}
f(network.conn)
}
}
func (u *user) getNetwork(name string) *network {
for _, network := range u.networks {
if network.Addr == name {
return network
}
if network.Name != "" && network.Name == name {
return network
}
}
return nil
}
func (u *user) getNetworkByID(id int64) *network {
for _, net := range u.networks {
if net.ID == id {
return net
}
}
return nil
}
func (u *user) run() {
defer func() {
if u.msgStore != nil {
if err := u.msgStore.Close(); err != nil {
u.logger.Printf("failed to close message store for user %q: %v", u.Username, err)
}
}
close(u.done)
}()
networks, err := u.srv.db.ListNetworks(context.TODO(), u.ID)
if err != nil {
u.logger.Printf("failed to list networks for user %q: %v", u.Username, err)
return
}
sort.Slice(networks, func(i, j int) bool {
return networks[i].ID < networks[j].ID
})
for _, record := range networks {
record := record
channels, err := u.srv.db.ListChannels(context.TODO(), record.ID)
if err != nil {
u.logger.Printf("failed to list channels for user %q, network %q: %v", u.Username, record.GetName(), err)
continue
}
network := newNetwork(u, &record, channels)
u.networks = append(u.networks, network)
if u.hasPersistentMsgStore() {
receipts, err := u.srv.db.ListDeliveryReceipts(context.TODO(), record.ID)
if err != nil {
u.logger.Printf("failed to load delivery receipts for user %q, network %q: %v", u.Username, network.GetName(), err)
return
}
for _, rcpt := range receipts {
network.delivered.StoreID(rcpt.Target, rcpt.Client, rcpt.InternalMsgID)
}
}
go network.run()
}
for e := range u.events {
switch e := e.(type) {
case eventUpstreamConnected:
uc := e.uc
uc.network.conn = uc
uc.updateAway()
uc.updateMonitor()
ctx := context.TODO()
uc.forEachDownstream(func(dc *downstreamConn) {
dc.updateSupportedCaps(ctx)
if !dc.caps.IsEnabled("soju.im/bouncer-networks") {
sendServiceNOTICE(dc, fmt.Sprintf("connected to %s", uc.network.GetName()))
}
dc.updateNick(ctx)
dc.updateHost(ctx)
dc.updateRealname(ctx)
dc.updateAccount(ctx)
dc.updateCasemapping()
})
u.notifyBouncerNetworkState(uc.network.ID, irc.Tags{
"state": "connected",
"error": "",
})
uc.network.lastError = nil
case eventUpstreamDisconnected:
u.handleUpstreamDisconnected(e.uc)
case eventUpstreamConnectionError:
net := e.net
stopped := false
select {
case <-net.stopped:
stopped = true
default:
}
if !stopped && (net.lastError == nil || net.lastError.Error() != e.err.Error()) {
net.forEachDownstream(func(dc *downstreamConn) {
sendServiceNOTICE(dc, fmt.Sprintf("failed connecting/registering to %s: %v", net.GetName(), e.err))
})
}
net.lastError = e.err
u.notifyBouncerNetworkState(net.ID, irc.Tags{
"error": net.lastError.Error(),
})
case eventUpstreamError:
uc := e.uc
uc.forEachDownstream(func(dc *downstreamConn) {
sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s: %v", uc.network.GetName(), e.err))
})
uc.network.lastError = e.err
u.notifyBouncerNetworkState(uc.network.ID, irc.Tags{
"error": uc.network.lastError.Error(),
})
case eventUpstreamMessage:
msg, uc := e.msg, e.uc
if uc.isClosed() {
uc.logger.Printf("ignoring message on closed connection: %v", msg)
break
}
if err := uc.handleMessage(context.TODO(), msg); err != nil {
uc.logger.Printf("failed to handle message %q: %v", msg, err)
}
case eventChannelDetach:
uc, name := e.uc, e.name
c := uc.network.channels.Get(name)
if c == nil || c.Detached {
continue
}
uc.network.detach(c)
if err := uc.srv.db.StoreChannel(context.TODO(), uc.network.ID, c); err != nil {
u.logger.Printf("failed to store updated detached channel %q: %v", c.Name, err)
}
case eventDownstreamConnected:
dc := e.dc
ctx := context.TODO()
if dc.network != nil {
dc.monitored.SetCaseMapping(dc.network.casemap)
}
if !u.Enabled && u.srv.Config().EnableUsersOnAuth {
err := u.updateUser(ctx, func(record *database.User) error {
record.Enabled = true
return nil
})
if err != nil {
dc.logger.Printf("failed to enable user after successful authentication: %v", err)
}
}
if !u.Enabled {
dc.SendMessage(ctx, &irc.Message{
Command: "ERROR",
Params: []string{"This bouncer account is disabled"},
})
// TODO: close dc after the error message is sent
break
}
if err := dc.welcome(ctx, u); err != nil {
if ircErr, ok := err.(ircError); ok {
msg := ircErr.Message.Copy()
msg.Prefix = dc.srv.prefix()
dc.SendMessage(ctx, msg)
} else {
dc.SendMessage(ctx, &irc.Message{
Command: "ERROR",
Params: []string{"Internal server error"},
})
}
dc.logger.Printf("failed to handle new registered connection: %v", err)
// TODO: close dc after the error message is sent
break
}
u.downstreamConns = append(u.downstreamConns, dc)
u.numDownstreamConns.Add(1)
dc.forEachNetwork(func(network *network) {
if network.lastError != nil {
sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s: %v", network.GetName(), network.lastError))
}
})
u.forEachUpstream(func(uc *upstreamConn) {
uc.updateAway()
})
if !dc.impersonating {
u.bumpDownstreamInteractionTime(ctx)
}
case eventDownstreamDisconnected:
dc := e.dc
ctx := context.TODO()
for i := range u.downstreamConns {
if u.downstreamConns[i] == dc {
u.downstreamConns = append(u.downstreamConns[:i], u.downstreamConns[i+1:]...)
u.numDownstreamConns.Add(-1)
break
}
}
dc.forEachNetwork(func(net *network) {
net.storeClientDeliveryReceipts(ctx, dc.clientName)
})
u.forEachUpstream(func(uc *upstreamConn) {
uc.cancelPendingCommandsByDownstreamID(dc.id)
uc.updateAway()
uc.updateMonitor()
})
if !dc.impersonating {
u.bumpDownstreamInteractionTime(ctx)
}
case eventDownstreamMessage:
msg, dc := e.msg, e.dc
if dc.isClosed() {
dc.logger.Printf("ignoring message on closed connection: %v", msg)
break
}
err := dc.handleMessage(context.TODO(), msg)
if ircErr, ok := err.(ircError); ok {
ircErr.Message.Prefix = dc.srv.prefix()
dc.SendMessage(context.TODO(), ircErr.Message)
} else if err != nil {
dc.logger.Printf("failed to handle message %q: %v", msg, err)
dc.Close()
}
case eventBroadcast:
msg := e.msg
for _, dc := range u.downstreamConns {
dc.SendMessage(context.TODO(), msg)
}
case eventUserUpdate:
e.done <- u.updateUser(context.TODO(), func(record *database.User) error {
if e.password != nil {
record.Password = *e.password
}
if e.admin != nil {
record.Admin = *e.admin
}
if e.enabled != nil {
record.Enabled = *e.enabled
}
if e.maxNetworks != nil {
record.MaxNetworks = *e.maxNetworks
}
return nil
})
// If the password was updated, kill all downstream connections to
// force them to re-authenticate with the new credentials.
if e.password != nil {
for _, dc := range u.downstreamConns {
dc.Close()
}
}
case eventTryRegainNick:
e.uc.tryRegainNick(e.nick)
case eventUserRun:
ctx := context.TODO()
err := handleServiceCommand(&serviceContext{
Context: ctx,
user: u,
srv: u.srv,
// Here we are setting an admin context on any user run command
// that is run.
// As a reminder, user run can only be run by an admin.
// This enables admins to run actions on a user with admin rights,
// for example to add a network past the user limit.
// Non-admin users cannot run user run, not even on themselves,
// so this cannot be used to escalate privileges.
admin: true,
print: func(text string) {
// Avoid blocking on e.print in case our context is canceled.
// This is a no-op right now because we use context.TODO(),
// but might be useful later when we add timeouts.
select {
case <-ctx.Done():
case e.ch <- userRunMsg{message: text}:
}
},
}, e.params)
select {
case <-ctx.Done():
case e.ch <- userRunMsg{err: err}:
}
case eventStop:
for _, dc := range u.downstreamConns {
dc.Close()
}
for _, n := range u.networks {
n.stop()
n.delivered.ForEachClient(func(clientName string) {
n.storeClientDeliveryReceipts(context.TODO(), clientName)
})
}
return
default:
panic(fmt.Sprintf("received unknown event type: %T", e))
}
}
}
func (u *user) handleUpstreamDisconnected(uc *upstreamConn) {
uc.network.conn = nil
uc.stopRegainNickTimer()
uc.abortPendingCommands()
uc.channels.ForEach(func(_ string, uch *upstreamChannel) {
uch.updateAutoDetach(0)
})
uc.forEachDownstream(func(dc *downstreamConn) {
dc.updateSupportedCaps(context.TODO())
})
// If the network has been removed, don't send a state change notification
found := false
for _, net := range u.networks {
if net == uc.network {
found = true
break
}
}
if !found {
return
}
u.notifyBouncerNetworkState(uc.network.ID, irc.Tags{"state": "disconnected"})
if uc.network.lastError == nil {
uc.forEachDownstream(func(dc *downstreamConn) {
if !dc.caps.IsEnabled("soju.im/bouncer-networks") {
sendServiceNOTICE(dc, fmt.Sprintf("disconnected from %s", uc.network.GetName()))
}
})
}
}
func (u *user) notifyBouncerNetworkState(netID int64, attrs irc.Tags) {
// Don't send state updates for removed networks
found := false
for _, net := range u.networks {
if net.ID == netID {
found = true
break
}
}
if !found {
return
}
netIDStr := fmt.Sprintf("%v", netID)
for _, dc := range u.downstreamConns {
if dc.caps.IsEnabled("soju.im/bouncer-networks-notify") {
dc.SendMessage(context.TODO(), &irc.Message{
Command: "BOUNCER",
Params: []string{"NETWORK", netIDStr, attrs.String()},
})
}
}
}
func (u *user) addNetwork(network *network) {
u.networks = append(u.networks, network)
sort.Slice(u.networks, func(i, j int) bool {
return u.networks[i].ID < u.networks[j].ID
})
go network.run()
}
func (u *user) removeNetwork(network *network) {
network.stop()
for _, dc := range u.downstreamConns {
if dc.network != nil && dc.network == network {
dc.Close()
}
}
for i, net := range u.networks {
if net == network {
u.networks = append(u.networks[:i], u.networks[i+1:]...)
return
}
}
panic("tried to remove a non-existing network")
}
func (u *user) canEnableNewNetwork() error {
max := u.MaxNetworks
if max < 0 {
max = u.srv.Config().MaxUserNetworks
}
if max < 0 {
return nil
}
n := 0
for _, network := range u.networks {
if network.Enabled {
n++
}
}
if n >= max {
return fmt.Errorf("maximum number of enabled networks reached")
}
return nil
}
func (u *user) checkNetwork(record *database.Network) error {
url, err := record.URL()
if err != nil {
return err
}
if url.User != nil {
return fmt.Errorf("%v:// URL must not have username and password information", url.Scheme)
}
if url.RawQuery != "" {
return fmt.Errorf("%v:// URL must not have query values", url.Scheme)
}
if url.Fragment != "" {
return fmt.Errorf("%v:// URL must not have a fragment", url.Scheme)
}
switch url.Scheme {
case "ircs", "irc+insecure":
if url.Host == "" {
return fmt.Errorf("%v:// URL must have a host", url.Scheme)
}
if url.Path != "" {
return fmt.Errorf("%v:// URL must not have a path", url.Scheme)
}
case "irc+unix", "unix":
if !u.Admin {
return fmt.Errorf("non-admin users cannot add networks with a unix address")
}
if url.Host != "" {
return fmt.Errorf("%v:// URL must not have a host", url.Scheme)
}
if url.Path == "" {
return fmt.Errorf("%v:// URL must have a path", url.Scheme)
}
default:
return fmt.Errorf("unknown URL scheme %q", url.Scheme)
}
if record.GetName() == "" {
return fmt.Errorf("network name cannot be empty")
}
if strings.HasPrefix(record.GetName(), "-") {
// Can be mixed up with flags when sending commands to the service
return fmt.Errorf("network name cannot start with a dash character")
}
for _, net := range u.networks {
if net.GetName() == record.GetName() && net.ID != record.ID {
return fmt.Errorf("a network with the name %q already exists", record.GetName())
}
}
return nil
}
func (u *user) createNetwork(ctx context.Context, record *database.Network, enforceLimit bool) (*network, error) {
if record.ID != 0 {
panic("tried creating an already-existing network")
}
if enforceLimit && record.Enabled {
if err := u.canEnableNewNetwork(); err != nil {
return nil, err
}
}
if err := u.checkNetwork(record); err != nil {
return nil, err
}
network := newNetwork(u, record, nil)
err := u.srv.db.StoreNetwork(ctx, u.ID, &network.Network)
if err != nil {
return nil, err
}
u.addNetwork(network)
attrs := getNetworkAttrs(network)
u.notifyBouncerNetworkState(network.ID, attrs)
return network, nil
}
func (u *user) updateNetwork(ctx context.Context, record *database.Network, enforceLimit bool) (*network, error) {
if record.ID == 0 {
panic("tried updating a new network")
}
if enforceLimit && record.Enabled {
if err := u.canEnableNewNetwork(); err != nil {
return nil, err
}
}
// If the nickname/realname is reset to the default, just wipe the
// per-network setting
if record.Nick == u.Nick {
record.Nick = ""
}
if record.Realname == u.Realname {
record.Realname = ""
}
if err := u.checkNetwork(record); err != nil {
return nil, err
}
network := u.getNetworkByID(record.ID)
if network == nil {
panic("tried updating a non-existing network")
}
if err := u.srv.db.StoreNetwork(ctx, u.ID, record); err != nil {
return nil, err
}
// Most network changes require us to re-connect to the upstream server
channels := make([]database.Channel, 0, network.channels.Len())
network.channels.ForEach(func(_ string, ch *database.Channel) {
channels = append(channels, *ch)
})
updatedNetwork := newNetwork(u, record, channels)
// If we're currently connected, disconnect and perform the necessary
// bookkeeping
network.stop()
if network.conn != nil {
// Note: this will set network.conn to nil
u.handleUpstreamDisconnected(network.conn)
}
// Patch downstream connections to use our fresh updated network
for _, dc := range u.downstreamConns {
if dc.network != nil && dc.network == network {
dc.network = updatedNetwork
}
}
// We need to remove the network after patching downstream connections,
// otherwise they'll get closed
u.removeNetwork(network)
// The filesystem message store needs to be notified whenever the network
// is renamed
renameNetMsgStore, ok := u.msgStore.(msgstore.RenameNetworkStore)
if ok && updatedNetwork.GetName() != network.GetName() {
if err := renameNetMsgStore.RenameNetwork(&network.Network, &updatedNetwork.Network); err != nil {
network.logger.Printf("failed to update message store network name to %q: %v", updatedNetwork.GetName(), err)
}
}
// This will re-connect to the upstream server
u.addNetwork(updatedNetwork)
// TODO: only broadcast attributes that have changed
attrs := getNetworkAttrs(updatedNetwork)
u.notifyBouncerNetworkState(updatedNetwork.ID, attrs)
return updatedNetwork, nil
}
func (u *user) deleteNetwork(ctx context.Context, id int64) error {
network := u.getNetworkByID(id)
if network == nil {
panic("tried deleting a non-existing network")
}
if err := u.srv.db.DeleteNetwork(ctx, network.ID); err != nil {
return err
}
u.removeNetwork(network)
idStr := fmt.Sprintf("%v", network.ID)
for _, dc := range u.downstreamConns {
if dc.caps.IsEnabled("soju.im/bouncer-networks-notify") {
dc.SendMessage(ctx, &irc.Message{
Command: "BOUNCER",
Params: []string{"NETWORK", idStr, "*"},
})
}
}
return nil
}
func (u *user) updateUser(ctx context.Context, update UserUpdateFunc) error {
record := u.User // copy
if err := update(&record); err != nil {
return err
}
nickUpdated := u.Nick != record.Nick
realnameUpdated := u.Realname != record.Realname
enabledUpdated := u.Enabled != record.Enabled
if err := u.srv.db.StoreUser(ctx, &record); err != nil {
return fmt.Errorf("failed to update user %q: %v", u.Username, err)
}
u.User = record
if nickUpdated {
for _, net := range u.networks {
if net.Nick != "" {
continue
}
if uc := net.conn; uc != nil {
uc.SendMessage(ctx, &irc.Message{
Command: "NICK",
Params: []string{database.GetNick(&u.User, &net.Network)},
})
}
}
}
if realnameUpdated || enabledUpdated {
// Re-connect to networks which use the default realname
var needUpdate []database.Network
for _, net := range u.networks {
// If only the realname was updated, maybe we can skip the
// re-connect
if realnameUpdated && !enabledUpdated {
// If this network has a custom realname set, no need to
// re-connect: the user-wide realname remains unused
if net.Realname != "" {
continue
}
// We only need to call updateNetwork for upstreams that don't
// support setname
if uc := net.conn; uc != nil && uc.caps.IsEnabled("setname") {
uc.SendMessage(ctx, &irc.Message{
Command: "SETNAME",
Params: []string{database.GetRealname(&u.User, &net.Network)},
})
continue
}
}
needUpdate = append(needUpdate, net.Network)
}
var netErr error
for _, net := range needUpdate {
if _, err := u.updateNetwork(ctx, &net, false); err != nil {
netErr = err
}
}
if netErr != nil {
return netErr
}
}
if !u.Enabled {
// TODO: send an error message before disconnecting
for _, dc := range u.downstreamConns {
dc.Close()
}
}
return nil
}
func (u *user) stop(ctx context.Context) error {
select {
case <-u.done:
return nil // already stopped
case u.events <- eventStop{}:
// we've requested to stop, let's wait for the user goroutine to exit
case <-ctx.Done():
return ctx.Err()
}
select {
case <-u.done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (u *user) hasPersistentMsgStore() bool {
if u.msgStore == nil {
return false
}
return !msgstore.IsMemoryStore(u.msgStore)
}
func (u *user) FormatServerTime(t time.Time) string {
if u.msgStore != nil && msgstore.IsFSStore(u.msgStore) {
// The FS message store truncates message timestamps to the second,
// so truncate them here to get consistent timestamps.
t = t.Truncate(time.Second)
}
return xirc.FormatServerTime(t)
}
// localTCPAddr returns the local address to use when connecting to a host.
// A nil address is returned when the OS should automatically pick one.
func (u *user) localTCPAddr(remoteIP net.IP) (*net.TCPAddr, error) {
upstreamUserIPs := u.srv.Config().UpstreamUserIPs
if len(upstreamUserIPs) == 0 {
return nil, nil
}
wantIPv6 := remoteIP.To4() == nil
var ipNet *net.IPNet
for _, in := range upstreamUserIPs {
if wantIPv6 == (in.IP.To4() == nil) {
ipNet = in
break
}
}
if ipNet == nil {
return nil, nil
}
var ipInt big.Int
ipInt.SetBytes(ipNet.IP)
ipInt.Add(&ipInt, big.NewInt(u.ID+1))
ip := net.IP(ipInt.Bytes())
if !ipNet.Contains(ip) {
return nil, fmt.Errorf("IP network %v too small", ipNet)
}
return &net.TCPAddr{IP: ip}, nil
}
func (u *user) bumpDownstreamInteractionTime(ctx context.Context) {
err := u.updateUser(ctx, func(record *database.User) error {
record.DownstreamInteractedAt = time.Now()
return nil
})
if err != nil {
u.logger.Printf("failed to bump downstream interaction time: %v", err)
}
}
|