aboutsummaryrefslogtreecommitdiff
path: root/libdino/src/service/connection_manager.vala
blob: e0f4e19c8a91e5bb486682b8674790c94556f1a0 (plain) (blame)
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
using Gee;

using Xmpp;
using Dino.Entities;

namespace Dino {

public class ConnectionManager : Object {

    public signal void stream_opened(Account account, XmppStream stream);
    public signal void connection_state_changed(Account account, ConnectionState state);
    public signal void connection_error(Account account, ConnectionError error);

    public enum ConnectionState {
        CONNECTED,
        CONNECTING,
        DISCONNECTED
    }

    private HashMap<Account, Connection> connections = new HashMap<Account, Connection>(Account.hash_func, Account.equals_func);
    private HashMap<Account, ConnectionError> connection_errors = new HashMap<Account, ConnectionError>(Account.hash_func, Account.equals_func);

    private HashMap<Account, bool> connection_ongoing = new HashMap<Account, bool>(Account.hash_func, Account.equals_func);
    private HashMap<Account, bool> connection_directly_retry = new HashMap<Account, bool>(Account.hash_func, Account.equals_func);

    private NetworkMonitor? network_monitor;
    private Login1Manager? login1;
    private ModuleManager module_manager;
    public string? log_options;

    public class ConnectionError {

        public enum Source {
            CONNECTION,
            SASL,
            TLS,
            STREAM_ERROR
        }

        public enum Reconnect {
            NOW,
            LATER,
            NEVER
        }

        public Source source;
        public string? identifier;
        public Reconnect reconnect_recomendation { get; set; default=Reconnect.NOW; }

        public ConnectionError(Source source, string? identifier) {
            this.source = source;
            this.identifier = identifier;
        }
    }

    private class Connection {
        public string uuid { get; set; }
        public XmppStream? stream { get; set; }
        public ConnectionState connection_state { get; set; default = ConnectionState.DISCONNECTED; }
        public DateTime? established { get; set; }
        public DateTime? last_activity { get; set; }

        public Connection() {
            reset();
        }

        public void reset() {
            if (stream != null) {
                stream.detach_modules();

                stream.disconnect.begin();
            }
            stream = null;
            established = last_activity = null;
            uuid = Xmpp.random_uuid();
        }

        public void make_offline() {
            Xmpp.Presence.Stanza presence = new Xmpp.Presence.Stanza();
            presence.type_ = Xmpp.Presence.Stanza.TYPE_UNAVAILABLE;
            if (stream != null) {
                stream.get_module(Presence.Module.IDENTITY).send_presence(stream, presence);
            }
        }

        public async void disconnect_account() {
            make_offline();

            if (stream != null) {
                try {
                    yield stream.disconnect();
                } catch (Error e) {
                    debug("Error disconnecting stream: %s", e.message);
                }
            }
        }
    }

    public ConnectionManager(ModuleManager module_manager) {
        this.module_manager = module_manager;
        network_monitor = GLib.NetworkMonitor.get_default();
        if (network_monitor != null) {
            network_monitor.network_changed.connect(on_network_changed);
            network_monitor.notify["connectivity"].connect(on_network_changed);
        }
        login1 = get_login1();
        if (login1 != null) {
            login1.PrepareForSleep.connect(on_prepare_for_sleep);
        }
        Timeout.add_seconds(60, () => {
            foreach (Account account in connections.keys) {
                if (connections[account].last_activity != null &&
                        connections[account].last_activity.compare(new DateTime.now_utc().add_minutes(-1)) < 0) {
                    check_reconnect(account);
                }
            }
            return true;
        });
    }

    public XmppStream? get_stream(Account account) {
        if (get_state(account) == ConnectionState.CONNECTED) {
            return connections[account].stream;
        }
        return null;
    }

    public ConnectionState get_state(Account account) {
        if (connections.has_key(account)){
            return connections[account].connection_state;
        }
        return ConnectionState.DISCONNECTED;
    }

