Skip to content

Commit

Permalink
Refactor kill_nonused_tcp()
Browse files Browse the repository at this point in the history
This makes the code a little more flat and renames some variables so it's easier
to understand. We also replace a VLA with a dynamically allocated array, and abort
the function at the start if we know that we won't be able to kill any connections
  • Loading branch information
JFreegman committed Dec 7, 2021
1 parent 1ce6aab commit 3578b1b
Showing 1 changed file with 30 additions and 16 deletions.
46 changes: 30 additions & 16 deletions toxcore/TCP_connection.c
Original file line number Diff line number Diff line change
Expand Up @@ -1438,43 +1438,57 @@ static void do_tcp_conns(const Logger *logger, TCP_Connections *tcp_c, void *use

static void kill_nonused_tcp(TCP_Connections *tcp_c)
{
if (tcp_c->tcp_connections_length == 0) {
const uint32_t num_tcp_connections = tcp_c->tcp_connections_length;

if (num_tcp_connections <= RECOMMENDED_FRIEND_TCP_CONNECTIONS) {
return;
}

uint32_t num_online = 0;
uint32_t num_kill = 0;
VLA(unsigned int, to_kill, tcp_c->tcp_connections_length);
uint32_t num_to_kill = 0;
uint32_t *to_kill = (uint32_t *)malloc(sizeof(uint32_t) * num_tcp_connections);

for (uint32_t i = 0; i < tcp_c->tcp_connections_length; ++i) {
if (to_kill == nullptr) {
return;
}

for (uint32_t i = 0; i < num_tcp_connections; ++i) {
TCP_con *tcp_con = get_tcp_connection(tcp_c, i);

if (tcp_con) {
if (tcp_con->status == TCP_CONN_CONNECTED) {
if (!tcp_con->onion && !tcp_con->lock_count
&& mono_time_is_timeout(tcp_c->mono_time, tcp_con->connected_time, TCP_CONNECTION_ANNOUNCE_TIMEOUT)) {
to_kill[num_kill] = i;
++num_kill;
}
if (tcp_con == nullptr) {
continue;
}

if (tcp_con->status == TCP_CONN_CONNECTED) {
++num_online;

++num_online;
if (tcp_con->onion || tcp_con->lock_count) { // connection is in use so we skip it
continue;
}

if (mono_time_is_timeout(tcp_c->mono_time, tcp_con->connected_time, TCP_CONNECTION_ANNOUNCE_TIMEOUT)) {
to_kill[num_to_kill] = i;
++num_to_kill;
}
}
}

if (num_online <= RECOMMENDED_FRIEND_TCP_CONNECTIONS) {
free(to_kill);
return;
}

uint32_t n = num_online - RECOMMENDED_FRIEND_TCP_CONNECTIONS;
const uint32_t max_kill_count = num_online - RECOMMENDED_FRIEND_TCP_CONNECTIONS;

if (n < num_kill) {
num_kill = n;
if (num_to_kill > max_kill_count) {
num_to_kill = max_kill_count;
}

for (uint32_t i = 0; i < num_kill; ++i) {
for (uint32_t i = 0; i < num_to_kill; ++i) {
kill_tcp_relay_connection(tcp_c, to_kill[i]);
}

free(to_kill);
}

void do_tcp_connections(const Logger *logger, TCP_Connections *tcp_c, void *userdata)
Expand Down

0 comments on commit 3578b1b

Please sign in to comment.