forked from mautrix/signal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
352 lines (306 loc) · 10.6 KB
/
main.go
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
// mautrix-signal - A Matrix-signal puppeting bridge.
// Copyright (C) 2023 Scott Weber
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"context"
_ "embed"
"fmt"
"os"
"sync"
"github.com/google/uuid"
"github.com/rs/zerolog"
"go.mau.fi/util/configupgrade"
"go.mau.fi/util/dbutil"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/bridge"
"maunium.net/go/mautrix/bridge/commands"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-signal/config"
"go.mau.fi/mautrix-signal/database"
"go.mau.fi/mautrix-signal/msgconv/matrixfmt"
"go.mau.fi/mautrix-signal/msgconv/signalfmt"
"go.mau.fi/mautrix-signal/pkg/signalmeow"
"go.mau.fi/mautrix-signal/pkg/signalmeow/store"
)
//go:embed example-config.yaml
var ExampleConfig string
// Information to find out exactly which commit the bridge was built from.
// These are filled at build time with the -X linker flag.
var (
Tag = "unknown"
Commit = "unknown"
BuildTime = "unknown"
)
type SignalBridge struct {
bridge.Bridge
Config *config.Config
DB *database.Database
Metrics *MetricsHandler
MeowStore *store.StoreContainer
provisioning *ProvisioningAPI
usersByMXID map[id.UserID]*User
usersBySignalID map[uuid.UUID]*User
usersLock sync.Mutex
managementRooms map[id.RoomID]*User
managementRoomsLock sync.Mutex
portalsByMXID map[id.RoomID]*Portal
portalsByID map[database.PortalKey]*Portal
portalsLock sync.Mutex
puppets map[uuid.UUID]*Puppet
puppetsByCustomMXID map[id.UserID]*Puppet
puppetsLock sync.Mutex
disappearingMessagesManager *DisappearingMessagesManager
}
var _ bridge.ChildOverride = (*SignalBridge)(nil)
func (br *SignalBridge) GetExampleConfig() string {
return ExampleConfig
}
func (br *SignalBridge) GetConfigPtr() interface{} {
br.Config = &config.Config{
BaseConfig: &br.Bridge.Config,
}
br.Config.BaseConfig.Bridge = &br.Config.Bridge
return br.Config
}
func (br *SignalBridge) Init() {
br.CommandProcessor = commands.NewProcessor(&br.Bridge)
br.RegisterCommands()
signalmeow.SetLogger(br.ZLog.With().Str("component", "signalmeow").Logger())
br.DB = database.New(br.Bridge.DB)
br.MeowStore = store.NewStore(br.Bridge.DB, dbutil.ZeroLogger(br.ZLog.With().Str("db_section", "signalmeow").Logger()))
ss := br.Config.Bridge.Provisioning.SharedSecret
if len(ss) > 0 && ss != "disable" {
br.provisioning = &ProvisioningAPI{bridge: br, log: br.ZLog.With().Str("component", "provisioning").Logger()}
}
br.disappearingMessagesManager = &DisappearingMessagesManager{
DB: br.DB,
Log: br.ZLog.With().Str("component", "disappearing messages").Logger(),
Bridge: br,
}
br.Metrics = NewMetricsHandler(br.Config.Metrics.Listen, br.ZLog.With().Str("component", "metrics").Logger(), br.DB)
br.MatrixHandler.TrackEventDuration = br.Metrics.TrackMatrixEvent
signalFormatParams = &signalfmt.FormatParams{
GetUserInfo: func(u uuid.UUID) signalfmt.UserInfo {
puppet := br.GetPuppetBySignalID(u)
if puppet == nil {
return signalfmt.UserInfo{}
}
user := br.GetUserBySignalID(u)
if user != nil {
return signalfmt.UserInfo{
MXID: user.MXID,
Name: puppet.Name,
}
}
return signalfmt.UserInfo{
MXID: puppet.MXID,
Name: puppet.Name,
}
},
}
matrixFormatParams = &matrixfmt.HTMLParser{
GetUUIDFromMXID: func(userID id.UserID) uuid.UUID {
parsed, ok := br.ParsePuppetMXID(userID)
if ok {
return parsed
}
user := br.GetUserByMXIDIfExists(userID)
if user != nil && user.SignalID != uuid.Nil {
return user.SignalID
}
return uuid.Nil
},
}
}
func (br *SignalBridge) logLostPortals(ctx context.Context) {
exists, err := br.DB.TableExists(ctx, "lost_portals")
if err != nil {
br.ZLog.Err(err).Msg("Failed to check if lost_portals table exists")
} else if !exists {
return
}
lostPortals, err := br.DB.LostPortal.GetAll(ctx)
if err != nil {
br.ZLog.Err(err).Msg("Failed to get lost portals")
return
} else if len(lostPortals) == 0 {
return
}
lostCountByReceiver := make(map[string]int)
for _, lost := range lostPortals {
lostCountByReceiver[lost.Receiver]++
}
br.ZLog.Warn().
Any("count_by_receiver", lostCountByReceiver).
Msg("Some portals were discarded due to the receiver not being logged into the bridge anymore. " +
"Use `!signal cleanup-lost-portals` to remove them from the database. " +
"Alternatively, you can re-insert the data into the portal table with the appropriate receiver column to restore the portals.")
}
func (br *SignalBridge) Start() {
go br.logLostPortals(context.TODO())
err := br.MeowStore.Upgrade(context.TODO())
if err != nil {
br.ZLog.Fatal().Err(err).Msg("Failed to upgrade signalmeow database")
os.Exit(15)
}
if br.provisioning != nil {
br.ZLog.Debug().Msg("Initializing provisioning API")
br.provisioning.Init()
}
go br.StartUsers()
if br.Config.Metrics.Enabled {
go br.Metrics.Start()
}
go br.disappearingMessagesManager.StartDisappearingLoop(context.TODO())
}
func (br *SignalBridge) Stop() {
br.Metrics.Stop()
for _, user := range br.usersByMXID {
br.ZLog.Debug().Stringer("user_id", user.MXID).Msg("Disconnecting user")
user.Disconnect()
}
}
func (br *SignalBridge) GetIPortal(mxid id.RoomID) bridge.Portal {
p := br.GetPortalByMXID(mxid)
if p == nil {
return nil
}
return p
}
func (br *SignalBridge) GetIUser(mxid id.UserID, create bool) bridge.User {
p := br.GetUserByMXID(mxid)
if p == nil {
return nil
}
return p
}
func (br *SignalBridge) IsGhost(mxid id.UserID) bool {
_, isGhost := br.ParsePuppetMXID(mxid)
return isGhost
}
func (br *SignalBridge) GetIGhost(mxid id.UserID) bridge.Ghost {
p := br.GetPuppetByMXID(mxid)
if p == nil {
return nil
}
return p
}
func (br *SignalBridge) CreatePrivatePortal(roomID id.RoomID, brInviter bridge.User, brGhost bridge.Ghost) {
inviter := brInviter.(*User)
puppet := brGhost.(*Puppet)
log := br.ZLog.With().
Str("action", "create private portal").
Stringer("target_room_id", roomID).
Stringer("inviter_mxid", brInviter.GetMXID()).
Stringer("invitee_uuid", puppet.SignalID).
Logger()
log.Debug().Msg("Creating private chat portal")
key := database.NewPortalKey(puppet.SignalID.String(), inviter.SignalID)
portal := br.GetPortalByChatID(key)
ctx := log.WithContext(context.TODO())
if len(portal.MXID) == 0 {
br.createPrivatePortalFromInvite(ctx, roomID, inviter, puppet, portal)
return
}
log.Debug().
Stringer("existing_room_id", portal.MXID).
Msg("Existing private chat portal found, trying to invite user")
ok := portal.ensureUserInvited(ctx, inviter)
if !ok {
log.Warn().Msg("Failed to invite user to existing private chat portal. Redirecting portal to new room")
br.createPrivatePortalFromInvite(ctx, roomID, inviter, puppet, portal)
return
}
intent := puppet.DefaultIntent()
errorMessage := fmt.Sprintf("You already have a private chat portal with me at [%[1]s](https://matrix.to/#/%[1]s)", portal.MXID)
errorContent := format.RenderMarkdown(errorMessage, true, false)
_, _ = intent.SendMessageEvent(ctx, roomID, event.EventMessage, errorContent)
log.Debug().Msg("Leaving ghost from private chat room after accepting invite because we already have a chat with the user")
_, _ = intent.LeaveRoom(ctx, roomID)
}
func (br *SignalBridge) createPrivatePortalFromInvite(ctx context.Context, roomID id.RoomID, inviter *User, puppet *Puppet, portal *Portal) {
log := zerolog.Ctx(ctx)
log.Debug().Msg("Creating private portal from invite")
// Check if room is already encrypted
var existingEncryption event.EncryptionEventContent
var encryptionEnabled bool
err := portal.MainIntent().StateEvent(ctx, roomID, event.StateEncryption, "", &existingEncryption)
if err != nil {
log.Err(err).Msg("Failed to check if encryption is enabled in private chat room")
} else {
encryptionEnabled = existingEncryption.Algorithm == id.AlgorithmMegolmV1
}
portal.MXID = roomID
br.portalsLock.Lock()
br.portalsByMXID[portal.MXID] = portal
br.portalsLock.Unlock()
intent := puppet.DefaultIntent()
if br.Config.Bridge.Encryption.Default || encryptionEnabled {
log.Debug().Msg("Adding bridge bot to new private chat portal as encryption is enabled")
_, err = intent.InviteUser(ctx, roomID, &mautrix.ReqInviteUser{UserID: br.Bot.UserID})
if err != nil {
log.Err(err).Msg("Failed to invite bridge bot to enable e2be")
}
err = br.Bot.EnsureJoined(ctx, roomID)
if err != nil {
log.Err(err).Msg("Failed to join as bridge bot to enable e2be")
}
if !encryptionEnabled {
_, err = intent.SendStateEvent(ctx, roomID, event.StateEncryption, "", portal.getEncryptionEventContent())
if err != nil {
log.Err(err).Msg("Failed to enable e2be")
}
}
br.AS.StateStore.SetMembership(ctx, roomID, inviter.MXID, event.MembershipJoin)
br.AS.StateStore.SetMembership(ctx, roomID, puppet.MXID, event.MembershipJoin)
br.AS.StateStore.SetMembership(ctx, roomID, br.Bot.UserID, event.MembershipJoin)
portal.Encrypted = true
}
portal.UpdateDMInfo(ctx, true)
_, _ = intent.SendNotice(ctx, roomID, "Private chat portal created")
log.Info().Msg("Created private chat portal after invite")
}
func main() {
br := &SignalBridge{
usersByMXID: make(map[id.UserID]*User),
usersBySignalID: make(map[uuid.UUID]*User),
managementRooms: make(map[id.RoomID]*User),
portalsByMXID: make(map[id.RoomID]*Portal),
portalsByID: make(map[database.PortalKey]*Portal),
puppets: make(map[uuid.UUID]*Puppet),
puppetsByCustomMXID: make(map[id.UserID]*Puppet),
}
br.Bridge = bridge.Bridge{
Name: "mautrix-signal",
URL: "https://github.com/mautrix/signal",
Description: "A Matrix-Signal puppeting bridge.",
Version: "0.5.0",
ProtocolName: "Signal",
BeeperServiceName: "signal",
BeeperNetworkName: "signal",
CryptoPickleKey: "mautrix.bridge.e2ee",
ConfigUpgrader: &configupgrade.StructUpgrader{
SimpleUpgrader: configupgrade.SimpleUpgrader(config.DoUpgrade),
Blocks: config.SpacedBlocks,
Base: ExampleConfig,
},
Child: br,
}
br.InitVersion(Tag, Commit, BuildTime)
br.Main()
}