Coverage Report

Created: 2023-11-22 10:24

/src/c-toxcore/toxcore/Messenger.c
Line
Count
Source (jump to first uncovered line)
1
/* SPDX-License-Identifier: GPL-3.0-or-later
2
 * Copyright © 2016-2018 The TokTok team.
3
 * Copyright © 2013 Tox project.
4
 */
5
6
/**
7
 * An implementation of a simple text chat only messenger on the tox network core.
8
 */
9
#include "Messenger.h"
10
11
#include <assert.h>
12
#include <stdio.h>
13
#include <stdlib.h>
14
#include <string.h>
15
#include <time.h>
16
17
#include "DHT.h"
18
#include "ccompat.h"
19
#include "group_chats.h"
20
#include "group_onion_announce.h"
21
#include "logger.h"
22
#include "mono_time.h"
23
#include "network.h"
24
#include "state.h"
25
#include "util.h"
26
27
static_assert(MAX_CONCURRENT_FILE_PIPES <= UINT8_MAX + 1,
28
              "uint8_t cannot represent all file transfer numbers");
29
30
static const Friend empty_friend = {{0}};
31
32
/**
33
 * Determines if the friendnumber passed is valid in the Messenger object.
34
 *
35
 * @param friendnumber The index in the friend list.
36
 */
37
bool friend_is_valid(const Messenger *m, int32_t friendnumber)
38
0
{
39
0
    return (uint32_t)friendnumber < m->numfriends && m->friendlist[friendnumber].status != 0;
40
0
}
41
42
/** @brief Set the size of the friend list to numfriends.
43
 *
44
 * @retval -1 if mem_vrealloc fails.
45
 */
46
non_null()
47
static int realloc_friendlist(Messenger *m, uint32_t num)
48
412
{
49
412
    if (num == 0) {
50
0
        mem_delete(m->mem, m->friendlist);
51
0
        m->friendlist = nullptr;
52
0
        return 0;
53
0
    }
54
55
412
    Friend *newfriendlist = (Friend *)mem_vrealloc(m->mem, m->friendlist, num, sizeof(Friend));
56
57
412
    if (newfriendlist == nullptr) {
58
0
        return -1;
59
0
    }
60
61
412
    m->friendlist = newfriendlist;
62
412
    return 0;
63
412
}
64
65
/** @return the friend number associated to that public key.
66
 * @retval -1 if no such friend.
67
 */
68
int32_t getfriend_id(const Messenger *m, const uint8_t *real_pk)
69
2.86k
{
70
3.87k
    for (uint32_t i = 0; i < m->numfriends; ++i) {
71
1.14k
        if (m->friendlist[i].status > 0 && pk_equal(real_pk, m->friendlist[i].real_pk)) {
72
127
            return i;
73
127
        }
74
1.14k
    }
75
76
2.73k
    return -1;
77
2.86k
}
78
79
/** @brief Copies the public key associated to that friend id into real_pk buffer.
80
 *
81
 * Make sure that real_pk is of size CRYPTO_PUBLIC_KEY_SIZE.
82
 *
83
 * @retval 0 if success.
84
 * @retval -1 if failure.
85
 */
86
int get_real_pk(const Messenger *m, int32_t friendnumber, uint8_t *real_pk)
87
0
{
88
0
    if (!m_friend_exists(m, friendnumber)) {
89
0
        return -1;
90
0
    }
91
92
0
    memcpy(real_pk, m->friendlist[friendnumber].real_pk, CRYPTO_PUBLIC_KEY_SIZE);
93
0
    return 0;
94
0
}
95
96
/** @return friend connection id on success.
97
 * @retval -1 if failure.
98
 */
99
int getfriendcon_id(const Messenger *m, int32_t friendnumber)
100
0
{
101
0
    if (!m_friend_exists(m, friendnumber)) {
102
0
        return -1;
103
0
    }
104
105
0
    return m->friendlist[friendnumber].friendcon_id;
106
0
}
107
108
/**
109
 * Format: `[real_pk (32 bytes)][nospam number (4 bytes)][checksum (2 bytes)]`
110
 *
111
 * @param[out] address FRIEND_ADDRESS_SIZE byte address to give to others.
112
 */
113
void getaddress(const Messenger *m, uint8_t *address)
114
0
{
115
0
    pk_copy(address, nc_get_self_public_key(m->net_crypto));
116
0
    uint32_t nospam = get_nospam(m->fr);
117
0
    memcpy(address + CRYPTO_PUBLIC_KEY_SIZE, &nospam, sizeof(nospam));
118
0
    uint16_t checksum = data_checksum(address, FRIEND_ADDRESS_SIZE - sizeof(checksum));
119
0
    memcpy(address + CRYPTO_PUBLIC_KEY_SIZE + sizeof(nospam), &checksum, sizeof(checksum));
120
0
}
121
122
non_null()
123
static bool send_online_packet(Messenger *m, int friendcon_id)
124
0
{
125
0
    uint8_t packet = PACKET_ID_ONLINE;
126
0
    return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, friendcon_id), &packet,
127
0
                             sizeof(packet), false) != -1;
128
0
}
129
130
non_null()
131
static bool send_offline_packet(Messenger *m, int friendcon_id)
132
0
{
133
0
    uint8_t packet = PACKET_ID_OFFLINE;
134
0
    return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, friendcon_id), &packet,
135
0
                             sizeof(packet), false) != -1;
136
0
}
137
138
non_null(1) nullable(4)
139
static int m_handle_status(void *object, int i, bool status, void *userdata);
140
non_null(1, 3) nullable(5)
141
static int m_handle_packet(void *object, int i, const uint8_t *temp, uint16_t len, void *userdata);
142
non_null(1, 3) nullable(5)
143
static int m_handle_lossy_packet(void *object, int friend_num, const uint8_t *packet, uint16_t length,
144
                                 void *userdata);
145
146
non_null()
147
static int32_t init_new_friend(Messenger *m, const uint8_t *real_pk, uint8_t status)
148
412
{
149
412
    if (m->numfriends == UINT32_MAX) {
150
0
        LOGGER_ERROR(m->log, "Friend list full: we have more than 4 billion friends");
151
        /* This is technically incorrect, but close enough. */
152
0
        return FAERR_NOMEM;
153
0
    }
154
155
    /* Resize the friend list if necessary. */
156
412
    if (realloc_friendlist(m, m->numfriends + 1) != 0) {
157
0
        return FAERR_NOMEM;
158
0
    }
159
160
412
    m->friendlist[m->numfriends] = empty_friend;
161
162
412
    const int friendcon_id = new_friend_connection(m->fr_c, real_pk);
163
164
412
    if (friendcon_id == -1) {
165
0
        return FAERR_NOMEM;
166
0
    }
167
168
1.00k
    for (uint32_t i = 0; i <= m->numfriends; ++i) {
169
1.00k
        if (m->friendlist[i].status == NOFRIEND) {
170
412
            m->friendlist[i].status = status;
171
412
            m->friendlist[i].friendcon_id = friendcon_id;
172
412
            m->friendlist[i].friendrequest_lastsent = 0;
173
412
            pk_copy(m->friendlist[i].real_pk, real_pk);
174
412
            m->friendlist[i].statusmessage_length = 0;
175
412
            m->friendlist[i].userstatus = USERSTATUS_NONE;
176
412
            m->friendlist[i].is_typing = false;
177
412
            m->friendlist[i].message_id = 0;
178
412
            friend_connection_callbacks(m->fr_c, friendcon_id, MESSENGER_CALLBACK_INDEX, &m_handle_status, &m_handle_packet,
179
412
                                        &m_handle_lossy_packet, m, i);
180
181
412
            if (m->numfriends == i) {
182
412
                ++m->numfriends;
183
412
            }
184
185
412
            if (friend_con_connected(m->fr_c, friendcon_id) == FRIENDCONN_STATUS_CONNECTED) {
186
0
                send_online_packet(m, friendcon_id);
187
0
            }
188
189
412
            return i;
190
412
        }
191
1.00k
    }
192
193
0
    return FAERR_NOMEM;
194
412
}
195
196
non_null()
197
static int32_t m_add_friend_contact_norequest(Messenger *m, const uint8_t *real_pk)
198
389
{
199
389
    if (getfriend_id(m, real_pk) != -1) {
200
12
        return FAERR_ALREADYSENT;
201
12
    }
202
203
377
    if (pk_equal(real_pk, nc_get_self_public_key(m->net_crypto))) {
204
0
        return FAERR_OWNKEY;
205
0
    }
206
207
377
    return init_new_friend(m, real_pk, FRIEND_CONFIRMED);
208
377
}
209
210
/**
211
 * Add a friend.
212
 *
213
 * Set the data that will be sent along with friend request.
214
 *
215
 * @param address is the address of the friend (returned by getaddress of the friend
216
 *   you wish to add) it must be FRIEND_ADDRESS_SIZE bytes.
217
 *   TODO(irungentoo): add checksum.
218
 * @param data is the data.
219
 * @param length is the length.
220
 *
221
 * @return the friend number if success.
222
 * @retval FA_TOOLONG if message length is too long.
223
 * @retval FAERR_NOMESSAGE if no message (message length must be >= 1 byte).
224
 * @retval FAERR_OWNKEY if user's own key.
225
 * @retval FAERR_ALREADYSENT if friend request already sent or already a friend.
226
 * @retval FAERR_BADCHECKSUM if bad checksum in address.
227
 * @retval FAERR_SETNEWNOSPAM if the friend was already there but the nospam was different.
228
 *   (the nospam for that friend was set to the new one).
229
 * @retval FAERR_NOMEM if increasing the friend list size fails.
230
 */
231
int32_t m_addfriend(Messenger *m, const uint8_t *address, const uint8_t *data, uint16_t length)
232
130
{
233
130
    if (length > MAX_FRIEND_REQUEST_DATA_SIZE) {
234
12
        return FAERR_TOOLONG;
235
12
    }
236
237
118
    uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE];
238
118
    pk_copy(real_pk, address);
239
240
118
    if (!public_key_valid(real_pk)) {
241
11
        return FAERR_BADCHECKSUM;
242
11
    }
243
244
107
    uint16_t check;
245
107
    const uint16_t checksum = data_checksum(address, FRIEND_ADDRESS_SIZE - sizeof(checksum));
246
107
    memcpy(&check, address + CRYPTO_PUBLIC_KEY_SIZE + sizeof(uint32_t), sizeof(check));
247
248
107
    if (check != checksum) {
249
0
        return FAERR_BADCHECKSUM;
250
0
    }
251
252
107
    if (length < 1) {
253
17
        return FAERR_NOMESSAGE;
254
17
    }
255
256
90
    if (pk_equal(real_pk, nc_get_self_public_key(m->net_crypto))) {
257
10
        return FAERR_OWNKEY;
258
10
    }
259
260
80
    const int32_t friend_id = getfriend_id(m, real_pk);
261
262
80
    if (friend_id != -1) {
263
45
        if (m->friendlist[friend_id].status >= FRIEND_CONFIRMED) {
264
10
            return FAERR_ALREADYSENT;
265
10
        }
266
267
35
        uint32_t nospam;
268
35
        memcpy(&nospam, address + CRYPTO_PUBLIC_KEY_SIZE, sizeof(nospam));
269
270
35
        if (m->friendlist[friend_id].friendrequest_nospam == nospam) {
271
18
            return FAERR_ALREADYSENT;
272
18
        }
273
274
17
        m->friendlist[friend_id].friendrequest_nospam = nospam;
275
17
        return FAERR_SETNEWNOSPAM;
276
35
    }
277
278
35
    const int32_t ret = init_new_friend(m, real_pk, FRIEND_ADDED);
279
280
35
    if (ret < 0) {
281
0
        return ret;
282
0
    }
283
284
35
    m->friendlist[ret].friendrequest_timeout = FRIENDREQUEST_TIMEOUT;
285
35
    memcpy(m->friendlist[ret].info, data, length);
286
35
    m->friendlist[ret].info_size = length;
287
35
    memcpy(&m->friendlist[ret].friendrequest_nospam, address + CRYPTO_PUBLIC_KEY_SIZE, sizeof(uint32_t));
288
289
35
    return ret;
290
35
}
291
292
int32_t m_addfriend_norequest(Messenger *m, const uint8_t *real_pk)
293
433
{
294
433
    if (!public_key_valid(real_pk)) {
295
32
        return FAERR_BADCHECKSUM;
296
32
    }
297
298
401
    if (pk_equal(real_pk, nc_get_self_public_key(m->net_crypto))) {
299
12
        return FAERR_OWNKEY;
300
12
    }
301
302
389
    return m_add_friend_contact_norequest(m, real_pk);
303
401
}
304
305
non_null()
306
static int clear_receipts(Messenger *m, int32_t friendnumber)
307
412
{
308
412
    if (!m_friend_exists(m, friendnumber)) {
309
0
        return -1;
310
0
    }
311
312
412
    struct Receipts *receipts = m->friendlist[friendnumber].receipts_start;
313
314
412
    while (receipts != nullptr) {
315
0
        struct Receipts *temp_r = receipts->next;
316
0
        mem_delete(m->mem, receipts);
317
0
        receipts = temp_r;
318
0
    }
319
320
412
    m->friendlist[friendnumber].receipts_start = nullptr;
321
412
    m->friendlist[friendnumber].receipts_end = nullptr;
322
412
    return 0;
323
412
}
324
325
non_null()
326
static int add_receipt(Messenger *m, int32_t friendnumber, uint32_t packet_num, uint32_t msg_id)
327
0
{
328
0
    if (!m_friend_exists(m, friendnumber)) {
329
0
        return -1;
330
0
    }
331
332
0
    struct Receipts *new_receipts = (struct Receipts *)mem_alloc(m->mem, sizeof(struct Receipts));
333
334
0
    if (new_receipts == nullptr) {
335
0
        return -1;
336
0
    }
337
338
0
    new_receipts->packet_num = packet_num;
339
0
    new_receipts->msg_id = msg_id;
340
341
0
    if (m->friendlist[friendnumber].receipts_start == nullptr) {
342
0
        m->friendlist[friendnumber].receipts_start = new_receipts;
343
0
    } else {
344
0
        m->friendlist[friendnumber].receipts_end->next = new_receipts;
345
0
    }
346
347
0
    m->friendlist[friendnumber].receipts_end = new_receipts;
348
0
    new_receipts->next = nullptr;
349
0
    return 0;
350
0
}
351
/**
352
 * return -1 on failure.
353
 * return 0 if packet was received.
354
 */
355
non_null()
356
static int friend_received_packet(const Messenger *m, int32_t friendnumber, uint32_t number)
357
0
{
358
0
    if (!m_friend_exists(m, friendnumber)) {
359
0
        return -1;
360
0
    }
361
362
0
    return cryptpacket_received(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
363
0
                                m->friendlist[friendnumber].friendcon_id), number);
364
0
}
365
366
bool m_create_group_connection(Messenger *m, GC_Chat *chat)
367
18
{
368
18
    random_bytes(m->rng, chat->m_group_public_key, CRYPTO_PUBLIC_KEY_SIZE);
369
18
    const int friendcon_id = new_friend_connection(m->fr_c, chat->m_group_public_key);
370
371
18
    if (friendcon_id == -1) {
372
0
        return false;
373
0
    }
374
375
18
    const Friend_Conn *connection = get_conn(m->fr_c, friendcon_id);
376
377
18
    if (connection == nullptr) {
378
0
        return false;
379
0
    }
380
381
18
    chat->friend_connection_id = friendcon_id;
382
383
18
    if (friend_con_connected(m->fr_c, friendcon_id) == FRIENDCONN_STATUS_CONNECTED) {
384
0
        send_online_packet(m, friendcon_id);
385
0
    }
386
387
18
    const int onion_friend_number = friend_conn_get_onion_friendnum(connection);
388
18
    Onion_Friend *onion_friend = onion_get_friend(m->onion_c, (uint16_t)onion_friend_number);
389
390
18
    onion_friend_set_gc_public_key(onion_friend, get_chat_id(chat->chat_public_key));
391
18
    onion_friend_set_gc_data(onion_friend, nullptr, 0);
392
393
18
    return true;
394
18
}
395
396
/**
397
 * Kills the friend connection for a groupchat.
398
 */
399
void m_kill_group_connection(Messenger *m, const GC_Chat *chat)
400
18
{
401
18
    remove_request_received(m->fr, chat->m_group_public_key);
402
403
18
    friend_connection_callbacks(m->fr_c, chat->friend_connection_id, MESSENGER_CALLBACK_INDEX, nullptr,
404
18
                                nullptr, nullptr, nullptr, 0);
405
406
18
    if (friend_con_connected(m->fr_c, chat->friend_connection_id) == FRIENDCONN_STATUS_CONNECTED) {
407
0
        send_offline_packet(m, chat->friend_connection_id);
408
0
    }
409
410
18
    kill_friend_connection(m->fr_c, chat->friend_connection_id);
411
18
}
412
413
non_null(1) nullable(3)
414
static int do_receipts(Messenger *m, int32_t friendnumber, void *userdata)
415
0
{
416
0
    if (!m_friend_exists(m, friendnumber)) {
417
0
        return -1;
418
0
    }
419
420
0
    struct Receipts *receipts = m->friendlist[friendnumber].receipts_start;
421
422
0
    while (receipts != nullptr) {
423
0
        if (friend_received_packet(m, friendnumber, receipts->packet_num) == -1) {
424
0
            break;
425
0
        }
426
427
0
        if (m->read_receipt != nullptr) {
428
0
            m->read_receipt(m, friendnumber, receipts->msg_id, userdata);
429
0
        }
430
431
0
        struct Receipts *r_next = receipts->next;
432
433
0
        mem_delete(m->mem, receipts);
434
435
0
        m->friendlist[friendnumber].receipts_start = r_next;
436
437
0
        receipts = r_next;
438
0
    }
439
440
0
    if (m->friendlist[friendnumber].receipts_start == nullptr) {
441
0
        m->friendlist[friendnumber].receipts_end = nullptr;
442
0
    }
443
444
0
    return 0;
445
0
}
446
447
/** @brief Remove a friend.
448
 *
449
 * @retval 0 if success.
450
 * @retval -1 if failure.
451
 */
452
int m_delfriend(Messenger *m, int32_t friendnumber)
453
0
{
454
0
    if (!m_friend_exists(m, friendnumber)) {
455
0
        return -1;
456
0
    }
457
458
0
    if (m->friend_connectionstatuschange_internal != nullptr) {
459
0
        m->friend_connectionstatuschange_internal(m, friendnumber, 0, m->friend_connectionstatuschange_internal_userdata);
460
0
    }
461
462
0
    clear_receipts(m, friendnumber);
463
0
    remove_request_received(m->fr, m->friendlist[friendnumber].real_pk);
464
0
    friend_connection_callbacks(m->fr_c, m->friendlist[friendnumber].friendcon_id, MESSENGER_CALLBACK_INDEX, nullptr,
465
0
                                nullptr, nullptr, nullptr, 0);
466
467
0
    if (friend_con_connected(m->fr_c, m->friendlist[friendnumber].friendcon_id) == FRIENDCONN_STATUS_CONNECTED) {
468
0
        send_offline_packet(m, m->friendlist[friendnumber].friendcon_id);
469
0
    }
470
471
0
    kill_friend_connection(m->fr_c, m->friendlist[friendnumber].friendcon_id);
472
0
    m->friendlist[friendnumber] = empty_friend;
473
474
0
    uint32_t i;
475
476
0
    for (i = m->numfriends; i != 0; --i) {
477
0
        if (m->friendlist[i - 1].status != NOFRIEND) {
478
0
            break;
479
0
        }
480
0
    }
481
482
0
    m->numfriends = i;
483
484
0
    if (realloc_friendlist(m, m->numfriends) != 0) {
485
0
        return FAERR_NOMEM;
486
0
    }
487
488
0
    return 0;
489
0
}
490
491
int m_get_friend_connectionstatus(const Messenger *m, int32_t friendnumber)
492
0
{
493
0
    if (!m_friend_exists(m, friendnumber)) {
494
0
        return -1;
495
0
    }
496
497
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
498
0
        return CONNECTION_NONE;
499
0
    }