    public ConnectionError? get_error(Account account) {
        if (connection_errors.has_key(account)) {
            return connection_errors[account];
        }
        return null;
    }

    public Collection<Account> get_managed_accounts() {
        return connections.keys;
    }

    public void connect_account(Account account) {
        if (!connections.has_key(account)) {
            connections[account] = new Connection();
            connection_ongoing[account] = false;
            connection_directly_retry[account] = false;

            connect_stream.begin(account);
        } else {
            check_reconnect(account);
        }
    }

    public void make_offline_all() {
        foreach (Account account in connections.keys) {
            make_offline(account);
        }
    }

    private void make_offline(Account account) {
        connections[account].make_offline();
        change_connection_state(account, ConnectionState.DISCONNECTED);
    }

    public async void disconnect_account(Account account) {
        if (connections.has_key(account)) {
            make_offline(account);
            connections[account].disconnect_account();
            connections.unset(account);
        }
    }

    private async void connect_stream(Account account, string? resource = null) {
        if (!connections.has_key(account)) return;

        debug("[%s] (Maybe) Establishing a new connection", account.bare_jid.to_string());

        connection_errors.unset(account);
        if (resource == null) resource = account.resourcepart;

        XmppStreamResult stream_result;

        if (connection_ongoing[account]) {
            debug("[%s] Connection attempt already in progress. Directly retry if it fails.", account.bare_jid.to_string());
            connection_directly_retry[account] = true;
            return;
        } else if (connections[account].stream != null) {
            debug("[%s] Cancelling connecting because there is already a stream", account.bare_jid.to_string());
            return;
        } else {
            connection_ongoing[account] = true;
            connection_directly_retry[account] = false;

            change_connection_state(account, ConnectionState.CONNECTING);
            stream_result = yield Xmpp.establish_stream(account.bare_jid, module_manager.get_modules(account, resource), log_options,
                    (peer_cert, errors) => { return on_invalid_certificate(account.domainpart, peer_cert, errors); }
            );
            connections[account].stream = stream_result.stream;

            connection_ongoing[account] = false;
        }

        if (stream_result.stream == null) {
            if (stream_result.tls_errors != null) {
                set_connection_error(account, new ConnectionError(ConnectionError.Source.TLS, null) { reconnect_recomendation=ConnectionError.Reconnect.NEVER});
                return;
            }

            debug("[%s] Could not connect", account.bare_jid.to_string());

            change_connection_state(account, ConnectionState.DISCONNECTED);

            check_reconnect(account, connection_directly_retry[account]);

            return;
        }

        XmppStream stream = stream_result.stream;

        debug("[%s] New connection with resource %s: %p", account.bare_jid.to_string(), resource, stream);

        connections[account].established = new DateTime.now_utc();
        stream.attached_modules.connect((stream) => {
            change_connection_state(account, ConnectionState.CONNECTED);
        });
        stream.get_module(Sasl.Module.IDENTITY).received_auth_failure.connect((stream, node) => {
            set_connection_error(account, new ConnectionError(ConnectionError.Source.SASL, null));
        });

        string connection_uuid = connections[account].uuid;
        stream.received_node.connect(() => {
            if (connections[account].uuid == connection_uuid) {
                connections[account].last_activity = new DateTime.now_utc();
            } else {
                warning("Got node for outdated connection");
            }
        });
        stream_opened(account, stream);

        try {
            yield stream.loop();
        } catch (Error e) {
            debug("[%s %p] Connection error: %s", account.bare_jid.to_string(), stream, e.message);

            change_connection_state(account, ConnectionState.DISCONNECTED);
            connections[account].reset();

            StreamError.Flag? flag = stream.get_flag(StreamError.Flag.IDENTITY);
            if (flag != null) {
                warning(@"[%s %p] Stream Error: %s", account.bare_jid.to_string(), stream, flag.error_type);
                set_connection_error(account, new ConnectionError(ConnectionError.Source.STREAM_ERROR, flag.error_type));

                if (flag.resource_rejected) {
                    connect_stream.begin(account, account.resourcepart + "-" + random_uuid());
                    return;
                }
            }

            ConnectionError? error = connection_errors[account];
            if (error != null && error.source == ConnectionError.Source.SASL) {
                return;
            }

            check_reconnect(account);
        }
    }

