From e18504e17e03acec28e325bcc727701c04348276 Mon Sep 17 00:00:00 2001 From: iphydf Date: Wed, 29 Dec 2021 02:18:00 +0000 Subject: [PATCH] feat: Add back the `tox_loop` implementation for low latency. Copied code from https://github.com/TokTok/c-toxcore/pull/335. --- CMakeLists.txt | 1 + auto_tests/tox_loop_test.c | 104 +++++++++++ toxcore/Messenger.c | 29 +++ toxcore/Messenger.h | 16 ++ toxcore/TCP_client.c | 30 ++++ toxcore/TCP_client.h | 1 + toxcore/TCP_connection.c | 32 ++++ toxcore/TCP_connection.h | 4 + toxcore/network.c | 30 ++++ toxcore/network.h | 1 + toxcore/tox.c | 360 +++++++++++++++++++++++++++++++++++++ toxcore/tox.h | 70 ++++++++ 12 files changed, 678 insertions(+) create mode 100644 auto_tests/tox_loop_test.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 59ed2ffb7c..a2b5de9861 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -437,6 +437,7 @@ auto_test(send_message) auto_test(set_name) auto_test(set_status_message) auto_test(skeleton) +auto_test(tox_loop) auto_test(tox_many) auto_test(tox_many_tcp) auto_test(tox_one) diff --git a/auto_tests/tox_loop_test.c b/auto_tests/tox_loop_test.c new file mode 100644 index 0000000000..09d2910005 --- /dev/null +++ b/auto_tests/tox_loop_test.c @@ -0,0 +1,104 @@ +#include +#include +#include +#include + +#include "../toxcore/tox.h" + +#include "check_compat.h" + +#define TCP_RELAY_PORT 33448 +/* The Travis-CI container responds poorly to ::1 as a localhost address + * You're encouraged to -D FORCE_TESTS_IPV6 on a local test */ +#ifdef FORCE_TESTS_IPV6 +#define TOX_LOCALHOST "::1" +#else +#define TOX_LOCALHOST "127.0.0.1" +#endif + +typedef struct { + int start_count, stop_count; + pthread_mutex_t mutex; + Tox *tox; +} loop_test; + +static void tox_loop_cb_start(Tox *tox, void *user_data) +{ + loop_test *userdata = (loop_test *) user_data; + pthread_mutex_lock(&userdata->mutex); + userdata->start_count++; +} + +static void tox_loop_cb_stop(Tox *tox, void *user_data) +{ + loop_test *userdata = (loop_test *) user_data; + userdata->stop_count++; + pthread_mutex_unlock(&userdata->mutex); +} + +static void *tox_loop_worker(void *data) +{ + loop_test *userdata = (loop_test *) data; + tox_loop(userdata->tox, data, NULL); + return NULL; +} + +static void test_tox_loop(void) +{ + pthread_t worker, worker_tcp; + struct Tox_Options *opts = tox_options_new(NULL); + loop_test userdata; + uint8_t dpk[TOX_PUBLIC_KEY_SIZE]; + int retval; + + userdata.start_count = 0; + userdata.stop_count = 0; + pthread_mutex_init(&userdata.mutex, NULL); + + tox_options_set_tcp_port(opts, TCP_RELAY_PORT); + userdata.tox = tox_new(opts, NULL); + tox_callback_loop_begin(userdata.tox, tox_loop_cb_start); + tox_callback_loop_end(userdata.tox, tox_loop_cb_stop); + pthread_create(&worker, NULL, tox_loop_worker, &userdata); + + tox_self_get_dht_id(userdata.tox, dpk); + + tox_options_default(opts); + loop_test userdata_tcp; + userdata_tcp.start_count = 0; + userdata_tcp.stop_count = 0; + pthread_mutex_init(&userdata_tcp.mutex, NULL); + userdata_tcp.tox = tox_new(opts, NULL); + tox_callback_loop_begin(userdata_tcp.tox, tox_loop_cb_start); + tox_callback_loop_end(userdata_tcp.tox, tox_loop_cb_stop); + pthread_create(&worker_tcp, NULL, tox_loop_worker, &userdata_tcp); + + pthread_mutex_lock(&userdata_tcp.mutex); + TOX_ERR_BOOTSTRAP error; + ck_assert_msg(tox_add_tcp_relay(userdata_tcp.tox, TOX_LOCALHOST, TCP_RELAY_PORT, dpk, &error), "Add relay error, %i", + error); + ck_assert_msg(tox_bootstrap(userdata_tcp.tox, TOX_LOCALHOST, 33445, dpk, &error), "Bootstrap error, %i", error); + pthread_mutex_unlock(&userdata_tcp.mutex); + + sleep(10); + + tox_loop_stop(userdata.tox); + pthread_join(worker, (void **)(void *)&retval); + ck_assert_msg(retval == 0, "tox_loop didn't return 0"); + + tox_kill(userdata.tox); + ck_assert_msg(userdata.start_count == userdata.stop_count, "start and stop must match"); + + tox_loop_stop(userdata_tcp.tox); + pthread_join(worker_tcp, (void **)(void *)&retval); + ck_assert_msg(retval == 0, "tox_loop didn't return 0"); + + tox_kill(userdata_tcp.tox); + ck_assert_msg(userdata_tcp.start_count == userdata_tcp.stop_count, "start and stop must match"); +} + +int main(int argc, char *argv[]) +{ + test_tox_loop(); + return 0; +} diff --git a/toxcore/Messenger.c b/toxcore/Messenger.c index bf1a3c4016..f96aa81130 100644 --- a/toxcore/Messenger.c +++ b/toxcore/Messenger.c @@ -1892,6 +1892,29 @@ Messenger *new_messenger(Mono_Time *mono_time, Messenger_Options *options, unsig return nullptr; } + +#ifdef HAVE_LIBEV + m->dispatcher = ev_loop_new(0); +#elif defined(HAVE_LIBEVENT) +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) + evthread_use_windows_threads(); +#else + evthread_use_pthreads(); +#endif /* WIN32 || _WIN32 || __WIN32__ */ + m->dispatcher = event_base_new(); +#else + m->loop_run = false; +#endif /* HAVE_LIBEV */ + +#if defined(HAVE_LIBEV) || defined(HAVE_LIBEVENT) + + if (!m->dispatcher) { + free(m); + return NULL; + } + +#endif /* HAVE_LIBEV || HAVE_LIBEVENT */ + m->mono_time = mono_time; m->fr = friendreq_new(); @@ -2044,6 +2067,12 @@ void kill_messenger(Messenger *m) clear_receipts(m, i); } +#ifdef HAVE_LIBEV + ev_loop_destroy(m->dispatcher); +#elif defined(HAVE_LIBEVENT) + event_base_free(m->dispatcher); +#endif + logger_kill(m->log); free(m->friendlist); friendreq_kill(m->fr); diff --git a/toxcore/Messenger.h b/toxcore/Messenger.h index bbe1633a2f..8308141e3b 100644 --- a/toxcore/Messenger.h +++ b/toxcore/Messenger.h @@ -16,6 +16,13 @@ #include "net_crypto.h" #include "state.h" +#ifdef HAVE_LIBEV +#include +#elif defined(HAVE_LIBEVENT) +#include +#include +#endif + #define MAX_NAME_LENGTH 128 /* TODO(irungentoo): this must depend on other variable. */ #define MAX_STATUSMESSAGE_LENGTH 1007 @@ -291,6 +298,15 @@ struct Messenger { m_self_connection_status_cb *core_connection_change; unsigned int last_connection_status; +#ifdef HAVE_LIBEV + struct ev_loop *dispatcher; + ev_async stop_loop; +#elif defined(HAVE_LIBEVENT) + struct event_base *dispatcher; +#else + bool loop_run; +#endif + Messenger_Options options; }; diff --git a/toxcore/TCP_client.c b/toxcore/TCP_client.c index 9899a93958..422c32d5cc 100644 --- a/toxcore/TCP_client.c +++ b/toxcore/TCP_client.c @@ -12,6 +12,12 @@ #include #include +#ifdef HAVE_LIBEV +#include +#elif defined(HAVE_LIBEVENT) +#include +#endif + #include "mono_time.h" #include "util.h" @@ -25,6 +31,14 @@ typedef struct TCP_Client_Conn { struct TCP_Client_Connection { TCP_Client_Status status; Socket sock; +#ifdef HAVE_LIBEV + struct { + ev_io listener; + struct ev_loop *dispatcher; + } sock_listener; +#elif defined(HAVE_LIBEVENT) + struct event *sock_listener; +#endif uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* our public key */ uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* public key of the server */ IP_Port ip_port; /* The ip and port of the server */ @@ -79,6 +93,11 @@ IP_Port tcp_con_ip_port(const TCP_Client_Connection *con) return con->ip_port; } +Socket tcp_con_sock(const TCP_Client_Connection *con) +{ + return con->sock; +} + TCP_Client_Status tcp_con_status(const TCP_Client_Connection *con) { return con->status; @@ -1052,6 +1071,17 @@ void kill_TCP_connection(TCP_Client_Connection *tcp_connection) wipe_priority_list(tcp_connection->priority_queue_start); kill_sock(tcp_connection->sock); + +#ifdef HAVE_LIBEV + ev_io_stop(TCP_connection->sock_listener.dispatcher, &TCP_connection->sock_listener.listener); +#elif defined(HAVE_LIBEVENT) + + if (TCP_connection->sock_listener) { + event_free(TCP_connection->sock_listener); + } + +#endif + crypto_memzero(tcp_connection, sizeof(TCP_Client_Connection)); free(tcp_connection); } diff --git a/toxcore/TCP_client.h b/toxcore/TCP_client.h index fed8b63738..c221daf5b8 100644 --- a/toxcore/TCP_client.h +++ b/toxcore/TCP_client.h @@ -40,6 +40,7 @@ typedef struct TCP_Client_Connection TCP_Client_Connection; const uint8_t *tcp_con_public_key(const TCP_Client_Connection *con); IP_Port tcp_con_ip_port(const TCP_Client_Connection *con); +Socket tcp_con_sock(const TCP_Client_Connection *con); TCP_Client_Status tcp_con_status(const TCP_Client_Connection *con); void *tcp_con_custom_object(const TCP_Client_Connection *con); diff --git a/toxcore/TCP_connection.c b/toxcore/TCP_connection.c index e128ca0fbf..f2227bdca9 100644 --- a/toxcore/TCP_connection.c +++ b/toxcore/TCP_connection.c @@ -56,6 +56,38 @@ uint32_t tcp_connections_count(const TCP_Connections *tcp_c) return tcp_c->tcp_connections_length; } + +/** + * Return number of elements of TCP connection array. + * + * @param tcp_c struct containing TCP_con array + * + * @return number of elements of TCP connection array + */ +uint32_t tcp_connections_length(const TCP_Connections *tcp_c) +{ + return tcp_c->tcp_connections_length; +} + + +/** + * Return TCP connection stored at "idx" position. + * + * @param tcp_c struct containing TCP_con array + * @param idx index of TCP connection to return (values from 0 to tcp_connections_length() - 1) + * + * @return TCP connection stored at "idx" position, or NULL if errors occurred + */ +const TCP_con *tcp_connections_connection_at(const TCP_Connections *tcp_c, uint32_t idx) +{ + if (idx >= tcp_c->tcp_connections_length) { + return NULL; + } + + return &tcp_c->tcp_connections[idx]; +} + + /** Set the size of the array to num. * * return -1 if realloc fails. diff --git a/toxcore/TCP_connection.h b/toxcore/TCP_connection.h index d27b3e941d..048b9fc183 100644 --- a/toxcore/TCP_connection.h +++ b/toxcore/TCP_connection.h @@ -70,6 +70,10 @@ typedef struct TCP_Connections TCP_Connections; const uint8_t *tcp_connections_public_key(const TCP_Connections *tcp_c); +uint32_t tcp_connections_length(const TCP_Connections *tcp_c); + +const TCP_con *tcp_connections_connection_at(const TCP_Connections *tcp_c, uint32_t idx); + uint32_t tcp_connections_count(const TCP_Connections *tcp_c); /** Returns the number of connected TCP relays */ diff --git a/toxcore/network.c b/toxcore/network.c index 00be27476d..a4c53545b1 100644 --- a/toxcore/network.c +++ b/toxcore/network.c @@ -86,6 +86,12 @@ #include #include +#ifdef HAVE_LIBEV +#include +#elif defined(HAVE_LIBEVENT) +#include +#endif + #ifndef VANILLA_NACL // Used for sodium_init() #include @@ -490,6 +496,14 @@ struct Networking_Core { uint16_t port; /* Our UDP socket. */ Socket sock; +#ifdef HAVE_LIBEV + struct { + ev_io listener; + struct ev_loop *dispatcher; + } sock_listener; +#elif defined(HAVE_LIBEVENT) + struct event *sock_listener; +#endif }; Family net_family(const Networking_Core *net) @@ -502,6 +516,11 @@ uint16_t net_port(const Networking_Core *net) return net->port; } +Socket net_sock(const Networking_Core *net) +{ + return net->sock; +} + /* Basic network functions: */ @@ -1003,6 +1022,17 @@ void kill_networking(Networking_Core *net) kill_sock(net->sock); } + +#ifdef HAVE_LIBEV + ev_io_stop(net->sock_listener.dispatcher, &net->sock_listener.listener); +#elif defined(HAVE_LIBEVENT) + + if (net->sock_listener) { + event_free(net->sock_listener); + } + +#endif + free(net); } diff --git a/toxcore/network.h b/toxcore/network.h index b3b8da246e..378e863ebb 100644 --- a/toxcore/network.h +++ b/toxcore/network.h @@ -322,6 +322,7 @@ typedef struct Networking_Core Networking_Core; Family net_family(const Networking_Core *net); uint16_t net_port(const Networking_Core *net); +Socket net_sock(const Networking_Core *net); /** Run this before creating sockets. * diff --git a/toxcore/tox.c b/toxcore/tox.c index eaf5516cf3..44b7354c86 100644 --- a/toxcore/tox.c +++ b/toxcore/tox.c @@ -21,9 +21,19 @@ #include "group.h" #include "logger.h" #include "mono_time.h" +#include "net_crypto.h" #include "../toxencryptsave/defines.h" +#include +#if !defined(HAVE_LIBEV) && !defined(HAVE_LIBEVENT) +#if defined (WIN32) || defined(_WIN32) || defined(__WIN32__) +#include +#else +#include +#endif // WIN32 || _WIN32 || __WIN32__ +#endif // !HAVE_LIBEV && !HAVE_LIBEVENT + #define SET_ERROR_PARAMETER(param, x) \ do { \ if (param) { \ @@ -48,6 +58,13 @@ static_assert(TOX_MAX_NAME_LENGTH == MAX_NAME_LENGTH, static_assert(TOX_MAX_STATUS_MESSAGE_LENGTH == MAX_STATUSMESSAGE_LENGTH, "TOX_MAX_STATUS_MESSAGE_LENGTH is assumed to be equal to MAX_STATUSMESSAGE_LENGTH"); +#if defined(HAVE_LIBEV) || defined(HAVE_LIBEVENT) +typedef struct { + Tox *tox; + void *user_data; +} Event_Arg; +#endif + struct Tox { // XXX: Messenger *must* be the first member, because toxav casts its // `Tox *` to `Messenger **`. @@ -77,6 +94,9 @@ struct Tox { tox_friend_lossy_packet_cb *friend_lossy_packet_callback_per_pktid[UINT8_MAX + 1]; tox_friend_lossless_packet_cb *friend_lossless_packet_callback_per_pktid[UINT8_MAX + 1]; + tox_loop_begin_cb *loop_begin_cb; + tox_loop_end_cb *loop_end_cb; + void *toxav_object; // workaround to store a ToxAV object (setter and getter functions are available) }; @@ -612,6 +632,7 @@ void tox_kill(Tox *tox) lock(tox); LOGGER_ASSERT(tox->m->log, tox->m->msi_packet == nullptr, "Attempted to kill tox while toxav is still alive"); + tox_loop_stop(tox); kill_groupchats(tox->m->conferences_object); kill_messenger(tox->m); mono_time_free(tox->mono_time); @@ -817,6 +838,345 @@ void tox_iterate(Tox *tox, void *user_data) unlock(tox); } +void tox_callback_loop_begin(Tox *tox, tox_loop_begin_cb *callback) +{ + if (tox == NULL) { + return; + } + + tox->loop_begin_cb = callback; +} + +void tox_callback_loop_end(Tox *tox, tox_loop_end_cb *callback) +{ + if (tox == NULL) { + return; + } + + tox->loop_end_cb = callback; +} + +#ifdef HAVE_LIBEV +static void tox_stop_loop_cb(struct ev_loop *dispatcher, ev_async *listener, int events) +{ + if (dispatcher == NULL || listener == NULL) { + return; + } + + Event_Arg *tmp = (Event_Arg *) listener->data; + Messenger *m = tmp->tox; + + if (ev_is_active(&m->net->sock_listener.listener) || ev_is_pending(&m->net->sock_listener.listener)) { + ev_io_stop(dispatcher, &m->net->sock_listener.listener); + } + + uint32_t len = tcp_connections_length(nc_get_tcp_c(m->net_crypto)); + + for (uint32_t i = 0; i < len; i++) { + const TCP_con *conn = tcp_connections_connection_at(nc_get_tcp_c(m->net_crypto), i); + + if (ev_is_active(&conn->connection->sock_listener.listener) + || ev_is_pending(&conn->connection->sock_listener.listener)) { + ev_io_stop(dispatcher, &conn->connection->sock_listener.listener); + } + } + + ev_async_stop(dispatcher, listener); + + ev_break(dispatcher, EVBREAK_ALL); +} + +static void tox_do_iterate(struct ev_loop *dispatcher, ev_io *sock_listener, int events) +{ + if (dispatcher == NULL || sock_listener == NULL) { + return; + } + + Event_Arg *tmp = (Event_Arg *) sock_listener->data; + Messenger *m = tmp->tox->m; + + if (tmp->tox->loop_begin_cb) { + tmp->tox->loop_begin_cb(tmp->tox, tmp->user_data); + } + + tox_iterate(tmp->tox, tmp->user_data); + + if (!ev_is_active(&m->net->sock_listener.listener) && !ev_is_pending(&m->net->sock_listener.listener)) { + m->net->sock_listener.dispatcher = dispatcher; + ev_io_init(&m->net->sock_listener.listener, tox_do_iterate, net_sock(m->net), EV_READ); + m->net->sock_listener.listener.data = sock_listener->data; + ev_io_start(dispatcher, &m->net->sock_listener.listener); + } + + uint32_t len = tcp_connections_length(nc_get_tcp_c(m->net_crypto)); + + for (uint32_t i = 0; i < len; i++) { + const TCP_con *conn = tcp_connections_connection_at(nc_get_tcp_c(m->net_crypto), i); + + if (!ev_is_active(&conn->connection->sock_listener.listener) + && !ev_is_pending(&conn->connection->sock_listener.listener)) { + conn->connection->sock_listener.dispatcher = dispatcher; + ev_io_init(&conn->connection->sock_listener.listener, tox_do_iterate, tcp_con_sock(conn->connection), EV_READ); + conn->connection->sock_listener.listener.data = sock_listener->data; + ev_io_start(m->dispatcher, &conn->connection->sock_listener.listener); + } + } + + if (m->loop_end_cb) { + m->loop_end_cb(m, tmp->user_data); + } +} +#elif defined(HAVE_LIBEVENT) +static void tox_do_iterate(evutil_socket_t fd, short events, void *arg) +{ + if (arg == NULL) { + return; + } + + Event_Arg *tmp = (Event_Arg *) arg; + Messenger *m = tmp->tox; + struct timeval timeout; + + if (m->loop_begin_cb) { + m->loop_begin_cb(m, tmp->user_data); + } + + tox_iterate(tmp->tox, tmp->user_data); + + timeout.tv_sec = 0; + + // TODO(cleverca22): use a longer timeout. + timeout.tv_usec = tox_iteration_interval(tmp->tox) * 1000 * 2; + + if (!m->net->sock_listener) { + m->net->sock_listener = event_new(m->dispatcher, net_sock(m->net), EV_READ | EV_PERSIST, tox_do_iterate, arg); + } + + event_add(m->net->sock_listener, &timeout); + + uint32_t len = tcp_connections_length(nc_get_tcp_c(m->net_crypto)); + + for (uint32_t i = 0; i < len; i++) { + const TCP_con *conn = tcp_connections_connection_at(nc_get_tcp_c(m->net_crypto), i); + + if (!conn->connection->sock_listener) { + conn->connection->sock_listener = event_new(m->dispatcher, tcp_con_sock(conn->connection), EV_READ | EV_PERSIST, + tox_do_iterate, arg); + } + + event_add(conn->connection->sock_listener, NULL); + } + + if (m->loop_end_cb) { + m->loop_end_cb(m, tmp->user_data); + } +} +#else +/** + * Gathers a list of every network file descriptor, + * where an activity is expected on. + * + * @param sockets a pointer to an array (the pointed array can be NULL). + * @param sockets_num the number of current known sockets (will be updated by the funciton). + * + * @return false if errors occurred, true otherwise. + */ +static bool tox_fds(Messenger *m, Socket **sockets, uint32_t *sockets_num) +{ + if (m == NULL || sockets == NULL || sockets_num == NULL) { + return false; + } + + uint32_t len = tcp_connections_length(nc_get_tcp_c(m->net_crypto)); + uint32_t fdcount = 1 + len; + + if (fdcount != *sockets_num || *sockets == NULL) { + Socket *tmp_sockets = (Socket *)realloc(*sockets, fdcount * sizeof(Socket)); + + if (tmp_sockets == NULL) { + return false; + } + + *sockets = tmp_sockets; + *sockets_num = fdcount; + } + + (*sockets)[0] = net_sock(m->net); + + uint32_t i = 0; + + while (i < fdcount - 1 && i < len) { + const TCP_con *conn = tcp_connections_connection_at(nc_get_tcp_c(m->net_crypto), i); + i++; + + if (conn != NULL) { + (*sockets)[i] = tcp_con_sock(conn->connection); + } else { + (*sockets)[i] = (Socket) { + 0 + }; + } + } + + return true; +} +#endif + +bool tox_loop(Tox *tox, void *user_data, TOX_ERR_LOOP *error) +{ + if (tox == NULL) { + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_NULL); + + return false; + } + + Messenger *m = tox->m; + +#ifdef HAVE_LIBEV + bool ret = true; + Event_Arg *tmp = (Event_Arg *) calloc(1, sizeof(Event_Arg)); + + tmp->tox = tox; + tmp->user_data = user_data; + + ev_async_init(&m->stop_loop, tox_stop_loop_cb); + m->stop_loop.data = tmp; + ev_async_start(m->dispatcher, &m->stop_loop); + + ev_io stub_listener; + ev_init(&stub_listener, tox_do_iterate); + stub_listener.data = tmp; + tox_do_iterate(m->dispatcher, &stub_listener, 0); + + // TODO(Ansa89): travis states that "ev_run" returns "void", + // but "man 3 ev" states it returns "bool" +#if 0 + ret = !ev_run(m->dispatcher, 0); + + if (ret) { + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_OK); + } else { + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_BREAK); + } + +#endif + + ev_run(m->dispatcher, 0); + + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_OK); + + free(tmp); +#elif defined(HAVE_LIBEVENT) + Event_Arg *tmp = (Event_Arg *) calloc(1, sizeof(Event_Arg)); + + tmp->tox = tox; + tmp->user_data = user_data; + + tox_do_iterate(0, 0, tmp); + bool ret = event_base_dispatch(m->dispatcher) < 0 ? false : true; + + if (ret) { + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_OK); + } else { + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_BREAK); + } + + free(tmp); +#else + bool ret = true; + uint32_t fdcount = 0; + Socket *fdlist = NULL; + + m->loop_run = true; + + while (m->loop_run) { + Socket maxfd; + fd_set readable; + + if (tox->loop_begin_cb) { + tox->loop_begin_cb(tox, user_data); + } + + tox_iterate(tox, user_data); + + maxfd = (Socket) { + 0 + }; + FD_ZERO(&readable); + + // TODO(cleverca22): is it a good idea to reuse previous fdlist when + // fdcount!=0 && tox_fds()==false? + if (fdcount == 0 && !tox_fds(m, &fdlist, &fdcount)) { + // We must stop because maxfd won't be set. + // TODO(cleverca22): should we call loop_end_cb() on error? + if (tox->loop_end_cb) { + tox->loop_end_cb(tox, user_data); + } + + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_GET_FDS); + + free(fdlist); + + return false; + } + + for (uint32_t i = 0; i < fdcount; i++) { + if (fdlist[i].socket == 0) { + continue; + } + + FD_SET(fdlist[i].socket, &readable); + + if (fdlist[i].socket > maxfd.socket) { + maxfd = fdlist[i]; + } + } + + struct timeval timeout; + + timeout.tv_sec = 0; + + // TODO(cleverca22): use a longer timeout. + timeout.tv_usec = tox_iteration_interval(tox) * 1000 * 2; + + if (tox->loop_end_cb) { + tox->loop_end_cb(tox, user_data); + } + + if (select(maxfd.socket, &readable, NULL, NULL, &timeout) < 0 && errno != EBADF) { + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_SELECT); + + free(fdlist); + + return false; + } + } + + SET_ERROR_PARAMETER(error, TOX_ERR_LOOP_OK); + + free(fdlist); +#endif + + return ret; +} + +void tox_loop_stop(Tox *tox) +{ + if (tox == NULL) { + return; + } + + Messenger *m = tox->m; + +#ifdef HAVE_LIBEV + ev_async_send(m->dispatcher, &m->stop_loop); +#elif defined(HAVE_LIBEVENT) + event_base_loopbreak(m->dispatcher); +#else + m->loop_run = false; +#endif +} + void tox_self_get_address(const Tox *tox, uint8_t *address) { assert(tox != nullptr); diff --git a/toxcore/tox.h b/toxcore/tox.h index 72f36f7dba..8acc6f58b2 100644 --- a/toxcore/tox.h +++ b/toxcore/tox.h @@ -1050,6 +1050,76 @@ uint32_t tox_iteration_interval(const Tox *tox); void tox_iterate(Tox *tox, void *user_data); +/** + * Error codes for tox_loop(). + */ +typedef enum TOX_ERR_LOOP { + + /** + * The function returned successfully. + */ + TOX_ERR_LOOP_OK, + + /** + * Invalid arguments passed. + */ + TOX_ERR_LOOP_NULL, + + /** + * Failed running events dispatcher. + */ + TOX_ERR_LOOP_BREAK, + + /** + * Failed running select(). + */ + TOX_ERR_LOOP_SELECT, + + /** + * Failed getting sockets file descriptors. + */ + TOX_ERR_LOOP_GET_FDS, + +} TOX_ERR_LOOP; + + +/** + * Run tox_iterate() any time a packet arrives, returns after tox_loop_stop() or tox_kill(). + */ +bool tox_loop(Tox *tox, void *user_data, TOX_ERR_LOOP *error); + +/** + * Tell tox_loop() to return. + */ +void tox_loop_stop(Tox *tox); + +/** + * No extra parameters. + */ +typedef void tox_loop_begin_cb(Tox *tox, void *user_data); + + +/** + * Set the callback for the `loop_begin` event. Pass NULL to unset. + * + * This callback is invoked when tox_loop() calls into tox_iterate(), the client can lock a mutex here. + */ +void tox_callback_loop_begin(Tox *tox, tox_loop_begin_cb *callback); + +/** + * No extra parameters. + */ +typedef void tox_loop_end_cb(Tox *tox, void *user_data); + + +/** + * Set the callback for the `loop_end` event. Pass NULL to unset. + * + * This callback is invoked when tox_loop() is finished with tox_iterate(), the client can unlock the mutex here. + */ +void tox_callback_loop_end(Tox *tox, tox_loop_end_cb *callback); + + /******************************************************************************* * * :: Internal client information (Tox address/id)