500
501
0
    bool direct_connected = false;
502
0
    uint32_t num_online_relays = 0;
503
0
    const int crypt_conn_id = friend_connection_crypt_connection_id(m->fr_c, m->friendlist[friendnumber].friendcon_id);
504
505
0
    if (!crypto_connection_status(m->net_crypto, crypt_conn_id, &direct_connected, &num_online_relays)) {
506
0
        return CONNECTION_NONE;
507
0
    }
508
509
0
    if (direct_connected) {
510
0
        return CONNECTION_UDP;
511
0
    }
512
513
0
    if (num_online_relays != 0) {
514
0
        return CONNECTION_TCP;
515
0
    }
516
517
    /* if we have a valid friend connection but do not have an established connection
518
     * we leave the connection status unchanged until the friend connection is either
519
     * established or dropped.
520
     */
521
0
    return m->friendlist[friendnumber].last_connection_udp_tcp;
522
0
}
523
524
/**
525
 * Checks if there exists a friend with given friendnumber.
526
 *
527
 * @param friendnumber The index in the friend list.
528
 *
529
 * @retval true if friend exists.
530
 * @retval false if friend doesn't exist.
531
 */
532
bool m_friend_exists(const Messenger *m, int32_t friendnumber)
533
924
{
534
924
    return (unsigned int)friendnumber < m->numfriends && m->friendlist[friendnumber].status != 0;
535
924
}
536
537
/** @brief Send a message of type to an online friend.
538
 *
539
 * @retval -1 if friend not valid.
540
 * @retval -2 if too large.
541
 * @retval -3 if friend not online.
542
 * @retval -4 if send failed (because queue is full).
543
 * @retval -5 if bad type.
544
 * @retval 0 if success.
545
 *
546
 * The value in message_id will be passed to your read_receipt callback when the other receives the message.
547
 */
548
int m_send_message_generic(Messenger *m, int32_t friendnumber, uint8_t type, const uint8_t *message, uint32_t length,
549
                           uint32_t *message_id)
550
0
{
551
0
    if (type > MESSAGE_ACTION) {
552
0
        LOGGER_WARNING(m->log, "message type %d is invalid", type);
553
0
        return -5;
554
0
    }
555
556
0
    if (!m_friend_exists(m, friendnumber)) {
557
0
        LOGGER_WARNING(m->log, "friend number %d is invalid", friendnumber);
558
0
        return -1;
559
0
    }
560
561
0
    if (length >= MAX_CRYPTO_DATA_SIZE) {
562
0
        LOGGER_WARNING(m->log, "message length %u is too large", length);
563
0
        return -2;
564
0
    }
565
566
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
567
0
        LOGGER_WARNING(m->log, "friend %d is not online", friendnumber);
568
0
        return -3;
569
0
    }
570
571
0
    VLA(uint8_t, packet, length + 1);
572
0
    packet[0] = PACKET_ID_MESSAGE + type;
573
574
0
    assert(message != nullptr);
575
0
    memcpy(packet + 1, message, length);
576
577
0
    const int64_t packet_num = write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
578
0
                                           m->friendlist[friendnumber].friendcon_id), packet, length + 1, false);
579
580
0
    if (packet_num == -1) {
581
0
        return -4;
582
0
    }
583
584
0
    const uint32_t msg_id = ++m->friendlist[friendnumber].message_id;
585
586
0
    add_receipt(m, friendnumber, packet_num, msg_id);
587
588
0
    if (message_id != nullptr) {
589
0
        *message_id = msg_id;
590
0
    }
591
592
0
    return 0;
593
0
}
594
595
non_null()
596
static bool write_cryptpacket_id(const Messenger *m, int32_t friendnumber, uint8_t packet_id, const uint8_t *data,
597
                                 uint32_t length, bool congestion_control)
598
0
{
599
0
    if (!m_friend_exists(m, friendnumber)) {
600
0
        return false;
601
0
    }
602
603
0
    if (length >= MAX_CRYPTO_DATA_SIZE || m->friendlist[friendnumber].status != FRIEND_ONLINE) {
604
0
        return false;
605
0
    }
606
607
0
    VLA(uint8_t, packet, length + 1);
608
0
    packet[0] = packet_id;
609
610
0
    assert(data != nullptr);
611
0
    memcpy(packet + 1, data, length);
612
613
0
    return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
614
0
                             m->friendlist[friendnumber].friendcon_id), packet, length + 1, congestion_control) != -1;
615
0
}
616
617
/** @brief Send a name packet to friendnumber.
618
 * length is the length with the NULL terminator.
619
 */
620
non_null()
621
static bool m_sendname(const Messenger *m, int32_t friendnumber, const uint8_t *name, uint16_t length)
622
0
{
623
0
    if (length > MAX_NAME_LENGTH) {
624
0
        return false;
625
0
    }
626
627
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_NICKNAME, name, length, false);
628
0
}
629
630
/** @brief Set the name and name_length of a friend.
631
 *
632
 * name must be a string of maximum MAX_NAME_LENGTH length.
633
 * length must be at least 1 byte.
634
 * length is the length of name with the NULL terminator.
635
 *
636
 * @retval 0 if success.
637
 * @retval -1 if failure.
638
 */
639
int setfriendname(Messenger *m, int32_t friendnumber, const uint8_t *name, uint16_t length)
640
256
{
641
256
    if (!m_friend_exists(m, friendnumber)) {
642
0
        return -1;
643
0
    }
644
645
256
    if (length > MAX_NAME_LENGTH || length == 0) {
646
183
        return -1;
647
183
    }
648
649
73
    m->friendlist[friendnumber].name_length = length;
650
73
    memcpy(m->friendlist[friendnumber].name, name, length);
651
73
    return 0;
652
256
}
653
654
/** @brief Set our nickname.
655
 *
656
 * name must be a string of maximum MAX_NAME_LENGTH length.
657
 * length must be at least 1 byte.
658
 * length is the length of name with the NULL terminator.
659
 *
660
 * @retval 0 if success.
661
 * @retval -1 if failure.
662
 */
663
int setname(Messenger *m, const uint8_t *name, uint16_t length)
664
295
{
665
295
    if (length > MAX_NAME_LENGTH) {
666
0
        return -1;
667
0
    }
668
669
295
    if (m->name_length == length && (length == 0 || memcmp(name, m->name, length) == 0)) {
670
69
        return 0;
671
69
    }
672
673
226
    if (length > 0) {
674
226
        memcpy(m->name, name, length);
675
226
    }
676
677
226
    m->name_length = length;
678
679
538
    for (uint32_t i = 0; i < m->numfriends; ++i) {
680
312
        m->friendlist[i].name_sent = false;
681
312
    }
682
683
226
    return 0;
684
295
}
685
686
/**
687
 * @brief Get your nickname.
688
 *
689
 * m - The messenger context to use.
690
 * name needs to be a valid memory location with a size of at least MAX_NAME_LENGTH bytes.
691
 *
692
 * @return length of the name.
693
 * @retval 0 on error.
694
 */
695
uint16_t getself_name(const Messenger *m, uint8_t *name)
696
0
{
697
0
    if (name == nullptr) {
698
0
        return 0;
699
0
    }
700
701
0
    memcpy(name, m->name, m->name_length);
702
703
0
    return m->name_length;
704
0
}
705
706
/** @brief Get name of friendnumber and put it in name.
707
 *
708
 * name needs to be a valid memory location with a size of at least MAX_NAME_LENGTH (128) bytes.
709
 *
710
 * @return length of name if success.
711
 * @retval -1 if failure.
712
 */
713
int getname(const Messenger *m, int32_t friendnumber, uint8_t *name)
714
0
{
715
0
    if (!m_friend_exists(m, friendnumber)) {
716
0
        return -1;
717
0
    }
718
719
0
    memcpy(name, m->friendlist[friendnumber].name, m->friendlist[friendnumber].name_length);
720
0
    return m->friendlist[friendnumber].name_length;
721
0
}
722
723
int m_get_name_size(const Messenger *m, int32_t friendnumber)
724
0
{
725
0
    if (!m_friend_exists(m, friendnumber)) {
726
0
        return -1;
727
0
    }
728
729
0
    return m->friendlist[friendnumber].name_length;
730
0
}
731
732
int m_get_self_name_size(const Messenger *m)
733
0
{
734
0
    return m->name_length;
735
0
}
736
737
int m_set_statusmessage(Messenger *m, const uint8_t *status, uint16_t length)
738
646
{
739
646
    if (length > MAX_STATUSMESSAGE_LENGTH) {
740
0
        return -1;
741
0
    }
742
743
646
    if (m->statusmessage_length == length && (length == 0 || memcmp(m->statusmessage, status, length) == 0)) {
744
148
        return 0;
745
148
    }
746
747
498
    if (length > 0) {
748
498
        memcpy(m->statusmessage, status, length);
749
498
    }
750
751
498
    m->statusmessage_length = length;
752
753
819
    for (uint32_t i = 0; i < m->numfriends; ++i) {
754
321
        m->friendlist[i].statusmessage_sent = false;
755
321
    }
756
757
498
    return 0;
758
646
}
759
760
int m_set_userstatus(Messenger *m, uint8_t status)
761
551
{
762
551
    if (status >= USERSTATUS_INVALID) {
763
265
        return -1;
764
265
    }
765
766
286
    if (m->userstatus == status) {
767
134
        return 0;
768
134
    }
769
770
152
    m->userstatus = (Userstatus)status;
771
772
307
    for (uint32_t i = 0; i < m->numfriends; ++i) {
773
155
        m->friendlist[i].userstatus_sent = false;
774
155
    }
775
776
152
    return 0;
777
286
}
778
779
/**
780
 * Guaranteed to be at most MAX_STATUSMESSAGE_LENGTH.
781
 *
782
 * @return the length of friendnumber's status message, including null on success.
783
 * @retval -1 on failure.
784
 */
785
int m_get_statusmessage_size(const Messenger *m, int32_t friendnumber)
786
0
{
787
0
    if (!m_friend_exists(m, friendnumber)) {
788
0
        return -1;
789
0
    }
790
791
0
    return m->friendlist[friendnumber].statusmessage_length;
792
0
}
793
794
/** @brief Copy friendnumber's status message into buf, truncating if size is over maxlen.
795
 *
796
 * Get the size you need to allocate from m_get_statusmessage_size.
797
 * The self variant will copy our own status message.
798
 *
799
 * @return the length of the copied data on success
800
 * @retval -1 on failure.
801
 */
802
int m_copy_statusmessage(const Messenger *m, int32_t friendnumber, uint8_t *buf, uint32_t maxlen)
803
0
{
804
0
    if (!m_friend_exists(m, friendnumber)) {
805
0
        return -1;
806
0
    }
807
808
    // TODO(iphydf): This should be uint16_t and min_u16. If maxlen exceeds
809
    // uint16_t's range, it won't affect the result.
810
0
    const uint32_t msglen = min_u32(maxlen, m->friendlist[friendnumber].statusmessage_length);
811
812
0
    memcpy(buf, m->friendlist[friendnumber].statusmessage, msglen);
813
0
    memset(buf + msglen, 0, maxlen - msglen);
814
0
    return msglen;
815
0
}
816
817
/** @return the size of friendnumber's user status.
818
 * Guaranteed to be at most MAX_STATUSMESSAGE_LENGTH.
819
 */
820
int m_get_self_statusmessage_size(const Messenger *m)
821
0
{
822
0
    return m->statusmessage_length;
823
0
}
824
825
int m_copy_self_statusmessage(const Messenger *m, uint8_t *buf)
826
0
{
827
0
    memcpy(buf, m->statusmessage, m->statusmessage_length);
828
0
    return m->statusmessage_length;
829
0
}
830
831
uint8_t m_get_userstatus(const Messenger *m, int32_t friendnumber)
832
0
{
833
0
    if (!m_friend_exists(m, friendnumber)) {
834
0
        return USERSTATUS_INVALID;
835
0
    }
836
837
0
    uint8_t status = m->friendlist[friendnumber].userstatus;
838
839
0
    if (status >= USERSTATUS_INVALID) {
840
0
        status = USERSTATUS_NONE;
841
0
    }
842
843
0
    return status;
844
0
}
845
846
uint8_t m_get_self_userstatus(const Messenger *m)
847
0
{
848
0
    return m->userstatus;
849
0
}
850
851
uint64_t m_get_last_online(const Messenger *m, int32_t friendnumber)
852
0
{
853
0
    if (!m_friend_exists(m, friendnumber)) {
854
0
        return UINT64_MAX;
855
0
    }
856
857
0
    return m->friendlist[friendnumber].last_seen_time;
858
0
}
859
860
int m_set_usertyping(Messenger *m, int32_t friendnumber, bool is_typing)
861
0
{
862
0
    if (!m_friend_exists(m, friendnumber)) {
863
0
        return -1;
864
0
    }
865
866
0
    if (m->friendlist[friendnumber].user_istyping == is_typing) {
867
0
        return 0;
868
0
    }
869
870
0
    m->friendlist[friendnumber].user_istyping = is_typing;
871
0
    m->friendlist[friendnumber].user_istyping_sent = false;
872
873
0
    return 0;
874
0
}
875
876
int m_get_istyping(const Messenger *m, int32_t friendnumber)
877
0
{
878
0
    if (!m_friend_exists(m, friendnumber)) {
879
0
        return -1;
880
0
    }
881
882
0
    return m->friendlist[friendnumber].is_typing ? 1 : 0;
883
0
}
884
885
non_null()
886
static bool send_statusmessage(const Messenger *m, int32_t friendnumber, const uint8_t *status, uint16_t length)
887
0
{
888
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_STATUSMESSAGE, status, length, false);
889
0
}
890
891
non_null()
892
static bool send_userstatus(const Messenger *m, int32_t friendnumber, uint8_t status)
893
0
{
894
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_USERSTATUS, &status, sizeof(status), false);
895
0
}
896
897
non_null()
898
static bool send_user_istyping(const Messenger *m, int32_t friendnumber, bool is_typing)
899
0
{
900
0
    const uint8_t typing = is_typing ? 1 : 0;
901
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_TYPING, &typing, sizeof(typing), false);
902
0
}
903
904
non_null()
905
static int set_friend_statusmessage(const Messenger *m, int32_t friendnumber, const uint8_t *status, uint16_t length)
906
256
{
907
256
    if (!m_friend_exists(m, friendnumber)) {
908
0
        return -1;
909
0
    }
910
911
256
    if (length > MAX_STATUSMESSAGE_LENGTH) {
912
122
        return -1;
913
122
    }
914
915
134
    if (length > 0) {
916
70
        memcpy(m->friendlist[friendnumber].statusmessage, status, length);
917
70
    }
918
919
134
    m->friendlist[friendnumber].statusmessage_length = length;
920
134
    return 0;
921
256
}
922
923
non_null()
924
static void set_friend_userstatus(const Messenger *m, int32_t friendnumber, uint8_t status)
925
256
{
926
256
    m->friendlist[friendnumber].userstatus = (Userstatus)status;
927
256
}
928
929
non_null()
930
static void set_friend_typing(const Messenger *m, int32_t friendnumber, bool is_typing)
931
0
{
932
0
    m->friendlist[friendnumber].is_typing = is_typing;
933
0
}
934
935
/** Set the function that will be executed when a friend request is received. */
936
void m_callback_friendrequest(Messenger *m, m_friend_request_cb *function)
937
2.44k
{
938
2.44k
    m->friend_request = function;
939
2.44k
}
940
941
/** Set the function that will be executed when a message from a friend is received. */
942
void m_callback_friendmessage(Messenger *m, m_friend_message_cb *function)
943
2.44k
{
944
2.44k
    m->friend_message = function;
945
2.44k
}
946
947
void m_callback_namechange(Messenger *m, m_friend_name_cb *function)
948
2.44k
{
949
2.44k
    m->friend_namechange = function;
950
2.44k
}
951
952
void m_callback_statusmessage(Messenger *m, m_friend_status_message_cb *function)
953
2.44k
{
954
2.44k
    m->friend_statusmessagechange = function;
955
2.44k
}
956
957
void m_callback_userstatus(Messenger *m, m_friend_status_cb *function)
958
2.44k
{
959
2.44k
    m->friend_userstatuschange = function;
960
2.44k
}
961
962
void m_callback_typingchange(Messenger *m, m_friend_typing_cb *function)
963
2.44k
{
964
2.44k
    m->friend_typingchange = function;
965
2.44k
}
966
967
void m_callback_read_receipt(Messenger *m, m_friend_read_receipt_cb *function)
968
2.44k
{
969
2.44k
    m->read_receipt = function;
970
2.44k
}
971
972
void m_callback_connectionstatus(Messenger *m, m_friend_connection_status_cb *function)
973
2.44k
{
974
2.44k
    m->friend_connectionstatuschange = function;
975
2.44k
}
976
977
void m_callback_core_connection(Messenger *m, m_self_connection_status_cb *function)
978
2.44k
{
979
2.44k
    m->core_connection_change = function;
980
2.44k
}
981
982
void m_callback_connectionstatus_internal_av(Messenger *m, m_friend_connectionstatuschange_internal_cb *function,
983
        void *userdata)
984
0
{
985
0
    m->friend_connectionstatuschange_internal = function;
986
0
    m->friend_connectionstatuschange_internal_userdata = userdata;
987
0
}
988
989
non_null(1) nullable(3)
990
static void check_friend_tcp_udp(Messenger *m, int32_t friendnumber, void *userdata)
991
0
{
992
0
    const int last_connection_udp_tcp = m->friendlist[friendnumber].last_connection_udp_tcp;
993
994
0
    const int ret = m_get_friend_connectionstatus(m, friendnumber);
995
996
0
    if (ret == -1) {
997
0
        return;
998
0
    }
999
1000
0
    if (last_connection_udp_tcp != ret) {
1001
0
        if (m->friend_connectionstatuschange != nullptr) {
1002
0
            m->friend_connectionstatuschange(m, friendnumber, ret, userdata);
1003
0
        }
1004
0
    }
1005
1006
0
    m->friendlist[friendnumber].last_connection_udp_tcp = (Connection_Status)ret;
1007
0
}
1008
1009
non_null()
1010
static void break_files(const Messenger *m, int32_t friendnumber);
1011
1012
non_null(1) nullable(4)
1013
static void check_friend_connectionstatus(Messenger *m, int32_t friendnumber, uint8_t status, void *userdata)
1014
0
{
1015
0
    if (status == NOFRIEND) {
1016
0
        return;
1017
0
    }
1018
1019
0
    const bool was_online = m->friendlist[friendnumber].status == FRIEND_ONLINE;
1020
0
    const bool is_online = status == FRIEND_ONLINE;
1021
1022
0
    if (is_online != was_online) {
1023
0
        if (was_online) {
1024
0
            break_files(m, friendnumber);
1025
0
            clear_receipts(m, friendnumber);
1026
0
        } else {
1027
0
            m->friendlist[friendnumber].name_sent = false;
1028
0
            m->friendlist[friendnumber].userstatus_sent = false;
1029
0
            m->friendlist[friendnumber].statusmessage_sent = false;
1030
0
            m->friendlist[friendnumber].user_istyping_sent = false;
1031
0
        }
1032
1033
0
        m->friendlist[friendnumber].status = status;
1034
1035
0
        check_friend_tcp_udp(m, friendnumber, userdata);
1036
1037
0
        if (m->friend_connectionstatuschange_internal != nullptr) {
1038
0
            m->friend_connectionstatuschange_internal(m, friendnumber, is_online,
1039
0
                    m->friend_connectionstatuschange_internal_userdata);
1040
0
        }
1041
0
    }
1042
0
}
1043
1044
non_null(1) nullable(4)
1045
static void set_friend_status(Messenger *m, int32_t friendnumber, uint8_t status, void *userdata)
1046
0
{
1047
0
    check_friend_connectionstatus(m, friendnumber, status, userdata);
1048
0
    m->friendlist[friendnumber].status = status;
1049
0
}
1050
1051
/*** CONFERENCES */
1052
1053
1054
/** @brief Set the callback for conference invites. */
1055
void m_callback_conference_invite(Messenger *m, m_conference_invite_cb *function)
1056
6.14k
{
1057
6.14k
    m->conference_invite = function;
1058
6.14k
}
1059
1060
/** @brief the callback for group invites. */
1061
void m_callback_group_invite(Messenger *m, m_group_invite_cb *function)
1062
2.44k
{
1063
2.44k
    m->group_invite = function;
1064
2.44k
}
1065
1066
/** @brief Send a conference invite packet.
1067
 *
1068
 * return true on success
1069
 * return false on failure
1070
 */