    private void check_reconnects() {
        foreach (Account account in connections.keys) {
            check_reconnect(account);
        }
    }

    private void check_reconnect(Account account, bool directly_reconnect = false) {
        if (!connections.has_key(account)) return;

        bool acked = false;
        DateTime? last_activity_was = connections[account].last_activity;

        if (connections[account].stream == null) {
            Timeout.add_seconds(10, () => {
                if (!connections.has_key(account)) return false;
                if (connections[account].stream != null) return false;
                if (connections[account].last_activity != last_activity_was) return false;

                connect_stream.begin(account);
                return false;
            });
            return;
        }

        XmppStream stream = connections[account].stream;

        stream.get_module(Xep.Ping.Module.IDENTITY).send_ping.begin(stream, account.bare_jid.domain_jid, () => {
            acked = true;
            if (connections[account].stream != stream) return;
            change_connection_state(account, ConnectionState.CONNECTED);
        });

        Timeout.add_seconds(10, () => {
            if (!connections.has_key(account)) return false;
            if (connections[account].stream != stream) return false;
            if (acked) return false;
            if (connections[account].last_activity != last_activity_was) return false;

            // Reconnect. Nothing gets through the stream.
            debug("[%s %p] Ping timeouted. Reconnecting", account.bare_jid.to_string(), stream);
            change_connection_state(account, ConnectionState.DISCONNECTED);

            connections[account].reset();
            connect_stream.begin(account);
            return false;
        });
    }

    private bool network_is_online() {
        /* FIXME: We should also check for connectivity eventually. For more
         * details on why we don't do it for now, see:
         *
         * - https://github.com/dino/dino/pull/236#pullrequestreview-86851793
         * - https://bugzilla.gnome.org/show_bug.cgi?id=792240
         */
        return network_monitor != null && network_monitor.network_available;
    }

    private void on_network_changed() {
        if (network_is_online()) {
            debug("NetworkMonitor: Network reported online");
            check_reconnects();
        } else {
            debug("NetworkMonitor: Network reported offline");
            foreach (Account account in connections.keys) {
                change_connection_state(account, ConnectionState.DISCONNECTED);
            }
        }
    }

    private async void on_prepare_for_sleep(bool suspend) {
        foreach (Account account in connections.keys) {
            change_connection_state(account, ConnectionState.DISCONNECTED);
        }
        if (suspend) {
            debug("Login1: Device suspended");
            foreach (Account account in connections.keys) {
                try {
                    make_offline(account);
                    yield connections[account].stream.disconnect();
                } catch (Error e) {
                    debug("Error disconnecting stream %p: %s", connections[account].stream, e.message);
                }
            }
        } else {
            debug("Login1: Device un-suspend");
            check_reconnects();
        }
    }

    private void change_connection_state(Account account, ConnectionState state) {
        if (connections.has_key(account)) {
            connections[account].connection_state = state;
            connection_state_changed(account, state);
        }
    }

    private void set_connection_error(Account account, ConnectionError error) {
        connection_errors[account] = error;
        connection_error(account, error);
    }

    public static bool on_invalid_certificate(string domain, TlsCertificate peer_cert, TlsCertificateFlags errors) {
        if (domain.has_suffix(".onion") && errors == TlsCertificateFlags.UNKNOWN_CA) {
            // It's barely possible for .onion servers to provide a non-self-signed cert.
            // But that's fine because encryption is provided independently though TOR.
            warning("Accepting TLS certificate from unknown CA from .onion address %s", domain);
            return true;
        }
        return false;
    }
}

}