forked from matrix-org/matrix-appservice-irc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIrcBridge.ts
More file actions
1694 lines (1538 loc) · 68 KB
/
Copy pathIrcBridge.ts
File metadata and controls
1694 lines (1538 loc) · 68 KB
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
import Bluebird from "bluebird";
import extend from "extend";
import * as promiseutil from "../promiseutil";
import { IrcHandler, MatrixMembership } from "./IrcHandler";
import { MatrixHandler, MatrixEventInvite, OnMemberEventData, MatrixEventKick } from "./MatrixHandler";
import { MemberListSyncer } from "./MemberListSyncer";
import { IrcServer } from "../irc/IrcServer";
import { ClientPool } from "../irc/ClientPool";
import { BridgedClient, BridgedClientStatus } from "../irc/BridgedClient";
import { IrcUser } from "../models/IrcUser";
import { IrcRoom } from "../models/IrcRoom";
import { BridgeRequest, BridgeRequestErr, BridgeRequestData, BridgeRequestEvent } from "../models/BridgeRequest";
import { NeDBDataStore } from "../datastore/NedbDataStore";
import { PgDataStore } from "../datastore/postgres/PgDataStore";
import { getLogger } from "../logging";
import { DebugApi } from "../DebugApi";
import { defaultEventFeatures } from "../EventFeatures";
import { Provisioner } from "../provisioning/Provisioner";
import { PublicitySyncer } from "./PublicitySyncer";
import { Histogram } from "prom-client";
import {
Bridge,
Intent,
MatrixUser,
MatrixRoom,
Logger,
Request,
PrometheusMetrics,
MembershipCache,
AgeCounters,
EphemeralEvent,
MembershipQueue,
MappingInfo,
BridgeInfoStateSyncer,
AppServiceRegistration,
AppService,
Rules,
ActivityTracker,
BridgeBlocker,
UserActivityState,
UserActivityTracker,
UserActivityTrackerConfig,
WeakStateEvent,
} from "matrix-appservice-bridge";
import { IrcAction } from "../models/IrcAction";
import { DataStore } from "../datastore/DataStore";
import { ActionType, MatrixAction, MatrixMessageEvent } from "../models/MatrixAction";
import { BridgeConfig } from "../config/BridgeConfig";
import { Registry } from "prom-client";
import { spawnMetricsWorker } from "../workers/MetricsWorker";
import { globalAgent as gAHTTP } from "http";
import { globalAgent as gAHTTPS } from "https";
import { RoomConfig } from "./RoomConfig";
import { PrivacyProtection } from "../irc/PrivacyProtection";
import { TestingOptions } from "../config/TestOpts";
import { MatrixBanSync } from "./MatrixBanSync";
const log = getLogger("IrcBridge");
const DEFAULT_PORT = 8090;
const DELAY_TIME_MS = 10 * 1000;
const DELAY_FETCH_ROOM_LIST_MS = 3 * 1000;
const DEAD_TIME_MS = 5 * 60 * 1000;
const TXN_SIZE_DEFAULT = 10000000 // 10MB
const CLIENTS_BY_HOMESERVER_TOP_N = 20;
export const MEMBERSHIP_DEFAULT_TTL = 10 * 60 * 1000;
/**
* How old can a receipt be before we treat
* it as stale.
*/
const RECEIPT_CUTOFF_TIME_MS = 60000;
export const METRIC_ACTIVE_USERS = "active_users";
type Timers = {
matrix_request_seconds: Histogram<string>;
remote_request_seconds: Histogram<string>;
irc_connection_time_ms: Histogram<string>;
}
export class IrcBridge {
public static readonly DEFAULT_LOCALPART = "appservice-irc";
public onAliasQueried: (() => void)|null = null;
public readonly matrixHandler: MatrixHandler;
public readonly ircHandler: IrcHandler;
public readonly publicitySyncer: PublicitySyncer;
public activityTracker: ActivityTracker|null = null;
public readonly roomConfigs: RoomConfig;
public readonly matrixBanSyncer?: MatrixBanSync;
private clientPool!: ClientPool; // This gets defined in the `run` function
private ircServers: IrcServer[] = [];
private memberListSyncers: {[domain: string]: MemberListSyncer} = {};
private joinedRoomList: string[] = [];
private dataStore!: DataStore;
private bridgeState: "not-started"|'starting'|"running"|"killed" = "not-started";
private debugApi: DebugApi|null = null;
private provisioner: Provisioner|null = null;
private bridge: Bridge;
private appservice: AppService;
private timers: Timers|null = null;
private membershipCache: MembershipCache;
private readonly membershipQueue: MembershipQueue;
private bridgeStateSyncer?: BridgeInfoStateSyncer<{
channel: string;
networkId: string;
}>;
private privacyProtection: PrivacyProtection;
private bridgeBlocker?: BridgeBlocker;
constructor(
public readonly config: BridgeConfig,
private registration: AppServiceRegistration,
private readonly testOpts: TestingOptions = {isDBInMemory: false},
) {
// TODO: Don't log this to stdout
Logger.configure({console: config.ircService.logging.level});
if (!this.config.database && this.config.ircService.databaseUri) {
log.warn("ircService.databaseUri is a deprecated config option." +
"Please use the database configuration block");
this.config.database = {
engine: "nedb",
connectionString: this.config.ircService.databaseUri,
}
}
let roomLinkValidationRules: Rules|undefined = undefined;
const provisioning = config.ircService.provisioning;
if (provisioning?.enabled && provisioning.rules) {
roomLinkValidationRules = provisioning.rules;
}
let bridgeStoreConfig = {};
if (this.config.database.engine === "nedb") {
const dirPath = this.config.database.connectionString.substring("nedb://".length);
bridgeStoreConfig = {
roomStore: `${dirPath}/rooms.db`,
userStore: `${dirPath}/users.db`,
userActivityStore: `${dirPath}/user-activity.db`,
};
}
else {
bridgeStoreConfig = {
disableStores: true,
};
}
this.membershipCache = new MembershipCache();
if (!this.registration.pushEphemeral) {
log.info("Sending ephemeral events to the bridge is currently disabled in the registration file," +
" so user activity will not be captured");
}
this.bridge = new Bridge({
registration: this.registration,
homeserverUrl: this.config.homeserver.url,
domain: this.config.homeserver.domain,
controller: {
onEvent: this.onEvent.bind(this),
onUserQuery: this.onUserQuery.bind(this),
onAliasQuery: this.onAliasQuery.bind(this),
onAliasQueried: this.onAliasQueried ?
this.onAliasQueried.bind(this) : undefined,
onLog: this.onLog.bind(this),
onEphemeralEvent: this.activityTracker ? this.onEphemeralEvent.bind(this) : undefined,
thirdPartyLookup: {
protocols: ["irc"],
getProtocol: this.getThirdPartyProtocol.bind(this),
getLocation: this.getThirdPartyLocation.bind(this),
getUser: this.getThirdPartyUser.bind(this),
},
},
...bridgeStoreConfig,
disableContext: true,
suppressEcho: false, // we use our own dupe suppress for now
logRequestOutcome: false, // we use our own which has better logging
queue: {
type: "none",
perRequest: false
},
intentOptions: {
clients: {
dontCheckPowerLevel: true,
enablePresence: this.config.homeserver.enablePresence,
},
bot: {
dontCheckPowerLevel: true,
enablePresence: this.config.homeserver.enablePresence,
}
},
// See note below for ESCAPE_DEFAULT
escapeUserIds: false,
roomLinkValidation: roomLinkValidationRules ? {
rules: roomLinkValidationRules,
} : undefined,
roomUpgradeOpts: {
consumeEvent: true,
migrateGhosts: false,
onRoomMigrated: this.onRoomUpgrade.bind(this),
migrateStoreEntries: false, // Only NeDB supports this.
},
membershipCache: this.membershipCache,
// For mocking the intent object,
onIntentCreate: testOpts.onIntentCreate,
});
this.membershipQueue = new MembershipQueue(this.bridge, {
concurrentRoomLimit: 3,
maxAttempts: 5,
actionDelayMs: 500,
maxActionDelayMs: 5 * 60 * 1000, // 5 mins,
defaultTtlMs: 10 * 60 * 1000, // 10 mins
});
this.matrixBanSyncer = this.config.ircService.banLists && new MatrixBanSync(this.config.ircService.banLists);
this.matrixHandler = new MatrixHandler(this, this.config.ircService.matrixHandler, this.membershipQueue);
this.privacyProtection = new PrivacyProtection(this);
this.ircHandler = new IrcHandler(
this, this.config.ircService.ircHandler, this.membershipQueue, this.privacyProtection
);
// By default the bridge will escape mxids, but the irc bridge isn't ready for this yet.
MatrixUser.ESCAPE_DEFAULT = false;
this.publicitySyncer = new PublicitySyncer(this);
const homeserverToken = this.registration.getHomeserverToken();
if (!homeserverToken) {
throw Error("No HS token defined");
}
this.appservice = new AppService({
homeserverToken,
httpMaxSizeBytes: this.config.advanced?.maxTxnSize ?? TXN_SIZE_DEFAULT,
});
this.roomConfigs = new RoomConfig(this.bridge, this.config.ircService.perRoomConfig);
if (this.config.ircService.RMAUlimit) {
this.bridgeBlocker = new BridgeBlocker(this.config.ircService.RMAUlimit);
}
}
public async onConfigChanged(newConfig: BridgeConfig) {
log.info(`Bridge config was reloaded, applying changes`);
const oldConfig = this.config;
if (oldConfig.advanced?.maxHttpSockets !== newConfig.advanced?.maxHttpSockets) {
const maxSockets = newConfig.advanced?.maxHttpSockets ?? 1000
gAHTTP.maxSockets = maxSockets;
gAHTTPS.maxSockets = maxSockets;
log.info(`Adjusted max sockets to ${maxSockets}`);
}
// We can't modify the maximum payload size after starting the http listener for the bridge, so
// newConfig.advanced.maxTxnSize is ignored.
if (oldConfig.homeserver.dropMatrixMessagesAfterSecs !== newConfig.homeserver.dropMatrixMessagesAfterSecs) {
oldConfig.homeserver.dropMatrixMessagesAfterSecs = newConfig.homeserver.dropMatrixMessagesAfterSecs;
log.info(`Adjusted dropMatrixMessagesAfterSecs to ${newConfig.homeserver.dropMatrixMessagesAfterSecs}`);
}
if (oldConfig.homeserver.media_url !== newConfig.homeserver.media_url) {
oldConfig.homeserver.media_url = newConfig.homeserver.media_url;
log.info(`Adjusted media_url to ${newConfig.homeserver.media_url}`);
}
this.ircHandler.onConfigChanged(newConfig.ircService.ircHandler || {});
this.config.ircService.ircHandler = newConfig.ircService.ircHandler;
this.matrixHandler.onConfigChanged(newConfig.ircService.matrixHandler);
this.config.ircService.matrixHandler = newConfig.ircService.matrixHandler;
this.config.ircService.permissions = newConfig.ircService.permissions;
this.bridge.updateRoomLinkValidatorRules(
// If no rules are specified, wipe them.
newConfig.ircService.provisioning?.rules || { userIds: { conflict: [], exempt: [] }}
);
this.config.ircService.provisioning.rules = newConfig.ircService.provisioning?.rules;
this.roomConfigs.config = newConfig.ircService.perRoomConfig;
const hasLoggingChanged = JSON.stringify(oldConfig.ircService.logging)
!== JSON.stringify(newConfig.ircService.logging);
if (hasLoggingChanged) {
Logger.configure({ console: newConfig.ircService.logging.level });
}
const banSyncPromise = this.matrixBanSyncer?.syncRules(this.bridge.getIntent());
await this.dataStore.removeConfigMappings();
// All config mapped channels will be briefly unavailable
await Promise.all(this.ircServers.map(async (server) => {
let newServerConfig = newConfig.ircService.servers[server.domain];
if (!newServerConfig) {
log.warn(`Server ${server.domain} removed from config. Bridge will need to be restarted`);
return;
}
newServerConfig = extend(
true, {}, IrcServer.DEFAULT_CONFIG, newConfig.ircService.servers[server.domain]
);
server.reconfigure(newServerConfig, newConfig.homeserver.dropMatrixMessagesAfterSecs);
await this.dataStore.setServerFromConfig(server, newServerConfig);
}));
await this.fetchJoinedRooms();
await this.joinMappedMatrixRooms();
await banSyncPromise;
await this.clientPool.checkForBannedConnectedUsers();
}
private initialiseMetrics(bindPort: number) {
const zeroAge = new AgeCounters();
const registry = new Registry();
if (!this.config.ircService.metrics) {
return;
}
const { userActivityThresholdHours, remoteUserAgeBuckets } = this.config.ircService.metrics;
const usingRemoteMetrics = !!this.config.ircService.metrics.port;
const metrics = this.bridge.getPrometheusMetrics(!usingRemoteMetrics, registry);
let metricsUrl = `${this.config.homeserver.bindHostname || "0.0.0.0"}:${bindPort}`;
if (this.config.ircService.metrics.port) {
const hostname = this.config.ircService.metrics.host || this.config.homeserver.bindHostname || "0.0.0.0";
metricsUrl = `${hostname}:${this.config.ircService.metrics.port}`;
spawnMetricsWorker(
this.config.ircService.metrics.port,
this.config.ircService.metrics.host,
() => {
metrics.refresh();
return registry.metrics();
},
);
}
log.info(`Started metrics on http://${metricsUrl}`);
this.bridge.registerBridgeGauges(() => {
const remoteUsersByAge = new PrometheusMetrics.AgeCounters(
remoteUserAgeBuckets || ["1h", "1d", "1w"]
);
this.ircServers.forEach((server) => {
this.clientPool.updateActiveConnectionMetrics(server.domain, remoteUsersByAge);
});
return {
// TODO(paul): actually fill these in
matrixRoomConfigs: 0,
remoteRoomConfigs: 0,
remoteGhosts: this.clientPool.countTotalConnections(),
// matrixGhosts is provided automatically by the bridge
// TODO(paul) IRC bridge doesn't maintain mtimes at the moment.
// Should probably make these metrics optional to most
// exporters
matrixRoomsByAge: zeroAge,
remoteRoomsByAge: zeroAge,
matrixUsersByAge: zeroAge,
remoteUsersByAge,
};
});
this.timers = {
matrix_request_seconds: metrics.addTimer({
name: "matrix_request_seconds",
help: "Histogram of processing durations of received Matrix messages",
labels: ["outcome"],
}),
remote_request_seconds: metrics.addTimer({
name: "remote_request_seconds",
help: "Histogram of processing durations of received remote messages",
labels: ["outcome"],
}),
irc_connection_time_ms: metrics.addTimer({
name: "irc_connection_time_ms",
help: "The time it took the user to receive the welcome message",
buckets: [100, 500, 1000, 2500, 10000, 30000],
}),
};
// Custom IRC metrics
const reconnQueue = metrics.addGauge({
name: "clientpool_reconnect_queue",
help: "Number of disconnected irc connections waiting to reconnect.",
labels: ["server"]
});
const clientStates = metrics.addGauge({
name: "clientpool_client_states",
help: "Number of clients in different states of connectedness.",
labels: ["server", "state"]
});
const clientsByHomeserver = metrics.addGauge({
name: "clientpool_by_homeserver",
help: "Number of clients by homeserver and state. " +
`Only lists the top ${CLIENTS_BY_HOMESERVER_TOP_N} homeservers`,
labels: ["homeserver", "state"]
});
const memberListLeaveQueue = metrics.addGauge({
name: "user_leave_queue",
help: "Number of leave requests queued up for virtual users on the bridge.",
labels: ["server"]
});
const memberListJoinQueue = metrics.addGauge({
name: "user_join_queue",
help: "Number of join requests queued up for virtual users on the bridge.",
labels: ["server"]
});
const activeUsers = metrics.addGauge({
name: METRIC_ACTIVE_USERS,
help: "Number of users actively using the bridge.",
labels: ["remote"],
});
const ircHandlerCalls = metrics.addCounter({
name: "irchandler_calls",
help: "Track calls made to the IRC Handler",
labels: ["method"]
});
const ircBlockedRooms = metrics.addGauge({
name: "irc_blocked_rooms",
help: "Track number of blocked rooms for I->M traffic",
labels: ["method"]
});
const matrixHandlerConnFailureKicks = metrics.addCounter({
name: "matrixhandler_connection_failure_kicks",
help: "Track IRC connection failures resulting in kicks",
labels: ["server"]
});
const maxRemoteGhosts = metrics.addGauge({
name: "remote_ghosts_max",
help: "The maximum number of remote ghosts",
labels: ["server"]
});
const bridgeBlocked = metrics.addGauge({
name: "bridge_blocked",
help: "Is the bridge currently blocking messages",
});
metrics.addCollector(() => {
this.ircServers.forEach((server) => {
reconnQueue.set({server: server.domain},
this.clientPool.totalReconnectsWaiting(server.domain)
);
const mxMetrics = this.matrixHandler.getMetrics(server.domain);
matrixHandlerConnFailureKicks.inc(
{server: server.domain},
mxMetrics["connection_failure_kicks"] || 0
);
maxRemoteGhosts.set({server: server.domain}, server.getMaxClients());
});
if (userActivityThresholdHours) {
// Only collect if defined
const currentTime = Date.now();
const appserviceBot = this.bridge.getBot();
if (!appserviceBot) {
// Not ready yet.
return;
}
this.dataStore.getLastSeenTimeForUsers().then((userSet) => {
let remote = 0;
let matrix = 0;
for (const user of userSet) {
const timeOffset = (currentTime - user.ts) / (60*60*1000); // Hours
if (timeOffset > userActivityThresholdHours) {
return;
}
else if (appserviceBot.isRemoteUser(user.user_id)) {
remote++;
}
else {
matrix++;
}
}
activeUsers.set({remote: "true"}, remote);
activeUsers.set({remote: "false"}, matrix);
}).catch((ex) => {
log.warn("Failed to scrape for user activity", ex);
});
}
Object.keys(this.memberListSyncers).forEach((server) => {
memberListLeaveQueue.set(
{server},
this.memberListSyncers[server].getUsersWaitingToLeave()
);
memberListJoinQueue.set(
{server},
this.memberListSyncers[server].getUsersWaitingToJoin()
);
});
ircBlockedRooms.set(this.privacyProtection.blockedRoomCount);
const ircMetrics = this.ircHandler.getMetrics();
Object.entries(ircMetrics).forEach((kv) => {
ircHandlerCalls.inc({method: kv[0]}, kv[1]);
});
bridgeBlocked.set(this.bridgeBlocker?.isBlocked ? 1 : 0);
});
metrics.addCollector(async () => {
this.clientPool.collectConnectionStatesForAllServers(
clientStates, clientsByHomeserver, CLIENTS_BY_HOMESERVER_TOP_N
);
});
this.membershipQueue.registerMetrics();
}
public get appServiceUserId() {
return `@${this.registration.getSenderLocalpart()}:${this.domain}`;
}
public getStore() {
return this.dataStore;
}
public getAppServiceBridge() {
return this.bridge;
}
public getClientPool() {
return this.clientPool;
}
public getProvisioner(): Provisioner {
return this.provisioner as Provisioner;
}
public get domain() {
return this.config.homeserver.domain;
}
public get stateSyncer() {
return this.bridgeStateSyncer;
}
private async pingBridge() {
let internalRoom: MatrixRoom|null;
try {
internalRoom = await this.dataStore.getAdminRoomByUserId("-internal-");
if (!internalRoom) {
const result = await this.bridge.getIntent().createRoom({ options: {}});
internalRoom = new MatrixRoom(result.room_id);
this.dataStore.storeAdminRoom(internalRoom, "-internal-");
}
const time = await this.bridge.pingAppserviceRoute(internalRoom.getId());
log.info(`Successfully pinged the bridge. Round trip took ${time}ms`);
}
catch (ex) {
log.error("Homeserver cannot reach the bridge. You probably need to adjust your configuration.", ex);
}
}
public createInfoMapping(channel: string, networkId: string): MappingInfo {
const network = this.getServer(networkId);
return {
protocol: {
id: 'irc',
displayname: 'IRC',
},
network: {
id: networkId,
displayname: network?.getReadableName(),
avatar_url: network?.getIcon() as `mxc://`,
},
channel: {
id: channel,
},
eventFeatures: defaultEventFeatures,
}
}
public async run(port: number|null) {
this.bridgeState = 'starting';
const dbConfig = this.config.database;
// cli port, then config port, then default port
port = port || this.config.homeserver.bindPort || DEFAULT_PORT;
const pkeyPath = this.config.ircService.passwordEncryptionKeyPath;
await this.bridge.initialise();
await this.matrixBanSyncer?.syncRules(this.bridge.getIntent());
this.matrixHandler.initialise();
this.activityTracker = new ActivityTracker(this.bridge.getIntent().matrixClient, {
usePresence: this.config.homeserver.enablePresence,
serverName: this.config.homeserver.domain,
defaultOnline: true,
});
if (dbConfig.engine === "postgres") {
log.info("Using PgDataStore for Datastore");
const pgDs = new PgDataStore(this.config.homeserver.domain, dbConfig.connectionString, pkeyPath);
await pgDs.ensureSchema();
this.dataStore = pgDs;
}
else if (dbConfig.engine === "nedb") {
await this.bridge.loadDatabases();
const userStore = this.bridge.getUserStore();
const roomStore = this.bridge.getRoomStore();
const userActivityStore = this.bridge.getUserActivityStore();
log.info("Using NeDBDataStore for Datastore");
if (!userStore || !roomStore || !userActivityStore) {
throw Error('Could not load user(Activity)Store or roomStore');
}
const ndbDatastore = new NeDBDataStore(
userStore,
userActivityStore,
roomStore,
this.config.homeserver.domain,
pkeyPath,
);
await ndbDatastore.runMigrations();
this.dataStore = ndbDatastore;
if (this.config.ircService.debugApi.enabled) {
// monkey patch inspect() values to avoid useless NeDB
// struct spam on the debug API.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(userStore as any).inspect = () => "UserStore";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(roomStore as any).inspect = () => "RoomStore";
}
}
else {
throw Error("Incorrect database config");
}
await this.dataStore.removeConfigMappings();
if (this.activityTracker) {
log.info("Restoring last active times from DB");
const users = await this.dataStore.getLastSeenTimeForUsers();
for (const user of users) {
this.activityTracker.setLastActiveTime(user.user_id, user.ts);
}
log.info(`Restored ${users.length} last active times from DB`);
}
// maintain a list of IRC servers in-use
const serverDomains = Object.keys(this.config.ircService.servers);
for (let i = 0; i < serverDomains.length; i++) {
const domain = serverDomains[i];
const completeConfig = extend(
true, {}, IrcServer.DEFAULT_CONFIG, this.config.ircService.servers[domain]
);
const server = new IrcServer(
domain, completeConfig, this.config.homeserver.domain,
this.config.homeserver.dropMatrixMessagesAfterSecs
);
// store the config mappings in the DB to keep everything in one place.
await this.dataStore.setServerFromConfig(server, completeConfig);
this.ircServers.push(server);
}
this.clientPool = new ClientPool(this, this.dataStore);
if (this.config.ircService.debugApi.enabled) {
this.debugApi = new DebugApi(
this,
this.config.ircService.debugApi.port,
this.ircServers,
this.clientPool,
this.registration.getAppServiceToken() as string
);
this.debugApi.run();
}
if (this.ircServers.length === 0) {
throw Error("No IRC servers specified.");
}
if (this.config.ircService.userActivity) {
const uatConfig = {
...UserActivityTrackerConfig.DEFAULT,
};
if (this.config.ircService.userActivity.minUserActiveDays !== undefined) {
uatConfig.minUserActiveDays = this.config.ircService.userActivity.minUserActiveDays;
}
if (this.config.ircService.userActivity.inactiveAfterDays !== undefined) {
uatConfig.inactiveAfterDays = this.config.ircService.userActivity.inactiveAfterDays;
}
this.bridge.opts.controller.userActivityTracker = new UserActivityTracker(
uatConfig,
await this.getStore().getUserActivity(),
(changes) => this.onUserActivityChanged(changes).catch(
(ex) => log.warn("onUserActivityChanged encountered an error", ex),
),
);
this.bridgeBlocker?.checkLimits(
this.bridge.opts.controller.userActivityTracker.countActiveUsers().allUsers
).catch(ex => {
log.warn(`Failed to run initial checkLimits for user activity tracker`, ex);
});
}
// run the bridge (needs to be done prior to configure IRC side)
await this.bridge.listen(port, this.config.homeserver.bindHostname, undefined, this.appservice);
log.info(`Listening on ${this.config.homeserver.bindHostname || "0.0.0.0"}:${port}`)
if (this.config.ircService.metrics && this.config.ircService.metrics.enabled) {
this.initialiseMetrics(port);
}
this.addRequestCallbacks();
if (!this.registration.getSenderLocalpart() ||
!this.registration.getAppServiceToken()) {
throw Error(
"FATAL: Registration file is missing a sender_localpart and/or AS token."
);
}
if (!this.testOpts.skipPingCheck) {
await this.pingBridge();
}
// Storing all the users we know about to avoid calling /register on them.
const allUsers = await this.dataStore.getAllUserIds();
const bot = this.bridge.getBot();
allUsers.filter((u) => bot.isRemoteUser(u))
.forEach((u) => this.membershipCache.setMemberEntry("", u, "join", {}));
log.info("Fetching Matrix rooms that are already joined to...");
await this.fetchJoinedRooms();
if (this.config.ircService.bridgeInfoState?.enabled) {
this.bridgeStateSyncer = new BridgeInfoStateSyncer(this.bridge, {
bridgeName: 'org.matrix.appservice-irc',
getMapping: async (roomId, { channel, networkId }) => this.createInfoMapping(channel, networkId),
});
if (this.config.ircService.bridgeInfoState.initial) {
const mappings = await this.dataStore.getAllChannelMappings();
this.bridgeStateSyncer.initialSync(mappings).then(() => {
log.info("Bridge state syncing completed");
}).catch((err) => {
log.error("Bridge state syncing resulted in an error:", err);
});
}
}
log.info("Joining mapped Matrix rooms...");
await this.joinMappedMatrixRooms();
log.info("Syncing relevant membership lists...");
const memberlistPromises: Promise<void>[] = [];
this.ircServers.forEach((server) => {
// If memberlist-syncing 100s of connections, the scheduler will cause massive
// waiting times for connections to be created.
// We disable this scheduling manually to allow people to send messages through
// quickly when starting up (effectively prioritising them).
server.toggleReconnectInterval(false);
// TODO reduce deps required to make MemberListSyncers.
// TODO Remove injectJoinFn bodge
this.memberListSyncers[server.domain] = new MemberListSyncer(
this, this.membershipQueue, this.bridge.getBot(), server, this.appServiceUserId,
(roomId: string, joiningUserId: string, displayName: string, isFrontier: boolean) => {
const req = new BridgeRequest(
this.bridge.getRequestFactory().newRequest()
);
const target = new MatrixUser(joiningUserId);
// inject a fake join event which will do M->I connections and
// therefore sync the member list
return this.matrixHandler.onJoin(req, {
room_id: roomId,
content: {
displayname: displayName,
membership: "join",
},
_injected: true,
state_key: joiningUserId,
type: "m.room.member",
event_id: "!injected",
_frontier: isFrontier
}, target);
}
);
memberlistPromises.push(
this.memberListSyncers[server.domain].sync()
);
});
log.info("Starting provisioning API...");
const homeserverToken = this.registration.getHomeserverToken();
if (!homeserverToken) {
throw Error("No HS token defined");
}
this.provisioner = new Provisioner(
this,
this.membershipQueue,
{
// Default to HS token if no secret is configured
secret: homeserverToken,
...this.config.ircService.provisioning,
},
);
await this.provisioner.start();
log.info("Connecting to IRC networks...");
await this.connectToIrcNetworks();
promiseutil.allSettled(this.ircServers.map((server) => {
// Call MODE on all known channels to get modes of all channels
return Bluebird.cast(this.publicitySyncer.initModes(server));
})).catch((err) => {
log.error('Could not init modes for publicity syncer');
log.error(err.stack);
});
await Promise.all(memberlistPromises);
// Reset reconnectIntervals
this.ircServers.forEach((server) => {
server.toggleReconnectInterval(true);
});
log.info("Startup complete.");
this.bridgeState = "running";
}
/*
* Send state events providing information about the state.
* @param intent if given, sends state events from this client instead of the AS bot
*/
public async syncState(ircChannel: string, server: IrcServer, roomId: string, intent?: Intent) {
if (this.stateSyncer) {
intent = intent || this.getAppServiceBridge().getIntent();
const events = await this.stateSyncer.createInitialState(roomId, {
channel: ircChannel,
networkId: server.getNetworkId(),
})
for (const event of events) {
// await after each event so they are sent in the right order
await intent.sendStateEvent(
roomId,
event.type,
event.state_key,
event.content as unknown as Record<string, unknown>,
);
}
}
}
private logMetric(req: Request<BridgeRequestData>, outcome: string) {
if (!this.timers) {
return; // metrics are disabled
}
const isFromIrc = Boolean((req.getData() || {}).isFromIrc);
const timer = this.timers[
isFromIrc ? "remote_request_seconds" : "matrix_request_seconds"
];
if (timer) {
timer.observe({outcome}, req.getDuration() / 1000);
}
}
public logTime(key: keyof Timers, time: number) {
if (!this.timers) {
return; // metrics are disabled
}
this.timers[key].observe(time);
}
private addRequestCallbacks() {
function logMessage(req: Request<BridgeRequestData>, msg: string) {
const data = req.getData();
const dir = data && data.isFromIrc ? "I->M" : "M->I";
const duration = " (" + req.getDuration() + "ms)";
log.info(`[${req.getId()}] [${dir}] ${msg} ${duration}`);
}
const factory = this.bridge.getRequestFactory();
// SUCCESS
factory.addDefaultResolveCallback((req, _res) => {
const res = _res as BridgeRequestErr|null;
const bridgeRequest = req as Request<BridgeRequestData>;
if (res === BridgeRequestErr.ERR_VIRTUAL_USER) {
logMessage(bridgeRequest, "IGNORE virtual user");
return; // these aren't true successes so don't skew graphs
}
else if (res === BridgeRequestErr.ERR_NOT_MAPPED) {
logMessage(bridgeRequest, "IGNORE not mapped");
return; // these aren't true successes so don't skew graphs
}
else if (res === BridgeRequestErr.ERR_DROPPED) {
logMessage(bridgeRequest, "IGNORE dropped");
this.logMetric(bridgeRequest, "dropped");
return;
}
logMessage(bridgeRequest, "SUCCESS");
this.logMetric(bridgeRequest, "success");
});
// FAILURE
factory.addDefaultRejectCallback((req) => {
const bridgeRequest = req as Request<BridgeRequestData>;
logMessage(bridgeRequest, "FAILED");
this.logMetric(bridgeRequest, "fail");
BridgeRequest.HandleExceptionForSentry(req as Request<BridgeRequestData>, "fail");
});
// DELAYED
factory.addDefaultTimeoutCallback((req) => {
logMessage(req as Request<BridgeRequestData>, "DELAYED");
}, DELAY_TIME_MS);
// DEAD
factory.addDefaultTimeoutCallback((req) => {
const bridgeRequest = req as Request<BridgeRequestData>;
logMessage(bridgeRequest, "DEAD");
this.logMetric(bridgeRequest, "dead");
BridgeRequest.HandleExceptionForSentry(req as Request<BridgeRequestData>, "dead");
}, DEAD_TIME_MS);
}
// Kill the bridge by killing all IRC clients in memory.
// Killing a client means that it will disconnect forever
// and never do anything useful again.
// There is no guarentee that the bridge will do anything
// usefull once this has been called.
//
// See (BridgedClient.prototype.kill)
public async kill(reason?: string) {
log.info("Killing bridge");
this.bridgeState = "killed";
log.info("Killing all clients");
await this.clientPool.killAllClients(reason);
if (this.dataStore) {
await this.dataStore.destroy();
}
log.info("Closing bridge");
await this.bridge.close();
await this.appservice.close();
}
public get isStartedUp() {
return this.bridgeState === "running";
}
private async joinMappedMatrixRooms() {
const roomIds = await this.getStore().getRoomIdsFromConfig();
const promises = roomIds.map(async (roomId) => {
if (this.joinedRoomList.includes(roomId)) {
log.debug(`Not joining ${roomId} because we are marked as joined`);
return;
}
await this.bridge.getIntent().join(roomId);
}).map(Bluebird.cast);
await promiseutil.allSettled(promises);
}
public async sendMatrixAction(room: MatrixRoom, from: MatrixUser|undefined, action: MatrixAction): Promise<void> {
if (this.bridgeBlocker?.isBlocked) {
log.info("Bridge is blocked, dropping Matrix action");
return;
}
const intent = this.bridge.getIntent(from?.userId);
const extraContent: Record<string, unknown> = {};
if (action.replyEvent) {
extraContent["m.relates_to"] = {
"m.in_reply_to": {
event_id: action.replyEvent,
}
}
}
if (action.msgType) {
if (action.htmlText) {
await intent.sendMessage(room.getId(), {
msgtype: action.msgType,
body: (
action.text || action.htmlText.replace(/(<([^>]+)>)/ig, "") // strip html tags
),
format: "org.matrix.custom.html",
formatted_body: action.htmlText,
...extraContent,
});
}
else {
await intent.sendMessage(room.getId(), {
msgtype: action.msgType,
body: action.text,
...extraContent,
});
}
return;
}
else if (action.type === "topic" && action.text) {
await intent.setRoomTopic(room.getId(), action.text);
return;
}
throw Error("Unknown action: " + action.type);
}
public async syncMembersInRoomToIrc(req: BridgeRequest, roomId: string, ircRoom: IrcRoom, kickFailures = false) {
const bot = this.getAppServiceBridge().getBot();
const members = await bot.getJoinedMembers(roomId);
req.log.info(