1071
bool send_conference_invite_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint16_t length)
1072
0
{
1073
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_INVITE_CONFERENCE, data, length, false);
1074
0
}
1075
1076
1077
/** @brief Send a group invite packet.
1078
 *
1079
 * @retval true if success
1080
 */
1081
bool send_group_invite_packet(const Messenger *m, uint32_t friendnumber, const uint8_t *data, uint16_t length)
1082
0
{
1083
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_INVITE_GROUPCHAT, data, length, false);
1084
0
}
1085
1086
1087
/*** FILE SENDING */
1088
1089
1090
/** @brief Set the callback for file send requests. */
1091
void callback_file_sendrequest(Messenger *m, m_file_recv_cb *function)
1092
2.44k
{
1093
2.44k
    m->file_sendrequest = function;
1094
2.44k
}
1095
1096
/** @brief Set the callback for file control requests. */
1097
void callback_file_control(Messenger *m, m_file_recv_control_cb *function)
1098
2.44k
{
1099
2.44k
    m->file_filecontrol = function;
1100
2.44k
}
1101
1102
/** @brief Set the callback for file data. */
1103
void callback_file_data(Messenger *m, m_file_recv_chunk_cb *function)
1104
2.44k
{
1105
2.44k
    m->file_filedata = function;
1106
2.44k
}
1107
1108
/** @brief Set the callback for file request chunk. */
1109
void callback_file_reqchunk(Messenger *m, m_file_chunk_request_cb *function)
1110
2.44k
{
1111
2.44k
    m->file_reqchunk = function;
1112
2.44k
}
1113
1114
0
#define MAX_FILENAME_LENGTH 255
1115
1116
/** @brief Copy the file transfer file id to file_id
1117
 *
1118
 * @retval 0 on success.
1119
 * @retval -1 if friend not valid.
1120
 * @retval -2 if filenumber not valid
1121
 */
1122
int file_get_id(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint8_t *file_id)
1123
0
{
1124
0
    if (!m_friend_exists(m, friendnumber)) {
1125
0
        return -1;
1126
0
    }
1127
1128
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1129
0
        return -2;
1130
0
    }
1131
1132
0
    uint32_t temp_filenum;
1133
0
    bool inbound;
1134
0
    uint8_t file_number;
1135
1136
0
    if (filenumber >= (1 << 16)) {
1137
0
        inbound = true;
1138
0
        temp_filenum = (filenumber >> 16) - 1;
1139
0
    } else {
1140
0
        inbound = false;
1141
0
        temp_filenum = filenumber;
1142
0
    }
1143
1144
0
    if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) {
1145
0
        return -2;
1146
0
    }
1147
1148
0
    file_number = temp_filenum;
1149
1150
0
    const struct File_Transfers *const ft = inbound
1151
0
        ? &m->friendlist[friendnumber].file_receiving[file_number]
1152
0
        : &m->friendlist[friendnumber].file_sending[file_number];
1153
1154
0
    if (ft->status == FILESTATUS_NONE) {
1155
0
        return -2;
1156
0
    }
1157
1158
0
    memcpy(file_id, ft->id, FILE_ID_LENGTH);
1159
0
    return 0;
1160
0
}
1161
1162
/** @brief Send a file send request.
1163
 * Maximum filename length is 255 bytes.
1164
 * @retval 1 on success
1165
 * @retval 0 on failure
1166
 */
1167
non_null()
1168
static bool file_sendrequest(const Messenger *m, int32_t friendnumber, uint8_t filenumber, uint32_t file_type,
1169
                             uint64_t filesize, const uint8_t *file_id, const uint8_t *filename, uint16_t filename_length)
1170
0
{
1171
0
    if (!m_friend_exists(m, friendnumber)) {
1172
0
        return false;
1173
0
    }
1174
1175
0
    if (filename_length > MAX_FILENAME_LENGTH) {
1176
0
        return false;
1177
0
    }
1178
1179
0
    VLA(uint8_t, packet, 1 + sizeof(file_type) + sizeof(filesize) + FILE_ID_LENGTH + filename_length);
1180
0
    packet[0] = filenumber;
1181
0
    file_type = net_htonl(file_type);
1182
0
    memcpy(packet + 1, &file_type, sizeof(file_type));
1183
0
    net_pack_u64(packet + 1 + sizeof(file_type), filesize);
1184
0
    memcpy(packet + 1 + sizeof(file_type) + sizeof(filesize), file_id, FILE_ID_LENGTH);
1185
1186
0
    if (filename_length > 0) {
1187
0
        memcpy(packet + 1 + sizeof(file_type) + sizeof(filesize) + FILE_ID_LENGTH, filename, filename_length);
1188
0
    }
1189
1190
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_FILE_SENDREQUEST, packet, SIZEOF_VLA(packet), false);
1191
0
}
1192
1193
/** @brief Send a file send request.
1194
 *
1195
 * Maximum filename length is 255 bytes.
1196
 *
1197
 * @return file number on success
1198
 * @retval -1 if friend not found.
1199
 * @retval -2 if filename length invalid.
1200
 * @retval -3 if no more file sending slots left.
1201
 * @retval -4 if could not send packet (friend offline).
1202
 */
1203
long int new_filesender(const Messenger *m, int32_t friendnumber, uint32_t file_type, uint64_t filesize,
1204
                        const uint8_t *file_id, const uint8_t *filename, uint16_t filename_length)
1205
0
{
1206
0
    if (!m_friend_exists(m, friendnumber)) {
1207
0
        return -1;
1208
0
    }
1209
1210
0
    if (filename_length > MAX_FILENAME_LENGTH) {
1211
0
        return -2;
1212
0
    }
1213
1214
0
    uint32_t i;
1215
1216
0
    for (i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) {
1217
0
        if (m->friendlist[friendnumber].file_sending[i].status == FILESTATUS_NONE) {
1218
0
            break;
1219
0
        }
1220
0
    }
1221
1222
0
    if (i == MAX_CONCURRENT_FILE_PIPES) {
1223
0
        return -3;
1224
0
    }
1225
1226
0
    if (!file_sendrequest(m, friendnumber, i, file_type, filesize, file_id, filename, filename_length)) {
1227
0
        return -4;
1228
0
    }
1229
1230
0
    struct File_Transfers *ft = &m->friendlist[friendnumber].file_sending[i];
1231
1232
0
    ft->status = FILESTATUS_NOT_ACCEPTED;
1233
1234
0
    ft->size = filesize;
1235
1236
0
    ft->transferred = 0;
1237
1238
0
    ft->requested = 0;
1239
1240
0
    ft->paused = FILE_PAUSE_NOT;
1241
1242
0
    memcpy(ft->id, file_id, FILE_ID_LENGTH);
1243
1244
0
    return i;
1245
0
}
1246
1247
non_null(1) nullable(6)
1248
static bool send_file_control_packet(const Messenger *m, int32_t friendnumber, bool inbound, uint8_t filenumber,
1249
                                     uint8_t control_type, const uint8_t *data, uint16_t data_length)
1250
0
{
1251
0
    assert(data_length == 0 || data != nullptr);
1252
1253
0
    if ((unsigned int)(1 + 3 + data_length) > MAX_CRYPTO_DATA_SIZE) {
1254
0
        return false;
1255
0
    }
1256
1257
0
    VLA(uint8_t, packet, 3 + data_length);
1258
1259
0
    packet[0] = inbound ? 1 : 0;
1260
0
    packet[1] = filenumber;
1261
0
    packet[2] = control_type;
1262
1263
0
    if (data_length > 0) {
1264
0
        memcpy(packet + 3, data, data_length);
1265
0
    }
1266
1267
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_FILE_CONTROL, packet, SIZEOF_VLA(packet), false);
1268
0
}
1269
1270
/** @brief Send a file control request.
1271
 *
1272
 * @retval 0 on success
1273
 * @retval -1 if friend not valid.
1274
 * @retval -2 if friend not online.
1275
 * @retval -3 if file number invalid.
1276
 * @retval -4 if file control is bad.
1277
 * @retval -5 if file already paused.
1278
 * @retval -6 if resume file failed because it was only paused by the other.
1279
 * @retval -7 if resume file failed because it wasn't paused.
1280
 * @retval -8 if packet failed to send.
1281
 */
1282
int file_control(const Messenger *m, int32_t friendnumber, uint32_t filenumber, unsigned int control)
1283
0
{
1284
0
    if (!m_friend_exists(m, friendnumber)) {
1285
0
        return -1;
1286
0
    }
1287
1288
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1289
0
        return -2;
1290
0
    }
1291
1292
0
    uint32_t temp_filenum;
1293
0
    bool inbound;
1294
0
    uint8_t file_number;
1295
1296
0
    if (filenumber >= (1 << 16)) {
1297
0
        inbound = true;
1298
0
        temp_filenum = (filenumber >> 16) - 1;
1299
0
    } else {
1300
0
        inbound = false;
1301
0
        temp_filenum = filenumber;
1302
0
    }
1303
1304
0
    if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) {
1305
0
        return -3;
1306
0
    }
1307
1308
0
    file_number = temp_filenum;
1309
1310
0
    struct File_Transfers *ft;
1311
1312
0
    if (inbound) {
1313
0
        ft = &m->friendlist[friendnumber].file_receiving[file_number];
1314
0
    } else {
1315
0
        ft = &m->friendlist[friendnumber].file_sending[file_number];
1316
0
    }
1317
1318
0
    if (ft->status == FILESTATUS_NONE) {
1319
0
        return -3;
1320
0
    }
1321
1322
0
    if (control > FILECONTROL_KILL) {
1323
0
        return -4;
1324
0
    }
1325
1326
0
    if (control == FILECONTROL_PAUSE && ((ft->paused & FILE_PAUSE_US) != 0 || ft->status != FILESTATUS_TRANSFERRING)) {
1327
0
        return -5;
1328
0
    }
1329
1330
0
    if (control == FILECONTROL_ACCEPT) {
1331
0
        if (ft->status == FILESTATUS_TRANSFERRING) {
1332
0
            if ((ft->paused & FILE_PAUSE_US) == 0) {
1333
0
                if ((ft->paused & FILE_PAUSE_OTHER) != 0) {
1334
0
                    return -6;
1335
0
                }
1336
1337
0
                return -7;
1338
0
            }
1339
0
        } else {
1340
0
            if (ft->status != FILESTATUS_NOT_ACCEPTED) {
1341
0
                return -7;
1342
0
            }
1343
1344
0
            if (!inbound) {
1345
0
                return -6;
1346
0
            }
1347
0
        }
1348
0
    }
1349
1350
0
    if (send_file_control_packet(m, friendnumber, inbound, file_number, control, nullptr, 0)) {
1351
0
        switch (control) {
1352
0
            case FILECONTROL_KILL: {
1353
0
                if (!inbound && (ft->status == FILESTATUS_TRANSFERRING || ft->status == FILESTATUS_FINISHED)) {
1354
                    // We are actively sending that file, remove from list
1355
0
                    --m->friendlist[friendnumber].num_sending_files;
1356
0
                }
1357
1358
0
                ft->status = FILESTATUS_NONE;
1359
0
                break;
1360
0
            }
1361
0
            case FILECONTROL_PAUSE: {
1362
0
                ft->paused |= FILE_PAUSE_US;
1363
0
                break;
1364
0
            }
1365
0
            case FILECONTROL_ACCEPT: {
1366
0
                ft->status = FILESTATUS_TRANSFERRING;
1367
1368
0
                if ((ft->paused & FILE_PAUSE_US) != 0) {
1369
0
                    ft->paused ^= FILE_PAUSE_US;
1370
0
                }
1371
0
                break;
1372
0
            }
1373
0
        }
1374
0
    } else {
1375
0
        return -8;
1376
0
    }
1377
1378
0
    return 0;
1379
0
}
1380
1381
/** @brief Send a seek file control request.
1382
 *
1383
 * @retval 0 on success
1384
 * @retval -1 if friend not valid.
1385
 * @retval -2 if friend not online.
1386
 * @retval -3 if file number invalid.
1387
 * @retval -4 if not receiving file.
1388
 * @retval -5 if file status wrong.
1389
 * @retval -6 if position bad.
1390
 * @retval -8 if packet failed to send.
1391
 */
1392
int file_seek(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint64_t position)
1393
0
{
1394
0
    if (!m_friend_exists(m, friendnumber)) {
1395
0
        return -1;
1396
0
    }
1397
1398
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1399
0
        return -2;
1400
0
    }
1401
1402
0
    if (filenumber < (1 << 16)) {
1403
        // Not receiving.
1404
0
        return -4;
1405
0
    }
1406
1407
0
    const uint32_t temp_filenum = (filenumber >> 16) - 1;
1408
1409
0
    if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) {
1410
0
        return -3;
1411
0
    }
1412
1413
0
    assert(temp_filenum <= UINT8_MAX);
1414
0
    const uint8_t file_number = temp_filenum;
1415
1416
    // We're always receiving at this point.
1417
0
    struct File_Transfers *ft = &m->friendlist[friendnumber].file_receiving[file_number];
1418
1419
0
    if (ft->status == FILESTATUS_NONE) {
1420
0
        return -3;
1421
0
    }
1422
1423
0
    if (ft->status != FILESTATUS_NOT_ACCEPTED) {
1424
0
        return -5;
1425
0
    }
1426
1427
0
    if (position >= ft->size) {
1428
0
        return -6;
1429
0
    }
1430
1431
0
    uint8_t sending_pos[sizeof(uint64_t)];
1432
0
    net_pack_u64(sending_pos, position);
1433
1434
0
    if (send_file_control_packet(m, friendnumber, true, file_number, FILECONTROL_SEEK, sending_pos,
1435
0
                                 sizeof(sending_pos))) {
1436
0
        ft->transferred = position;
1437
0
    } else {
1438
0
        return -8;
1439
0
    }
1440
1441
0
    return 0;
1442
0
}
1443
1444
/** @return packet number on success.
1445
 * @retval -1 on failure.
1446
 */
1447
non_null(1) nullable(4)
1448
static int64_t send_file_data_packet(const Messenger *m, int32_t friendnumber, uint8_t filenumber, const uint8_t *data,
1449
                                     uint16_t length)
1450
0
{
1451
0
    assert(length == 0 || data != nullptr);
1452
1453
0
    if (!m_friend_exists(m, friendnumber)) {
1454
0
        return -1;
1455
0
    }
1456
1457
0
    VLA(uint8_t, packet, 2 + length);
1458
0
    packet[0] = PACKET_ID_FILE_DATA;
1459
0
    packet[1] = filenumber;
1460
1461
0
    if (length > 0) {
1462
0
        memcpy(packet + 2, data, length);
1463
0
    }
1464
1465
0
    return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1466
0
                             m->friendlist[friendnumber].friendcon_id), packet, SIZEOF_VLA(packet), true);
1467
0
}
1468
1469
0
#define MAX_FILE_DATA_SIZE (MAX_CRYPTO_DATA_SIZE - 2)
1470
0
#define MIN_SLOTS_FREE (CRYPTO_MIN_QUEUE_LENGTH / 4)
1471
/** @brief Send file data.
1472
 *
1473
 * @retval 0 on success
1474
 * @retval -1 if friend not valid.
1475
 * @retval -2 if friend not online.
1476
 * @retval -3 if filenumber invalid.
1477
 * @retval -4 if file transfer not transferring.
1478
 * @retval -5 if bad data size.
1479
 * @retval -6 if packet queue full.
1480
 * @retval -7 if wrong position.
1481
 */
1482
int send_file_data(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint64_t position,
1483
                   const uint8_t *data, uint16_t length)
1484
0
{
1485
0
    assert(length == 0 || data != nullptr);
1486
1487
0
    if (!m_friend_exists(m, friendnumber)) {
1488
0
        return -1;
1489
0
    }
1490
1491
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1492
0
        return -2;
1493
0
    }
1494
1495
0
    if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
1496
0
        return -3;
1497
0
    }
1498
1499
0
    struct File_Transfers *ft = &m->friendlist[friendnumber].file_sending[filenumber];
1500
1501
0
    if (ft->status != FILESTATUS_TRANSFERRING) {
1502
0
        return -4;
1503
0
    }
1504
1505
0
    if (length > MAX_FILE_DATA_SIZE) {
1506
0
        return -5;
1507
0
    }
1508
1509
0
    if (ft->size - ft->transferred < length) {
1510
0
        return -5;
1511
0
    }
1512
1513
0
    if (ft->size != UINT64_MAX && length != MAX_FILE_DATA_SIZE && (ft->transferred + length) != ft->size) {
1514
0
        return -5;
1515
0
    }
1516
1517
0
    if (position != ft->transferred || (ft->requested <= position && ft->size != 0)) {
1518
0
        return -7;
1519
0
    }
1520
1521
    /* Prevent file sending from filling up the entire buffer preventing messages from being sent.
1522
     * TODO(irungentoo): remove */
1523
0
    if (crypto_num_free_sendqueue_slots(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1524
0
                                        m->friendlist[friendnumber].friendcon_id)) < MIN_SLOTS_FREE) {
1525
0
        return -6;
1526
0
    }
1527
1528
0
    const int64_t ret = send_file_data_packet(m, friendnumber, filenumber, data, length);
1529
1530
0
    if (ret != -1) {
1531
        // TODO(irungentoo): record packet ids to check if other received complete file.
1532
0
        ft->transferred += length;
1533
1534
0
        if (length != MAX_FILE_DATA_SIZE || ft->size == ft->transferred) {
1535
0
            ft->status = FILESTATUS_FINISHED;
1536
0
            ft->last_packet_number = ret;
1537
0
        }
1538
1539
0
        return 0;
1540
0
    }
1541
1542
0
    return -6;
1543
0
}
1544
1545
/**
1546
 * Iterate over all file transfers and request chunks (from the client) for each
1547
 * of them.
1548
 *
1549
 * The free_slots parameter is updated by this function.
1550
 *
1551
 * @param m Our messenger object.
1552
 * @param friendnumber The friend we're sending files to.
1553
 * @param userdata The client userdata to pass along to chunk request callbacks.
1554
 * @param free_slots A pointer to the number of free send queue slots in the
1555
 *   crypto connection.
1556
 * @return true if there's still work to do, false otherwise.
1557
 *
1558
 */
1559
non_null()
1560
static bool do_all_filetransfers(Messenger *m, int32_t friendnumber, void *userdata, uint32_t *free_slots)
1561
0
{
1562
0
    Friend *const friendcon = &m->friendlist[friendnumber];
1563
1564
    // Iterate over file transfers as long as we're sending files
1565
0
    for (uint32_t i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) {
1566
0
        if (friendcon->num_sending_files == 0) {
1567
            // no active file transfers anymore
1568
0
            return false;
1569
0
        }
1570
1571
0
        if (*free_slots == 0) {
1572
            // send buffer full enough
1573
0
            return false;
1574
0
        }
1575
1576
0
        struct File_Transfers *const ft = &friendcon->file_sending[i];
1577
1578
0
        if (ft->status == FILESTATUS_NONE || ft->status == FILESTATUS_NOT_ACCEPTED) {
1579
            // Filetransfers not actively sending, nothing to do
1580
0
            continue;
1581
0
        }
1582
1583
0
        if (max_speed_reached(m->net_crypto, friend_connection_crypt_connection_id(
1584
0
                                  m->fr_c, friendcon->friendcon_id))) {
1585
0
            LOGGER_DEBUG(m->log, "maximum connection speed reached");
1586
            // connection doesn't support any more data
1587
0
            return false;
1588
0
        }
1589
1590
        // If the file transfer is complete, we request a chunk of size 0.
1591
0
        if (ft->status == FILESTATUS_FINISHED && friend_received_packet(m, friendnumber, ft->last_packet_number) == 0) {
1592
0
            if (m->file_reqchunk != nullptr) {
1593
0
                m->file_reqchunk(m, friendnumber, i, ft->transferred, 0, userdata);
1594
0
            }
1595
1596
            // Now it's inactive, we're no longer sending this.
1597
0
            ft->status = FILESTATUS_NONE;
1598
0
            --friendcon->num_sending_files;
1599
0
        } else if (ft->status == FILESTATUS_TRANSFERRING && ft->paused == FILE_PAUSE_NOT) {
1600
0
            if (ft->size == 0) {
1601
                /* Send 0 data to friend if file is 0 length. */
1602
0
                send_file_data(m, friendnumber, i, 0, nullptr, 0);
1603
0
                continue;
1604
0
            }
1605
1606
0
            if (ft->size == ft->requested) {
1607
                // This file transfer is done.
1608
0
                continue;
1609
0
            }
1610
1611
0
            const uint16_t length = min_u64(ft->size - ft->requested, MAX_FILE_DATA_SIZE);
1612
0
            const uint64_t position = ft->requested;
1613
0
            ft->requested += length;
1614
1615
0
            if (m->file_reqchunk != nullptr) {
1616
0
                m->file_reqchunk(m, friendnumber, i, position, length, userdata);
1617
0
            }
1618
1619
            // The allocated slot is no longer free.
1620
0
            --*free_slots;
1621
0
        }
1622
0
    }
1623
1624
0
    return true;
1625
0
}
1626
1627
non_null(1) nullable(3)
1628
static void do_reqchunk_filecb(Messenger *m, int32_t friendnumber, void *userdata)
1629
0
{
1630
    // We're not currently doing any file transfers.
1631
0
    if (m->friendlist[friendnumber].num_sending_files == 0) {
1632
0
        return;
1633
0
    }
1634
1635
    // The number of packet slots left in the sendbuffer.
1636
    // This is a per friend count (CRYPTO_PACKET_BUFFER_SIZE).
1637
0
    uint32_t free_slots = crypto_num_free_sendqueue_slots(
1638
0
                              m->net_crypto,
1639
0
                              friend_connection_crypt_connection_id(
1640
0
                                  m->fr_c,
1641
0
                                  m->friendlist[friendnumber].friendcon_id));
1642
1643
    // We keep MIN_SLOTS_FREE slots free for other packets, otherwise file
1644
    // transfers might block other traffic for a long time.
1645
0
    free_slots = max_s32(0, (int32_t)free_slots - MIN_SLOTS_FREE);
1646
1647
    // Maximum number of outer loops below. If the client doesn't send file
1648
    // chunks from within the chunk request callback handler, we never realise
1649
    // that the file transfer has finished and may end up in an infinite loop.
1650
    //
1651
    // Request up to that number of chunks per file from the client
1652
    //
1653
    // TODO(Jfreegman): set this cap dynamically
1654
0
    const uint32_t max_ft_loops = 128;
1655
1656
0
    for (uint32_t i = 0; i < max_ft_loops; ++i) {
1657
0
        if (!do_all_filetransfers(m, friendnumber, userdata, &free_slots)) {
1658
0
            break;
1659
0
        }
1660
1661
0
        if (free_slots == 0) {
1662
            // stop when the buffer is full enough
1663
0
            break;
1664
0
        }
1665
0
    }
1666
0
}
1667
1668
1669
/** @brief Run this when the friend disconnects.
1670
 * Kill all current file transfers.
1671
 */
1672
static void break_files(const Messenger *m, int32_t friendnumber)
1673
0
{
1674
0
    Friend *const f = &m->friendlist[friendnumber];
1675
1676
    // TODO(irungentoo): Inform the client which file transfers get killed with a callback?
1677
0
    for (uint32_t i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) {
1678
0
        f->file_sending[i].status = FILESTATUS_NONE;
1679
0
        f->file_receiving[i].status = FILESTATUS_NONE;
1680
0
    }
1681
0
}
1682
1683
non_null()
1684
static struct File_Transfers *get_file_transfer(bool outbound, uint8_t filenumber,
1685
        uint32_t *real_filenumber, Friend *sender)
1686
0
{
1687
0
    struct File_Transfers *ft;
1688
1689
0
    if (outbound) {
1690
0
        *real_filenumber = filenumber;
1691
0
        ft = &sender->file_sending[filenumber];
1692
0
    } else {
1693
0
        *real_filenumber = (filenumber + 1) << 16;
1694
0
        ft = &sender->file_receiving[filenumber];
1695
0
    }
1696
1697
0
    if (ft->status == FILESTATUS_NONE) {
1698
0
        return nullptr;
1699
0
    }
1700
1701
0
    return ft;
1702
0
}
1703
1704
/** @retval -1 on failure
1705
 * @retval 0 on success.
1706
 */
1707
non_null(1, 6) nullable(8)
1708
static int handle_filecontrol(Messenger *m, int32_t friendnumber, bool outbound, uint8_t filenumber,
1709
                              uint8_t control_type, const uint8_t *data, uint16_t length, void *userdata)
1710
0
{
1711
0
    uint32_t real_filenumber;
1712
0
    struct File_Transfers *ft = get_file_transfer(outbound, filenumber, &real_filenumber, &m->friendlist[friendnumber]);
1713
1714
0
    if (ft == nullptr) {
1715
0
        LOGGER_DEBUG(m->log, "file control (friend %d, file %d): file transfer does not exist; telling the other to kill it",
1716
0
                     friendnumber, filenumber);
1717
0
        send_file_control_packet(m, friendnumber, !outbound, filenumber, FILECONTROL_KILL, nullptr, 0);
1718
0
        return -1;
1719
0
    }
1720
1721
0
    switch (control_type) {
1722
0
        case FILECONTROL_ACCEPT: {
1723
0
            if (outbound && ft->status == FILESTATUS_NOT_ACCEPTED) {
1724
0
                ft->status = FILESTATUS_TRANSFERRING;
1725
0
                ++m->friendlist[friendnumber].num_sending_files;
1726
0
            } else {
1727
0
                if ((ft->paused & FILE_PAUSE_OTHER) != 0) {
1728
0
                    ft->paused ^= FILE_PAUSE_OTHER;
1729
0
                } else {
1730
0
                    LOGGER_DEBUG(m->log, "file control (friend %d, file %d): friend told us to resume file transfer that wasn't paused",
1731
0
                                 friendnumber, filenumber);
1732
0
                    return -1;
1733
0
                }
1734
0
            }
1735
1736
0
            if (m->file_filecontrol != nullptr) {
1737
0
                m->file_filecontrol(m, friendnumber, real_filenumber, control_type, userdata);
1738
0
            }
1739
1740
0
            return 0;
1741
0
        }
1742
1743
0
        case FILECONTROL_PAUSE: {
1744
0
            if ((ft->paused & FILE_PAUSE_OTHER) != 0 || ft->status != FILESTATUS_TRANSFERRING) {
1745
0
                LOGGER_DEBUG(m->log, "file control (friend %d, file %d): friend told us to pause file transfer that is already paused",
1746
0
                             friendnumber, filenumber);
1747
0
                return -1;
1748
0
            }
1749
1750
0
            ft->paused |= FILE_PAUSE_OTHER;
1751
1752
0
            if (m->file_filecontrol != nullptr) {
1753
0
                m->file_filecontrol(m, friendnumber, real_filenumber, control_type, userdata);
1754
0
            }
1755
1756
0
            return 0;
1757
0
        }
1758
1759
0
        case FILECONTROL_KILL: {
1760
0
            if (m->file_filecontrol != nullptr) {
1761
0
                m->file_filecontrol(m, friendnumber, real_filenumber, control_type, userdata);
1762
0
            }
1763
1764
0
            if (outbound && (ft->status == FILESTATUS_TRANSFERRING || ft->status == FILESTATUS_FINISHED)) {
1765
0
                --m->friendlist[friendnumber].num_sending_files;
1766
0
            }
1767
1768
0
            ft->status = FILESTATUS_NONE;
1769
1770
0
            return 0;
1771
0
        }
1772
1773
0
        case FILECONTROL_SEEK: {
1774
0
            uint64_t position;
1775
1776
0
            if (length != sizeof(position)) {
1777
0
                LOGGER_DEBUG(m->log, "file control (friend %d, file %d): expected payload of length %d, but got %d",
1778
0
                             friendnumber, filenumber, (uint32_t)sizeof(position), length);
1779
0
                return -1;
1780
0
            }
1781
1782
            /* seek can only be sent by the receiver to seek before resuming broken transfers. */
1783
0
            if (ft->status != FILESTATUS_NOT_ACCEPTED || !outbound) {
1784
0
                LOGGER_DEBUG(m->log,
1785
0
                             "file control (friend %d, file %d): seek was either sent by a sender or by the receiver after accepting",
1786
0
                             friendnumber, filenumber);
1787
0
                return -1;
1788
0
            }
1789
1790
0
            net_unpack_u64(data, &position);
1791
1792
0
            if (position >= ft->size) {
1793
0
                LOGGER_DEBUG(m->log,
1794
0
                             "file control (friend %d, file %d): seek position %ld exceeds file size %ld",
1795
0
                             friendnumber, filenumber, (unsigned long)position, (unsigned long)ft->size);
1796
0
                return -1;
1797
0
            }
1798
1799
0
            ft->requested = position;
1800
0
            ft->transferred = position;
1801
0
            return 0;
1802
0
        }
1803
1804
0
        default: {
1805
0
            LOGGER_DEBUG(m->log, "file control (friend %d, file %d): invalid file control: %d",
1806
0
                         friendnumber, filenumber, control_type);
1807
0
            return -1;
1808
0
        }
1809
0
    }
1810
0
}
1811
1812
/** @brief Set the callback for msi packets. */
1813
void m_callback_msi_packet(Messenger *m, m_msi_packet_cb *function, void *userdata)
1814
0
{
1815
0
    m->msi_packet = function;
1816
0
    m->msi_packet_userdata = userdata;
1817
0
}
1818
1819
/** @brief Send an msi packet.
1820
 *
1821
 * @retval true on success
1822
 * @retval false on failure
1823
 */
1824
bool m_msi_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint16_t length)
1825
0
{
1826
0
    return write_cryptpacket_id(m, friendnumber, PACKET_ID_MSI, data, length, false);
1827
0
}
1828
1829
static int m_handle_lossy_packet(void *object, int friend_num, const uint8_t *packet, uint16_t length,
1830
                                 void *userdata)
1831
0
{
1832
0
    Messenger *m = (Messenger *)object;
1833
1834
0
    if (!m_friend_exists(m, friend_num)) {
1835
0
        return 1;
1836
0
    }
1837
1838
0
    if (packet[0] <= PACKET_ID_RANGE_LOSSY_AV_END) {
1839
0
        const RTP_Packet_Handler *const ph =
1840
0
            &m->friendlist[friend_num].lossy_rtp_packethandlers[packet[0] % PACKET_ID_RANGE_LOSSY_AV_SIZE];
1841
1842
0
        if (ph->function != nullptr) {
1843
0
            return ph->function(m, friend_num, packet, length, ph->object);
1844
0
        }
1845
1846
0
        return 1;
1847
0
    }
1848
1849
0
    if (m->lossy_packethandler != nullptr) {
1850
0
        m->lossy_packethandler(m, friend_num, packet[0], packet, length, userdata);
1851
0
    }
1852
1853
0
    return 1;
1854
0
}
1855
1856
void custom_lossy_packet_registerhandler(Messenger *m, m_friend_lossy_packet_cb *lossy_packethandler)
1857
2.44k
{
1858
2.44k
    m->lossy_packethandler = lossy_packethandler;
1859
2.44k
}
1860
1861
int m_callback_rtp_packet(Messenger *m, int32_t friendnumber, uint8_t byte, m_lossy_rtp_packet_cb *function,
1862
                          void *object)
1863
0
{
1864
0
    if (!m_friend_exists(m, friendnumber)) {
1865
0
        return -1;
1866
0
    }
1867
1868
0
    if (byte < PACKET_ID_RANGE_LOSSY_AV_START || byte > PACKET_ID_RANGE_LOSSY_AV_END) {
1869
0
        return -1;
1870
0
    }
1871
1872
0
    m->friendlist[friendnumber].lossy_rtp_packethandlers[byte % PACKET_ID_RANGE_LOSSY_AV_SIZE].function = function;
1873
0
    m->friendlist[friendnumber].lossy_rtp_packethandlers[byte % PACKET_ID_RANGE_LOSSY_AV_SIZE].object = object;
1874
0
    return 0;
1875
0
}
1876
1877
1878
/** @brief High level function to send custom lossy packets.
1879
 *
1880
 * TODO(oxij): this name is confusing, because this function sends both av and custom lossy packets.
1881
 * Meanwhile, m_handle_lossy_packet routes custom packets to custom_lossy_packet_registerhandler
1882
 * as you would expect from its name.
1883
 *
1884
 * I.e. custom_lossy_packet_registerhandler's "custom lossy packet" and this "custom lossy packet"
1885
 * are not the same set of packets.
1886
 *
1887
 * @retval -1 if friend invalid.
1888
 * @retval -2 if length wrong.
1889
 * @retval -3 if first byte invalid.
1890
 * @retval -4 if friend offline.
1891
 * @retval -5 if packet failed to send because of other error.
1892
 * @retval 0 on success.
1893
 */
1894
int m_send_custom_lossy_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint32_t length)
1895
0
{
1896
0
    if (!m_friend_exists(m, friendnumber)) {
1897
0
        return -1;
1898
0
    }
1899
1900
0
    if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
1901
0
        return -2;
1902
0
    }
1903
1904
    // TODO(oxij): send_lossy_cryptpacket makes this check already, similarly for other similar places
1905
0
    if (data[0] < PACKET_ID_RANGE_LOSSY_START || data[0] > PACKET_ID_RANGE_LOSSY_END) {
1906
0
        return -3;
1907
0
    }
1908
1909
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1910
0
        return -4;
1911
0
    }
1912
1913
0
    if (send_lossy_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1914
0
                               m->friendlist[friendnumber].friendcon_id), data, length) == -1) {
1915
0
        return -5;
1916
0
    }
1917
1918
0
    return 0;
1919
0
}
1920
1921
non_null(1, 3) nullable(5)
1922
static int handle_custom_lossless_packet(void *object, int friend_num, const uint8_t *packet, uint16_t length,
1923
        void *userdata)
1924
0
{
1925
0
    Messenger *m = (Messenger *)object;
1926
1927
0
    if (!m_friend_exists(m, friend_num)) {
1928
0
        return -1;
1929
0
    }
1930
1931
0
    if (packet[0] < PACKET_ID_RANGE_LOSSLESS_CUSTOM_START || packet[0] > PACKET_ID_RANGE_LOSSLESS_CUSTOM_END) {
1932
0
        return -1;
1933
0
    }
1934
1935
0
    if (m->lossless_packethandler != nullptr) {
1936
0
        m->lossless_packethandler(m, friend_num, packet[0], packet, length, userdata);
1937
0
    }
1938
1939
0
    return 1;
1940
0
}
1941
1942
void custom_lossless_packet_registerhandler(Messenger *m, m_friend_lossless_packet_cb *lossless_packethandler)
1943
2.44k
{
1944
2.44k
    m->lossless_packethandler = lossless_packethandler;
1945
2.44k
}
1946
1947
int send_custom_lossless_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint32_t length)
1948
0
{
1949
0
    if (!m_friend_exists(m, friendnumber)) {
1950
0
        return -1;
1951
0
    }
1952
1953
0
    if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
1954
0
        return -2;
1955
0
    }
1956
1957
0
    if ((data[0] < PACKET_ID_RANGE_LOSSLESS_CUSTOM_START || data[0] > PACKET_ID_RANGE_LOSSLESS_CUSTOM_END)
1958
0
            && data[0] != PACKET_ID_MSI) {
1959
0
        return -3;
1960
0
    }
1961
1962
0
    if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1963
0
        return -4;
1964
0
    }
1965
1966
0
    if (write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1967
0
                          m->friendlist[friendnumber].friendcon_id), data, length, true) == -1) {
1968
0
        return -5;
1969
0
    }
1970
1971
0
    return 0;
1972
0
}
1973
1974
/** Function to filter out some friend requests*/
1975
non_null()
1976
static int friend_already_added(const uint8_t *real_pk, void *data)
1977
128
{
1978
128
    const Messenger *m = (const Messenger *)data;
1979
1980
128
    if (getfriend_id(m, real_pk) == -1) {
1981
128
        return 0;
1982
128
    }
1983
1984
0
    return -1;
1985
128
}
1986
1987
/** @brief Check for and handle a timed-out friend request.
1988
 *
1989
 * If the request has timed-out then the friend status is set back to FRIEND_ADDED.
1990
 * @param i friendlist index of the timed-out friend
1991
 * @param t time
1992
 */
1993
non_null(1) nullable(4)
1994
static void check_friend_request_timed_out(Messenger *m, uint32_t i, uint64_t t, void *userdata)
1995
0
{
1996
0
    Friend *f = &m->friendlist[i];
1997
1998
0
    if (f->friendrequest_lastsent + f->friendrequest_timeout < t) {
1999
0
        set_friend_status(m, i, FRIEND_ADDED, userdata);
2000
        /* Double the default timeout every time if friendrequest is assumed
2001
         * to have been sent unsuccessfully.
2002
         */
2003
0
        f->friendrequest_timeout *= 2;
2004
0
    }
2005
0
}
2006
2007
non_null(1) nullable(4)
2008
static int m_handle_status(void *object, int i, bool status, void *userdata)
2009
0
{
2010
0
    Messenger *m = (Messenger *)object;
2011
2012
0
    if (status) { /* Went online. */
2013
0
        send_online_packet(m, m->friendlist[i].friendcon_id);
2014
0
    } else { /* Went offline. */
2015
0
        if (m->friendlist[i].status == FRIEND_ONLINE) {
2016
0
            set_friend_status(m, i, FRIEND_CONFIRMED, userdata);
2017
0
        }
2018
0
    }
2019
2020
0
    return 0;
2021
0
}
2022
2023
non_null(1, 3) nullable(5)
2024
static int m_handle_packet_offline(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2025
0
{
2026
0
    if (data_length == 0) {
2027
0
      set_friend_status(m, i, FRIEND_CONFIRMED, userdata);
2028
0
    }
2029
2030
0
    return 0;
2031
0
}
2032
2033
non_null(1, 3) nullable(5)
2034
static int m_handle_packet_nickname(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2035
0
{
2036
0
    if (data_length > MAX_NAME_LENGTH) {
2037
0
        return 0;
2038
0
    }
2039
2040
    /* Make sure the NULL terminator is present. */
2041
0
    VLA(uint8_t, data_terminated, data_length + 1);
2042
0
    memcpy(data_terminated, data, data_length);
2043
0
    data_terminated[data_length] = 0;
2044
2045
    /* inform of namechange before we overwrite the old name */
2046
0
    if (m->friend_namechange != nullptr) {
2047
0
        m->friend_namechange(m, i, data_terminated, data_length, userdata);
2048
0
    }
2049
2050
0
    memcpy(m->friendlist[i].name, data_terminated, data_length);
2051
0
    m->friendlist[i].name_length = data_length;
2052
2053
0
    return 0;
2054
0
}
2055
2056
non_null(1, 3) nullable(5)
2057
static int m_handle_packet_statusmessage(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2058
0
{
2059
0
    if (data_length > MAX_STATUSMESSAGE_LENGTH) {
2060
0
        return 0;
2061
0
    }
2062
2063
    /* Make sure the NULL terminator is present. */
2064
0
    VLA(uint8_t, data_terminated, data_length + 1);
2065
0
    memcpy(data_terminated, data, data_length);
2066
0
    data_terminated[data_length] = 0;
2067
2068
0
    if (m->friend_statusmessagechange != nullptr) {
2069
0
        m->friend_statusmessagechange(m, i, data_terminated, data_length, userdata);
2070
0
    }
2071
2072
0
    set_friend_statusmessage(m, i, data_terminated, data_length);
2073
2074
0
    return 0;
2075
0
}
2076
2077
non_null(1, 3) nullable(5)
2078
static int m_handle_packet_userstatus(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2079
0
{
2080
0
    if (data_length != 1) {
2081
0
        return 0;
2082
0
    }
2083
2084
0
    const Userstatus status = (Userstatus)data[0];
2085
2086
0
    if (status >= USERSTATUS_INVALID) {
2087
0
        return 0;
2088
0
    }
2089
2090
0
    if (m->friend_userstatuschange != nullptr) {
2091
0
        m->friend_userstatuschange(m, i, status, userdata);
2092
0
    }
2093
2094
0
    set_friend_userstatus(m, i, status);
2095
2096
0
    return 0;
2097
0
}
2098
2099
non_null(1, 3) nullable(5)
2100
static int m_handle_packet_typing(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2101
0
{
2102
0
    if (data_length != 1) {
2103
0
        return 0;
2104
0
    }
2105
2106
0
    const bool typing = data[0] != 0;
2107
2108
0
    set_friend_typing(m, i, typing);
2109
2110
0
    if (m->friend_typingchange != nullptr) {
2111
0
        m->friend_typingchange(m, i, typing, userdata);
2112
0
    }
2113
2114
0
    return 0;
2115
0
}
2116
2117
non_null(1, 3) nullable(6)
2118
static int m_handle_packet_message(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, const Message_Type message_type, void *userdata)
2119
0
{
2120
0
    if (data_length == 0) {
2121
0
        return 0;
2122
0
    }
2123
2124
0
    const uint8_t *message = data;
2125
0
    const uint16_t message_length = data_length;
2126
2127
    /* Make sure the NULL terminator is present. */
2128
0
    VLA(uint8_t, message_terminated, message_length + 1);
2129
0
    memcpy(message_terminated, message, message_length);
2130
0
    message_terminated[message_length] = 0;
2131
2132
0
    if (m->friend_message != nullptr) {
2133
0
        m->friend_message(m, i, message_type, message_terminated, message_length, userdata);
2134
0
    }
2135
2136
0
    return 0;
2137
0
}
2138
2139
non_null(1, 3) nullable(5)
2140
static int m_handle_packet_invite_conference(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2141
0
{
2142
0
    if (data_length == 0) {
2143
0
        return 0;
2144
0
    }
2145
2146
0
    if (m->conference_invite != nullptr) {
2147
0
        m->conference_invite(m, i, data, data_length, userdata);
2148
0
    }
2149
2150
0
    return 0;
2151
0
}
2152
2153
non_null(1, 3) nullable(5)
2154
static int m_handle_packet_file_sendrequest(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2155
0
{
2156
0
    const unsigned int head_length = 1 + sizeof(uint32_t) + sizeof(uint64_t) + FILE_ID_LENGTH;
2157
2158
0
    if (data_length < head_length) {
2159
0
        return 0;
2160
0
    }
2161
2162
0
    const uint8_t filenumber = data[0];
2163
2164
#if UINT8_MAX >= MAX_CONCURRENT_FILE_PIPES
2165
2166
    if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
2167
        return 0;
2168
    }
2169
2170
#endif
2171
2172
0
    uint64_t filesize;
2173
0
    uint32_t file_type;
2174
0
    const uint16_t filename_length = data_length - head_length;
2175
2176
0
    if (filename_length > MAX_FILENAME_LENGTH) {
2177
0
        return 0;
2178
0
    }
2179
2180
0
    memcpy(&file_type, data + 1, sizeof(file_type));
2181
0
    file_type = net_ntohl(file_type);
2182
2183
0
    net_unpack_u64(data + 1 + sizeof(uint32_t), &filesize);
2184
0
    struct File_Transfers *ft = &m->friendlist[i].file_receiving[filenumber];
2185
2186
0
    if (ft->status != FILESTATUS_NONE) {
2187
0
        return 0;
2188
0
    }
2189
2190
0
    ft->status = FILESTATUS_NOT_ACCEPTED;
2191
0
    ft->size = filesize;
2192
0
    ft->transferred = 0;
2193
0
    ft->paused = FILE_PAUSE_NOT;
2194
0
    memcpy(ft->id, data + 1 + sizeof(uint32_t) + sizeof(uint64_t), FILE_ID_LENGTH);
2195
2196
0
    VLA(uint8_t, filename_terminated, filename_length + 1);
2197
0
    const uint8_t *filename = nullptr;
2198
2199
0
    if (filename_length > 0) {
2200
        /* Force NULL terminate file name. */
2201
0
        memcpy(filename_terminated, data + head_length, filename_length);
2202
0
        filename_terminated[filename_length] = 0;
2203
0
        filename = filename_terminated;
2204
0
    }
2205
2206
0
    uint32_t real_filenumber = filenumber;
2207
0
    real_filenumber += 1;
2208
0
    real_filenumber <<= 16;
2209
2210
0
    if (m->file_sendrequest != nullptr) {
2211
0
        m->file_sendrequest(m, i, real_filenumber, file_type, filesize, filename, filename_length,
2212
0
                            userdata);
2213
0
    }
2214
2215
0
    return 0;
2216
0
}
2217
2218
non_null(1, 3) nullable(5)
2219
static int m_handle_packet_file_control(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2220
0
{
2221
0
    if (data_length < 3) {
2222
0
        return 0;
2223
0
    }
2224
2225
    // On the other side, "outbound" is "inbound", i.e. if they send 1,
2226
    // that means "inbound" on their side, but we call it "outbound"
2227
    // here.
2228
0
    const bool outbound = data[0] == 1;
2229
0
    const uint8_t filenumber = data[1];
2230
0
    const uint8_t control_type = data[2];
2231
2232
#if UINT8_MAX >= MAX_CONCURRENT_FILE_PIPES
2233
2234
    if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
2235
        return 0;
2236
    }
2237
2238
#endif
2239
2240
0
    if (handle_filecontrol(m, i, outbound, filenumber, control_type, data + 3, data_length - 3, userdata) == -1) {
2241
        // TODO(iphydf): Do something different here? Right now, this
2242
        // check is pointless.
2243
0
        return 0;
2244
0
    }
2245
2246
0
    return 0;
2247
0
}
2248
2249
non_null(1, 3) nullable(5)
2250
static int m_handle_packet_file_data(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2251
0
{
2252
0
    if (data_length < 1) {
2253
0
        return 0;
2254
0
    }
2255
2256
0
    const uint8_t filenumber = data[0];
2257
2258
#if UINT8_MAX >= MAX_CONCURRENT_FILE_PIPES
2259
2260
    if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
2261
        return 0;
2262
    }
2263
2264
#endif
2265
2266
0
    struct File_Transfers *ft = &m->friendlist[i].file_receiving[filenumber];
2267
2268
0
    if (ft->status != FILESTATUS_TRANSFERRING) {
2269
0
        return 0;
2270
0
    }
2271
2272
0
    uint64_t position = ft->transferred;
2273
0
    uint32_t real_filenumber = filenumber;
2274
0
    real_filenumber += 1;
2275
0
    real_filenumber <<= 16;
2276
0
    uint16_t file_data_length = data_length - 1;
2277
0
    const uint8_t *file_data;
2278
2279
0
    if (file_data_length == 0) {
2280
0
        file_data = nullptr;
2281
0
    } else {
2282
0
        file_data = data + 1;
2283
0
    }
2284
2285
    /* Prevent more data than the filesize from being passed to clients. */
2286
0
    if ((ft->transferred + file_data_length) > ft->size) {
2287
0
        file_data_length = ft->size - ft->transferred;
2288
0
    }
2289
2290
0
    if (m->file_filedata != nullptr) {
2291
0
        m->file_filedata(m, i, real_filenumber, position, file_data, file_data_length, userdata);
2292
0
    }
2293
2294
0
    ft->transferred += file_data_length;
2295
2296
0
    if (file_data_length > 0 && (ft->transferred >= ft->size || file_data_length != MAX_FILE_DATA_SIZE)) {
2297
0
        file_data_length = 0;
2298
0
        file_data = nullptr;
2299
0
        position = ft->transferred;
2300
2301
        /* Full file received. */
2302
0
        if (m->file_filedata != nullptr) {
2303
0
            m->file_filedata(m, i, real_filenumber, position, file_data, file_data_length, userdata);
2304
0
        }
2305
0
    }
2306
2307
    /* Data is zero, filetransfer is over. */
2308
0
    if (file_data_length == 0) {
2309
0
        ft->status = FILESTATUS_NONE;
2310
0
    }
2311
2312
0
    return 0;
2313
0
}
2314
2315
non_null(1, 3) nullable(5)
2316
static int m_handle_packet_msi(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2317
0
{
2318
0
    if (data_length == 0) {
2319
0
        return 0;
2320
0
    }
2321
2322
0
    if (m->msi_packet != nullptr) {
2323
0
        m->msi_packet(m, i, data, data_length, m->msi_packet_userdata);
2324
0
    }
2325
2326
0
    return 0;
2327
0
}
2328
2329
non_null(1, 3) nullable(5)
2330
static int m_handle_packet_invite_groupchat(Messenger *m, const int i, const uint8_t *data, const uint16_t data_length, void *userdata)
2331
0
{
2332
0
#ifndef VANILLA_NACL
2333
2334
    // first two bytes are messenger packet type and group invite type
2335
0
    if (data_length < 2 + GC_JOIN_DATA_LENGTH) {
2336
0
        return 0;
2337
0
    }
2338
2339
0
    const uint8_t invite_type = data[1];
2340
0
    const uint8_t *join_data = data + 2;
2341
0
    const uint32_t join_data_len = data_length - 2;
2342
2343
0
    if (m->group_invite != nullptr && data[1] == GROUP_INVITE && data_length != 2 + GC_JOIN_DATA_LENGTH) {
2344
0
        if (group_not_added(m->group_handler, join_data, join_data_len)) {
2345
0
            m->group_invite(m, i, join_data, GC_JOIN_DATA_LENGTH,
2346
0
                            join_data + GC_JOIN_DATA_LENGTH, join_data_len - GC_JOIN_DATA_LENGTH, userdata);
2347
0
        }
2348
0
    } else if (invite_type == GROUP_INVITE_ACCEPTED) {
2349
0
        handle_gc_invite_accepted_packet(m->group_handler, i, join_data, join_data_len);
2350
0
    } else if (invite_type == GROUP_INVITE_CONFIRMATION) {
2351
0
        handle_gc_invite_confirmed_packet(m->group_handler, i, join_data, join_data_len);
2352
0
    }
2353
2354
0
#endif // VANILLA_NACL
2355
2356
0
    return 0;
2357
0
}
2358
2359
non_null(1, 3) nullable(5)
2360
static int m_handle_packet(void *object, int i, const uint8_t *temp, uint16_t len, void *userdata)
2361
0
{
2362
0
    if (len == 0) {
2363
0
        return -1;
2364
0
    }
2365
2366
0
    Messenger *m = (Messenger *)object;
2367
0
    const uint8_t packet_id = temp[0];
2368
0
    const uint8_t *data = temp + 1;
2369
0
    const uint16_t data_length = len - 1;
2370
2371
0
    if (m->friendlist[i].status != FRIEND_ONLINE) {
2372
0
        if (packet_id == PACKET_ID_ONLINE && len == 1) {
2373
0
            set_friend_status(m, i, FRIEND_ONLINE, userdata);
2374
0
            send_online_packet(m, m->friendlist[i].friendcon_id);
2375
0
        } else {
2376
0
            return -1;
2377
0
        }
2378
0
    }
2379
2380
0
    switch (packet_id) {
2381
        // TODO(Green-Sky): now all return 0 on error AND success, make errors errors?
2382
0
        case PACKET_ID_OFFLINE:
2383
0
            return m_handle_packet_offline(m, i, data, data_length, userdata);
2384
0
        case PACKET_ID_NICKNAME:
2385
0
            return m_handle_packet_nickname(m, i, data, data_length, userdata);
2386
0
        case PACKET_ID_STATUSMESSAGE:
2387
0
            return m_handle_packet_statusmessage(m, i, data, data_length, userdata);
2388
0
        case PACKET_ID_USERSTATUS:
2389
0
            return m_handle_packet_userstatus(m, i, data, data_length, userdata);
2390
0
        case PACKET_ID_TYPING:
2391
0
            return m_handle_packet_typing(m, i, data, data_length, userdata);
2392
0
        case PACKET_ID_MESSAGE:
2393
0
            return m_handle_packet_message(m, i, data, data_length, MESSAGE_NORMAL, userdata);
2394
0
        case PACKET_ID_ACTION:
2395
0
            return m_handle_packet_message(m, i, data, data_length, MESSAGE_ACTION, userdata);
2396
0
        case PACKET_ID_INVITE_CONFERENCE:
2397
0
            return m_handle_packet_invite_conference(m, i, data, data_length, userdata);
2398
0
        case PACKET_ID_FILE_SENDREQUEST:
2399
0
            return m_handle_packet_file_sendrequest(m, i, data, data_length, userdata);
2400
0
        case PACKET_ID_FILE_CONTROL:
2401
0
            return m_handle_packet_file_control(m, i, data, data_length, userdata);
2402
0
        case PACKET_ID_FILE_DATA:
2403
0
            return m_handle_packet_file_data(m, i, data, data_length, userdata);
2404
0
        case PACKET_ID_MSI:
2405
0
            return m_handle_packet_msi(m, i, data, data_length, userdata);
2406
0
      case PACKET_ID_INVITE_GROUPCHAT:
2407
0
          return m_handle_packet_invite_groupchat(m, i, data, data_length, userdata);
2408
0
    }
2409
2410
0
    return handle_custom_lossless_packet(object, i, temp, len, userdata);
2411
0
}
2412
2413
non_null(1) nullable(2)
2414
static void do_friends(Messenger *m, void *userdata)
2415
72.6k
{
2416
72.6k
    const uint64_t temp_time = mono_time_get(m->mono_time);
2417
2418
74.9k
    for (uint32_t i = 0; i < m->numfriends; ++i) {
2419
2.26k
        if (m->friendlist[i].status == FRIEND_ADDED) {
2420
0
            const int fr = send_friend_request_packet(m->fr_c, m->friendlist[i].friendcon_id, m->friendlist[i].friendrequest_nospam,
2421
0
                                                m->friendlist[i].info,
2422
0
                                                m->friendlist[i].info_size);
2423
2424
0
            if (fr >= 0) {
2425
0
                set_friend_status(m, i, FRIEND_REQUESTED, userdata);
2426
0
                m->friendlist[i].friendrequest_lastsent = temp_time;
2427
0
            }
2428
0
        }
2429
2430
2.26k
        if (m->friendlist[i].status == FRIEND_REQUESTED
2431
2.26k
                || m->friendlist[i].status == FRIEND_CONFIRMED) { /* friend is not online. */
2432
2.26k
            if (m->friendlist[i].status == FRIEND_REQUESTED) {
2433
                /* If we didn't connect to friend after successfully sending him a friend request the request is deemed
2434
                 * unsuccessful so we set the status back to FRIEND_ADDED and try again.
2435
                 */
2436
0
                check_friend_request_timed_out(m, i, temp_time, userdata);
2437
0
            }
2438
2.26k
        }
2439
2440
2.26k
        if (m->friendlist[i].status == FRIEND_ONLINE) { /* friend is online. */
2441
0
            if (!m->friendlist[i].name_sent) {
2442
0
                if (m_sendname(m, i, m->name, m->name_length)) {
2443
0
                    m->friendlist[i].name_sent = true;
2444
0
                }
2445
0
            }
2446
2447
0
            if (!m->friendlist[i].statusmessage_sent) {
2448
0
                if (send_statusmessage(m, i, m->statusmessage, m->statusmessage_length)) {
2449
0
                    m->friendlist[i].statusmessage_sent = true;
2450
0
                }
2451
0
            }
2452
2453
0
            if (!m->friendlist[i].userstatus_sent) {
2454
0
                if (send_userstatus(m, i, m->userstatus)) {
2455
0
                    m->friendlist[i].userstatus_sent = true;
2456
0
                }
2457
0
            }
2458
2459
0
            if (!m->friendlist[i].user_istyping_sent) {
2460
0
                if (send_user_istyping(m, i, m->friendlist[i].user_istyping)) {
2461
0
                    m->friendlist[i].user_istyping_sent = true;
2462
0
                }
2463
0
            }
2464
2465
0
            check_friend_tcp_udp(m, i, userdata);
2466
0
            do_receipts(m, i, userdata);
2467
0
            do_reqchunk_filecb(m, i, userdata);
2468
2469
0
            m->friendlist[i].last_seen_time = (uint64_t) time(nullptr);
2470
0
        }
2471
2.26k
    }
2472
72.6k
}
2473
2474
non_null(1) nullable(2)
2475
static void m_connection_status_callback(Messenger *m, void *userdata)
2476
72.6k
{
2477
72.6k
    const Onion_Connection_Status conn_status = onion_connection_status(m->onion_c);
2478
2479
72.6k
    if (conn_status != m->last_connection_status) {
2480
0
        if (m->core_connection_change != nullptr) {
2481
0
            m->core_connection_change(m, conn_status, userdata);
2482
0
        }
2483
2484
0
        m->last_connection_status = conn_status;
2485
0
    }
2486
72.6k
}
2487
2488
2489
72.6k
#define DUMPING_CLIENTS_FRIENDS_EVERY_N_SECONDS 60UL
2490
2491
#define IDSTRING_LEN (CRYPTO_PUBLIC_KEY_SIZE * 2 + 1)
2492
/** id_str should be of length at least IDSTRING_LEN */
2493
non_null()
2494
static char *id_to_string(const uint8_t *pk, char *id_str, size_t length)
2495
0
{
2496
0
    if (length < IDSTRING_LEN) {
2497
0
        snprintf(id_str, length, "Bad buf length");
2498
0
        return id_str;
2499
0
    }
2500
0
2501
0
    for (uint32_t i = 0; i < CRYPTO_PUBLIC_KEY_SIZE; ++i) {
2502
0
        snprintf(&id_str[i * 2], length - i * 2, "%02X", pk[i]);
2503
0
    }
2504
0
2505
0
    id_str[CRYPTO_PUBLIC_KEY_SIZE * 2] = '\0';
2506
0
    return id_str;
2507
0
}
2508
2509
/** @brief Minimum messenger run interval in ms
2510
 * TODO(mannol): A/V
2511
 */
2512
0
#define MIN_RUN_INTERVAL 50
2513
2514
/**
2515
 * @brief Return the time in milliseconds before `do_messenger()` should be called again
2516
 *   for optimal performance.
2517
 *
2518
 * @return time (in ms) before the next `do_messenger()` needs to be run on success.
2519
 */
2520
uint32_t messenger_run_interval(const Messenger *m)
2521
0
{
2522
0
    const uint32_t crypto_interval = crypto_run_interval(m->net_crypto);
2523
2524
0
    if (crypto_interval > MIN_RUN_INTERVAL) {
2525
0
        return MIN_RUN_INTERVAL;
2526
0
    }
2527
2528
0
    return crypto_interval;
2529
0
}
2530
2531
/** @brief Attempts to create a DHT announcement for a group chat with our connection info. An
2532
 * announcement can only be created if we either have a UDP or TCP connection to the network.
2533
 *
2534
 * @retval true if success.
2535
 */
2536
#ifndef VANILLA_NACL
2537
non_null()
2538
static bool self_announce_group(const Messenger *m, GC_Chat *chat, Onion_Friend *onion_friend)
2539
0
{
2540
0
    GC_Public_Announce announce = {{{{{0}}}}};
2541
2542
0
    const bool ip_port_is_set = chat->self_udp_status != SELF_UDP_STATUS_NONE;
2543
0
    const int tcp_num = tcp_copy_connected_relays(chat->tcp_conn, announce.base_announce.tcp_relays,
2544
0
                        GCA_MAX_ANNOUNCED_TCP_RELAYS);
2545
2546
0
    if (tcp_num == 0 && !ip_port_is_set) {
2547
0
        onion_friend_set_gc_data(onion_friend, nullptr, 0);
2548
0
        return false;
2549
0
    }
2550
2551
0
    announce.base_announce.tcp_relays_count = (uint8_t)tcp_num;
2552
0
    announce.base_announce.ip_port_is_set = (uint8_t)(ip_port_is_set ? 1 : 0);
2553
2554
0
    if (ip_port_is_set) {
2555
0
        memcpy(&announce.base_announce.ip_port, &chat->self_ip_port, sizeof(IP_Port));
2556
0
    }
2557
2558
0
    memcpy(announce.base_announce.peer_public_key, chat->self_public_key, ENC_PUBLIC_KEY_SIZE);
2559
0
    memcpy(announce.chat_public_key, get_chat_id(chat->chat_public_key), ENC_PUBLIC_KEY_SIZE);
2560
2561
0
    uint8_t gc_data[GCA_MAX_DATA_LENGTH];
2562
0
    const int length = gca_pack_public_announce(m->log, gc_data, GCA_MAX_DATA_LENGTH, &announce);
2563
2564
0
    if (length <= 0) {
2565
0
        onion_friend_set_gc_data(onion_friend, nullptr, 0);
2566
0
        return false;
2567
0
    }
2568
2569
0
    if (gca_add_announce(m->mono_time, m->group_announce, &announce) == nullptr) {
2570
0
        onion_friend_set_gc_data(onion_friend, nullptr, 0);
2571
0
        return false;
2572
0
    }
2573
2574
0
    onion_friend_set_gc_data(onion_friend, gc_data, (uint16_t)length);
2575
0
    chat->update_self_announces = false;
2576
0
    chat->last_time_self_announce = mono_time_get(chat->mono_time);
2577
2578
0
    if (tcp_num > 0) {
2579
0
        pk_copy(chat->announced_tcp_relay_pk, announce.base_announce.tcp_relays[0].public_key);
2580
0
    } else {
2581
0
        memset(chat->announced_tcp_relay_pk, 0, sizeof(chat->announced_tcp_relay_pk));
2582
0
    }
2583
2584
0
    LOGGER_DEBUG(chat->log, "Published group announce. TCP relays: %d, UDP status: %d", tcp_num,
2585
0
                 chat->self_udp_status);
2586
0
    return true;
2587
0
}
2588
2589
non_null()
2590
static void do_gc_onion_friends(const Messenger *m)
2591
72.6k
{
2592
72.6k
    const uint16_t num_friends = onion_get_friend_count(m->onion_c);
2593
2594
74.9k
    for (uint16_t i = 0; i < num_friends; ++i) {
2595
2.26k
        Onion_Friend *onion_friend = onion_get_friend(m->onion_c, i);
2596
2597
2.26k
        if (!onion_friend_is_groupchat(onion_friend)) {
2598
2.26k
            continue;
2599
2.26k
        }
2600
2601
0
        GC_Chat *chat = gc_get_group_by_public_key(m->group_handler, onion_friend_get_gc_public_key(onion_friend));
2602
2603
0
        if (chat == nullptr) {
2604
0
            continue;
2605
0
        }
2606
2607
0
        if (chat->update_self_announces) {
2608
0
            self_announce_group(m, chat, onion_friend);
2609
0
        }
2610
0
    }
2611
72.6k
}
2612
#endif  // VANILLA_NACL
2613
2614
/** @brief The main loop that needs to be run at least 20 times per second. */
2615
void do_messenger(Messenger *m, void *userdata)
2616
72.6k
{
2617
    // Add the TCP relays, but only if this is the first time calling do_messenger
2618
72.6k
    if (!m->has_added_relays) {
2619
914
        m->has_added_relays = true;
2620
2621
914
        for (uint16_t i = 0; i < m->num_loaded_relays; ++i) {
2622
0
            add_tcp_relay(m->net_crypto, &m->loaded_relays[i].ip_port, m->loaded_relays[i].public_key);
2623
0
        }
2624
2625
914
        m->num_loaded_relays = 0;
2626
2627
914
        if (m->tcp_server != nullptr) {
2628
            /* Add self tcp server. */
2629
137
            IP_Port local_ip_port;
2630
137
            local_ip_port.port = m->options.tcp_server_port;
2631
137
            local_ip_port.ip.family = net_family_ipv4();
2632
137
            local_ip_port.ip.ip.v4 = get_ip4_loopback();
2633
137
            add_tcp_relay(m->net_crypto, &local_ip_port, tcp_server_public_key(m->tcp_server));
2634
137
        }
2635
914
    }
2636
2637
72.6k
    if (!m->options.udp_disabled) {
2638
12.0k
        networking_poll(m->net, userdata);
2639
12.0k
        do_dht(m->dht);
2640
12.0k
    }
2641
2642
72.6k
    if (m->tcp_server != nullptr) {
2643
174
        do_tcp_server(m->tcp_server, m->mono_time);
2644
174
    }
2645
2646
72.6k
    do_net_crypto(m->net_crypto, userdata);
2647
72.6k
    do_onion_client(m->onion_c);
2648
72.6k
    do_friend_connections(m->fr_c, userdata);
2649
72.6k
    do_friends(m, userdata);
2650
72.6k
#ifndef VANILLA_NACL
2651
72.6k
    do_gc(m->group_handler, userdata);
2652
72.6k
    do_gca(m->mono_time, m->group_announce);
2653
72.6k
    do_gc_onion_friends(m);
2654
72.6k
#endif
2655
72.6k
    m_connection_status_callback(m, userdata);
2656
2657
72.6k
    if (mono_time_get(m->mono_time) > m->lastdump + DUMPING_CLIENTS_FRIENDS_EVERY_N_SECONDS) {
2658
1.09k
        m->lastdump = mono_time_get(m->mono_time);
2659
1.09k
        uint32_t last_pinged;
2660
2661
1.12M
        for (uint32_t client = 0; client < LCLIENT_LIST; ++client) {
2662
1.12M
            const Client_data *cptr = dht_get_close_client(m->dht, client);
2663
1.12M
            const IPPTsPng *const assocs[] = { &cptr->assoc4, &cptr->assoc6, nullptr };
2664
2665
3.36M
            for (const IPPTsPng * const *it = assocs; *it != nullptr; ++it) {
2666
2.24M
                const IPPTsPng *const assoc = *it;
2667
2668
2.24M
                if (ip_isset(&assoc->ip_port.ip)) {
2669
0
                    last_pinged = m->lastdump - assoc->last_pinged;
2670
2671
0
                    if (last_pinged > 999) {
2672
0
                        last_pinged = 999;
2673
0
                    }
2674
2675
0
                    Ip_Ntoa ip_str;
2676
0
                    char id_str[IDSTRING_LEN];
2677
0
                    LOGGER_TRACE(m->log, "C[%2u] %s:%u [%3u] %s",
2678
0
                                 client, net_ip_ntoa(&assoc->ip_port.ip, &ip_str),
2679
0
                                 net_ntohs(assoc->ip_port.port), last_pinged,
2680
0
                                 id_to_string(cptr->public_key, id_str, sizeof(id_str)));
2681
0
                }
2682
2.24M
            }
2683
1.12M
        }
2684
2685
2686
        /* dht contains additional "friends" (requests) */
2687
1.09k
        const uint32_t num_dhtfriends = dht_get_num_friends(m->dht);
2688
1.09k
        VLA(int32_t, m2dht, num_dhtfriends);
2689
1.09k
        VLA(int32_t, dht2m, num_dhtfriends);
2690
2691
3.28k
        for (uint32_t friend_idx = 0; friend_idx < num_dhtfriends; ++friend_idx) {
2692
2.19k
            m2dht[friend_idx] = -1;
2693
2.19k
            dht2m[friend_idx] = -1;
2694
2695
2.19k
            if (friend_idx >= m->numfriends) {
2696
2.19k
                continue;
2697
2.19k
            }
2698
2699
3
            for (uint32_t dhtfriend = 0; dhtfriend < dht_get_num_friends(m->dht); ++dhtfriend) {
2700
2
                if (pk_equal(m->friendlist[friend_idx].real_pk, dht_get_friend_public_key(m->dht, dhtfriend))) {
2701
0
                    assert(dhtfriend < INT32_MAX);
2702
0
                    m2dht[friend_idx] = (int32_t)dhtfriend;
2703
0
                    break;
2704
0
                }
2705
2
            }
2706
1
        }
2707
2708
3.28k
        for (uint32_t friend_idx = 0; friend_idx < num_dhtfriends; ++friend_idx) {
2709
2.19k
            if (m2dht[friend_idx] >= 0) {
2710
0
                assert(friend_idx < INT32_MAX);
2711
0
                dht2m[m2dht[friend_idx]] = (int32_t)friend_idx;
2712
0
            }
2713
2.19k
        }
2714
2715
1.09k
        if (m->numfriends != dht_get_num_friends(m->dht)) {
2716
1.09k
            LOGGER_TRACE(m->log, "Friend num in DHT %u != friend num in msger %u", dht_get_num_friends(m->dht), m->numfriends);
2717
1.09k
        }
2718
2719
3.28k
        for (uint32_t friend_idx = 0; friend_idx < num_dhtfriends; ++friend_idx) {
2720
2.19k
            const Friend *const msgfptr = dht2m[friend_idx] >= 0 ?  &m->friendlist[dht2m[friend_idx]] : nullptr;
2721
2.19k
            const DHT_Friend *const dhtfptr = dht_get_friend(m->dht, friend_idx);
2722
2723
2.19k
            if (msgfptr != nullptr) {
2724
0
                char id_str[IDSTRING_LEN];
2725
0
                LOGGER_TRACE(m->log, "F[%2u:%2u] <%s> %s",
2726
0
                             dht2m[friend_idx], friend_idx, msgfptr->name,
2727
0
                             id_to_string(msgfptr->real_pk, id_str, sizeof(id_str)));
2728
2.19k
            } else {
2729
2.19k
                char id_str[IDSTRING_LEN];
2730
2.19k
                LOGGER_TRACE(m->log, "F[--:%2u] %s", friend_idx,
2731
2.19k
                             id_to_string(dht_friend_public_key(dhtfptr), id_str, sizeof(id_str)));
2732
2.19k
            }
2733
2734
19.7k
            for (uint32_t client = 0; client < MAX_FRIEND_CLIENTS; ++client) {
2735
17.5k
                const Client_data *cptr = dht_friend_client(dhtfptr, client);
2736
17.5k
                const IPPTsPng *const assocs[] = {&cptr->assoc4, &cptr->assoc6};
2737
2738
52.6k
                for (size_t a = 0; a < sizeof(assocs) / sizeof(assocs[0]); ++a) {
2739
35.0k
                    const IPPTsPng *const assoc = assocs[a];
2740
2741
35.0k
                    if (ip_isset(&assoc->ip_port.ip)) {
2742
0
                        last_pinged = m->lastdump - assoc->last_pinged;
2743
2744
0
                        if (last_pinged > 999) {
2745
0
                            last_pinged = 999;
2746
0
                        }
2747
2748
0
                        Ip_Ntoa ip_str;
2749
0
                        char id_str[IDSTRING_LEN];
2750
0
                        LOGGER_TRACE(m->log, "F[%2u] => C[%2u] %s:%u [%3u] %s",
2751
0
                                     friend_idx, client, net_ip_ntoa(&assoc->ip_port.ip, &ip_str),
2752
0
                                     net_ntohs(assoc->ip_port.port), last_pinged,
2753
0
                                     id_to_string(cptr->public_key, id_str, sizeof(id_str)));
2754
0
                    }
2755
35.0k
                }
2756
17.5k
            }
2757
2.19k
        }
2758
1.09k
    }
2759
72.6k
}
2760
2761
/** new messenger format for load/save, more robust and forward compatible */
2762
2763
25
#define SAVED_FRIEND_REQUEST_SIZE 1024
2764
6.31k
#define NUM_SAVED_PATH_NODES 8
2765
2766
struct Saved_Friend {
2767
    uint8_t status;
2768
    uint8_t real_pk[CRYPTO_PUBLIC_KEY_SIZE];
2769
    uint8_t info[SAVED_FRIEND_REQUEST_SIZE]; // the data that is sent during the friend requests we do.
2770
    uint16_t info_size; // Length of the info.
2771
    uint8_t name[MAX_NAME_LENGTH];
2772
    uint16_t name_length;
2773
    uint8_t statusmessage[MAX_STATUSMESSAGE_LENGTH];
2774
    uint16_t statusmessage_length;
2775
    uint8_t userstatus;
2776
    uint32_t friendrequest_nospam;
2777
    uint8_t last_seen_time[sizeof(uint64_t)];
2778
};
2779
2780
static uint32_t friend_size(void)
2781
6.54k
{
2782
6.54k
    uint32_t data = 0;
2783
6.54k
    const struct Saved_Friend *const temp = nullptr;
2784
2785
6.54k
#define VALUE_MEMBER(data, name) \
2786
39.2k
    do {                         \
2787
39.2k
        data += sizeof(name);    \
2788
39.2k
    } while (0)
2789
6.54k
#define ARRAY_MEMBER(data, name) \
2790
32.7k
    do {                         \
2791
32.7k
        data += sizeof(name);    \
2792
32.7k
    } while (0)
2793
2794
    // Exactly the same in friend_load, friend_save, and friend_size
2795
6.54k
    VALUE_MEMBER(data, temp->status);
2796
6.54k
    ARRAY_MEMBER(data, temp->real_pk);
2797
6.54k
    ARRAY_MEMBER(data, temp->info);
2798
6.54k
    ++data; // padding
2799
6.54k
    VALUE_MEMBER(data, temp->info_size);
2800
6.54k
    ARRAY_MEMBER(data, temp->name);
2801
6.54k
    VALUE_MEMBER(data, temp->name_length);
2802
6.54k
    ARRAY_MEMBER(data, temp->statusmessage);
2803
6.54k
    ++data; // padding
2804
6.54k
    VALUE_MEMBER(data, temp->statusmessage_length);
2805
6.54k
    VALUE_MEMBER(data, temp->userstatus);
2806
6.54k
    data += 3; // padding
2807
6.54k
    VALUE_MEMBER(data, temp->friendrequest_nospam);
2808
6.54k
    ARRAY_MEMBER(data, temp->last_seen_time);
2809
2810
6.54k
#undef VALUE_MEMBER
2811
6.54k
#undef ARRAY_MEMBER
2812
2813
6.54k
    return data;
2814
6.54k
}
2815
2816
non_null()
2817
static uint8_t *friend_save(const struct Saved_Friend *temp, uint8_t *data)
2818
128
{
2819
128
#define VALUE_MEMBER(data, name)           \
2820
768
    do {                                   \
2821
768
        memcpy(data, &name, sizeof(name)); \
2822
768
        data += sizeof(name);              \
2823
768
    } while (0)
2824
2825
128
#define ARRAY_MEMBER(data, name)          \
2826
640
    do {                                  \
2827
640
        memcpy(data, name, sizeof(name)); \
2828
640
        data += sizeof(name);             \
2829
640
    } while (0)
2830
2831
    // Exactly the same in friend_load, friend_save, and friend_size
2832
128
    VALUE_MEMBER(data, temp->status);
2833
128
    ARRAY_MEMBER(data, temp->real_pk);
2834
128
    ARRAY_MEMBER(data, temp->info);
2835
128
    ++data; // padding
2836
128
    VALUE_MEMBER(data, temp->info_size);
2837
128
    ARRAY_MEMBER(data, temp->name);
2838
128
    VALUE_MEMBER(data, temp->name_length);
2839
128
    ARRAY_MEMBER(data, temp->statusmessage);
2840
128
    ++data; // padding
2841
128
    VALUE_MEMBER(data, temp->statusmessage_length);
2842
128
    VALUE_MEMBER(data, temp->userstatus);
2843
128
    data += 3; // padding
2844
128
    VALUE_MEMBER(data, temp->friendrequest_nospam);
2845
128
    ARRAY_MEMBER(data, temp->last_seen_time);
2846
2847
128
#undef VALUE_MEMBER
2848
128
#undef ARRAY_MEMBER
2849
2850
128
    return data;
2851
128
}
2852
2853
2854
non_null()
2855
static const uint8_t *friend_load(struct Saved_Friend *temp, const uint8_t *data)
2856
517
{
2857
517
#define VALUE_MEMBER(data, name)           \
2858
3.10k
    do {                                   \
2859
3.10k
        memcpy(&name, data, sizeof(name)); \
2860
3.10k
        data += sizeof(name);              \
2861
3.10k
    } while (0)
2862
2863
517
#define ARRAY_MEMBER(data, name)          \
2864
2.58k
    do {                                  \
2865
2.58k
        memcpy(name, data, sizeof(name)); \
2866
2.58k
        data += sizeof(name);             \
2867
2.58k
    } while (0)
2868
2869
    // Exactly the same in friend_load, friend_save, and friend_size
2870
517
    VALUE_MEMBER(data, temp->status);
2871
517
    ARRAY_MEMBER(data, temp->real_pk);
2872
517
    ARRAY_MEMBER(data, temp->info);
2873
517
    ++data; // padding
2874
517
    VALUE_MEMBER(data, temp->info_size);
2875
517
    ARRAY_MEMBER(data, temp->name);
2876
517
    VALUE_MEMBER(data, temp->name_length);
2877
517
    ARRAY_MEMBER(data, temp->statusmessage);
2878
517
    ++data; // padding
2879
517
    VALUE_MEMBER(data, temp->statusmessage_length);
2880
517
    VALUE_MEMBER(data, temp->userstatus);
2881
517
    data += 3; // padding
2882
517
    VALUE_MEMBER(data, temp->friendrequest_nospam);
2883
517
    ARRAY_MEMBER(data, temp->last_seen_time);
2884
2885
517
#undef VALUE_MEMBER
2886
517
#undef ARRAY_MEMBER
2887
2888
517
    return data;
2889
517
}
2890
2891
2892
non_null()
2893
static uint32_t m_state_plugins_size(const Messenger *m)
2894
3.01k
{
2895
3.01k
    const uint32_t size32 = sizeof(uint32_t);
2896
3.01k
    const uint32_t sizesubhead = size32 * 2;
2897
2898
3.01k
    uint32_t size = 0;
2899
2900
3.01k
    for (const Messenger_State_Plugin *plugin = m->options.state_plugins;
2901
30.1k
            plugin != m->options.state_plugins + m->options.state_plugins_length;
2902
27.1k
            ++plugin) {
2903
27.1k
        size += sizesubhead + plugin->size(m);
2904
27.1k
    }
2905
2906
3.01k
    return size;
2907
3.01k
}
2908
2909
/** @brief Registers a state plugin for saving, loading, and getting the size of a section of the save.
2910
 *
2911
 * @retval true on success
2912
 * @retval false on error
2913
 */
2914
bool m_register_state_plugin(Messenger *m, State_Type type, m_state_size_cb *size_callback,
2915
                             m_state_load_cb *load_callback,
2916
                             m_state_save_cb *save_callback)
2917
27.6k
{
2918
27.6k
    const uint32_t new_length = m->options.state_plugins_length + 1;
2919
27.6k
    Messenger_State_Plugin *temp = (Messenger_State_Plugin *)mem_vrealloc(
2920
27.6k
            m->mem, m->options.state_plugins, new_length, sizeof(Messenger_State_Plugin));
2921
2922
27.6k
    if (temp == nullptr) {
2923
3.40k
        return false;
2924
3.40k
    }
2925
2926
24.2k
    m->options.state_plugins = temp;
2927
24.2k
    m->options.state_plugins_length = new_length;
2928
2929
24.2k
    const uint8_t index = m->options.state_plugins_length - 1;
2930
24.2k
    m->options.state_plugins[index].type = type;
2931
24.2k
    m->options.state_plugins[index].size = size_callback;
2932
24.2k
    m->options.state_plugins[index].load = load_callback;
2933
24.2k
    m->options.state_plugins[index].save = save_callback;
2934
2935
24.2k
    return true;
2936
27.6k
}
2937
2938
non_null()
2939
static uint32_t m_plugin_size(const Messenger *m, State_Type type)
2940
9.86k
{
2941
34.2k
    for (uint8_t i = 0; i < m->options.state_plugins_length; ++i) {
2942
34.2k
        const Messenger_State_Plugin plugin = m->options.state_plugins[i];
2943
2944
34.2k
        if (plugin.type == type) {
2945
9.86k
            return plugin.size(m);
2946
9.86k
        }
2947
34.2k
    }
2948
2949
0
    LOGGER_ERROR(m->log, "Unknown type encountered: %u", type);
2950
2951
0
    return UINT32_MAX;
2952
9.86k
}
2953
2954
/** return size of the messenger data (for saving). */
2955
uint32_t messenger_size(const Messenger *m)
2956
3.01k
{
2957
3.01k
    return m_state_plugins_size(m);
2958
3.01k
}
2959
2960
/** Save the messenger in data (must be allocated memory of size at least `Messenger_size()`) */
2961
uint8_t *messenger_save(const Messenger *m, uint8_t *data)
2962
1.50k
{
2963
15.0k
    for (uint8_t i = 0; i < m->options.state_plugins_length; ++i) {
2964
13.5k
        const Messenger_State_Plugin plugin = m->options.state_plugins[i];
2965
13.5k
        data = plugin.save(m, data);
2966
13.5k
    }
2967
2968
1.50k
    return data;
2969
1.50k
}
2970
2971
// nospam state plugin
2972
non_null()
2973
static uint32_t nospam_keys_size(const Messenger *m)
2974
5.05k
{
2975
5.05k
    return sizeof(uint32_t) + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SECRET_KEY_SIZE;
2976
5.05k
}
2977
2978
non_null()
2979
static State_Load_Status load_nospam_keys(Messenger *m, const uint8_t *data, uint32_t length)
2980
533
{
2981
533
    if (length != m_plugin_size(m, STATE_TYPE_NOSPAMKEYS)) {
2982
1
        return STATE_LOAD_STATUS_ERROR;
2983
1
    }
2984
2985
532
    uint32_t nospam;
2986
532
    lendian_bytes_to_host32(&nospam, data);
2987
532
    set_nospam(m->fr, nospam);
2988
532
    load_secret_key(m->net_crypto, data + sizeof(uint32_t) + CRYPTO_PUBLIC_KEY_SIZE);
2989
2990
532
    if (!pk_equal(data + sizeof(uint32_t), nc_get_self_public_key(m->net_crypto))) {
2991
3
        LOGGER_ERROR(m->log, "public key stored in savedata does not match its secret key");
2992
3
        return STATE_LOAD_STATUS_ERROR;
2993
3
    }
2994
2995
529
    return STATE_LOAD_STATUS_CONTINUE;
2996
532
}
2997
2998
non_null()
2999
static uint8_t *save_nospam_keys(const Messenger *m, uint8_t *data)
3000
1.50k
{
3001
1.50k
    const uint32_t len = m_plugin_size(m, STATE_TYPE_NOSPAMKEYS);
3002
1.50k
    static_assert(sizeof(get_nospam(m->fr)) == sizeof(uint32_t), "nospam doesn't fit in a 32 bit int");
3003
1.50k
    data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_NOSPAMKEYS);
3004
1.50k
    const uint32_t nospam = get_nospam(m->fr);
3005
1.50k
    host_to_lendian_bytes32(data, nospam);
3006
1.50k
    save_keys(m->net_crypto, data + sizeof(uint32_t));
3007
1.50k
    data += len;
3008
1.50k
    return data;
3009
1.50k
}
3010
3011
// DHT state plugin
3012
non_null()
3013
static uint32_t m_dht_size(const Messenger *m)
3014
4.52k
{
3015
4.52k
    return dht_size(m->dht);
3016
4.52k
}
3017
3018
non_null()
3019
static uint8_t *save_dht(const Messenger *m, uint8_t *data)
3020
1.50k
{
3021
1.50k
    const uint32_t len = m_plugin_size(m, STATE_TYPE_DHT);
3022
1.50k
    data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_DHT);
3023
1.50k
    dht_save(m->dht, data);
3024
1.50k
    data += len;
3025
1.50k
    return data;
3026
1.50k
}
3027
3028
non_null()
3029
static State_Load_Status m_dht_load(Messenger *m, const uint8_t *data, uint32_t length)
3030
675
{
3031
675
    dht_load(m->dht, data, length); // TODO(endoffile78): Should we throw an error if dht_load fails?
3032
675
    return STATE_LOAD_STATUS_CONTINUE;
3033
675
}
3034
3035
// friendlist state plugin
3036
non_null()
3037
static uint32_t saved_friendslist_size(const Messenger *m)
3038
4.52k
{
3039
4.52k
    return count_friendlist(m) * friend_size();
3040
4.52k
}
3041
3042
non_null()
3043
static uint8_t *friends_list_save(const Messenger *m, uint8_t *data)
3044
1.50k
{
3045
1.50k
    const uint32_t len = m_plugin_size(m, STATE_TYPE_FRIENDS);
3046
1.50k
    data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_FRIENDS);
3047
3048
1.50k
    uint32_t num = 0;
3049
1.50k
    uint8_t *cur_data = data;
3050
3051
1.63k
    for (uint32_t i = 0; i < m->numfriends; ++i) {
3052
128
        if (m->friendlist[i].status > 0) {
3053
128
            struct Saved_Friend temp = { 0 };
3054
128
            temp.status = m->friendlist[i].status;
3055
128
            memcpy(temp.real_pk, m->friendlist[i].real_pk, CRYPTO_PUBLIC_KEY_SIZE);
3056
3057
128
            if (temp.status < 3) {
3058
                // TODO(iphydf): Use uint16_t and min_u16 here.
3059
25
                const size_t friendrequest_length =
3060
25
                    min_u32(m->friendlist[i].info_size,
3061
25
                            min_u32(SAVED_FRIEND_REQUEST_SIZE, MAX_FRIEND_REQUEST_DATA_SIZE));
3062
25
                memcpy(temp.info, m->friendlist[i].info, friendrequest_length);
3063
3064
25
                temp.info_size = net_htons(m->friendlist[i].info_size);
3065
25
                temp.friendrequest_nospam = m->friendlist[i].friendrequest_nospam;
3066
103
            } else {
3067
103
                temp.status = 3;
3068
103
                memcpy(temp.name, m->friendlist[i].name, m->friendlist[i].name_length);
3069
103
                temp.name_length = net_htons(m->friendlist[i].name_length);
3070
103
                memcpy(temp.statusmessage, m->friendlist[i].statusmessage, m->friendlist[i].statusmessage_length);
3071
103
                temp.statusmessage_length = net_htons(m->friendlist[i].statusmessage_length);
3072
103
                temp.userstatus = m->friendlist[i].userstatus;
3073
3074
103
                net_pack_u64(temp.last_seen_time, m->friendlist[i].last_seen_time);
3075
103
            }
3076
3077
128
            uint8_t *next_data = friend_save(&temp, cur_data);
3078
128
            assert(next_data - cur_data == friend_size());
3079
0
#ifdef __LP64__
3080
0
            assert(memcmp(cur_data, &temp, friend_size()) == 0);
3081
0
#endif
3082
0
            cur_data = next_data;
3083
128
            ++num;
3084
128
        }
3085
128
    }
3086
3087
1.50k
    assert(cur_data - data == num * friend_size());
3088
0
    data += len;
3089
3090
1.50k
    return data;
3091
1.50k
}
3092
3093
non_null()
3094
static State_Load_Status friends_list_load(Messenger *m, const uint8_t *data, uint32_t length)
3095
265
{
3096
265
    const uint32_t l_friend_size = friend_size();
3097
3098
265
    if (length % l_friend_size != 0) {
3099
1
        return STATE_LOAD_STATUS_ERROR; // TODO(endoffile78): error or continue?
3100
1
    }
3101
3102
264
    const uint32_t num = length / l_friend_size;
3103
264
    const uint8_t *cur_data = data;
3104
3105
781
    for (uint32_t i = 0; i < num; ++i) {
3106
517
        struct Saved_Friend temp = { 0 };
3107
517
        const uint8_t *next_data = friend_load(&temp, cur_data);
3108
517
        assert(next_data - cur_data == l_friend_size);
3109
3110
0
        cur_data = next_data;
3111
3112
517
        if (temp.status >= 3) {
3113
305
            const int fnum = m_addfriend_norequest(m, temp.real_pk);
3114
3115
305
            if (fnum < 0) {
3116
49
                continue;
3117
49
            }
3118
3119
256
            setfriendname(m, fnum, temp.name, net_ntohs(temp.name_length));
3120
256
            set_friend_statusmessage(m, fnum, temp.statusmessage, net_ntohs(temp.statusmessage_length));
3121
256
            set_friend_userstatus(m, fnum, temp.userstatus);
3122
256
            net_unpack_u64(temp.last_seen_time, &m->friendlist[fnum].last_seen_time);
3123
256
        } else if (temp.status != 0) {
3124
            /* TODO(irungentoo): This is not a good way to do this. */
3125
130
            uint8_t address[FRIEND_ADDRESS_SIZE];
3126
130
            pk_copy(address, temp.real_pk);
3127
130
            memcpy(address + CRYPTO_PUBLIC_KEY_SIZE, &temp.friendrequest_nospam, sizeof(uint32_t));
3128
130
            uint16_t checksum = data_checksum(address, FRIEND_ADDRESS_SIZE - sizeof(checksum));
3129
130
            memcpy(address + CRYPTO_PUBLIC_KEY_SIZE + sizeof(uint32_t), &checksum, sizeof(checksum));
3130
130
            m_addfriend(m, address, temp.info, net_ntohs(temp.info_size));
3131
130
        }
3132
517
    }
3133
3134
264
    return STATE_LOAD_STATUS_CONTINUE;
3135
265
}
3136
3137
#ifndef VANILLA_NACL
3138
non_null()
3139
static void pack_groupchats(const GC_Session *c, Bin_Pack *bp)
3140
3.59k
{
3141
3.59k
    assert(bp != nullptr && c != nullptr);
3142
0
    bin_pack_array(bp, gc_count_groups(c));
3143
3144
10.0k
    for (uint32_t i = 0; i < c->chats_index; ++i) { // this loop must match the one in gc_count_groups()
3145
6.44k
        const GC_Chat *chat = &c->chats[i];
3146
3147
6.44k
        if (!gc_group_is_valid(chat)) {
3148
2.61k
            continue;
3149
2.61k
        }
3150
3151
3.83k
        gc_group_save(chat, bp);
3152
3.83k
    }
3153
3.59k
}
3154
3155
non_null()
3156
static bool pack_groupchats_handler(Bin_Pack *bp, const void *obj)
3157
3.59k
{
3158
3.59k
    pack_groupchats((const GC_Session *)obj, bp);
3159
3.59k
    return true;  // TODO(iphydf): Return bool from pack functions.
3160
3.59k
}
3161
3162
non_null()
3163
static uint32_t saved_groups_size(const Messenger *m)
3164
3.30k
{
3165
3.30k
    GC_Session *c = m->group_handler;
3166
3.30k
    return bin_pack_obj_size(pack_groupchats_handler, c);
3167
3.30k
}
3168
3169
non_null()
3170
static uint8_t *groups_save(const Messenger *m, uint8_t *data)
3171
1.50k
{
3172
1.50k
    const GC_Session *c = m->group_handler;
3173
3174
1.50k
    const uint32_t num_groups = gc_count_groups(c);
3175
3176
1.50k
    if (num_groups == 0) {
3177
1.21k
        return data;
3178
1.21k
    }
3179
3180
292
    const uint32_t len = m_plugin_size(m, STATE_TYPE_GROUPS);
3181
3182
292
    if (len == 0) {
3183
0
        return data;
3184
0
    }
3185
3186
292
    data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_GROUPS);
3187
3188
292
    if (!bin_pack_obj(pack_groupchats_handler, c, data, len)) {
3189
0
        LOGGER_FATAL(m->log, "failed to pack group chats into buffer of length %u", len);
3190
0
        return data;
3191
0
    }
3192
3193
292
    data += len;
3194
3195
292
    LOGGER_DEBUG(m->log, "Saved %u groups (length %u)", num_groups, len);
3196
3197
292
    return data;
3198
292
}
3199
3200
non_null()
3201
static State_Load_Status groups_load(Messenger *m, const uint8_t *data, uint32_t length)
3202
27.3k
{
3203
27.3k
    Bin_Unpack *bu = bin_unpack_new(data, length);
3204
27.3k
    if (bu == nullptr) {
3205
0
        LOGGER_ERROR(m->log, "failed to allocate binary unpacker");
3206
0
        return STATE_LOAD_STATUS_ERROR;
3207
0
    }
3208
3209
27.3k
    uint32_t num_groups;
3210
27.3k
    if (!bin_unpack_array(bu, &num_groups)) {
3211
57
        LOGGER_ERROR(m->log, "msgpack failed to unpack groupchats array: expected array");
3212
57
        bin_unpack_free(bu);
3213
57
        return STATE_LOAD_STATUS_ERROR;
3214
57
    }
3215
3216
27.2k
    LOGGER_DEBUG(m->log, "Loading %u groups (length %u)", num_groups, length);
3217
3218
27.4k
    for (uint32_t i = 0; i < num_groups; ++i) {
3219
27.4k
        const int group_number = gc_group_load(m->group_handler, bu);
3220
3221
27.4k
        if (group_number < 0) {
3222
27.1k
            LOGGER_WARNING(m->log, "Failed to load group %u", i);
3223
            // Can't recover trivially. We may need to skip over some data here.
3224
27.1k
            break;
3225
27.1k
        }
3226
27.4k
    }
3227
3228
27.2k
    LOGGER_DEBUG(m->log, "Successfully loaded %u groups", gc_count_groups(m->group_handler));
3229
3230
27.2k
    bin_unpack_free(bu);
3231
3232
27.2k
    return STATE_LOAD_STATUS_CONTINUE;
3233
27.3k
}
3234
#endif /* VANILLA_NACL */
3235
3236
// name state plugin
3237
non_null()
3238
static uint32_t name_size(const Messenger *m)
3239
4.52k
{
3240
4.52k
    return m->name_length;
3241
4.52k
}
3242
3243
non_null()
3244
static uint8_t *save_name(const Messenger *m, uint8_t *data)
3245
1.50k
{
3246
1.50k
    const uint32_t len = m_plugin_size(m, STATE_TYPE_NAME);
3247
1.50k
    data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_NAME);
3248
1.50k
    memcpy(data, m->name, len);
3249
1.50k
    data += len;
3250
1.50k
    return data;
3251
1.50k
}
3252
3253
non_null()
3254
static State_Load_Status load_name(Messenger *m, const uint8_t *data, uint32_t length)
3255
427
{
3256
427
    if (length > 0 && length <= MAX_NAME_LENGTH) {
3257
295
        setname(m, data, length);
3258
295
    }
3259
3260
427
    return STATE_LOAD_STATUS_CONTINUE;
3261
427
}
3262
3263
// status message state plugin
3264
non_null()
3265
static uint32_t status_message_size(const Messenger *m)
3266
4.52k
{
3267
4.52k
    return m->statusmessage_length;
3268
4.52k
}
3269
3270
non_null()
3271
static uint8_t *save_status_message(const Messenger *m, uint8_t *data)
3272
1.50k
{
3273
1.50k
    const uint32_t len = m_plugin_size(m, STATE_TYPE_STATUSMESSAGE);
3274
1.50k
    data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_STATUSMESSAGE);
3275
1.50k
    memcpy(data, m->statusmessage, len);
3276
1.50k
    data += len;
3277
1.50k
    return data;
3278
1.50k
}
3279
3280
non_null()
3281
static State_Load_Status load_status_message(Messenger *m, const uint8_t *data, uint32_t length)
3282
722
{
3283
722
    if (length > 0 && length <= MAX_STATUSMESSAGE_LENGTH) {
3284
646
        m_set_statusmessage(m, data, length);
3285
646
    }
3286
3287
722
    return STATE_LOAD_STATUS_CONTINUE;
3288
722
}
3289
3290
// status state plugin
3291
non_null()
3292
static uint32_t status_size(const Messenger *m)
3293
4.52k
{
3294
4.52k
    return 1;
3295
4.52k
}
3296
3297
non_null()
3298
static uint8_t *save_status(const Messenger *m, uint8_t *data)
3299
1.50k
{
3300
1.50k
    const uint32_t len = m_plugin_size(m, STATE_TYPE_STATUS);
3301
1.50k
    data = state_write_section_header(data, STATE_COOKIE_TYPE, len, STATE_TYPE_STATUS);
3302
1.50k
    *data = m->userstatus;
3303
1.50k
    data += len;
3304
1.50k
    return data;
3305
1.50k
}
3306
3307
non_null()
3308
static State_Load_Status load_status(Messenger *m, const uint8_t *data, uint32_t length)
3309
594
{
3310
594
    if (length == 1) {
3311
551
        m_set_userstatus(m, *data);
3312
551
    }
3313
3314
594
    return STATE_LOAD_STATUS_CONTINUE;
3315
594
}
3316
3317
// TCP Relay state plugin
3318
non_null()
3319
static uint32_t tcp_relay_size(const Messenger *m)
3320
3.01k
{
3321
3.01k
    return NUM_SAVED_TCP_RELAYS * packed_node_size(net_family_tcp_ipv6());
3322
3.01k
}
3323
3324
non_null()
3325
static uint8_t *save_tcp_relays(const Messenger *m, uint8_t *data)
3326
1.50k
{
3327
1.50k
    Node_format relays[NUM_SAVED_TCP_RELAYS] = {{{0}}};
3328
1.50k
    uint8_t *temp_data = data;
3329
1.50k
    data = state_write_section_header(temp_data, STATE_COOKIE_TYPE, 0, STATE_TYPE_TCP_RELAY);
3330
3331
1.50k
    if (m->num_loaded_relays > 0) {
3332
26
        memcpy(relays, m->loaded_relays, sizeof(Node_format) * m->num_loaded_relays);
3333
26
    }
3334
3335
1.50k
    uint32_t num = m->num_loaded_relays;
3336
1.50k
    num += copy_connected_tcp_relays(m->net_crypto, relays + num, NUM_SAVED_TCP_RELAYS - num);
3337
3338
1.50k
    const int l = pack_nodes(m->log, data, NUM_SAVED_TCP_RELAYS * packed_node_size(net_family_tcp_ipv6()), relays, num);
3339
3340
1.50k
    if (l > 0) {
3341
26
        const uint32_t len = l;
3342
26
        data = state_write_section_header(temp_data, STATE_COOKIE_TYPE, len, STATE_TYPE_TCP_RELAY);
3343
26
        data += len;
3344
26
    }
3345
3346
1.50k
    return data;
3347
1.50k
}
3348
3349
non_null()
3350
static State_Load_Status load_tcp_relays(Messenger *m, const uint8_t *data, uint32_t length)
3351
657
{
3352
657
    if (length > 0) {
3353
591
        const int num = unpack_nodes(m->loaded_relays, NUM_SAVED_TCP_RELAYS, nullptr, data, length, true);
3354
3355
591
        if (num == -1) {
3356
216
            m->num_loaded_relays = 0;
3357
216
            return STATE_LOAD_STATUS_CONTINUE;
3358
216
        }
3359
3360
375
        m->num_loaded_relays = num;
3361
375
        m->has_added_relays = false;
3362
375
    }
3363
3364
441
    return STATE_LOAD_STATUS_CONTINUE;
3365
657
}
3366
3367
// path node state plugin
3368
non_null()
3369
static uint32_t path_node_size(const Messenger *m)
3370
3.01k
{
3371
3.01k
    return NUM_SAVED_PATH_NODES * packed_node_size(net_family_tcp_ipv6());
3372
3.01k
}
3373
3374
non_null()
3375
static uint8_t *save_path_nodes(const Messenger *m, uint8_t *data)
3376
1.50k
{
3377
1.50k
    Node_format nodes[NUM_SAVED_PATH_NODES];
3378
1.50k
    uint8_t *temp_data = data;
3379
1.50k
    data = state_write_section_header(data, STATE_COOKIE_TYPE, 0, STATE_TYPE_PATH_NODE);
3380
1.50k
    memset(nodes, 0, sizeof(nodes));
3381
1.50k
    const unsigned int num = onion_backup_nodes(m->onion_c, nodes, NUM_SAVED_PATH_NODES);
3382
1.50k
    const int l = pack_nodes(m->log, data, NUM_SAVED_PATH_NODES * packed_node_size(net_family_tcp_ipv6()), nodes, num);
3383
3384
1.50k
    if (l > 0) {
3385
31
        const uint32_t len = l;
3386
31
        data = state_write_section_header(temp_data, STATE_COOKIE_TYPE, len, STATE_TYPE_PATH_NODE);
3387
31
        data += len;
3388
31
    }
3389
3390
1.50k
    return data;
3391
1.50k
}
3392
3393
non_null()
3394
static State_Load_Status load_path_nodes(Messenger *m, const uint8_t *data, uint32_t length)
3395
351
{
3396
351
    if (length > 0) {
3397
283
        Node_format nodes[NUM_SAVED_PATH_NODES];
3398
283
        const int num = unpack_nodes(nodes, NUM_SAVED_PATH_NODES, nullptr, data, length, false);
3399
3400
283
        if (num == -1) {
3401
102
            return STATE_LOAD_STATUS_CONTINUE;
3402
102
        }
3403
3404
1.57k
        for (int i = 0; i < num; ++i) {
3405
1.38k
            onion_add_bs_path_node(m->onion_c, &nodes[i].ip_port, nodes[i].public_key);
3406
1.38k
        }
3407
181
    }
3408
3409
249
    return STATE_LOAD_STATUS_CONTINUE;
3410
351
}
3411
3412
non_null()
3413
static void m_register_default_plugins(Messenger *m)
3414
3.07k
{
3415
3.07k
    m_register_state_plugin(m, STATE_TYPE_NOSPAMKEYS, nospam_keys_size, load_nospam_keys, save_nospam_keys);
3416
3.07k
    m_register_state_plugin(m, STATE_TYPE_DHT, m_dht_size, m_dht_load, save_dht);
3417
3.07k
    m_register_state_plugin(m, STATE_TYPE_FRIENDS, saved_friendslist_size, friends_list_load, friends_list_save);
3418
3.07k
    m_register_state_plugin(m, STATE_TYPE_NAME, name_size, load_name, save_name);
3419
3.07k
    m_register_state_plugin(m, STATE_TYPE_STATUSMESSAGE, status_message_size, load_status_message,
3420
3.07k
                            save_status_message);
3421
3.07k
    m_register_state_plugin(m, STATE_TYPE_STATUS, status_size, load_status, save_status);
3422
3.07k
#ifndef VANILLA_NACL
3423
3.07k
    m_register_state_plugin(m, STATE_TYPE_GROUPS, saved_groups_size, groups_load, groups_save);
3424
3.07k
#endif
3425
3.07k
    m_register_state_plugin(m, STATE_TYPE_TCP_RELAY, tcp_relay_size, load_tcp_relays, save_tcp_relays);
3426
3.07k
    m_register_state_plugin(m, STATE_TYPE_PATH_NODE, path_node_size, load_path_nodes, save_path_nodes);
3427
3.07k
}
3428
3429
bool messenger_load_state_section(Messenger *m, const uint8_t *data, uint32_t length, uint16_t type,
3430
                                  State_Load_Status *status)
3431
32.3k
{
3432
219k
    for (uint8_t i = 0; i < m->options.state_plugins_length; ++i) {
3433
218k
        const Messenger_State_Plugin *const plugin = &m->options.state_plugins[i];
3434
3435
218k
        if (plugin->type == type) {
3436
31.5k
            *status = plugin->load(m, data, length);
3437
31.5k
            return true;
3438
31.5k
        }
3439
218k
    }
3440
3441
803
    return false;
3442
32.3k
}
3443
3444
/** @brief Return the number of friends in the instance m.
3445
 *
3446
 * You should use this to determine how much memory to allocate
3447
 * for copy_friendlist.
3448
 */
3449
uint32_t count_friendlist(const Messenger *m)
3450
4.52k
{
3451
4.52k
    uint32_t ret = 0;
3452
3453
4.90k
    for (uint32_t i = 0; i < m->numfriends; ++i) {
3454
384
        if (m->friendlist[i].status > 0) {
3455
384
            ++ret;
3456
384
        }
3457
384
    }
3458
3459
4.52k
    return ret;
3460
4.52k
}
3461
3462
/** @brief Copy a list of valid friend IDs into the array out_list.
3463
 * If out_list is NULL, returns 0.
3464
 * Otherwise, returns the number of elements copied.
3465
 * If the array was too small, the contents
3466
 * of out_list will be truncated to list_size.
3467
 */
3468
uint32_t copy_friendlist(Messenger const *m, uint32_t *out_list, uint32_t list_size)
3469
0
{
3470
0
    if (out_list == nullptr) {
3471
0
        return 0;
3472
0
    }
3473
3474
0
    if (m->numfriends == 0) {
3475
0
        return 0;
3476
0
    }
3477
3478
0
    uint32_t ret = 0;
3479
3480
0
    for (uint32_t i = 0; i < m->numfriends; ++i) {
3481
0
        if (ret >= list_size) {
3482
0
            break; /* Abandon ship */
3483
0
        }
3484
3485
0
        if (m->friendlist[i].status > 0) {
3486
0
            out_list[ret] = i;
3487
0
            ++ret;
3488
0
        }
3489
0
    }
3490
3491
0
    return ret;
3492
0
}
3493
3494
static fr_friend_request_cb m_handle_friend_request;
3495
non_null(1, 2, 3) nullable(5)
3496
static void m_handle_friend_request(
3497
    void *object, const uint8_t *public_key, const uint8_t *message, size_t length, void *user_data)
3498
128
{
3499
128
    Messenger *m = (Messenger *)object;
3500
128
    assert(m != nullptr);
3501
0
    m->friend_request(m, public_key, message, length, user_data);
3502
128
}
3503
3504
/** @brief Run this at startup.
3505
 *
3506
 * @return allocated instance of Messenger on success.
3507
 * @retval 0 if there are problems.
3508
 *
3509
 * if error is not NULL it will be set to one of the values in the enum above.
3510
 */
3511
Messenger *new_messenger(Mono_Time *mono_time, const Memory *mem, const Random *rng, const Network *ns,
3512
                         Messenger_Options *options, Messenger_Error *error)
3513
3.10k
{
3514
3.10k
    if (options == nullptr) {
3515
0
        return nullptr;
3516
0
    }
3517
3518
3.10k
    if (error != nullptr) {
3519
3.10k
        *error = MESSENGER_ERROR_OTHER;
3520
3.10k
    }
3521
3522
3.10k
    Messenger *m = (Messenger *)mem_alloc(mem, sizeof(Messenger));
3523
3524
3.10k
    if (m == nullptr) {
3525
1
        return nullptr;
3526
1
    }
3527
3528
3.10k
    m->mono_time = mono_time;
3529
3.10k
    m->mem = mem;
3530
3.10k
    m->rng = rng;
3531
3.10k
    m->ns = ns;
3532
3533
3.10k
    m->fr = friendreq_new();
3534
3535
3.10k
    if (m->fr == nullptr) {
3536
0
        mem_delete(mem, m);
3537
0
        return nullptr;
3538
0
    }
3539
3540
3.10k
    m->log = logger_new();
3541
3542
3.10k
    if (m->log == nullptr) {
3543
0
        friendreq_kill(m->fr);
3544
0
        mem_delete(mem, m);
3545
0
        return nullptr;
3546
0
    }
3547
3548
3.10k
    logger_callback_log(m->log, options->log_callback, options->log_context, options->log_user_data);
3549
3550
3.10k
    unsigned int net_err = 0;
3551
3552
3.10k
    if (!options->udp_disabled && options->proxy_info.proxy_type != TCP_PROXY_NONE) {
3553
        // We don't currently support UDP over proxy.
3554
277
        LOGGER_INFO(m->log, "UDP enabled and proxy set: disabling UDP");
3555
277
        options->udp_disabled = true;
3556
277
    }
3557
3558
3.10k
    if (options->udp_disabled) {
3559
277
        m->net = new_networking_no_udp(m->log, m->mem, m->ns);
3560
2.82k
    } else {
3561
2.82k
        IP ip;
3562
2.82k
        ip_init(&ip, options->ipv6enabled);
3563
2.82k
        m->net = new_networking_ex(m->log, m->mem, m->ns, &ip, options->port_range[0], options->port_range[1], &net_err);
3564
2.82k
    }
3565
3566
3.10k
    if (m->net == nullptr) {
3567
2
        friendreq_kill(m->fr);
3568
2
        logger_kill(m->log);
3569
2
        mem_delete(mem, m);
3570
3571
2
        if (error != nullptr && net_err == 1) {
3572
0
            *error = MESSENGER_ERROR_PORT;
3573
0
        }
3574
3575
2
        return nullptr;
3576
2
    }
3577
3578
3.10k
    m->dht = new_dht(m->log, m->mem, m->rng, m->ns, m->mono_time, m->net, options->hole_punching_enabled, options->local_discovery_enabled);
3579
3580
3.10k
    if (m->dht == nullptr) {
3581
14
        kill_networking(m->net);
3582
14
        friendreq_kill(m->fr);
3583
14
        logger_kill(m->log);
3584
14
        mem_delete(mem, m);
3585
14
        return nullptr;
3586
14
    }
3587
3588
3.08k
    m->net_crypto = new_net_crypto(m->log, m->mem, m->rng, m->ns, m->mono_time, m->dht, &options->proxy_info);
3589
3590
3.08k
    if (m->net_crypto == nullptr) {
3591
2
        kill_dht(m->dht);
3592
2
        kill_networking(m->net);
3593
2
        friendreq_kill(m->fr);
3594
2
        logger_kill(m->log);
3595
2
        mem_delete(mem, m);
3596
2
        return nullptr;
3597
2
    }
3598
3599
3.08k
#ifndef VANILLA_NACL
3600
3.08k
    m->group_announce = new_gca_list();
3601
3602
3.08k
    if (m->group_announce == nullptr) {
3603
0
        kill_net_crypto(m->net_crypto);
3604
0
        kill_dht(m->dht);
3605
0
        kill_networking(m->net);
3606
0
        friendreq_kill(m->fr);
3607
0
        logger_kill(m->log);
3608
0
        mem_delete(mem, m);
3609
0
        return nullptr;
3610
0
    }
3611
3612
3.08k
#endif /* VANILLA_NACL */
3613
3614
3.08k
    if (options->dht_announcements_enabled) {
3615
3.08k
        m->forwarding = new_forwarding(m->log, m->rng, m->mono_time, m->dht);
3616
3.08k
        m->announce = new_announcements(m->log, m->mem, m->rng, m->mono_time, m->forwarding);
3617
3.08k
    } else {
3618
0
        m->forwarding = nullptr;
3619
0
        m->announce = nullptr;
3620
0
    }
3621
3622
3.08k
    m->onion = new_onion(m->log, m->mem, m->mono_time, m->rng, m->dht);
3623
3.08k
    m->onion_a = new_onion_announce(m->log, m->mem, m->rng, m->mono_time, m->dht);
3624
3.08k
    m->onion_c = new_onion_client(m->log, m->mem, m->rng, m->mono_time, m->net_crypto);
3625
3.08k
    m->fr_c = new_friend_connections(m->log, m->mono_time, m->ns, m->onion_c, options->local_discovery_enabled);
3626
3627
3.08k
    if ((options->dht_announcements_enabled && (m->forwarding == nullptr || m->announce == nullptr)) ||
3628
3.08k
            m->onion == nullptr || m->onion_a == nullptr || m->onion_c == nullptr || m->fr_c == nullptr) {
3629
11
        kill_onion(m->onion);
3630
11
        kill_onion_announce(m->onion_a);
3631
11
        kill_onion_client(m->onion_c);
3632
11
#ifndef VANILLA_NACL
3633
11
        kill_gca(m->group_announce);
3634
11
#endif /* VANILLA_NACL */
3635
11
        kill_friend_connections(m->fr_c);
3636
11
        kill_announcements(m->announce);
3637
11
        kill_forwarding(m->forwarding);
3638
11
        kill_net_crypto(m->net_crypto);
3639
11
        kill_dht(m->dht);
3640
11
        kill_networking(m->net);
3641
11
        friendreq_kill(m->fr);
3642
11
        logger_kill(m->log);
3643
11
        mem_delete(mem, m);
3644
11
        return nullptr;
3645
11
    }
3646
3647
3.07k
#ifndef VANILLA_NACL
3648
3.07k
    gca_onion_init(m->group_announce, m->onion_a);
3649
3650
3.07k
    m->group_handler = new_dht_groupchats(m);
3651
3652
3.07k
    if (m->group_handler == nullptr) {
3653
0
        kill_onion(m->onion);
3654
0
        kill_onion_announce(m->onion_a);
3655
0
        kill_onion_client(m->onion_c);
3656
0
        kill_gca(m->group_announce);
3657
0
        kill_friend_connections(m->fr_c);
3658
0
        kill_announcements(m->announce);
3659
0
        kill_forwarding(m->forwarding);
3660
0
        kill_net_crypto(m->net_crypto);
3661
0
        kill_dht(m->dht);
3662
0
        kill_networking(m->net);
3663
0
        friendreq_kill(m->fr);
3664
0
        logger_kill(m->log);
3665
0
        mem_delete(mem, m);
3666
0
        return nullptr;
3667
0
    }
3668
3669
3.07k
#endif /* VANILLA_NACL */
3670
3671
3.07k
    if (options->tcp_server_port != 0) {
3672
147
        m->tcp_server = new_tcp_server(m->log, m->mem, m->rng, m->ns, options->ipv6enabled, 1,
3673
147
                                       &options->tcp_server_port, dht_get_self_secret_key(m->dht),
3674
147
                                       m->onion, m->forwarding);
3675
3676
147
        if (m->tcp_server == nullptr) {
3677
2
            kill_onion(m->onion);
3678
2
            kill_onion_announce(m->onion_a);
3679
2
#ifndef VANILLA_NACL
3680
2
            kill_dht_groupchats(m->group_handler);
3681
2
#endif
3682
2
            kill_friend_connections(m->fr_c);
3683
2
            kill_onion_client(m->onion_c);
3684
2
#ifndef VANILLA_NACL
3685
2
            kill_gca(m->group_announce);
3686
2
#endif
3687
2
            kill_announcements(m->announce);
3688
2
            kill_forwarding(m->forwarding);
3689
2
            kill_net_crypto(m->net_crypto);
3690
2
            kill_dht(m->dht);
3691
2
            kill_networking(m->net);
3692
2
            friendreq_kill(m->fr);
3693
2
            logger_kill(m->log);
3694
2
            mem_delete(mem, m);
3695
3696
2
            if (error != nullptr) {
3697
2
                *error = MESSENGER_ERROR_TCP_SERVER;
3698
2
            }
3699
3700
2
            return nullptr;
3701
2
        }
3702
147
    }
3703
3704
3.07k
    m->options = *options;
3705
3.07k
    friendreq_init(m->fr, m->fr_c);
3706
3.07k
    set_nospam(m->fr, random_u32(m->rng));
3707
3.07k
    set_filter_function(m->fr, &friend_already_added, m);
3708
3709
3.07k
    m->lastdump = 0;
3710
3.07k
    m->is_receiving_file = 0;
3711
3712
3.07k
    m_register_default_plugins(m);
3713
3.07k
    callback_friendrequest(m->fr, m_handle_friend_request, m);
3714
3715
3.07k
    if (error != nullptr) {
3716
3.07k
        *error = MESSENGER_ERROR_NONE;
3717
3.07k
    }
3718
3719
3.07k
    return m;
3720
3.07k
}
3721
3722
/** @brief Run this before closing shop.
3723
 *
3724
 * Free all datastructures.
3725
 */
3726
void kill_messenger(Messenger *m)
3727
3.07k
{
3728
3.07k
    if (m == nullptr) {
3729
0
        return;
3730
0
    }
3731
3732
3.07k
    if (m->tcp_server != nullptr) {
3733
145
        kill_tcp_server(m->tcp_server);
3734
145
    }
3735
3736
3.07k
    kill_onion(m->onion);
3737
3.07k
    kill_onion_announce(m->onion_a);
3738
3.07k
#ifndef VANILLA_NACL
3739
3.07k
    kill_dht_groupchats(m->group_handler);
3740
3.07k
#endif
3741
3.07k
    kill_friend_connections(m->fr_c);
3742
3.07k
    kill_onion_client(m->onion_c);
3743
3.07k
#ifndef VANILLA_NACL
3744
3.07k
    kill_gca(m->group_announce);
3745
3.07k
#endif
3746
3.07k
    kill_announcements(m->announce);
3747
3.07k
    kill_forwarding(m->forwarding);
3748
3.07k
    kill_net_crypto(m->net_crypto);
3749
3.07k
    kill_dht(m->dht);
3750
3.07k
    kill_networking(m->net);
3751
3752
3.48k
    for (uint32_t i = 0; i < m->numfriends; ++i) {
3753
412
        clear_receipts(m, i);
3754
412
    }
3755
3756
3.07k
    logger_kill(m->log);
3757
3.07k
    mem_delete(m->mem, m->friendlist);
3758
3.07k
    friendreq_kill(m->fr);
3759
3760
3.07k
    mem_delete(m->mem, m->options.state_plugins);
3761
3.07k
    mem_delete(m->mem, m);
3762
3.07k
}
3763
3764
bool m_is_receiving_file(Messenger *m)
3765
0
{
3766
    // Only run the expensive loop below once every 64 tox_iterate calls.
3767
0
    const uint8_t skip_count = 64;
3768
3769
0
    if (m->is_receiving_file != 0) {
3770
0
        --m->is_receiving_file;
3771
0
        return true;
3772
0
    }
3773
3774
    // TODO(iphydf): This is a very expensive loop. Consider keeping track of
3775
    // the number of live file transfers.
3776
0
    for (size_t friend_number = 0; friend_number < m->numfriends; ++friend_number) {
3777
0
        for (size_t i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) {
3778
0
            if (m->friendlist[friend_number].file_receiving[i].status == FILESTATUS_TRANSFERRING) {
3779
0
                m->is_receiving_file = skip_count;
3780
0
                return true;
3781
0
            }
3782
0
        }
3783
0
    }
3784
3785
0
    return false;
3786
0
}