diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000000..3ad05109d47 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +_build +_install diff --git a/.github/scripts/flags-clang.sh b/.github/scripts/flags-clang.sh index d083672e4dc..039c4740c39 100644 --- a/.github/scripts/flags-clang.sh +++ b/.github/scripts/flags-clang.sh @@ -9,6 +9,9 @@ add_flag -Weverything # Disable specific warning flags for both C and C++. +# TODO(iphydf): Investigate these. +add_flag -Wno-unsafe-buffer-usage + # Very verbose, not very useful. This warns about things like int -> uint # conversions that change sign without a cast and narrowing conversions. add_flag -Wno-conversion diff --git a/.github/scripts/flags.sh b/.github/scripts/flags.sh index 80a56c017df..d2af1292c48 100644 --- a/.github/scripts/flags.sh +++ b/.github/scripts/flags.sh @@ -29,7 +29,7 @@ add_flag -O3 -march=native # Warn on non-ISO C. add_c_flag -pedantic add_c_flag -std=c99 -add_cxx_flag -std=c++11 +add_cxx_flag -std=c++17 add_flag -g3 add_flag -ftrapv diff --git a/BUILD.bazel b/BUILD.bazel index 4d39dab3332..472347b04b7 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -8,19 +8,49 @@ project() genrule( name = "public_headers", srcs = [ + "toxav.h", + "tox.h", + "toxencryptsave.h", "//c-toxcore/toxav:toxav.h", "//c-toxcore/toxcore:tox.h", + "//c-toxcore/toxcore:tox_attributes.h", + "//c-toxcore/toxcore:tox_logger.h", + "//c-toxcore/toxcore:tox_memory.h", + "//c-toxcore/toxcore:tox_network.h", + "//c-toxcore/toxcore:tox_random.h", + "//c-toxcore/toxcore:tox_system.h", + "//c-toxcore/toxcore:tox_time.h", "//c-toxcore/toxencryptsave:toxencryptsave.h", ], outs = [ "tox/toxav.h", "tox/tox.h", "tox/toxencryptsave.h", + "tox/toxav/toxav.h", + "tox/toxcore/tox.h", + "tox/toxcore/tox_attributes.h", + "tox/toxcore/tox_logger.h", + "tox/toxcore/tox_memory.h", + "tox/toxcore/tox_network.h", + "tox/toxcore/tox_random.h", + "tox/toxcore/tox_system.h", + "tox/toxcore/tox_time.h", + "tox/toxencryptsave/toxencryptsave.h", ], cmd = """ - cp $(location //c-toxcore/toxav:toxav.h) $(GENDIR)/c-toxcore/tox/toxav.h - cp $(location //c-toxcore/toxcore:tox.h) $(GENDIR)/c-toxcore/tox/tox.h - cp $(location //c-toxcore/toxencryptsave:toxencryptsave.h) $(GENDIR)/c-toxcore/tox/toxencryptsave.h + cp $(location toxav.h) $(GENDIR)/c-toxcore/tox/toxav.h + cp $(location tox.h) $(GENDIR)/c-toxcore/tox/tox.h + cp $(location toxencryptsave.h) $(GENDIR)/c-toxcore/tox/toxencryptsave.h + cp $(location //c-toxcore/toxav:toxav.h) $(GENDIR)/c-toxcore/tox/toxav/toxav.h + cp $(location //c-toxcore/toxcore:tox.h) $(GENDIR)/c-toxcore/tox/toxcore/tox.h + cp $(location //c-toxcore/toxcore:tox_attributes.h) $(GENDIR)/c-toxcore/tox/toxcore/tox_attributes.h + cp $(location //c-toxcore/toxcore:tox_logger.h) $(GENDIR)/c-toxcore/tox/toxcore/tox_logger.h + cp $(location //c-toxcore/toxcore:tox_memory.h) $(GENDIR)/c-toxcore/tox/toxcore/tox_memory.h + cp $(location //c-toxcore/toxcore:tox_network.h) $(GENDIR)/c-toxcore/tox/toxcore/tox_network.h + cp $(location //c-toxcore/toxcore:tox_random.h) $(GENDIR)/c-toxcore/tox/toxcore/tox_random.h + cp $(location //c-toxcore/toxcore:tox_system.h) $(GENDIR)/c-toxcore/tox/toxcore/tox_system.h + cp $(location //c-toxcore/toxcore:tox_time.h) $(GENDIR)/c-toxcore/tox/toxcore/tox_time.h + cp $(location //c-toxcore/toxencryptsave:toxencryptsave.h) $(GENDIR)/c-toxcore/tox/toxencryptsave/toxencryptsave.h """, visibility = ["//visibility:public"], ) diff --git a/CMakeLists.txt b/CMakeLists.txt index d3cabf06c66..8c18fe0fa02 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -282,6 +282,17 @@ set(toxcore_SOURCES toxcore/onion_client.c toxcore/onion_client.h toxcore/onion.h + toxcore/os_logger.c + toxcore/os_logger.h + toxcore/os_memory.c + toxcore/os_memory.h + toxcore/os_network.c + toxcore/os_network.h + toxcore/os_network_impl.h + toxcore/os_random.c + toxcore/os_random.h + toxcore/os_system.c + toxcore/os_system.h toxcore/ping_array.c toxcore/ping_array.h toxcore/ping.c @@ -302,11 +313,29 @@ set(toxcore_SOURCES toxcore/timed_auth.h toxcore/tox_api.c toxcore/tox.c + toxcore/tox.h toxcore/tox_dispatch.c toxcore/tox_dispatch.h toxcore/tox_events.c toxcore/tox_events.h - toxcore/tox.h + toxcore/tox_logger.c + toxcore/tox_logger.h + toxcore/tox_logger_impl.h + toxcore/tox_memory.c + toxcore/tox_memory.h + toxcore/tox_memory_impl.h + toxcore/tox_network.c + toxcore/tox_network.h + toxcore/tox_network_impl.h + toxcore/tox_random.c + toxcore/tox_random.h + toxcore/tox_random_impl.h + toxcore/tox_system.c + toxcore/tox_system.h + toxcore/tox_system_impl.h + toxcore/tox_time.c + toxcore/tox_time.h + toxcore/tox_time_impl.h toxcore/tox_private.c toxcore/tox_private.h toxcore/tox_unpack.c @@ -317,8 +346,14 @@ set(toxcore_LINK_MODULES ${toxcore_LINK_MODULES} ${LIBSODIUM_LIBRARIES}) set(toxcore_PKGCONFIG_REQUIRES ${toxcore_PKGCONFIG_REQUIRES} libsodium) set(toxcore_API_HEADERS ${toxcore_SOURCE_DIR}/toxcore/tox.h^tox + ${toxcore_SOURCE_DIR}/toxcore/tox_dispatch.h^tox ${toxcore_SOURCE_DIR}/toxcore/tox_events.h^tox - ${toxcore_SOURCE_DIR}/toxcore/tox_dispatch.h^tox) + ${toxcore_SOURCE_DIR}/toxcore/tox_logger.h^tox + ${toxcore_SOURCE_DIR}/toxcore/tox_memory.h^tox + ${toxcore_SOURCE_DIR}/toxcore/tox_network.h^tox + ${toxcore_SOURCE_DIR}/toxcore/tox_random.h^tox + ${toxcore_SOURCE_DIR}/toxcore/tox_system.h^tox + ${toxcore_SOURCE_DIR}/toxcore/tox_time.h^tox) ################################################################################ # diff --git a/auto_tests/BUILD.bazel b/auto_tests/BUILD.bazel index babd3aca845..d5731890e78 100644 --- a/auto_tests/BUILD.bazel +++ b/auto_tests/BUILD.bazel @@ -19,6 +19,7 @@ cc_library( "//c-toxcore/toxcore:Messenger", "//c-toxcore/toxcore:mono_time", "//c-toxcore/toxcore:tox", + "//c-toxcore/toxcore:tox_time", ], ) @@ -61,9 +62,13 @@ flaky_tests = { "//c-toxcore/toxcore:onion", "//c-toxcore/toxcore:onion_announce", "//c-toxcore/toxcore:onion_client", + "//c-toxcore/toxcore:os_memory", + "//c-toxcore/toxcore:os_network", + "//c-toxcore/toxcore:os_random", "//c-toxcore/toxcore:tox", "//c-toxcore/toxcore:tox_dispatch", "//c-toxcore/toxcore:tox_events", + "//c-toxcore/toxcore:tox_time", "//c-toxcore/toxcore:util", "//c-toxcore/toxencryptsave", "@libsodium", diff --git a/auto_tests/TCP_test.c b/auto_tests/TCP_test.c index d5455cf0e83..dfa3d7b96b8 100644 --- a/auto_tests/TCP_test.c +++ b/auto_tests/TCP_test.c @@ -8,6 +8,9 @@ #include "../toxcore/TCP_server.h" #include "../toxcore/crypto_core.h" #include "../toxcore/mono_time.h" +#include "../toxcore/os_random.h" +#include "../toxcore/os_network.h" +#include "../toxcore/os_memory.h" #include "../toxcore/util.h" #include "auto_test_support.h" @@ -45,14 +48,14 @@ static uint16_t ports[NUM_PORTS] = {13215, 33445, 25643}; static void test_basic(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); Logger *logger = logger_new(); logger_callback_log(logger, print_debug_logger, nullptr, nullptr); @@ -303,14 +306,14 @@ static int read_packet_sec_TCP(const Logger *logger, struct sec_TCP_con *con, ui static void test_some(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); Logger *logger = logger_new(); uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE]; @@ -498,15 +501,15 @@ static int oob_data_callback(void *object, const uint8_t *public_key, const uint static void test_client(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); Logger *logger = logger_new(); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE]; @@ -632,14 +635,14 @@ static void test_client(void) // Test how the client handles servers that don't respond. static void test_client_invalid(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); Logger *logger = logger_new(); uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE]; @@ -711,14 +714,14 @@ static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t static void test_tcp_connection(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); Logger *logger = logger_new(); tcp_data_callback_called = 0; @@ -824,14 +827,14 @@ static int tcp_oobdata_callback(void *object, const uint8_t *public_key, unsigne static void test_tcp_connection2(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); Logger *logger = logger_new(); tcp_oobdata_callback_called = 0; diff --git a/auto_tests/announce_test.c b/auto_tests/announce_test.c index f0929c757c6..97fa9fe76a1 100644 --- a/auto_tests/announce_test.c +++ b/auto_tests/announce_test.c @@ -7,13 +7,16 @@ #include "../toxcore/mono_time.h" #include "../toxcore/forwarding.h" #include "../toxcore/net_crypto.h" +#include "../toxcore/os_memory.h" +#include "../toxcore/os_network.h" +#include "../toxcore/os_random.h" #include "../toxcore/util.h" #include "auto_test_support.h" #include "check_compat.h" static void test_bucketnum(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); uint8_t key1[CRYPTO_PUBLIC_KEY_SIZE], key2[CRYPTO_PUBLIC_KEY_SIZE]; random_bytes(rng, key1, sizeof(key1)); @@ -50,17 +53,17 @@ static void test_announce_data(void *object, const uint8_t *data, uint16_t lengt static void test_store_data(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); Logger *log = logger_new(); ck_assert(log != nullptr); logger_callback_log(log, print_debug_logger, nullptr, nullptr); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); Networking_Core *net = new_networking_no_udp(log, mem, ns); DHT *dht = new_dht(log, mem, rng, ns, mono_time, net, true, true); Forwarding *forwarding = new_forwarding(log, rng, mono_time, dht); diff --git a/auto_tests/auto_test_support.c b/auto_tests/auto_test_support.c index cb409738ef4..b7d52b9c089 100644 --- a/auto_tests/auto_test_support.c +++ b/auto_tests/auto_test_support.c @@ -6,6 +6,7 @@ #include "../toxcore/Messenger.h" #include "../toxcore/mono_time.h" #include "../toxcore/tox_struct.h" +#include "../toxcore/tox_time_impl.h" #include "auto_test_support.h" @@ -13,7 +14,7 @@ #define ABORT_ON_LOG_ERROR true #endif -Run_Auto_Options default_run_auto_options() +Run_Auto_Options default_run_auto_options(void) { return (Run_Auto_Options) { .graph = GRAPH_COMPLETE, @@ -159,15 +160,23 @@ static uint64_t get_state_clock_callback(void *user_data) return *clock; } +static const Tox_Time_Funcs autotox_time_funcs = { + get_state_clock_callback, +}; + void set_mono_time_callback(AutoTox *autotox) { ck_assert(autotox != nullptr); + if (autotox->tm == nullptr) { + autotox->tm = tox_time_new(&autotox_time_funcs, &autotox->clock, autotox->tox->sys.mem); + } + Mono_Time *mono_time = autotox->tox->mono_time; autotox->clock = current_time_monotonic(mono_time); - mono_time_set_current_time_callback(mono_time, nullptr, nullptr); // set to default first - mono_time_set_current_time_callback(mono_time, get_state_clock_callback, &autotox->clock); + mono_time_set_current_time_callback(mono_time, nullptr); // set to default first + mono_time_set_current_time_callback(mono_time, autotox->tm); } void save_autotox(AutoTox *autotox) @@ -193,6 +202,8 @@ void kill_autotox(AutoTox *autotox) fprintf(stderr, "Killing #%u\n", autotox->index); autotox->alive = false; tox_kill(autotox->tox); + tox_time_free(autotox->tm); + autotox->tm = nullptr; } void reload(AutoTox *autotox) @@ -380,6 +391,7 @@ void run_auto_test(struct Tox_Options *options, uint32_t tox_count, void test(Au for (uint32_t i = 0; i < tox_count; ++i) { tox_kill(autotoxes[i].tox); + tox_time_free(autotoxes[i].tm); free(autotoxes[i].state); free(autotoxes[i].save_state); } diff --git a/auto_tests/auto_test_support.h b/auto_tests/auto_test_support.h index eab121aa367..10a250a0ffa 100644 --- a/auto_tests/auto_test_support.h +++ b/auto_tests/auto_test_support.h @@ -10,6 +10,7 @@ typedef struct AutoTox { Tox *tox; + Tox_Time *tm; uint32_t index; uint64_t clock; diff --git a/auto_tests/conference_av_test.c b/auto_tests/conference_av_test.c index 9bbc4182699..2fbcd5e7f21 100644 --- a/auto_tests/conference_av_test.c +++ b/auto_tests/conference_av_test.c @@ -7,6 +7,7 @@ #include #include "../toxav/toxav.h" +#include "../toxcore/os_random.h" #include "check_compat.h" #define NUM_AV_GROUP_TOX 16 @@ -287,7 +288,7 @@ static void do_audio(AutoTox *autotoxes, uint32_t iterations) static void run_conference_tests(AutoTox *autotoxes) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); bool disabled[NUM_AV_GROUP_TOX] = {0}; diff --git a/auto_tests/conference_test.c b/auto_tests/conference_test.c index 66edddd85c7..d7e3fe6283c 100644 --- a/auto_tests/conference_test.c +++ b/auto_tests/conference_test.c @@ -6,6 +6,7 @@ #include #include +#include "../toxcore/os_random.h" #include "../toxcore/util.h" #include "check_compat.h" @@ -192,7 +193,7 @@ static uint32_t random_false_index(const Random *rng, bool *list, const uint32_t static void run_conference_tests(AutoTox *autotoxes) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); /* disabling name change propagation check for now, as it occasionally * fails due to disconnections too short to trigger freezing */ diff --git a/auto_tests/crypto_test.c b/auto_tests/crypto_test.c index f4fdf3e22de..546259d06d9 100644 --- a/auto_tests/crypto_test.c +++ b/auto_tests/crypto_test.c @@ -4,6 +4,7 @@ #include "../testing/misc_tools.h" #include "../toxcore/crypto_core.h" +#include "../toxcore/os_random.h" #include "../toxcore/net_crypto.h" #include "check_compat.h" @@ -129,7 +130,7 @@ static void test_fast_known(void) static void test_endtoend(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); // Test 100 random messages and keypairs @@ -196,7 +197,7 @@ static void test_endtoend(void) static void test_large_data(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); uint8_t k[CRYPTO_SHARED_KEY_SIZE]; uint8_t n[CRYPTO_NONCE_SIZE]; @@ -240,7 +241,7 @@ static void test_large_data(void) static void test_large_data_symmetric(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); uint8_t k[CRYPTO_SYMMETRIC_KEY_SIZE]; @@ -296,7 +297,7 @@ static void increment_nonce_number_cmp(uint8_t *nonce, uint32_t num) static void test_increment_nonce(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); uint32_t i; diff --git a/auto_tests/encryptsave_test.c b/auto_tests/encryptsave_test.c index fb49c4e2af2..cd56f65710b 100644 --- a/auto_tests/encryptsave_test.c +++ b/auto_tests/encryptsave_test.c @@ -9,6 +9,7 @@ #include "../testing/misc_tools.h" #include "../toxcore/ccompat.h" #include "../toxcore/crypto_core.h" +#include "../toxcore/os_random.h" #include "../toxcore/tox.h" #include "../toxencryptsave/toxencryptsave.h" #include "auto_test_support.h" @@ -169,7 +170,7 @@ static void test_keys(void) ck_assert(encrypted2a != nullptr); uint8_t *in_plaintext2a = (uint8_t *)malloc(plaintext_length2a); ck_assert(in_plaintext2a != nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); random_bytes(rng, in_plaintext2a, plaintext_length2a); ret = tox_pass_encrypt(in_plaintext2a, plaintext_length2a, key_char, 12, encrypted2a, &encerr); diff --git a/auto_tests/forwarding_test.c b/auto_tests/forwarding_test.c index f9c82784f20..40a2a01fa26 100644 --- a/auto_tests/forwarding_test.c +++ b/auto_tests/forwarding_test.c @@ -8,6 +8,9 @@ #include "../toxcore/mono_time.h" #include "../toxcore/forwarding.h" #include "../toxcore/net_crypto.h" +#include "../toxcore/os_memory.h" +#include "../toxcore/os_network.h" +#include "../toxcore/os_random.h" #include "../toxcore/util.h" #include "auto_test_support.h" #include "check_compat.h" @@ -104,9 +107,9 @@ typedef struct Forwarding_Subtox { static Forwarding_Subtox *new_forwarding_subtox(const Memory *mem, bool no_udp, uint32_t *index, uint16_t port) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); Forwarding_Subtox *subtox = (Forwarding_Subtox *)calloc(1, sizeof(Forwarding_Subtox)); @@ -115,7 +118,7 @@ static Forwarding_Subtox *new_forwarding_subtox(const Memory *mem, bool no_udp, subtox->log = logger_new(); ck_assert(subtox->log != nullptr); logger_callback_log(subtox->log, print_debug_logger, nullptr, index); - subtox->mono_time = mono_time_new(mem, nullptr, nullptr); + subtox->mono_time = mono_time_new(mem, nullptr); if (no_udp) { subtox->net = new_networking_no_udp(subtox->log, mem, ns); @@ -152,11 +155,11 @@ static void kill_forwarding_subtox(const Memory *mem, Forwarding_Subtox *subtox) static void test_forwarding(void) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); uint32_t index[NUM_FORWARDER]; diff --git a/auto_tests/group_message_test.c b/auto_tests/group_message_test.c index d7a00a9fee0..8d5d7cc64d3 100644 --- a/auto_tests/group_message_test.c +++ b/auto_tests/group_message_test.c @@ -12,6 +12,7 @@ #include "auto_test_support.h" #include "check_compat.h" +#include "../toxcore/os_random.h" #include "../toxcore/util.h" typedef struct State { @@ -334,7 +335,7 @@ static void group_message_test(AutoTox *autotoxes) #ifndef VANILLA_NACL ck_assert_msg(NUM_GROUP_TOXES >= 2, "NUM_GROUP_TOXES is too small: %d", NUM_GROUP_TOXES); - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); Tox *tox0 = autotoxes[0].tox; diff --git a/auto_tests/group_sync_test.c b/auto_tests/group_sync_test.c index 4d2bc1866dc..fdd895ed344 100644 --- a/auto_tests/group_sync_test.c +++ b/auto_tests/group_sync_test.c @@ -10,6 +10,7 @@ #include "auto_test_support.h" +#include "../toxcore/os_random.h" #include "../toxcore/tox.h" #include "../toxcore/util.h" @@ -332,7 +333,7 @@ static void group_sync_test(AutoTox *autotoxes) { #ifndef VANILLA_NACL ck_assert(NUM_GROUP_TOXES >= 5); - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); for (size_t i = 0; i < NUM_GROUP_TOXES; ++i) { diff --git a/auto_tests/group_topic_test.c b/auto_tests/group_topic_test.c index 26dafcb459a..00fff8555d8 100644 --- a/auto_tests/group_topic_test.c +++ b/auto_tests/group_topic_test.c @@ -11,8 +11,9 @@ #include "auto_test_support.h" #include "check_compat.h" -#include "../toxcore/tox.h" #include "../toxcore/group_chats.h" +#include "../toxcore/os_random.h" +#include "../toxcore/tox.h" #define NUM_GROUP_TOXES 3 @@ -206,7 +207,7 @@ static void group_topic_test(AutoTox *autotoxes) #ifndef VANILLA_NACL ck_assert_msg(NUM_GROUP_TOXES >= 3, "NUM_GROUP_TOXES is too small: %d", NUM_GROUP_TOXES); - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); Tox *tox0 = autotoxes[0].tox; diff --git a/auto_tests/lan_discovery_test.c b/auto_tests/lan_discovery_test.c index d7bf594b2bf..8ea4e39764c 100644 --- a/auto_tests/lan_discovery_test.c +++ b/auto_tests/lan_discovery_test.c @@ -3,6 +3,8 @@ #include "../testing/misc_tools.h" #include "../toxcore/ccompat.h" +#include "../toxcore/os_memory.h" +#include "../toxcore/tox_time_impl.h" #include "../toxcore/tox_struct.h" #include "auto_test_support.h" @@ -12,6 +14,10 @@ static uint64_t get_state_clock_callback(void *user_data) return *clock; } +static const Tox_Time_Funcs mock_time_funcs = { + get_state_clock_callback, +}; + int main(void) { setvbuf(stdout, nullptr, _IONBF, 0); @@ -21,14 +27,18 @@ int main(void) ck_assert(tox1 != nullptr); ck_assert(tox2 != nullptr); + const Memory *mem = os_memory(); + uint64_t clock = current_time_monotonic(tox1->mono_time); + Tox_Time *tm = tox_time_new(&mock_time_funcs, &clock, mem); + Mono_Time *mono_time; mono_time = tox1->mono_time; - mono_time_set_current_time_callback(mono_time, get_state_clock_callback, &clock); + mono_time_set_current_time_callback(mono_time, tm); mono_time = tox2->mono_time; - mono_time_set_current_time_callback(mono_time, get_state_clock_callback, &clock); + mono_time_set_current_time_callback(mono_time, tm); printf("Waiting for LAN discovery. This loop will attempt to run until successful."); @@ -49,5 +59,7 @@ int main(void) tox_kill(tox2); tox_kill(tox1); + + tox_time_free(tm); return 0; } diff --git a/auto_tests/network_test.c b/auto_tests/network_test.c index df3b625a9e1..f96618385e2 100644 --- a/auto_tests/network_test.c +++ b/auto_tests/network_test.c @@ -3,6 +3,7 @@ #include "../testing/misc_tools.h" #include "../toxcore/network.h" +#include "../toxcore/os_network.h" #include "check_compat.h" #ifndef USE_IPV6 @@ -20,7 +21,7 @@ static void test_addr_resolv_localhost(void) errno = 0; #endif - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); const char localhost[] = "localhost"; diff --git a/auto_tests/onion_test.c b/auto_tests/onion_test.c index 282b99637e6..720b907b548 100644 --- a/auto_tests/onion_test.c +++ b/auto_tests/onion_test.c @@ -6,6 +6,9 @@ #include "../toxcore/onion.h" #include "../toxcore/onion_announce.h" #include "../toxcore/onion_client.h" +#include "../toxcore/os_memory.h" +#include "../toxcore/os_network.h" +#include "../toxcore/os_random.h" #include "../toxcore/util.h" #include "auto_test_support.h" #include "check_compat.h" @@ -223,11 +226,11 @@ static Networking_Core *new_networking(const Logger *log, const Memory *mem, con static void test_basic(void) { uint32_t index[] = { 1, 2, 3 }; - const Network *ns = system_network(); + const Network *ns = os_network(); ck_assert(ns != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); Logger *log1 = logger_new(); @@ -235,8 +238,8 @@ static void test_basic(void) Logger *log2 = logger_new(); logger_callback_log(log2, print_debug_logger, nullptr, &index[1]); - Mono_Time *mono_time1 = mono_time_new(mem, nullptr, nullptr); - Mono_Time *mono_time2 = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time1 = mono_time_new(mem, nullptr); + Mono_Time *mono_time2 = mono_time_new(mem, nullptr); IP ip = get_loopback(); Onion *onion1 = new_onion(log1, mem, mono_time1, rng, new_dht(log1, mem, rng, ns, mono_time1, new_networking(log1, mem, ns, &ip, 36567), true, false)); @@ -334,7 +337,7 @@ static void test_basic(void) Logger *log3 = logger_new(); logger_callback_log(log3, print_debug_logger, nullptr, &index[2]); - Mono_Time *mono_time3 = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time3 = mono_time_new(mem, nullptr); Onion *onion3 = new_onion(log3, mem, mono_time3, rng, new_dht(log3, mem, rng, ns, mono_time3, new_networking(log3, mem, ns, &ip, 36569), true, false)); ck_assert_msg((onion3 != nullptr), "Onion failed initializing."); @@ -407,7 +410,7 @@ static Onions *new_onions(const Memory *mem, const Random *rng, uint16_t port, u { IP ip = get_loopback(); ip.ip.v6.uint8[15] = 1; - const Network *ns = system_network(); + const Network *ns = os_network(); Onions *on = (Onions *)malloc(sizeof(Onions)); if (!on) { @@ -423,7 +426,7 @@ static Onions *new_onions(const Memory *mem, const Random *rng, uint16_t port, u logger_callback_log(on->log, print_debug_logger, nullptr, index); - on->mono_time = mono_time_new(mem, nullptr, nullptr); + on->mono_time = mono_time_new(mem, nullptr); if (!on->mono_time) { logger_kill(on->log); @@ -577,9 +580,9 @@ static void test_announce(void) uint32_t i, j; uint32_t index[NUM_ONIONS]; Onions *onions[NUM_ONIONS]; - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); ck_assert(mem != nullptr); for (i = 0; i < NUM_ONIONS; ++i) { diff --git a/auto_tests/reconnect_test.c b/auto_tests/reconnect_test.c index 253f66b0c5c..ad6a021f227 100644 --- a/auto_tests/reconnect_test.c +++ b/auto_tests/reconnect_test.c @@ -11,6 +11,7 @@ #include "../testing/misc_tools.h" #include "../toxcore/friend_connection.h" +#include "../toxcore/os_random.h" #include "../toxcore/tox.h" #include "../toxcore/util.h" #include "check_compat.h" @@ -51,7 +52,7 @@ static bool all_disconnected_from(uint32_t tox_count, AutoTox *autotoxes, uint32 static void test_reconnect(AutoTox *autotoxes) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); const time_t test_start_time = time(nullptr); diff --git a/auto_tests/save_friend_test.c b/auto_tests/save_friend_test.c index 80a6ed037e8..4a546cc53c6 100644 --- a/auto_tests/save_friend_test.c +++ b/auto_tests/save_friend_test.c @@ -8,6 +8,7 @@ #include "../testing/misc_tools.h" #include "../toxcore/ccompat.h" #include "../toxcore/crypto_core.h" +#include "../toxcore/os_random.h" #include "../toxcore/tox.h" #include "auto_test_support.h" #include "check_compat.h" @@ -86,7 +87,7 @@ int main(void) ck_assert(reference_name != nullptr); ck_assert(reference_status != nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); set_random(tox1, rng, tox_self_set_name, tox_max_name_length()); set_random(tox2, rng, tox_self_set_name, tox_max_name_length()); diff --git a/auto_tests/save_load_test.c b/auto_tests/save_load_test.c index 97077735633..41ac2bb48bf 100644 --- a/auto_tests/save_load_test.c +++ b/auto_tests/save_load_test.c @@ -8,8 +8,10 @@ #include "../testing/misc_tools.h" #include "../toxcore/ccompat.h" +#include "../toxcore/os_memory.h" #include "../toxcore/tox.h" #include "../toxcore/tox_struct.h" +#include "../toxcore/tox_time_impl.h" #include "../toxcore/util.h" #include "auto_test_support.h" #include "check_compat.h" @@ -119,6 +121,10 @@ static uint64_t get_state_clock_callback(void *user_data) return clock; } +static const Tox_Time_Funcs mock_time_funcs = { + get_state_clock_callback, +}; + static void increment_clock(Time_Data *time_data, uint64_t count) { pthread_mutex_lock(&time_data->lock); @@ -126,10 +132,10 @@ static void increment_clock(Time_Data *time_data, uint64_t count) pthread_mutex_unlock(&time_data->lock); } -static void set_current_time_callback(Tox *tox, Time_Data *time_data) +static void set_current_time_callback(Tox *tox, Tox_Time *tm) { Mono_Time *mono_time = tox->mono_time; - mono_time_set_current_time_callback(mono_time, get_state_clock_callback, time_data); + mono_time_set_current_time_callback(mono_time, tm); } static void test_few_clients(void) @@ -161,9 +167,12 @@ static void test_few_clients(void) Time_Data time_data; ck_assert_msg(pthread_mutex_init(&time_data.lock, nullptr) == 0, "Failed to init time_data mutex"); time_data.clock = current_time_monotonic(tox1->mono_time); - set_current_time_callback(tox1, &time_data); - set_current_time_callback(tox2, &time_data); - set_current_time_callback(tox3, &time_data); + + const Memory *mem = os_memory(); + Tox_Time *tm = tox_time_new(&mock_time_funcs, &time_data, mem); + set_current_time_callback(tox1, tm); + set_current_time_callback(tox2, tm); + set_current_time_callback(tox3, tm); uint8_t dht_key[TOX_PUBLIC_KEY_SIZE]; tox_self_get_dht_id(tox1, dht_key); @@ -257,6 +266,8 @@ static void test_few_clients(void) tox_options_free(opts2); tox_options_free(opts3); + + tox_time_free(tm); } int main(void) diff --git a/auto_tests/tox_dispatch_test.c b/auto_tests/tox_dispatch_test.c index 209e13788f2..c887176717b 100644 --- a/auto_tests/tox_dispatch_test.c +++ b/auto_tests/tox_dispatch_test.c @@ -43,7 +43,7 @@ static void dump_events(const char *path, const Tox_Events *events) } } -static void print_events(const Tox_System *sys, Tox_Events *events) +static void print_events(const struct Tox_System *sys, Tox_Events *events) { const uint32_t size = tox_events_bytes_size(events); @@ -64,7 +64,7 @@ static void print_events(const Tox_System *sys, Tox_Events *events) static bool await_message(Tox **toxes, const Tox_Dispatch *dispatch) { - const Tox_System *sys = tox_get_system(toxes[0]); + const struct Tox_System *sys = tox_get_system(toxes[0]); for (uint32_t i = 0; i < 100; ++i) { // Ignore events on tox 1. @@ -103,7 +103,7 @@ static void test_tox_events(void) ck_assert_msg(toxes[i] != nullptr, "failed to create tox instances %u", i); } - const Tox_System *sys = tox_get_system(toxes[0]); + const struct Tox_System *sys = tox_get_system(toxes[0]); Tox_Err_Dispatch_New err_new; Tox_Dispatch *dispatch = tox_dispatch_new(&err_new); diff --git a/auto_tests/tox_events_test.c b/auto_tests/tox_events_test.c index 04549b2179c..9bc211fd33d 100644 --- a/auto_tests/tox_events_test.c +++ b/auto_tests/tox_events_test.c @@ -7,9 +7,11 @@ #include #include "../testing/misc_tools.h" +#include "../toxcore/os_memory.h" #include "../toxcore/tox.h" #include "../toxcore/tox_events.h" #include "../toxcore/tox_struct.h" +#include "../toxcore/tox_time_impl.h" #include "auto_test_support.h" #include "check_compat.h" @@ -43,6 +45,9 @@ static uint64_t get_state_clock_callback(void *user_data) const uint64_t *clock = (const uint64_t *)user_data; return *clock; } +static const Tox_Time_Funcs mock_time_funcs = { + get_state_clock_callback, +}; static void test_tox_events(void) { @@ -59,13 +64,17 @@ static void test_tox_events(void) ck_assert_msg(toxes[i] != nullptr, "failed to create tox instances %u", i); } + const Memory *mem = os_memory(); + uint64_t clock = current_time_monotonic(toxes[0]->mono_time); + Tox_Time *tm = tox_time_new(&mock_time_funcs, &clock, mem); + Mono_Time *mono_time; mono_time = toxes[0]->mono_time; - mono_time_set_current_time_callback(mono_time, get_state_clock_callback, &clock); + mono_time_set_current_time_callback(mono_time, tm); mono_time = toxes[1]->mono_time; - mono_time_set_current_time_callback(mono_time, get_state_clock_callback, &clock); + mono_time_set_current_time_callback(mono_time, tm); uint8_t pk[TOX_PUBLIC_KEY_SIZE]; tox_self_get_dht_id(toxes[0], pk); @@ -113,6 +122,8 @@ static void test_tox_events(void) for (uint32_t i = 0; i < 2; ++i) { tox_kill(toxes[i]); } + + tox_time_free(tm); } int main(void) diff --git a/auto_tests/tox_many_tcp_test.c b/auto_tests/tox_many_tcp_test.c index f466e3e1711..816707cb13b 100644 --- a/auto_tests/tox_many_tcp_test.c +++ b/auto_tests/tox_many_tcp_test.c @@ -8,6 +8,7 @@ #include "../testing/misc_tools.h" #include "../toxcore/crypto_core.h" +#include "../toxcore/os_random.h" #include "../toxcore/tox.h" #include "../toxcore/util.h" #include "auto_test_support.h" @@ -41,7 +42,7 @@ static uint16_t tcp_relay_port = 33448; static void test_many_clients_tcp(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); long long unsigned int cur_time = time(nullptr); Tox *toxes[NUM_TOXES_TCP]; @@ -144,7 +145,7 @@ static void test_many_clients_tcp(void) static void test_many_clients_tcp_b(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); long long unsigned int cur_time = time(nullptr); Tox *toxes[NUM_TOXES_TCP]; diff --git a/auto_tests/tox_many_test.c b/auto_tests/tox_many_test.c index 8501b5c172a..da44f23c4e2 100644 --- a/auto_tests/tox_many_test.c +++ b/auto_tests/tox_many_test.c @@ -8,6 +8,7 @@ #include "../testing/misc_tools.h" #include "../toxcore/crypto_core.h" +#include "../toxcore/os_random.h" #include "../toxcore/tox.h" #include "../toxcore/util.h" #include "auto_test_support.h" @@ -26,7 +27,7 @@ static void accept_friend_request(Tox *m, const uint8_t *public_key, const uint8 static void test_many_clients(void) { - const Random *rng = system_random(); + const Random *rng = os_random(); ck_assert(rng != nullptr); time_t cur_time = time(nullptr); Tox *toxes[TCP_TEST_NUM_TOXES]; diff --git a/auto_tests/toxav_many_test.c b/auto_tests/toxav_many_test.c index 725fe61317f..30d36df5943 100644 --- a/auto_tests/toxav_many_test.c +++ b/auto_tests/toxav_many_test.c @@ -15,8 +15,10 @@ #include "../toxav/toxav.h" #include "../toxcore/crypto_core.h" #include "../toxcore/logger.h" +#include "../toxcore/os_memory.h" #include "../toxcore/tox.h" #include "../toxcore/tox_struct.h" +#include "../toxcore/tox_time_impl.h" #include "../toxcore/util.h" #include "auto_test_support.h" #include "check_compat.h" @@ -144,6 +146,10 @@ static uint64_t get_state_clock_callback(void *user_data) return clock; } +static const Tox_Time_Funcs mock_time_funcs = { + get_state_clock_callback, +}; + static void increment_clock(Time_Data *time_data, uint64_t count) { pthread_mutex_lock(&time_data->lock); @@ -151,10 +157,10 @@ static void increment_clock(Time_Data *time_data, uint64_t count) pthread_mutex_unlock(&time_data->lock); } -static void set_current_time_callback(Tox *tox, Time_Data *time_data) +static void set_current_time_callback(Tox *tox, Tox_Time *tm) { Mono_Time *mono_time = tox->mono_time; - mono_time_set_current_time_callback(mono_time, get_state_clock_callback, time_data); + mono_time_set_current_time_callback(mono_time, tm); } static void test_av_three_calls(void) @@ -168,6 +174,10 @@ static void test_av_three_calls(void) Time_Data time_data; pthread_mutex_init(&time_data.lock, nullptr); + + const Memory *mem = os_memory(); + Tox_Time *tm = tox_time_new(&mock_time_funcs, &time_data, mem); + { Tox_Err_New error; @@ -175,23 +185,23 @@ static void test_av_three_calls(void) ck_assert(error == TOX_ERR_NEW_OK); time_data.clock = current_time_monotonic(bootstrap->mono_time); - set_current_time_callback(bootstrap, &time_data); + set_current_time_callback(bootstrap, tm); Alice = tox_new_log(nullptr, &error, &index[1]); ck_assert(error == TOX_ERR_NEW_OK); - set_current_time_callback(Alice, &time_data); + set_current_time_callback(Alice, tm); Bobs[0] = tox_new_log(nullptr, &error, &index[2]); ck_assert(error == TOX_ERR_NEW_OK); - set_current_time_callback(Bobs[0], &time_data); + set_current_time_callback(Bobs[0], tm); Bobs[1] = tox_new_log(nullptr, &error, &index[3]); ck_assert(error == TOX_ERR_NEW_OK); - set_current_time_callback(Bobs[1], &time_data); + set_current_time_callback(Bobs[1], tm); Bobs[2] = tox_new_log(nullptr, &error, &index[4]); ck_assert(error == TOX_ERR_NEW_OK); - set_current_time_callback(Bobs[2], &time_data); + set_current_time_callback(Bobs[2], tm); } printf("Created 5 instances of Tox\n"); @@ -367,6 +377,8 @@ static void test_av_three_calls(void) tox_kill(Alice); tox_kill(bootstrap); + tox_time_free(tm); + pthread_mutex_destroy(&time_data.lock); printf("\nTest successful!\n"); diff --git a/other/BUILD.bazel b/other/BUILD.bazel index 1a8929a3758..4ed80ec49c4 100644 --- a/other/BUILD.bazel +++ b/other/BUILD.bazel @@ -28,6 +28,9 @@ cc_binary( "//c-toxcore/toxcore:mono_time", "//c-toxcore/toxcore:network", "//c-toxcore/toxcore:onion_announce", + "//c-toxcore/toxcore:os_memory", + "//c-toxcore/toxcore:os_network", + "//c-toxcore/toxcore:os_random", "//c-toxcore/toxcore:tox", "//c-toxcore/toxcore:util", ], diff --git a/other/DHT_bootstrap.c b/other/DHT_bootstrap.c index e59f9eedea2..7eca4a0cf58 100644 --- a/other/DHT_bootstrap.c +++ b/other/DHT_bootstrap.c @@ -20,6 +20,9 @@ #include "../toxcore/group_onion_announce.h" #include "../toxcore/logger.h" #include "../toxcore/mono_time.h" +#include "../toxcore/os_memory.h" +#include "../toxcore/os_network.h" +#include "../toxcore/os_random.h" #include "../toxcore/tox.h" #include "../toxcore/util.h" @@ -143,11 +146,11 @@ int main(int argc, char *argv[]) logger_callback_log(logger, print_log, nullptr, nullptr); } - const Random *rng = system_random(); - const Network *ns = system_network(); - const Memory *mem = system_memory(); + const Random *rng = os_random(); + const Network *ns = os_network(); + const Memory *mem = os_memory(); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); const uint16_t start_port = PORT; const uint16_t end_port = start_port + (TOX_PORTRANGE_TO - TOX_PORTRANGE_FROM); DHT *dht = new_dht(logger, mem, rng, ns, mono_time, new_networking_ex(logger, mem, ns, &ip, start_port, end_port, nullptr), true, true); diff --git a/other/bootstrap_daemon/BUILD.bazel b/other/bootstrap_daemon/BUILD.bazel index e1a2e41f449..8e083558b77 100644 --- a/other/bootstrap_daemon/BUILD.bazel +++ b/other/bootstrap_daemon/BUILD.bazel @@ -19,6 +19,9 @@ cc_binary( "//c-toxcore/toxcore:logger", "//c-toxcore/toxcore:mono_time", "//c-toxcore/toxcore:onion_announce", + "//c-toxcore/toxcore:os_memory", + "//c-toxcore/toxcore:os_network", + "//c-toxcore/toxcore:os_random", "//c-toxcore/toxcore:tox", "//c-toxcore/toxcore:util", "@libconfig", diff --git a/other/bootstrap_daemon/src/tox-bootstrapd.c b/other/bootstrap_daemon/src/tox-bootstrapd.c index 7efd2c889d3..c799eb1f8f0 100644 --- a/other/bootstrap_daemon/src/tox-bootstrapd.c +++ b/other/bootstrap_daemon/src/tox-bootstrapd.c @@ -33,6 +33,9 @@ #include "../../../toxcore/logger.h" #include "../../../toxcore/mono_time.h" #include "../../../toxcore/onion_announce.h" +#include "../../../toxcore/os_memory.h" +#include "../../../toxcore/os_network.h" +#include "../../../toxcore/os_random.h" #include "../../../toxcore/util.h" // misc @@ -280,9 +283,9 @@ int main(int argc, char *argv[]) } const uint16_t end_port = start_port + (TOX_PORTRANGE_TO - TOX_PORTRANGE_FROM); - const Memory *mem = system_memory(); - const Random *rng = system_random(); - const Network *ns = system_network(); + const Memory *mem = os_memory(); + const Random *rng = os_random(); + const Network *ns = os_network(); Networking_Core *net = new_networking_ex(logger, mem, ns, &ip, start_port, end_port, nullptr); if (net == nullptr) { @@ -310,7 +313,7 @@ int main(int argc, char *argv[]) } } - Mono_Time *const mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *const mono_time = mono_time_new(mem, nullptr); if (mono_time == nullptr) { log_write(LOG_LEVEL_ERROR, "Couldn't initialize monotonic timer. Exiting.\n"); diff --git a/testing/BUILD.bazel b/testing/BUILD.bazel index 68e89a15918..b9c0f63f31d 100644 --- a/testing/BUILD.bazel +++ b/testing/BUILD.bazel @@ -57,5 +57,8 @@ cc_binary( "//c-toxcore/toxcore:Messenger", "//c-toxcore/toxcore:ccompat", "//c-toxcore/toxcore:mono_time", + "//c-toxcore/toxcore:os_memory", + "//c-toxcore/toxcore:os_network", + "//c-toxcore/toxcore:os_random", ], ) diff --git a/testing/Messenger_test.c b/testing/Messenger_test.c index 4c2c8f85ffb..a5548c86810 100644 --- a/testing/Messenger_test.c +++ b/testing/Messenger_test.c @@ -35,6 +35,9 @@ #include "../toxcore/Messenger.h" #include "../toxcore/ccompat.h" #include "../toxcore/mono_time.h" +#include "../toxcore/os_memory.h" +#include "../toxcore/os_network.h" +#include "../toxcore/os_random.h" #include "misc_tools.h" static void print_message(Messenger *m, uint32_t friendnumber, unsigned int type, const uint8_t *string, size_t length, @@ -92,8 +95,8 @@ int main(int argc, char *argv[]) exit(0); } - const Memory *mem = system_memory(); - Mono_Time *const mono_time = mono_time_new(mem, nullptr, nullptr); + const Memory *mem = os_memory(); + Mono_Time *const mono_time = mono_time_new(mem, nullptr); if (mono_time == nullptr) { fputs("Failed to allocate monotonic timer datastructure\n", stderr); @@ -103,7 +106,7 @@ int main(int argc, char *argv[]) Messenger_Options options = {0}; options.ipv6enabled = ipv6enabled; Messenger_Error err; - m = new_messenger(mono_time, mem, system_random(), system_network(), &options, &err); + m = new_messenger(mono_time, mem, os_random(), os_network(), &options, &err); if (!m) { fprintf(stderr, "Failed to allocate messenger datastructure: %d\n", err); diff --git a/testing/fuzzing/BUILD.bazel b/testing/fuzzing/BUILD.bazel index 386516d72bf..68696f7ef09 100644 --- a/testing/fuzzing/BUILD.bazel +++ b/testing/fuzzing/BUILD.bazel @@ -15,7 +15,13 @@ cc_library( deps = [ "//c-toxcore/toxcore:crypto_core", "//c-toxcore/toxcore:network", + "//c-toxcore/toxcore:os_network", "//c-toxcore/toxcore:tox", + "//c-toxcore/toxcore:tox_memory", + "//c-toxcore/toxcore:tox_network", + "//c-toxcore/toxcore:tox_random", + "//c-toxcore/toxcore:tox_system", + "//c-toxcore/toxcore:tox_time", ], ) diff --git a/testing/fuzzing/bootstrap_harness.cc b/testing/fuzzing/bootstrap_harness.cc index 9ffb69d1f1b..ee98f84608b 100644 --- a/testing/fuzzing/bootstrap_harness.cc +++ b/testing/fuzzing/bootstrap_harness.cc @@ -107,6 +107,9 @@ void setup_callbacks(Tox_Dispatch *dispatch) void TestBootstrap(Fuzz_Data &input) { + // Null system for regularly working memory allocations needed in + // tox_events_equal. + Null_System null_sys; Fuzz_System sys(input); Ptr opts(tox_options_new(nullptr), tox_options_free); @@ -154,11 +157,8 @@ void TestBootstrap(Fuzz_Data &input) uint8_t pub_key[TOX_PUBLIC_KEY_SIZE] = {0}; - const bool udp_success = tox_bootstrap(tox, "127.0.0.2", 33446, pub_key, nullptr); - assert(udp_success); - - const bool tcp_success = tox_add_tcp_relay(tox, "127.0.0.2", 33446, pub_key, nullptr); - assert(tcp_success); + tox_bootstrap(tox, "127.0.0.2", 33446, pub_key, nullptr); + tox_add_tcp_relay(tox, "127.0.0.2", 33446, pub_key, nullptr); tox_events_init(tox); @@ -169,7 +169,7 @@ void TestBootstrap(Fuzz_Data &input) while (input.size > 0) { Tox_Err_Events_Iterate error_iterate; Tox_Events *events = tox_events_iterate(tox, true, &error_iterate); - assert(tox_events_equal(sys.sys.get(), events, events)); + assert(tox_events_equal(null_sys.sys.get(), events, events)); tox_dispatch_invoke(dispatch, events, tox, nullptr); tox_events_free(events); // Move the clock forward a decent amount so all the time-based checks diff --git a/testing/fuzzing/fuzz_support.cc b/testing/fuzzing/fuzz_support.cc index 510a6563f33..12e752abff0 100644 --- a/testing/fuzzing/fuzz_support.cc +++ b/testing/fuzzing/fuzz_support.cc @@ -17,17 +17,16 @@ #include "../../toxcore/crypto_core.h" #include "../../toxcore/network.h" -#include "../../toxcore/tox_private.h" +#include "../../toxcore/os_network_impl.h" +#include "../../toxcore/tox_memory_impl.h" +#include "../../toxcore/tox_network_impl.h" +#include "../../toxcore/tox_random_impl.h" +#include "../../toxcore/tox_system_impl.h" +#include "../../toxcore/tox_time_impl.h" #include "func_conversion.h" const bool DEBUG = false; -// TODO(iphydf): Put this somewhere shared. -struct Network_Addr { - struct sockaddr_storage addr; - size_t size; -}; - System::~System() { } static int recv_common(Fuzz_Data &input, uint8_t *buf, size_t buf_len) @@ -72,7 +71,7 @@ static void *alloc_common(Fuzz_Data &data, F func) return func(); } -static constexpr Memory_Funcs fuzz_memory_funcs = { +static constexpr Tox_Memory_Funcs fuzz_memory_funcs = { /* .malloc = */ ![](Fuzz_System *self, uint32_t size) { return alloc_common(self->data, [=]() { return std::malloc(size); }); @@ -82,14 +81,14 @@ static constexpr Memory_Funcs fuzz_memory_funcs = { return alloc_common(self->data, [=]() { return std::calloc(nmemb, size); }); }, /* .realloc = */ - ![](Fuzz_System *self, void *ptr, uint32_t size) { - return alloc_common(self->data, [=]() { return std::realloc(ptr, size); }); + ![](Fuzz_System *self, void *ptr, uint32_t nmemb, uint32_t size) { + return alloc_common(self->data, [=]() { return std::realloc(ptr, nmemb * size); }); }, /* .free = */ ![](Fuzz_System *self, void *ptr) { std::free(ptr); }, }; -static constexpr Network_Funcs fuzz_network_funcs = { +static constexpr Tox_Network_Funcs fuzz_network_funcs = { /* .close = */ ![](Fuzz_System *self, int sock) { return 0; }, /* .accept = */ ![](Fuzz_System *self, int sock) { return 1337; }, /* .bind = */ ![](Fuzz_System *self, int sock, const Network_Addr *addr) { return 0; }, @@ -109,16 +108,14 @@ static constexpr Network_Funcs fuzz_network_funcs = { /* .recvfrom = */ ![](Fuzz_System *self, int sock, uint8_t *buf, size_t len, Network_Addr *addr) { assert(sock == 42 || sock == 1337); - - addr->addr = sockaddr_storage{}; - // Dummy Addr - addr->addr.ss_family = AF_INET; + assert(addr != nullptr); // We want an AF_INET address with dummy values - sockaddr_in *addr_in = reinterpret_cast(&addr->addr); - addr_in->sin_port = htons(33446); - addr_in->sin_addr.s_addr = htonl(0x7f000002); // 127.0.0.2 - addr->size = sizeof(struct sockaddr); + sockaddr_in addr_in{}; + addr_in.sin_port = htons(33446); + addr_in.sin_addr.s_addr = htonl(0x7f000002); // 127.0.0.2 + + net_addr_set(addr, &addr_in, sizeof(addr_in)); return recv_common(self->data, buf, len); }, @@ -147,7 +144,7 @@ static constexpr Network_Funcs fuzz_network_funcs = { }, }; -static constexpr Random_Funcs fuzz_random_funcs = { +static constexpr Tox_Random_Funcs fuzz_random_funcs = { /* .random_bytes = */ ![](Fuzz_System *self, uint8_t *bytes, size_t length) { // Amount of data is limited @@ -165,7 +162,7 @@ static constexpr Random_Funcs fuzz_random_funcs = { ![](Fuzz_System *self, uint32_t upper_bound) { uint32_t randnum = 0; if (upper_bound > 0) { - self->rng->funcs->random_bytes( + self->rng->funcs->bytes_callback( self, reinterpret_cast(&randnum), sizeof(randnum)); randnum %= upper_bound; } @@ -173,34 +170,41 @@ static constexpr Random_Funcs fuzz_random_funcs = { }, }; +static constexpr Tox_Time_Funcs fuzz_time_funcs = { + /* .monotonic = */ + ![](Fuzz_System *self) { return self->clock; }, +}; + Fuzz_System::Fuzz_System(Fuzz_Data &input) : System{ std::make_unique(), std::make_unique(Memory{&fuzz_memory_funcs, this}), std::make_unique(Network{&fuzz_network_funcs, this}), std::make_unique(Random{&fuzz_random_funcs, this}), + std::make_unique(Tox_Time{&fuzz_time_funcs, this}), } , data(input) { - sys->mono_time_callback = ![](Fuzz_System *self) { return self->clock; }; - sys->mono_time_user_data = this; sys->mem = mem.get(); sys->ns = ns.get(); sys->rng = rng.get(); + sys->tm = tm.get(); } -static constexpr Memory_Funcs null_memory_funcs = { +static constexpr Tox_Memory_Funcs null_memory_funcs = { /* .malloc = */ ![](Null_System *self, uint32_t size) { return std::malloc(size); }, /* .calloc = */ ![](Null_System *self, uint32_t nmemb, uint32_t size) { return std::calloc(nmemb, size); }, /* .realloc = */ - ![](Null_System *self, void *ptr, uint32_t size) { return std::realloc(ptr, size); }, + ![](Null_System *self, void *ptr, uint32_t nmemb, uint32_t size) { + return std::realloc(ptr, nmemb * size); + }, /* .free = */ ![](Null_System *self, void *ptr) { std::free(ptr); }, }; -static constexpr Network_Funcs null_network_funcs = { +static constexpr Tox_Network_Funcs null_network_funcs = { /* .close = */ ![](Null_System *self, int sock) { return 0; }, /* .accept = */ ![](Null_System *self, int sock) { return 1337; }, /* .bind = */ ![](Null_System *self, int sock, const Network_Addr *addr) { return 0; }, @@ -248,7 +252,7 @@ static uint64_t simple_rng(uint64_t &seed) return seed; } -static constexpr Random_Funcs null_random_funcs = { +static constexpr Tox_Random_Funcs null_random_funcs = { /* .random_bytes = */ ![](Null_System *self, uint8_t *bytes, size_t length) { for (size_t i = 0; i < length; ++i) { @@ -264,36 +268,27 @@ static constexpr Random_Funcs null_random_funcs = { Null_System::Null_System() : System{ std::make_unique(), - std::make_unique(Memory{&null_memory_funcs, this}), - std::make_unique(Network{&null_network_funcs, this}), - std::make_unique(Random{&null_random_funcs, this}), + std::make_unique(Tox_Memory{&null_memory_funcs, this}), + std::make_unique(Tox_Network{&null_network_funcs, this}), + std::make_unique(Tox_Random{&null_random_funcs, this}), + std::make_unique(Tox_Time{&fuzz_time_funcs, this}), } { - sys->mono_time_callback = ![](Fuzz_System *self) { return self->clock; }; - sys->mono_time_user_data = this; sys->mem = mem.get(); sys->ns = ns.get(); sys->rng = rng.get(); + sys->tm = tm.get(); } -static uint16_t get_port(const Network_Addr *addr) -{ - if (addr->addr.ss_family == AF_INET6) { - return reinterpret_cast(&addr->addr)->sin6_port; - } else { - assert(addr->addr.ss_family == AF_INET); - return reinterpret_cast(&addr->addr)->sin_port; - } -} +static constexpr Tox_Memory_Funcs record_memory_funcs = null_memory_funcs; -static constexpr Memory_Funcs record_memory_funcs = null_memory_funcs; - -static constexpr Network_Funcs record_network_funcs = { +static constexpr Tox_Network_Funcs record_network_funcs = { /* .close = */ ![](Record_System *self, int sock) { return 0; }, /* .accept = */ ![](Record_System *self, int sock) { return 2; }, /* .bind = */ ![](Record_System *self, int sock, const Network_Addr *addr) { - const uint16_t port = get_port(addr); + assert(addr != nullptr); + const uint16_t port = net_addr_get_port(addr); if (self->global_.bound.find(port) != self->global_.bound.end()) { errno = EADDRINUSE; return -1; @@ -313,6 +308,7 @@ static constexpr Network_Funcs record_network_funcs = { /* .recvfrom = */ ![](Record_System *self, int sock, uint8_t *buf, size_t len, Network_Addr *addr) { assert(sock == 42); + assert(addr != nullptr); if (self->recvq.empty()) { self->recording.push_back(0xff); self->recording.push_back(0xff); @@ -327,15 +323,13 @@ static constexpr Network_Funcs record_network_funcs = { const size_t recvlen = std::min(len, packet.size()); std::copy(packet.begin(), packet.end(), buf); - addr->addr = sockaddr_storage{}; - // Dummy Addr - addr->addr.ss_family = AF_INET; - // We want an AF_INET address with dummy values - sockaddr_in *addr_in = reinterpret_cast(&addr->addr); - addr_in->sin_port = from; - addr_in->sin_addr.s_addr = htonl(0x7f000002); // 127.0.0.2 - addr->size = sizeof(struct sockaddr); + sockaddr_in addr_in{}; + addr_in.sin_family = AF_INET; + addr_in.sin_port = from; + addr_in.sin_addr.s_addr = htonl(0x7f000002); // 127.0.0.2 + + net_addr_set(addr, &addr_in, sizeof(addr_in)); assert(recvlen > 0 && recvlen <= INT_MAX); self->recording.push_back(recvlen >> 8); @@ -355,7 +349,8 @@ static constexpr Network_Funcs record_network_funcs = { /* .sendto = */ ![](Record_System *self, int sock, const uint8_t *buf, size_t len, const Network_Addr *addr) { assert(sock == 42); - auto backend = self->global_.bound.find(get_port(addr)); + assert(addr != nullptr); + auto backend = self->global_.bound.find(net_addr_get_port(addr)); assert(backend != self->global_.bound.end()); backend->second->receive(self->port, buf, len); return static_cast(len); @@ -373,7 +368,7 @@ static constexpr Network_Funcs record_network_funcs = { }, }; -static constexpr Random_Funcs record_random_funcs = { +static constexpr Tox_Random_Funcs record_random_funcs = { /* .random_bytes = */ ![](Record_System *self, uint8_t *bytes, size_t length) { for (size_t i = 0; i < length; ++i) { @@ -386,7 +381,7 @@ static constexpr Random_Funcs record_random_funcs = { } }, /* .random_uniform = */ - fuzz_random_funcs.random_uniform, + fuzz_random_funcs.uniform_callback, }; Record_System::Record_System(Global &global, uint64_t seed, const char *name) @@ -395,16 +390,16 @@ Record_System::Record_System(Global &global, uint64_t seed, const char *name) std::make_unique(Memory{&record_memory_funcs, this}), std::make_unique(Network{&record_network_funcs, this}), std::make_unique(Random{&record_random_funcs, this}), + std::make_unique(Tox_Time{&fuzz_time_funcs, this}), } , global_(global) , seed_(seed) , name_(name) { - sys->mono_time_callback = ![](Fuzz_System *self) { return self->clock; }; - sys->mono_time_user_data = this; sys->mem = mem.get(); sys->ns = ns.get(); sys->rng = rng.get(); + sys->tm = tm.get(); } void Record_System::receive(uint16_t send_port, const uint8_t *buf, size_t len) diff --git a/testing/fuzzing/fuzz_support.h b/testing/fuzzing/fuzz_support.h index a20d85b4f2e..e52e4cc7828 100644 --- a/testing/fuzzing/fuzz_support.h +++ b/testing/fuzzing/fuzz_support.h @@ -117,15 +117,17 @@ void fuzz_select_target(const uint8_t *data, std::size_t size, Args &&... args) return fuzz_select_target(selector, input, std::forward(args)...); } -struct Memory; -struct Network; -struct Random; +struct Tox_Memory; +struct Tox_Network; +struct Tox_Random; +struct Tox_Time; struct System { std::unique_ptr sys; - std::unique_ptr mem; - std::unique_ptr ns; - std::unique_ptr rng; + std::unique_ptr mem; + std::unique_ptr ns; + std::unique_ptr rng; + std::unique_ptr tm; // Not inline because sizeof of the above 2 structs is not known everywhere. ~System(); diff --git a/tox.h b/tox.h new file mode 100644 index 00000000000..64973f472f5 --- /dev/null +++ b/tox.h @@ -0,0 +1 @@ +#include "toxcore/tox.h" diff --git a/toxav.h b/toxav.h new file mode 100644 index 00000000000..25f999d9fd6 --- /dev/null +++ b/toxav.h @@ -0,0 +1 @@ +#include "toxav/toxav.h" diff --git a/toxav/BUILD.bazel b/toxav/BUILD.bazel index ca88f1334aa..c3f3423a89a 100644 --- a/toxav/BUILD.bazel +++ b/toxav/BUILD.bazel @@ -81,6 +81,7 @@ cc_test( deps = [ ":rtp", "//c-toxcore/toxcore:crypto_core", + "//c-toxcore/toxcore:os_random", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], diff --git a/toxav/rtp_test.cc b/toxav/rtp_test.cc index b29c937ac91..24e5244804d 100644 --- a/toxav/rtp_test.cc +++ b/toxav/rtp_test.cc @@ -3,6 +3,7 @@ #include #include "../toxcore/crypto_core.h" +#include "../toxcore/os_random.h" namespace { @@ -29,7 +30,7 @@ RTPHeader random_header(const Random *rng) TEST(Rtp, Deserialisation) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); RTPHeader const header = random_header(rng); diff --git a/toxav/toxav.c b/toxav/toxav.c index bdec43b504a..c9a3d1db70a 100644 --- a/toxav/toxav.c +++ b/toxav/toxav.c @@ -181,7 +181,7 @@ ToxAV *toxav_new(Tox *tox, Toxav_Err_New *error) av->tox = tox; av->m = m; - av->toxav_mono_time = mono_time_new(tox->sys.mem, nullptr, nullptr); + av->toxav_mono_time = mono_time_new(tox->sys.mem, nullptr); av->msi = msi_new(av->m); if (av->msi == nullptr) { diff --git a/toxcore/BUILD.bazel b/toxcore/BUILD.bazel index 4701cf437d3..38f693333c0 100644 --- a/toxcore/BUILD.bazel +++ b/toxcore/BUILD.bazel @@ -5,13 +5,22 @@ load("//tools:no_undefined.bzl", "cc_library") package(features = ["layering_check"]) exports_files( - srcs = ["tox.h"], + srcs = [ + "tox.h", + "tox_attributes.h", + "tox_logger.h", + "tox_memory.h", + "tox_network.h", + "tox_random.h", + "tox_system.h", + "tox_time.h", + ], visibility = ["//c-toxcore:__pkg__"], ) cc_library( - name = "attributes", - hdrs = ["attributes.h"], + name = "tox_attributes", + hdrs = ["tox_attributes.h"], visibility = ["//c-toxcore:__subpackages__"], ) @@ -20,7 +29,163 @@ cc_library( srcs = ["ccompat.c"], hdrs = ["ccompat.h"], visibility = ["//c-toxcore:__subpackages__"], - deps = [":attributes"], + deps = [":tox_attributes"], +) + +cc_library( + name = "tox_memory", + srcs = ["tox_memory.c"], + hdrs = [ + "tox_memory.h", + "tox_memory_impl.h", + ], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_attributes", + ], +) + +cc_library( + name = "tox_logger", + srcs = ["tox_logger.c"], + hdrs = [ + "tox_logger.h", + "tox_logger_impl.h", + ], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_attributes", + ":tox_memory", + ], +) + +cc_library( + name = "tox_network", + srcs = ["tox_network.c"], + hdrs = [ + "tox_network.h", + "tox_network_impl.h", + ], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_attributes", + ":tox_memory", + ], +) + +cc_library( + name = "tox_random", + srcs = ["tox_random.c"], + hdrs = [ + "tox_random.h", + "tox_random_impl.h", + ], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_attributes", + ":tox_memory", + ], +) + +cc_library( + name = "tox_time", + srcs = ["tox_time.c"], + hdrs = [ + "tox_time.h", + "tox_time_impl.h", + ], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_attributes", + ":tox_memory", + ], +) + +cc_library( + name = "tox_system", + srcs = ["tox_system.c"], + hdrs = [ + "tox_system.h", + "tox_system_impl.h", + ], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_attributes", + ":tox_logger", + ":tox_memory", + ":tox_network", + ":tox_random", + ":tox_time", + ], +) + +cc_library( + name = "os_logger", + srcs = ["os_logger.c"], + hdrs = ["os_logger.h"], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_logger", + ], +) + +cc_library( + name = "os_memory", + srcs = ["os_memory.c"], + hdrs = ["os_memory.h"], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_memory", + ], +) + +cc_library( + name = "os_network", + srcs = ["os_network.c"], + hdrs = [ + "os_network.h", + "os_network_impl.h", + ], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_network", + ], +) + +cc_library( + name = "os_random", + srcs = ["os_random.c"], + hdrs = ["os_random.h"], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":tox_random", + "@libsodium", + ], +) + +cc_library( + name = "os_system", + srcs = ["os_system.c"], + hdrs = ["os_system.h"], + visibility = ["//c-toxcore:__subpackages__"], + deps = [ + ":ccompat", + ":os_logger", + ":os_memory", + ":os_network", + ":os_random", + ":tox_system", + ], ) cc_library( @@ -29,8 +194,9 @@ cc_library( hdrs = ["mem.h"], visibility = ["//c-toxcore:__subpackages__"], deps = [ - ":attributes", ":ccompat", + ":tox_attributes", + ":tox_memory", ], ) @@ -40,6 +206,7 @@ cc_test( srcs = ["mem_test.cc"], deps = [ ":mem", + ":os_memory", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], @@ -57,9 +224,9 @@ cc_library( "//c-toxcore/toxav:__pkg__", ], deps = [ - ":attributes", ":ccompat", ":mem", + ":tox_attributes", "@pthread", ], ) @@ -70,6 +237,7 @@ cc_test( srcs = ["util_test.cc"], deps = [ ":crypto_core", + ":os_random", ":util", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", @@ -82,8 +250,8 @@ cc_library( hdrs = ["bin_pack.h"], visibility = ["//c-toxcore:__subpackages__"], deps = [ - ":attributes", ":ccompat", + ":tox_attributes", "//c-toxcore/third_party:cmp", ], ) @@ -94,8 +262,8 @@ cc_library( hdrs = ["bin_unpack.h"], visibility = ["//c-toxcore:__subpackages__"], deps = [ - ":attributes", ":ccompat", + ":tox_attributes", "//c-toxcore/third_party:cmp", ], ) @@ -118,8 +286,9 @@ cc_library( hdrs = ["crypto_core.h"], visibility = ["//c-toxcore:__subpackages__"], deps = [ - ":attributes", ":ccompat", + ":tox_attributes", + ":tox_random", "@libsodium", ], ) @@ -131,6 +300,7 @@ cc_test( flaky = True, deps = [ ":crypto_core", + ":os_random", ":util", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", @@ -142,8 +312,8 @@ cc_library( srcs = ["list.c"], hdrs = ["list.h"], deps = [ - ":attributes", ":ccompat", + ":tox_attributes", ], ) @@ -169,8 +339,8 @@ cc_library( "//c-toxcore/toxav:__pkg__", ], deps = [ - ":attributes", ":ccompat", + ":tox_attributes", ], ) @@ -196,9 +366,10 @@ cc_library( "//c-toxcore/toxav:__pkg__", ], deps = [ - ":attributes", ":ccompat", ":mem", + ":tox_attributes", + ":tox_time", "@pthread", ], ) @@ -209,6 +380,8 @@ cc_test( srcs = ["mono_time_test.cc"], deps = [ ":mono_time", + ":os_memory", + ":tox_time", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], @@ -250,6 +423,8 @@ cc_library( ":logger", ":mem", ":mono_time", + ":os_network", + ":tox_network", ":util", "@libsodium", "@psocket", @@ -298,6 +473,8 @@ cc_test( srcs = ["ping_array_test.cc"], deps = [ ":mono_time", + ":os_memory", + ":os_random", ":ping_array", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", @@ -338,7 +515,6 @@ cc_library( ], deps = [ ":LAN_discovery", - ":attributes", ":ccompat", ":crypto_core", ":logger", @@ -348,6 +524,7 @@ cc_library( ":ping_array", ":shared_key_cache", ":state", + ":tox_attributes", ":util", ], ) @@ -359,6 +536,9 @@ cc_test( deps = [ ":DHT", ":crypto_core", + ":os_memory", + ":os_network", + ":os_random", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], @@ -409,6 +589,8 @@ cc_fuzz_test( #corpus = ["//tools/toktok-fuzzer/corpus:forwarding_fuzz_test"], deps = [ ":forwarding", + ":os_memory", + ":os_network", "//c-toxcore/testing/fuzzing:fuzz_support", "//c-toxcore/testing/fuzzing:fuzz_tox", ], @@ -438,11 +620,11 @@ cc_library( hdrs = ["TCP_common.h"], visibility = ["//c-toxcore/auto_tests:__pkg__"], deps = [ - ":attributes", ":ccompat", ":crypto_core", ":mem", ":network", + ":tox_attributes", ], ) @@ -580,6 +762,8 @@ cc_test( deps = [ ":group_announce", ":mono_time", + ":os_memory", + ":tox_time", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], @@ -607,6 +791,8 @@ cc_fuzz_test( #corpus = ["//tools/toktok-fuzzer/corpus:group_announce_fuzz_test"], deps = [ ":group_announce", + ":os_memory", + ":tox_time", "//c-toxcore/testing/fuzzing:fuzz_support", ], ) @@ -698,6 +884,8 @@ cc_test( ":crypto_core", ":group_moderation", ":logger", + ":os_memory", + ":os_random", ":util", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", @@ -710,6 +898,7 @@ cc_fuzz_test( corpus = ["//tools/toktok-fuzzer/corpus:group_moderation_fuzz_test"], deps = [ ":group_moderation", + ":os_memory", "//c-toxcore/testing/fuzzing:fuzz_support", ], ) @@ -798,6 +987,9 @@ cc_library( ":mem", ":mono_time", ":network", + ":os_system", + ":tox_logger", + ":tox_system", "//c-toxcore/toxencryptsave:defines", ], ) @@ -808,6 +1000,7 @@ cc_test( srcs = ["tox_test.cc"], deps = [ ":crypto_core", + ":os_random", ":tox", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", @@ -820,10 +1013,10 @@ cc_library( hdrs = ["tox_unpack.h"], visibility = ["//c-toxcore:__subpackages__"], deps = [ - ":attributes", ":bin_unpack", ":ccompat", ":tox", + ":tox_attributes", ], ) @@ -836,12 +1029,13 @@ cc_library( hdrs = ["tox_events.h"], visibility = ["//c-toxcore:__subpackages__"], deps = [ - ":attributes", ":bin_pack", ":bin_unpack", ":ccompat", ":mem", ":tox", + ":tox_attributes", + ":tox_system", ":tox_unpack", "//c-toxcore/third_party:cmp", ], @@ -853,8 +1047,10 @@ cc_test( srcs = ["tox_events_test.cc"], deps = [ ":crypto_core", + ":os_system", ":tox", ":tox_events", + ":tox_system", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], diff --git a/toxcore/DHT.c b/toxcore/DHT.c index 1b4062cbbe4..0fc0103fe68 100644 --- a/toxcore/DHT.c +++ b/toxcore/DHT.c @@ -92,7 +92,7 @@ struct DHT { const Network *ns; Mono_Time *mono_time; const Memory *mem; - const Random *rng; + const Tox_Random *rng; Networking_Core *net; bool hole_punching_enabled; @@ -275,7 +275,7 @@ const uint8_t *dht_get_shared_key_sent(DHT *dht, const uint8_t *public_key) #define CRYPTO_SIZE (1 + CRYPTO_PUBLIC_KEY_SIZE * 2 + CRYPTO_NONCE_SIZE) -int create_request(const Random *rng, const uint8_t *send_public_key, const uint8_t *send_secret_key, +int create_request(const Tox_Random *rng, const uint8_t *send_public_key, const uint8_t *send_secret_key, uint8_t *packet, const uint8_t *recv_public_key, const uint8_t *data, uint32_t data_length, uint8_t request_id) { @@ -415,7 +415,7 @@ int pack_ip_port(const Logger *logger, uint8_t *data, uint16_t length, const IP_ } } -int dht_create_packet(const Memory *mem, const Random *rng, +int dht_create_packet(const Memory *mem, const Tox_Random *rng, const uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE], const uint8_t *shared_key, const uint8_t type, const uint8_t *plain, size_t plain_length, @@ -2449,7 +2449,7 @@ static void do_NAT(DHT *dht) * @return the number of nodes. */ non_null() -static uint16_t list_nodes(const Random *rng, const Client_data *list, size_t length, +static uint16_t list_nodes(const Tox_Random *rng, const Client_data *list, size_t length, uint64_t cur_time, Node_format *nodes, uint16_t max_num) { if (max_num == 0) { @@ -2609,7 +2609,7 @@ static int handle_LANdiscovery(void *object, const IP_Port *source, const uint8_ /*----------------------------------------------------------------------------------*/ -DHT *new_dht(const Logger *log, const Memory *mem, const Random *rng, const Network *ns, +DHT *new_dht(const Logger *log, const Memory *mem, const Tox_Random *rng, const Network *ns, Mono_Time *mono_time, Networking_Core *net, bool hole_punching_enabled, bool lan_discovery_enabled) { diff --git a/toxcore/DHT.h b/toxcore/DHT.h index 95f442e79fa..19bae82ce33 100644 --- a/toxcore/DHT.h +++ b/toxcore/DHT.h @@ -11,7 +11,7 @@ #include -#include "attributes.h" +#include "tox_attributes.h" #include "crypto_core.h" #include "logger.h" #include "mem.h" @@ -113,7 +113,7 @@ extern "C" { * @return the length of the created packet on success. */ non_null() -int create_request(const Random *rng, const uint8_t *send_public_key, const uint8_t *send_secret_key, +int create_request(const Tox_Random *rng, const uint8_t *send_public_key, const uint8_t *send_secret_key, uint8_t *packet, const uint8_t *recv_public_key, const uint8_t *data, uint32_t data_length, uint8_t request_id); @@ -220,7 +220,7 @@ int pack_ip_port(const Logger *logger, uint8_t *data, uint16_t length, const IP_ * @retval -1 on failure. */ non_null() -int dht_create_packet(const Memory *mem, const Random *rng, +int dht_create_packet(const Memory *mem, const Tox_Random *rng, const uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE], const uint8_t *shared_key, const uint8_t type, const uint8_t *plain, size_t plain_length, @@ -495,7 +495,7 @@ int dht_load(DHT *dht, const uint8_t *data, uint32_t length); /** Initialize DHT. */ non_null() -DHT *new_dht(const Logger *log, const Memory *mem, const Random *rng, const Network *ns, +DHT *new_dht(const Logger *log, const Memory *mem, const Tox_Random *rng, const Network *ns, Mono_Time *mono_time, Networking_Core *net, bool hole_punching_enabled, bool lan_discovery_enabled); nullable(1) diff --git a/toxcore/DHT_test.cc b/toxcore/DHT_test.cc index 84d3b9820a1..0f158b6dbc5 100644 --- a/toxcore/DHT_test.cc +++ b/toxcore/DHT_test.cc @@ -6,6 +6,9 @@ #include #include "crypto_core.h" +#include "os_memory.h" +#include "os_network.h" +#include "os_random.h" namespace { @@ -36,7 +39,7 @@ PublicKey random_pk(const Random *rng) TEST(IdClosest, IdenticalKeysAreSameDistance) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); PublicKey pk0 = random_pk(rng); @@ -48,7 +51,7 @@ TEST(IdClosest, IdenticalKeysAreSameDistance) TEST(IdClosest, DistanceIsCommutative) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); for (uint32_t i = 0; i < 100; ++i) { @@ -130,7 +133,7 @@ TEST(AddToList, OverridesKeysWithCloserKeys) TEST(Request, CreateAndParse) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); // Peers. @@ -187,12 +190,12 @@ TEST(Request, CreateAndParse) TEST(AnnounceNodes, SetAndTest) { - const Random *rng = system_random(); - const Network *ns = system_network(); - const Memory *mem = system_memory(); + const Random *rng = os_random(); + const Network *ns = os_network(); + const Memory *mem = os_memory(); Logger *log = logger_new(); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + Mono_Time *mono_time = mono_time_new(mem, nullptr); Networking_Core *net = new_networking_no_udp(log, mem, ns); DHT *dht = new_dht(log, mem, rng, ns, mono_time, net, true, true); ASSERT_NE(dht, nullptr); diff --git a/toxcore/Makefile.inc b/toxcore/Makefile.inc index 70df82b39e6..cc132cafa07 100644 --- a/toxcore/Makefile.inc +++ b/toxcore/Makefile.inc @@ -7,19 +7,26 @@ libtoxcore_la_includedir = $(includedir)/tox libtoxcore_la_SOURCES = ../third_party/cmp/cmp.c \ ../third_party/cmp/cmp.h \ - ../toxcore/attributes.h \ + ../toxcore/announce.c \ + ../toxcore/announce.h \ ../toxcore/bin_pack.c \ ../toxcore/bin_pack.h \ ../toxcore/bin_unpack.c \ ../toxcore/bin_unpack.h \ ../toxcore/ccompat.c \ ../toxcore/ccompat.h \ + ../toxcore/crypto_core.c \ + ../toxcore/crypto_core.h \ + ../toxcore/DHT.c \ + ../toxcore/DHT.h \ ../toxcore/events/conference_connected.c \ ../toxcore/events/conference_invite.c \ ../toxcore/events/conference_message.c \ ../toxcore/events/conference_peer_list_changed.c \ ../toxcore/events/conference_peer_name.c \ ../toxcore/events/conference_title.c \ + ../toxcore/events/events_alloc.c \ + ../toxcore/events/events_alloc.h \ ../toxcore/events/file_chunk_request.c \ ../toxcore/events/file_recv.c \ ../toxcore/events/file_recv_chunk.c \ @@ -34,90 +41,112 @@ libtoxcore_la_SOURCES = ../third_party/cmp/cmp.c \ ../toxcore/events/friend_status.c \ ../toxcore/events/friend_status_message.c \ ../toxcore/events/friend_typing.c \ - ../toxcore/events/events_alloc.c \ - ../toxcore/events/events_alloc.h \ ../toxcore/events/self_connection_status.c \ - ../toxcore/DHT.h \ - ../toxcore/DHT.c \ - ../toxcore/mem.h \ - ../toxcore/mem.c \ - ../toxcore/mono_time.h \ - ../toxcore/mono_time.c \ - ../toxcore/network.h \ - ../toxcore/network.c \ - ../toxcore/crypto_core.h \ - ../toxcore/crypto_core.c \ - ../toxcore/timed_auth.h \ - ../toxcore/timed_auth.c \ - ../toxcore/ping_array.h \ - ../toxcore/ping_array.c \ - ../toxcore/net_crypto.h \ - ../toxcore/net_crypto.c \ - ../toxcore/friend_requests.h \ - ../toxcore/friend_requests.c \ - ../toxcore/LAN_discovery.h \ - ../toxcore/LAN_discovery.c \ - ../toxcore/friend_connection.h \ + ../toxcore/forwarding.c \ + ../toxcore/forwarding.h \ ../toxcore/friend_connection.c \ - ../toxcore/Messenger.h \ - ../toxcore/Messenger.c \ - ../toxcore/ping.h \ - ../toxcore/ping.c \ - ../toxcore/shared_key_cache.h \ - ../toxcore/shared_key_cache.c \ - ../toxcore/state.h \ - ../toxcore/state.c \ - ../toxcore/tox.h \ - ../toxcore/tox.c \ - ../toxcore/tox_dispatch.h \ - ../toxcore/tox_dispatch.c \ - ../toxcore/tox_events.h \ - ../toxcore/tox_events.c \ - ../toxcore/tox_unpack.h \ - ../toxcore/tox_unpack.c \ - ../toxcore/tox_private.c \ - ../toxcore/tox_private.h \ - ../toxcore/tox_struct.h \ - ../toxcore/tox_api.c \ - ../toxcore/util.h \ - ../toxcore/util.c \ - ../toxcore/group.h \ - ../toxcore/group.c \ - ../toxcore/group_announce.h \ + ../toxcore/friend_connection.h \ + ../toxcore/friend_requests.c \ + ../toxcore/friend_requests.h \ ../toxcore/group_announce.c \ - ../toxcore/group_onion_announce.c \ - ../toxcore/group_onion_announce.h \ - ../toxcore/group_chats.h \ + ../toxcore/group_announce.h \ + ../toxcore/group.c \ ../toxcore/group_chats.c \ + ../toxcore/group_chats.h \ ../toxcore/group_common.h \ ../toxcore/group_connection.c \ ../toxcore/group_connection.h \ - ../toxcore/group_pack.c \ - ../toxcore/group_pack.h \ + ../toxcore/group.h \ ../toxcore/group_moderation.c \ ../toxcore/group_moderation.h \ - ../toxcore/onion.h \ - ../toxcore/onion.c \ - ../toxcore/logger.h \ + ../toxcore/group_onion_announce.c \ + ../toxcore/group_onion_announce.h \ + ../toxcore/group_pack.c \ + ../toxcore/group_pack.h \ + ../toxcore/LAN_discovery.c \ + ../toxcore/LAN_discovery.h \ + ../toxcore/list.c \ + ../toxcore/list.h \ ../toxcore/logger.c \ - ../toxcore/onion_announce.h \ + ../toxcore/logger.h \ + ../toxcore/mem.c \ + ../toxcore/mem.h \ + ../toxcore/Messenger.c \ + ../toxcore/Messenger.h \ + ../toxcore/mono_time.c \ + ../toxcore/mono_time.h \ + ../toxcore/net_crypto.c \ + ../toxcore/net_crypto.h \ + ../toxcore/network.c \ + ../toxcore/network.h \ ../toxcore/onion_announce.c \ - ../toxcore/onion_client.h \ + ../toxcore/onion_announce.h \ + ../toxcore/onion.c \ ../toxcore/onion_client.c \ - ../toxcore/announce.h \ - ../toxcore/announce.c \ - ../toxcore/forwarding.h \ - ../toxcore/forwarding.c \ - ../toxcore/TCP_client.h \ + ../toxcore/onion_client.h \ + ../toxcore/onion.h \ + ../toxcore/os_logger.c \ + ../toxcore/os_logger.h \ + ../toxcore/os_memory.c \ + ../toxcore/os_memory.h \ + ../toxcore/os_network.c \ + ../toxcore/os_network.h \ + ../toxcore/os_network_impl.h \ + ../toxcore/os_random.c \ + ../toxcore/os_random.h \ + ../toxcore/os_system.c \ + ../toxcore/os_system.h \ + ../toxcore/ping_array.c \ + ../toxcore/ping_array.h \ + ../toxcore/ping.c \ + ../toxcore/ping.h \ + ../toxcore/shared_key_cache.c \ + ../toxcore/shared_key_cache.h \ + ../toxcore/state.c \ + ../toxcore/state.h \ ../toxcore/TCP_client.c \ - ../toxcore/TCP_common.h \ + ../toxcore/TCP_client.h \ ../toxcore/TCP_common.c \ - ../toxcore/TCP_server.h \ - ../toxcore/TCP_server.c \ - ../toxcore/TCP_connection.h \ + ../toxcore/TCP_common.h \ ../toxcore/TCP_connection.c \ - ../toxcore/list.c \ - ../toxcore/list.h + ../toxcore/TCP_connection.h \ + ../toxcore/TCP_server.c \ + ../toxcore/TCP_server.h \ + ../toxcore/timed_auth.c \ + ../toxcore/timed_auth.h \ + ../toxcore/tox_api.c \ + ../toxcore/tox_attributes.h \ + ../toxcore/tox.c \ + ../toxcore/tox_dispatch.c \ + ../toxcore/tox_dispatch.h \ + ../toxcore/tox_events.c \ + ../toxcore/tox_events.h \ + ../toxcore/tox.h \ + ../toxcore/tox_logger.c \ + ../toxcore/tox_logger.h \ + ../toxcore/tox_logger_impl.h \ + ../toxcore/tox_memory.c \ + ../toxcore/tox_memory.h \ + ../toxcore/tox_memory_impl.h \ + ../toxcore/tox_network.c \ + ../toxcore/tox_network.h \ + ../toxcore/tox_network_impl.h \ + ../toxcore/tox_private.c \ + ../toxcore/tox_private.h \ + ../toxcore/tox_random.c \ + ../toxcore/tox_random.h \ + ../toxcore/tox_random_impl.h \ + ../toxcore/tox_struct.h \ + ../toxcore/tox_system.c \ + ../toxcore/tox_system.h \ + ../toxcore/tox_system_impl.h \ + ../toxcore/tox_time.c \ + ../toxcore/tox_time.h \ + ../toxcore/tox_time_impl.h \ + ../toxcore/tox_unpack.c \ + ../toxcore/tox_unpack.h \ + ../toxcore/util.c \ + ../toxcore/util.h libtoxcore_la_CFLAGS = -I$(top_srcdir) \ -I$(top_srcdir)/toxcore \ diff --git a/toxcore/Messenger.c b/toxcore/Messenger.c index f5ae68a0f21..4338d7fa672 100644 --- a/toxcore/Messenger.c +++ b/toxcore/Messenger.c @@ -3503,7 +3503,7 @@ static void m_handle_friend_request( * * if error is not NULL it will be set to one of the values in the enum above. */ -Messenger *new_messenger(Mono_Time *mono_time, const Memory *mem, const Random *rng, const Network *ns, +Messenger *new_messenger(Mono_Time *mono_time, const Memory *mem, const Tox_Random *rng, const Network *ns, Messenger_Options *options, Messenger_Error *error) { if (options == nullptr) { diff --git a/toxcore/Messenger.h b/toxcore/Messenger.h index cabb2af89d8..e4a42b952c4 100644 --- a/toxcore/Messenger.h +++ b/toxcore/Messenger.h @@ -246,7 +246,7 @@ struct Messenger { Logger *log; Mono_Time *mono_time; const Memory *mem; - const Random *rng; + const Tox_Random *rng; const Network *ns; Networking_Core *net; @@ -814,7 +814,7 @@ typedef enum Messenger_Error { * if error is not NULL it will be set to one of the values in the enum above. */ non_null() -Messenger *new_messenger(Mono_Time *mono_time, const Memory *mem, const Random *rng, const Network *ns, +Messenger *new_messenger(Mono_Time *mono_time, const Memory *mem, const Tox_Random *rng, const Network *ns, Messenger_Options *options, Messenger_Error *error); /** @brief Run this before closing shop. diff --git a/toxcore/TCP_client.c b/toxcore/TCP_client.c index 5aec2337f5b..ac1338e737d 100644 --- a/toxcore/TCP_client.c +++ b/toxcore/TCP_client.c @@ -571,7 +571,7 @@ void forwarding_handler(TCP_Client_Connection *con, forwarded_response_cb *forwa /** Create new TCP connection to ip_port/public_key */ TCP_Client_Connection *new_TCP_connection( - const Logger *logger, const Memory *mem, const Mono_Time *mono_time, const Random *rng, const Network *ns, + const Logger *logger, const Memory *mem, const Mono_Time *mono_time, const Tox_Random *rng, const Network *ns, const IP_Port *ip_port, const uint8_t *public_key, const uint8_t *self_public_key, const uint8_t *self_secret_key, const TCP_Proxy_Info *proxy_info) { diff --git a/toxcore/TCP_client.h b/toxcore/TCP_client.h index b020aaad91a..8b0c4bc2c5b 100644 --- a/toxcore/TCP_client.h +++ b/toxcore/TCP_client.h @@ -59,7 +59,7 @@ void tcp_con_set_custom_uint(TCP_Client_Connection *con, uint32_t value); /** Create new TCP connection to ip_port/public_key */ non_null(1, 2, 3, 4, 5, 6, 7, 8, 9) nullable(10) TCP_Client_Connection *new_TCP_connection( - const Logger *logger, const Memory *mem, const Mono_Time *mono_time, const Random *rng, const Network *ns, + const Logger *logger, const Memory *mem, const Mono_Time *mono_time, const Tox_Random *rng, const Network *ns, const IP_Port *ip_port, const uint8_t *public_key, const uint8_t *self_public_key, const uint8_t *self_secret_key, const TCP_Proxy_Info *proxy_info); diff --git a/toxcore/TCP_common.h b/toxcore/TCP_common.h index 44dc2e71e0d..4ac024c824c 100644 --- a/toxcore/TCP_common.h +++ b/toxcore/TCP_common.h @@ -65,7 +65,7 @@ void wipe_priority_list(const Memory *mem, TCP_Priority_List *p); typedef struct TCP_Connection { const Memory *mem; - const Random *rng; + const Tox_Random *rng; const Network *ns; Socket sock; IP_Port ip_port; // for debugging. diff --git a/toxcore/TCP_connection.c b/toxcore/TCP_connection.c index 2c75e74ea5f..5f36acf46b0 100644 --- a/toxcore/TCP_connection.c +++ b/toxcore/TCP_connection.c @@ -20,7 +20,7 @@ struct TCP_Connections { const Logger *logger; const Memory *mem; - const Random *rng; + const Tox_Random *rng; Mono_Time *mono_time; const Network *ns; DHT *dht; @@ -1585,7 +1585,7 @@ int set_tcp_onion_status(TCP_Connections *tcp_c, bool status) * * Returns NULL on failure. */ -TCP_Connections *new_tcp_connections(const Logger *logger, const Memory *mem, const Random *rng, const Network *ns, +TCP_Connections *new_tcp_connections(const Logger *logger, const Memory *mem, const Tox_Random *rng, const Network *ns, Mono_Time *mono_time, const uint8_t *secret_key, const TCP_Proxy_Info *proxy_info) { assert(logger != nullptr); diff --git a/toxcore/TCP_connection.h b/toxcore/TCP_connection.h index f01e7054459..3c75cae7161 100644 --- a/toxcore/TCP_connection.h +++ b/toxcore/TCP_connection.h @@ -298,7 +298,7 @@ uint32_t tcp_copy_connected_relays_index(const TCP_Connections *tcp_c, Node_form * Returns NULL on failure. */ non_null() -TCP_Connections *new_tcp_connections(const Logger *logger, const Memory *mem, const Random *rng, const Network *ns, +TCP_Connections *new_tcp_connections(const Logger *logger, const Memory *mem, const Tox_Random *rng, const Network *ns, Mono_Time *mono_time, const uint8_t *secret_key, const TCP_Proxy_Info *proxy_info); non_null() diff --git a/toxcore/TCP_server.c b/toxcore/TCP_server.c index 80a1f0165aa..a87b77dc5ae 100644 --- a/toxcore/TCP_server.c +++ b/toxcore/TCP_server.c @@ -59,7 +59,7 @@ typedef struct TCP_Secure_Connection { struct TCP_Server { const Logger *logger; const Memory *mem; - const Random *rng; + const Tox_Random *rng; const Network *ns; Onion *onion; Forwarding *forwarding; @@ -903,7 +903,7 @@ static int accept_connection(TCP_Server *tcp_server, Socket sock) } non_null() -static Socket new_listening_TCP_socket(const Logger *logger, const Network *ns, Family family, uint16_t port) +static Socket new_listening_TCP_socket(const Logger *logger, const Network *ns, const Memory *mem, Family family, uint16_t port) { const Socket sock = net_socket(ns, family, TOX_SOCK_STREAM, TOX_PROTO_TCP); @@ -922,7 +922,7 @@ static Socket new_listening_TCP_socket(const Logger *logger, const Network *ns, ok = set_socket_reuseaddr(ns, sock); } - ok = ok && bind_to_port(ns, sock, family, port) && (net_listen(ns, sock, TCP_MAX_BACKLOG) == 0); + ok = ok && bind_to_port(ns, mem, sock, family, port) && (net_listen(ns, sock, TCP_MAX_BACKLOG) == 0); if (!ok) { char *const error = net_new_strerror(net_error()); @@ -937,7 +937,7 @@ static Socket new_listening_TCP_socket(const Logger *logger, const Network *ns, return sock; } -TCP_Server *new_TCP_server(const Logger *logger, const Memory *mem, const Random *rng, const Network *ns, +TCP_Server *new_TCP_server(const Logger *logger, const Memory *mem, const Tox_Random *rng, const Network *ns, bool ipv6_enabled, uint16_t num_sockets, const uint16_t *ports, const uint8_t *secret_key, Onion *onion, Forwarding *forwarding) { @@ -986,7 +986,7 @@ TCP_Server *new_TCP_server(const Logger *logger, const Memory *mem, const Random const Family family = ipv6_enabled ? net_family_ipv6() : net_family_ipv4(); for (uint32_t i = 0; i < num_sockets; ++i) { - const Socket sock = new_listening_TCP_socket(logger, ns, family, ports[i]); + const Socket sock = new_listening_TCP_socket(logger, ns, mem, family, ports[i]); if (!sock_valid(sock)) { continue; diff --git a/toxcore/TCP_server.h b/toxcore/TCP_server.h index 090e821607d..5ec2f4f32c7 100644 --- a/toxcore/TCP_server.h +++ b/toxcore/TCP_server.h @@ -35,7 +35,7 @@ size_t tcp_server_listen_count(const TCP_Server *tcp_server); /** Create new TCP server instance. */ non_null(1, 2, 3, 4, 7, 8) nullable(9, 10) -TCP_Server *new_TCP_server(const Logger *logger, const Memory *mem, const Random *rng, const Network *ns, +TCP_Server *new_TCP_server(const Logger *logger, const Memory *mem, const Tox_Random *rng, const Network *ns, bool ipv6_enabled, uint16_t num_sockets, const uint16_t *ports, const uint8_t *secret_key, Onion *onion, Forwarding *forwarding); diff --git a/toxcore/announce.c b/toxcore/announce.c index fbbb2350c60..5a33a7972cc 100644 --- a/toxcore/announce.c +++ b/toxcore/announce.c @@ -51,7 +51,7 @@ typedef struct Announce_Entry { struct Announcements { const Logger *log; const Memory *mem; - const Random *rng; + const Tox_Random *rng; Forwarding *forwarding; const Mono_Time *mono_time; DHT *dht; @@ -637,7 +637,7 @@ static int handle_dht_announce_request(void *object, const IP_Port *source, return sendpacket(announce->net, source, reply, len) == len ? 0 : -1; } -Announcements *new_announcements(const Logger *log, const Memory *mem, const Random *rng, const Mono_Time *mono_time, +Announcements *new_announcements(const Logger *log, const Memory *mem, const Tox_Random *rng, const Mono_Time *mono_time, Forwarding *forwarding) { if (log == nullptr || mono_time == nullptr || forwarding == nullptr) { diff --git a/toxcore/announce.h b/toxcore/announce.h index bbd7a72b452..e3e1d22b80d 100644 --- a/toxcore/announce.h +++ b/toxcore/announce.h @@ -16,7 +16,7 @@ uint8_t announce_response_of_request_type(uint8_t request_type); typedef struct Announcements Announcements; non_null() -Announcements *new_announcements(const Logger *log, const Memory *mem, const Random *rng, const Mono_Time *mono_time, +Announcements *new_announcements(const Logger *log, const Memory *mem, const Tox_Random *rng, const Mono_Time *mono_time, Forwarding *forwarding); /** diff --git a/toxcore/bin_pack.h b/toxcore/bin_pack.h index 51646c088a5..f38ab5f0331 100644 --- a/toxcore/bin_pack.h +++ b/toxcore/bin_pack.h @@ -7,7 +7,7 @@ #include #include -#include "attributes.h" +#include "tox_attributes.h" #ifdef __cplusplus extern "C" { diff --git a/toxcore/bin_unpack.h b/toxcore/bin_unpack.h index bd4d8785c1f..a1b73b3c9a8 100644 --- a/toxcore/bin_unpack.h +++ b/toxcore/bin_unpack.h @@ -8,7 +8,7 @@ #include #include -#include "attributes.h" +#include "tox_attributes.h" #ifdef __cplusplus extern "C" { diff --git a/toxcore/ccompat.h b/toxcore/ccompat.h index 9ea6739a7d3..05525ef6691 100644 --- a/toxcore/ccompat.h +++ b/toxcore/ccompat.h @@ -10,7 +10,7 @@ #include // NULL, size_t -#include "attributes.h" +#include "tox_attributes.h" //!TOKSTYLE- diff --git a/toxcore/crypto_core.c b/toxcore/crypto_core.c index 14025252c41..f8fbb4eb1bd 100644 --- a/toxcore/crypto_core.c +++ b/toxcore/crypto_core.c @@ -29,6 +29,7 @@ #endif #include "ccompat.h" +#include "tox_random_impl.h" #ifndef crypto_box_MACBYTES #define crypto_box_MACBYTES (crypto_box_ZEROBYTES - crypto_box_BOXZEROBYTES) @@ -245,7 +246,7 @@ uint64_t random_u64(const Random *rng) uint32_t random_range_u32(const Random *rng, uint32_t upper_bound) { - return rng->funcs->random_uniform(rng->obj, upper_bound); + return tox_random_uniform(rng, upper_bound); } bool crypto_signature_create(uint8_t *signature, const uint8_t *message, uint64_t message_length, @@ -530,53 +531,7 @@ void crypto_sha512(uint8_t *hash, const uint8_t *data, size_t length) #endif } -non_null() -static void sys_random_bytes(void *obj, uint8_t *bytes, size_t length) -{ - randombytes(bytes, length); -} - -non_null() -static uint32_t sys_random_uniform(void *obj, uint32_t upper_bound) -{ -#ifdef VANILLA_NACL - if (upper_bound == 0) { - return 0; - } - - uint32_t randnum; - sys_random_bytes(obj, (uint8_t *)&randnum, sizeof(randnum)); - return randnum % upper_bound; -#else - return randombytes_uniform(upper_bound); -#endif -} - -static const Random_Funcs system_random_funcs = { - sys_random_bytes, - sys_random_uniform, -}; - -static const Random system_random_obj = {&system_random_funcs}; - -const Random *system_random(void) -{ -#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - if ((true)) { - return nullptr; - } -#endif -#ifndef VANILLA_NACL - // It is safe to call this function more than once and from different - // threads -- subsequent calls won't have any effects. - if (sodium_init() == -1) { - return nullptr; - } -#endif - return &system_random_obj; -} - void random_bytes(const Random *rng, uint8_t *bytes, size_t length) { - rng->funcs->random_bytes(rng->obj, bytes, length); + tox_random_bytes(rng, bytes, length); } diff --git a/toxcore/crypto_core.h b/toxcore/crypto_core.h index 3b9f27d677c..5e6c6a1d406 100644 --- a/toxcore/crypto_core.h +++ b/toxcore/crypto_core.h @@ -13,7 +13,8 @@ #include #include -#include "attributes.h" +#include "tox_attributes.h" +#include "tox_random.h" #ifdef __cplusplus extern "C" { @@ -75,21 +76,6 @@ extern "C" { */ #define CRYPTO_SHA512_SIZE 64 -typedef void crypto_random_bytes_cb(void *obj, uint8_t *bytes, size_t length); -typedef uint32_t crypto_random_uniform_cb(void *obj, uint32_t upper_bound); - -typedef struct Random_Funcs { - crypto_random_bytes_cb *random_bytes; - crypto_random_uniform_cb *random_uniform; -} Random_Funcs; - -typedef struct Random { - const Random_Funcs *funcs; - void *obj; -} Random; - -const Random *system_random(void); - /** * @brief The number of bytes in an encryption public key used by DHT group chats. */ @@ -208,6 +194,8 @@ bool crypto_sha512_eq(const uint8_t *cksum1, const uint8_t *cksum2); non_null() bool crypto_sha256_eq(const uint8_t *cksum1, const uint8_t *cksum2); +typedef Tox_Random Random; + /** * @brief Return a random 8 bit integer. */ diff --git a/toxcore/crypto_core_test.cc b/toxcore/crypto_core_test.cc index 4f2a9f3085b..bde7ec7bac8 100644 --- a/toxcore/crypto_core_test.cc +++ b/toxcore/crypto_core_test.cc @@ -6,6 +6,7 @@ #include #include +#include "os_random.h" #include "util.h" namespace { @@ -52,7 +53,7 @@ TEST(CryptoCore, IncrementNonceNumber) TEST(CryptoCore, Signatures) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); ExtPublicKey pk; @@ -76,7 +77,7 @@ TEST(CryptoCore, Signatures) TEST(CryptoCore, Hmac) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); HmacKey sk; diff --git a/toxcore/events/events_alloc.h b/toxcore/events/events_alloc.h index 6c5a7abd4f7..06a24942763 100644 --- a/toxcore/events/events_alloc.h +++ b/toxcore/events/events_alloc.h @@ -5,7 +5,7 @@ #ifndef C_TOXCORE_TOXCORE_TOX_EVENTS_INTERNAL_H #define C_TOXCORE_TOXCORE_TOX_EVENTS_INTERNAL_H -#include "../attributes.h" +#include "../tox_attributes.h" #include "../bin_pack.h" #include "../bin_unpack.h" #include "../tox_events.h" diff --git a/toxcore/forwarding.c b/toxcore/forwarding.c index 5e885abd211..a4812a72366 100644 --- a/toxcore/forwarding.c +++ b/toxcore/forwarding.c @@ -14,7 +14,7 @@ struct Forwarding { const Logger *log; - const Random *rng; + const Tox_Random *rng; DHT *dht; const Mono_Time *mono_time; Networking_Core *net; @@ -352,7 +352,7 @@ void set_callback_forward_reply(Forwarding *forwarding, forward_reply_cb *functi forwarding->forward_reply_callback_object = object; } -Forwarding *new_forwarding(const Logger *log, const Random *rng, const Mono_Time *mono_time, DHT *dht) +Forwarding *new_forwarding(const Logger *log, const Tox_Random *rng, const Mono_Time *mono_time, DHT *dht) { if (log == nullptr || mono_time == nullptr || dht == nullptr) { return nullptr; diff --git a/toxcore/forwarding.h b/toxcore/forwarding.h index 36ce8ad8943..168cfc7bda6 100644 --- a/toxcore/forwarding.h +++ b/toxcore/forwarding.h @@ -113,7 +113,7 @@ non_null(1) nullable(2, 3) void set_callback_forward_reply(Forwarding *forwarding, forward_reply_cb *function, void *object); non_null() -Forwarding *new_forwarding(const Logger *log, const Random *rng, const Mono_Time *mono_time, DHT *dht); +Forwarding *new_forwarding(const Logger *log, const Tox_Random *rng, const Mono_Time *mono_time, DHT *dht); nullable(1) void kill_forwarding(Forwarding *forwarding); diff --git a/toxcore/forwarding_fuzz_test.cc b/toxcore/forwarding_fuzz_test.cc index ce263f1e6fd..a6c5581aa51 100644 --- a/toxcore/forwarding_fuzz_test.cc +++ b/toxcore/forwarding_fuzz_test.cc @@ -5,14 +5,16 @@ #include "../testing/fuzzing/fuzz_support.h" #include "../testing/fuzzing/fuzz_tox.h" +#include "os_memory.h" +#include "os_network.h" namespace { void TestSendForwardRequest(Fuzz_Data &input) { - const Network *ns = system_network(); // TODO(iphydf): fuzz_network + const Network *ns = os_network(); // TODO(iphydf): fuzz_network assert(ns != nullptr); - const Memory *mem = system_memory(); // TODO(iphydf): fuzz_memory + const Memory *mem = os_memory(); // TODO(iphydf): fuzz_memory assert(mem != nullptr); with{} >> with{input, ns, mem} >> [&input](Ptr net) { @@ -29,9 +31,9 @@ void TestSendForwardRequest(Fuzz_Data &input) void TestForwardReply(Fuzz_Data &input) { - const Network *ns = system_network(); // TODO(iphydf): fuzz_network + const Network *ns = os_network(); // TODO(iphydf): fuzz_network assert(ns != nullptr); - const Memory *mem = system_memory(); // TODO(iphydf): fuzz_memory + const Memory *mem = os_memory(); // TODO(iphydf): fuzz_memory assert(mem != nullptr); with{} >> with{input, ns, mem} >> [&input](Ptr net) { diff --git a/toxcore/group.c b/toxcore/group.c index 0e851b1e348..7b02a056a77 100644 --- a/toxcore/group.c +++ b/toxcore/group.c @@ -1309,13 +1309,13 @@ static void remove_connection_reason(Group_Chats *g_c, Group_c *g, uint16_t i, u /** @brief Creates a new groupchat and puts it in the chats array. * - * @param rng Random number generator used for generating the group ID. + * @param rng Tox_Random number generator used for generating the group ID. * @param type is one of `GROUPCHAT_TYPE_*` * * @return group number on success. * @retval -1 on failure. */ -int add_groupchat(Group_Chats *g_c, const Random *rng, uint8_t type) +int add_groupchat(Group_Chats *g_c, const Tox_Random *rng, uint8_t type) { const int32_t groupnumber = create_group_chat(g_c); diff --git a/toxcore/group.h b/toxcore/group.h index e6f6c447333..cdc3a6d6a1e 100644 --- a/toxcore/group.h +++ b/toxcore/group.h @@ -93,14 +93,14 @@ void g_callback_peer_list_changed(Group_Chats *g_c, peer_list_changed_cb *functi /** @brief Creates a new groupchat and puts it in the chats array. * - * @param rng Random number generator used for generating the group ID. + * @param rng Tox_Random number generator used for generating the group ID. * @param type is one of `GROUPCHAT_TYPE_*` * * @return group number on success. * @retval -1 on failure. */ non_null() -int add_groupchat(Group_Chats *g_c, const Random *rng, uint8_t type); +int add_groupchat(Group_Chats *g_c, const Tox_Random *rng, uint8_t type); /** @brief Delete a groupchat from the chats array, informing the group first as * appropriate. diff --git a/toxcore/group_announce_fuzz_test.cc b/toxcore/group_announce_fuzz_test.cc index 6728e712840..89c6cd9a9bc 100644 --- a/toxcore/group_announce_fuzz_test.cc +++ b/toxcore/group_announce_fuzz_test.cc @@ -6,6 +6,8 @@ #include #include "../testing/fuzzing/fuzz_support.h" +#include "os_memory.h" +#include "tox_time_impl.h" namespace { @@ -45,15 +47,17 @@ void TestUnpackPublicAnnounce(Fuzz_Data &input) void TestDoGca(Fuzz_Data &input) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); std::unique_ptr logger(logger_new(), logger_kill); + constexpr Tox_Time_Funcs mock_time_funcs = { + [](void *user_data) { return *static_cast(user_data); }, + }; + uint64_t clock = 1; + std::unique_ptr tm( + tox_time_new(&mock_time_funcs, &clock, mem), tox_time_free); std::unique_ptr> mono_time( - mono_time_new(mem, nullptr, nullptr), [mem](Mono_Time *ptr) { mono_time_free(mem, ptr); }); + mono_time_new(mem, tm.get()), [mem](Mono_Time *ptr) { mono_time_free(mem, ptr); }); assert(mono_time != nullptr); - uint64_t clock = 1; - mono_time_set_current_time_callback( - mono_time.get(), [](void *user_data) { return *static_cast(user_data); }, - &clock); std::unique_ptr gca(new_gca_list(), kill_gca); assert(gca != nullptr); diff --git a/toxcore/group_announce_test.cc b/toxcore/group_announce_test.cc index d3d5d715817..736bb8375f4 100644 --- a/toxcore/group_announce_test.cc +++ b/toxcore/group_announce_test.cc @@ -3,12 +3,18 @@ #include #include "mono_time.h" +#include "os_memory.h" +#include "tox_time_impl.h" namespace { struct Announces : ::testing::Test { protected: - const Memory *mem_ = system_memory(); + const Memory *mem_ = os_memory(); + static constexpr Tox_Time_Funcs mock_time_funcs = { + [](void *user_data) { return *static_cast(user_data); }, + }; + Tox_Time *tm_ = tox_time_new(&mock_time_funcs, &this->clock_, mem_); uint64_t clock_ = 0; Mono_Time *mono_time_ = nullptr; GC_Announces_List *gca_ = nullptr; @@ -17,11 +23,8 @@ struct Announces : ::testing::Test { void SetUp() override { - mono_time_ = mono_time_new(mem_, nullptr, nullptr); + mono_time_ = mono_time_new(mem_, tm_); ASSERT_NE(mono_time_, nullptr); - mono_time_set_current_time_callback( - mono_time_, [](void *user_data) { return *static_cast(user_data); }, - &clock_); gca_ = new_gca_list(); ASSERT_NE(gca_, nullptr); } @@ -30,6 +33,7 @@ struct Announces : ::testing::Test { { kill_gca(gca_); mono_time_free(mem_, mono_time_); + tox_time_free(tm_); } void advance_clock(uint64_t increment) diff --git a/toxcore/group_chats.c b/toxcore/group_chats.c index a18ba1494c9..e0d581ccb4b 100644 --- a/toxcore/group_chats.c +++ b/toxcore/group_chats.c @@ -153,7 +153,7 @@ non_null() static bool group_exists(const GC_Session *c, const uint8_t *chat_id) non_null() static void add_tcp_relays_to_chat(const GC_Session *c, GC_Chat *chat); non_null(1, 2) nullable(4) static bool peer_delete(const GC_Session *c, GC_Chat *chat, uint32_t peer_number, void *userdata); -non_null() static void create_gc_session_keypair(const Logger *log, const Random *rng, uint8_t *public_key, +non_null() static void create_gc_session_keypair(const Logger *log, const Tox_Random *rng, uint8_t *public_key, uint8_t *secret_key); non_null() static size_t load_gc_peers(GC_Chat *chat, const GC_SavedPeerInfo *addrs, uint16_t num_addrs); non_null() static bool saved_peer_is_valid(const GC_SavedPeerInfo *saved_peer); @@ -744,7 +744,7 @@ static bool expand_chat_id(uint8_t *dest, const uint8_t *chat_id) /** Copies peer connect info from `gconn` to `addr`. */ non_null() -static void copy_gc_saved_peer(const Random *rng, const GC_Connection *gconn, GC_SavedPeerInfo *addr) +static void copy_gc_saved_peer(const Tox_Random *rng, const GC_Connection *gconn, GC_SavedPeerInfo *addr) { if (!gcc_copy_tcp_relay(rng, &addr->tcp_relay, gconn)) { addr->tcp_relay = (Node_format) { @@ -1469,7 +1469,7 @@ static int group_packet_unwrap(const Logger *log, const GC_Connection *gconn, ui } int group_packet_wrap( - const Logger *log, const Random *rng, const uint8_t *self_pk, const uint8_t *shared_key, uint8_t *packet, + const Logger *log, const Tox_Random *rng, const uint8_t *self_pk, const uint8_t *shared_key, uint8_t *packet, uint16_t packet_size, const uint8_t *data, uint16_t length, uint64_t message_id, uint8_t gp_packet_type, uint8_t net_packet_type) { @@ -5401,7 +5401,7 @@ static int unwrap_group_handshake_packet(const Logger *log, const uint8_t *self_ */ non_null() static int wrap_group_handshake_packet( - const Logger *log, const Random *rng, const uint8_t *self_pk, const uint8_t *self_sk, + const Logger *log, const Tox_Random *rng, const uint8_t *self_pk, const uint8_t *self_sk, const uint8_t *target_pk, uint8_t *packet, uint32_t packet_size, const uint8_t *data, uint16_t length) { @@ -7483,6 +7483,10 @@ int gc_group_load(GC_Session *c, Bin_Unpack *bu) chat->last_ping_interval = tm; chat->friend_connection_id = -1; + // Initialise these first, because we may need to log/dealloc things on cleanup. + chat->moderation.log = m->log; + chat->moderation.mem = m->mem; + if (!gc_load_unpack_group(chat, bu)) { LOGGER_ERROR(chat->log, "Failed to unpack group"); return -1; @@ -8266,7 +8270,7 @@ static bool group_exists(const GC_Session *c, const uint8_t *chat_id) } /** Creates a new 32-byte session encryption keypair and puts the results in `public_key` and `secret_key`. */ -static void create_gc_session_keypair(const Logger *log, const Random *rng, uint8_t *public_key, uint8_t *secret_key) +static void create_gc_session_keypair(const Logger *log, const Tox_Random *rng, uint8_t *public_key, uint8_t *secret_key) { if (crypto_new_keypair(rng, public_key, secret_key) != 0) { LOGGER_FATAL(log, "Failed to create group session keypair"); diff --git a/toxcore/group_chats.h b/toxcore/group_chats.h index 821e629a641..02963bce663 100644 --- a/toxcore/group_chats.h +++ b/toxcore/group_chats.h @@ -140,7 +140,7 @@ int get_peer_number_of_enc_pk(const GC_Chat *chat, const uint8_t *public_enc_key */ non_null(1, 2, 3, 4, 5) nullable(7) int group_packet_wrap( - const Logger *log, const Random *rng, const uint8_t *self_pk, const uint8_t *shared_key, uint8_t *packet, + const Logger *log, const Tox_Random *rng, const uint8_t *self_pk, const uint8_t *shared_key, uint8_t *packet, uint16_t packet_size, const uint8_t *data, uint16_t length, uint64_t message_id, uint8_t gp_packet_type, uint8_t net_packet_type); diff --git a/toxcore/group_common.h b/toxcore/group_common.h index 34d67dc8d62..65600d5f40a 100644 --- a/toxcore/group_common.h +++ b/toxcore/group_common.h @@ -248,7 +248,7 @@ typedef struct GC_Chat { Mono_Time *mono_time; const Logger *log; const Memory *mem; - const Random *rng; + const Tox_Random *rng; uint32_t connected_tcp_relays; Self_UDP_Status self_udp_status; diff --git a/toxcore/group_connection.c b/toxcore/group_connection.c index 86c353c00c0..b2e2cbe1ccc 100644 --- a/toxcore/group_connection.c +++ b/toxcore/group_connection.c @@ -268,7 +268,7 @@ void gcc_set_ip_port(GC_Connection *gconn, const IP_Port *ipp) } } -bool gcc_copy_tcp_relay(const Random *rng, Node_format *tcp_node, const GC_Connection *gconn) +bool gcc_copy_tcp_relay(const Tox_Random *rng, Node_format *tcp_node, const GC_Connection *gconn) { if (gconn == nullptr || tcp_node == nullptr) { return false; @@ -289,7 +289,7 @@ bool gcc_copy_tcp_relay(const Random *rng, Node_format *tcp_node, const GC_Conne return true; } -int gcc_save_tcp_relay(const Random *rng, GC_Connection *gconn, const Node_format *tcp_node) +int gcc_save_tcp_relay(const Tox_Random *rng, GC_Connection *gconn, const Node_format *tcp_node) { if (gconn == nullptr || tcp_node == nullptr) { return -1; diff --git a/toxcore/group_connection.h b/toxcore/group_connection.h index 2202c7ab36e..3756baf8633 100644 --- a/toxcore/group_connection.h +++ b/toxcore/group_connection.h @@ -88,7 +88,7 @@ void gcc_set_ip_port(GC_Connection *gconn, const IP_Port *ipp); * Return true on success. */ non_null() -bool gcc_copy_tcp_relay(const Random *rng, Node_format *tcp_node, const GC_Connection *gconn); +bool gcc_copy_tcp_relay(const Tox_Random *rng, Node_format *tcp_node, const GC_Connection *gconn); /** @brief Saves tcp_node to gconn's list of connected tcp relays. * @@ -99,7 +99,7 @@ bool gcc_copy_tcp_relay(const Random *rng, Node_format *tcp_node, const GC_Conne * Return -2 if node is already in list. */ non_null() -int gcc_save_tcp_relay(const Random *rng, GC_Connection *gconn, const Node_format *tcp_node); +int gcc_save_tcp_relay(const Tox_Random *rng, GC_Connection *gconn, const Node_format *tcp_node); /** @brief Checks for and handles messages that are in proper sequence in gconn's recv_array. * This should always be called after a new packet is successfully handled. diff --git a/toxcore/group_moderation_fuzz_test.cc b/toxcore/group_moderation_fuzz_test.cc index c5f46f3417c..dc4fbed76a1 100644 --- a/toxcore/group_moderation_fuzz_test.cc +++ b/toxcore/group_moderation_fuzz_test.cc @@ -1,13 +1,14 @@ #include "group_moderation.h" #include "../testing/fuzzing/fuzz_support.h" +#include "os_memory.h" namespace { void TestModListUnpack(Fuzz_Data &input) { CONSUME1_OR_RETURN(const uint16_t num_mods, input); - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; mod_list_unpack(&mods, input.data, input.size, num_mods); mod_list_cleanup(&mods); } diff --git a/toxcore/group_moderation_test.cc b/toxcore/group_moderation_test.cc index e55122896ad..07bec7c8141 100644 --- a/toxcore/group_moderation_test.cc +++ b/toxcore/group_moderation_test.cc @@ -8,6 +8,8 @@ #include "crypto_core.h" #include "logger.h" +#include "os_memory.h" +#include "os_random.h" #include "util.h" namespace { @@ -18,7 +20,7 @@ using ModerationHash = std::array; TEST(ModList, PackedSizeOfEmptyModListIsZero) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; EXPECT_EQ(mod_list_packed_size(&mods), 0); uint8_t byte = 1; @@ -28,14 +30,14 @@ TEST(ModList, PackedSizeOfEmptyModListIsZero) TEST(ModList, UnpackingZeroSizeArrayIsNoop) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; const uint8_t byte = 1; EXPECT_EQ(mod_list_unpack(&mods, &byte, 0, 0), 0); } TEST(ModList, AddRemoveMultipleMods) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; uint8_t sig_pk1[32] = {1}; uint8_t sig_pk2[32] = {2}; EXPECT_TRUE(mod_list_add_entry(&mods, sig_pk1)); @@ -47,7 +49,7 @@ TEST(ModList, AddRemoveMultipleMods) TEST(ModList, PackingAndUnpackingList) { using ModListEntry = std::array; - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; EXPECT_TRUE(mod_list_add_entry(&mods, ModListEntry{}.data())); std::vector packed(mod_list_packed_size(&mods)); @@ -55,7 +57,7 @@ TEST(ModList, PackingAndUnpackingList) EXPECT_TRUE(mod_list_remove_entry(&mods, ModListEntry{}.data())); - Moderation mods2{system_memory()}; + Moderation mods2{os_memory()}; EXPECT_EQ(mod_list_unpack(&mods2, packed.data(), packed.size(), 1), packed.size()); EXPECT_TRUE(mod_list_remove_entry(&mods2, ModListEntry{}.data())); } @@ -63,13 +65,13 @@ TEST(ModList, PackingAndUnpackingList) TEST(ModList, UnpackingTooManyModsFails) { using ModListEntry = std::array; - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; EXPECT_TRUE(mod_list_add_entry(&mods, ModListEntry{}.data())); std::vector packed(mod_list_packed_size(&mods)); mod_list_pack(&mods, packed.data()); - Moderation mods2{system_memory()}; + Moderation mods2{os_memory()}; EXPECT_EQ(mod_list_unpack(&mods2, packed.data(), packed.size(), 2), -1); EXPECT_TRUE(mod_list_remove_entry(&mods, ModListEntry{}.data())); } @@ -78,16 +80,16 @@ TEST(ModList, UnpackingFromEmptyBufferFails) { std::vector packed(1); - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; EXPECT_EQ(mod_list_unpack(&mods, packed.end().base(), 0, 1), -1); } TEST(ModList, HashOfEmptyModListZeroesOutBuffer) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; // Fill with random data, check that it's zeroed. ModerationHash hash; @@ -98,21 +100,21 @@ TEST(ModList, HashOfEmptyModListZeroesOutBuffer) TEST(ModList, RemoveIndexFromEmptyModListFails) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; EXPECT_FALSE(mod_list_remove_index(&mods, 0)); EXPECT_FALSE(mod_list_remove_index(&mods, UINT16_MAX)); } TEST(ModList, RemoveEntryFromEmptyModListFails) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; uint8_t sig_pk[32] = {0}; EXPECT_FALSE(mod_list_remove_entry(&mods, sig_pk)); } TEST(ModList, ModListRemoveIndex) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; uint8_t sig_pk[32] = {1}; EXPECT_TRUE(mod_list_add_entry(&mods, sig_pk)); EXPECT_TRUE(mod_list_remove_index(&mods, 0)); @@ -120,20 +122,20 @@ TEST(ModList, ModListRemoveIndex) TEST(ModList, CleanupOnEmptyModsIsNoop) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; mod_list_cleanup(&mods); } TEST(ModList, EmptyModListCannotVerifyAnySigPk) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; uint8_t sig_pk[32] = {1}; EXPECT_FALSE(mod_list_verify_sig_pk(&mods, sig_pk)); } TEST(ModList, ModListAddVerifyRemoveSigPK) { - Moderation mods{system_memory()}; + Moderation mods{os_memory()}; uint8_t sig_pk[32] = {1}; EXPECT_TRUE(mod_list_add_entry(&mods, sig_pk)); EXPECT_TRUE(mod_list_verify_sig_pk(&mods, sig_pk)); @@ -143,7 +145,7 @@ TEST(ModList, ModListAddVerifyRemoveSigPK) TEST(ModList, ModListHashCheck) { - Moderation mods1{system_memory()}; + Moderation mods1{os_memory()}; uint8_t sig_pk1[32] = {1}; std::array hash1; @@ -165,7 +167,7 @@ TEST(SanctionsList, PackingIntoUndersizedBufferFails) TEST(SanctionsList, PackUnpackSanctionsCreds) { - Moderation mod{system_memory()}; + Moderation mod{os_memory()}; std::array packed; EXPECT_EQ(sanctions_creds_pack(&mod.sanctions_creds, packed.data()), MOD_SANCTIONS_CREDS_SIZE); EXPECT_EQ( @@ -177,7 +179,7 @@ struct SanctionsListMod : ::testing::Test { ExtPublicKey pk; ExtSecretKey sk; Logger *log = logger_new(); - Moderation mod{system_memory()}; + Moderation mod{os_memory()}; Mod_Sanction sanctions[2] = {}; const uint8_t sanctioned_pk1[32] = {1}; diff --git a/toxcore/group_onion_announce.c b/toxcore/group_onion_announce.c index b797770e520..6e29d36ebe0 100644 --- a/toxcore/group_onion_announce.c +++ b/toxcore/group_onion_announce.c @@ -69,7 +69,7 @@ void gca_onion_init(GC_Announces_List *group_announce, Onion_Announce *onion_a) #ifndef VANILLA_NACL int create_gca_announce_request( - const Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, + const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id, const uint8_t *data_public_key, uint64_t sendback_data, const uint8_t *gc_data, uint16_t gc_data_length) diff --git a/toxcore/group_onion_announce.h b/toxcore/group_onion_announce.h index 5c6d64ec594..57f8cbd675e 100644 --- a/toxcore/group_onion_announce.h +++ b/toxcore/group_onion_announce.h @@ -14,7 +14,7 @@ void gca_onion_init(GC_Announces_List *group_announce, Onion_Announce *onion_a); non_null() int create_gca_announce_request( - const Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, + const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id, const uint8_t *data_public_key, uint64_t sendback_data, const uint8_t *gc_data, uint16_t gc_data_length); diff --git a/toxcore/list.h b/toxcore/list.h index a7c0e56c061..a05daf4f3cb 100644 --- a/toxcore/list.h +++ b/toxcore/list.h @@ -14,7 +14,7 @@ #include #include -#include "attributes.h" +#include "tox_attributes.h" #ifdef __cplusplus extern "C" { diff --git a/toxcore/logger.h b/toxcore/logger.h index ee5838ae734..a879e11fb95 100644 --- a/toxcore/logger.h +++ b/toxcore/logger.h @@ -11,7 +11,7 @@ #include -#include "attributes.h" +#include "tox_attributes.h" #ifdef __cplusplus extern "C" { diff --git a/toxcore/mem.c b/toxcore/mem.c index a15b9728df6..424c86bfc0e 100644 --- a/toxcore/mem.c +++ b/toxcore/mem.c @@ -1,88 +1,35 @@ /* SPDX-License-Identifier: GPL-3.0-or-later - * Copyright © 2016-2018 The TokTok team. + * Copyright © 2016-2023 The TokTok team. * Copyright © 2013 Tox project. */ #include "mem.h" -#include - -#include "ccompat.h" - -nullable(1) -static void *sys_malloc(void *obj, uint32_t size) -{ - return malloc(size); -} - -nullable(1) -static void *sys_calloc(void *obj, uint32_t nmemb, uint32_t size) -{ - return calloc(nmemb, size); -} - -nullable(1, 2) -static void *sys_realloc(void *obj, void *ptr, uint32_t size) -{ - return realloc(ptr, size); -} - -nullable(1, 2) -static void sys_free(void *obj, void *ptr) -{ - free(ptr); -} - -static const Memory_Funcs system_memory_funcs = { - sys_malloc, - sys_calloc, - sys_realloc, - sys_free, -}; -static const Memory system_memory_obj = {&system_memory_funcs}; - -const Memory *system_memory(void) -{ - return &system_memory_obj; -} - void *mem_balloc(const Memory *mem, uint32_t size) { - void *const ptr = mem->funcs->malloc(mem->obj, size); + void *const ptr = tox_memory_malloc(mem, size); return ptr; } void *mem_alloc(const Memory *mem, uint32_t size) { - void *const ptr = mem->funcs->calloc(mem->obj, 1, size); + void *const ptr = tox_memory_calloc(mem, 1, size); return ptr; } void *mem_valloc(const Memory *mem, uint32_t nmemb, uint32_t size) { - const uint32_t bytes = nmemb * size; - - if (size != 0 && bytes / size != nmemb) { - return nullptr; - } - - void *const ptr = mem->funcs->calloc(mem->obj, nmemb, size); + void *const ptr = tox_memory_calloc(mem, nmemb, size); return ptr; } void *mem_vrealloc(const Memory *mem, void *ptr, uint32_t nmemb, uint32_t size) { - const uint32_t bytes = nmemb * size; - - if (size != 0 && bytes / size != nmemb) { - return nullptr; - } - - void *const new_ptr = mem->funcs->realloc(mem->obj, ptr, bytes); + void *const new_ptr = tox_memory_vrealloc(mem, ptr, nmemb, size); return new_ptr; } void mem_delete(const Memory *mem, void *ptr) { - mem->funcs->free(mem->obj, ptr); + tox_memory_dealloc(mem, ptr); } diff --git a/toxcore/mem.h b/toxcore/mem.h index a9d9e1d2c9a..a8c6899d60d 100644 --- a/toxcore/mem.h +++ b/toxcore/mem.h @@ -11,31 +11,14 @@ #include // uint*_t -#include "attributes.h" +#include "tox_attributes.h" +#include "tox_memory.h" #ifdef __cplusplus extern "C" { #endif -typedef void *mem_malloc_cb(void *obj, uint32_t size); -typedef void *mem_calloc_cb(void *obj, uint32_t nmemb, uint32_t size); -typedef void *mem_realloc_cb(void *obj, void *ptr, uint32_t size); -typedef void mem_free_cb(void *obj, void *ptr); - -/** @brief Functions wrapping standard C memory allocation functions. */ -typedef struct Memory_Funcs { - mem_malloc_cb *malloc; - mem_calloc_cb *calloc; - mem_realloc_cb *realloc; - mem_free_cb *free; -} Memory_Funcs; - -typedef struct Memory { - const Memory_Funcs *funcs; - void *obj; -} Memory; - -const Memory *system_memory(void); +typedef Tox_Memory Memory; /** * @brief Allocate an array of a given size for built-in types. diff --git a/toxcore/mem_test.cc b/toxcore/mem_test.cc index f787036616c..bdd567cf07e 100644 --- a/toxcore/mem_test.cc +++ b/toxcore/mem_test.cc @@ -2,6 +2,8 @@ #include +#include "os_memory.h" + namespace { TEST(Mem, AllocLarge) @@ -9,7 +11,7 @@ TEST(Mem, AllocLarge) // Mebi prefix: https://en.wikipedia.org/wiki/Binary_prefix. constexpr uint32_t MI = 1024 * 1024; - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); void *ptr = mem_valloc(mem, 4, MI); EXPECT_NE(ptr, nullptr); @@ -22,18 +24,18 @@ TEST(Mem, AllocOverflow) // Gibi prefix. constexpr uint32_t GI = 1024 * 1024 * 1024; - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); // 1 gibi-elements of 100 bytes each. - void *ptr = mem_valloc(mem, GI, 100); + void *ptr = mem_vrealloc(mem, nullptr, GI, 100); EXPECT_EQ(ptr, nullptr); // 100 elements of 1 gibibyte each. - ptr = mem_valloc(mem, 100, GI); + ptr = mem_vrealloc(mem, nullptr, 100, GI); EXPECT_EQ(ptr, nullptr); // 128 (a multiple of 2) elements of 1 gibibyte each. - ptr = mem_valloc(mem, 128, GI); + ptr = mem_vrealloc(mem, nullptr, 128, GI); EXPECT_EQ(ptr, nullptr); } diff --git a/toxcore/mono_time.c b/toxcore/mono_time.c index e03046f799a..8683810fbef 100644 --- a/toxcore/mono_time.c +++ b/toxcore/mono_time.c @@ -32,6 +32,7 @@ #include #include "ccompat.h" +#include "tox_time_impl.h" /** don't call into system billions of times for no reason */ struct Mono_Time { @@ -49,8 +50,8 @@ struct Mono_Time { pthread_rwlock_t *time_update_lock; #endif - mono_time_current_time_cb *current_time_callback; - void *user_data; + const Tox_Time *tm; + Tox_Time default_tm; }; #ifdef OS_WIN32 @@ -121,8 +122,12 @@ static uint64_t current_time_monotonic_default(void *user_data) #endif // !__APPLE__ #endif // !OS_WIN32 +static const Tox_Time_Funcs os_time_funcs = { + current_time_monotonic_default, +}; + -Mono_Time *mono_time_new(const Memory *mem, mono_time_current_time_cb *current_time_callback, void *user_data) +Mono_Time *mono_time_new(const Memory *mem, const Tox_Time *tm) { Mono_Time *mono_time = (Mono_Time *)mem_alloc(mem, sizeof(Mono_Time)); @@ -145,7 +150,10 @@ Mono_Time *mono_time_new(const Memory *mem, mono_time_current_time_cb *current_t } #endif - mono_time_set_current_time_callback(mono_time, current_time_callback, user_data); + mono_time->default_tm.funcs = &os_time_funcs; + mono_time->default_tm.user_data = mono_time; + + mono_time->tm = tm != nullptr ? tm : &mono_time->default_tm; #ifdef OS_WIN32 @@ -196,7 +204,7 @@ void mono_time_update(Mono_Time *mono_time) pthread_mutex_lock(&mono_time->last_clock_lock); mono_time->last_clock_update = true; #endif - cur_time = mono_time->current_time_callback(mono_time->user_data) / 1000ULL; + cur_time = tox_time_monotonic(mono_time->tm) / 1000ULL; cur_time += mono_time->base_time; #ifdef OS_WIN32 pthread_mutex_unlock(&mono_time->last_clock_lock); @@ -233,16 +241,9 @@ bool mono_time_is_timeout(const Mono_Time *mono_time, uint64_t timestamp, uint64 return timestamp + timeout <= mono_time_get(mono_time); } -void mono_time_set_current_time_callback(Mono_Time *mono_time, - mono_time_current_time_cb *current_time_callback, void *user_data) +void mono_time_set_current_time_callback(Mono_Time *mono_time, const Tox_Time *tm) { - if (current_time_callback == nullptr) { - mono_time->current_time_callback = current_time_monotonic_default; - mono_time->user_data = mono_time; - } else { - mono_time->current_time_callback = current_time_callback; - mono_time->user_data = user_data; - } + mono_time->tm = tm != nullptr ? tm : &mono_time->default_tm; } /** @@ -257,7 +258,7 @@ uint64_t current_time_monotonic(Mono_Time *mono_time) * but must protect against other threads */ pthread_mutex_lock(&mono_time->last_clock_lock); #endif - const uint64_t cur_time = mono_time->current_time_callback(mono_time->user_data); + const uint64_t cur_time = tox_time_monotonic(mono_time->tm); #ifdef OS_WIN32 pthread_mutex_unlock(&mono_time->last_clock_lock); #endif diff --git a/toxcore/mono_time.h b/toxcore/mono_time.h index fa1df840e0c..b98bcf971ae 100644 --- a/toxcore/mono_time.h +++ b/toxcore/mono_time.h @@ -8,8 +8,9 @@ #include #include -#include "attributes.h" #include "mem.h" +#include "tox_attributes.h" +#include "tox_time.h" #ifdef __cplusplus extern "C" { @@ -46,10 +47,8 @@ extern "C" { */ typedef struct Mono_Time Mono_Time; -typedef uint64_t mono_time_current_time_cb(void *user_data); - -non_null(1) nullable(2, 3) -Mono_Time *mono_time_new(const Memory *mem, mono_time_current_time_cb *current_time_callback, void *user_data); +non_null(1) nullable(2) +Mono_Time *mono_time_new(const Memory *mem, const Tox_Time *tm); non_null(1) nullable(2) void mono_time_free(const Memory *mem, Mono_Time *mono_time); @@ -86,9 +85,8 @@ uint64_t current_time_monotonic(Mono_Time *mono_time); * The caller is obligated to ensure that `current_time_monotonic()` continues * to increase monotonically. */ -non_null(1) nullable(2, 3) -void mono_time_set_current_time_callback(Mono_Time *mono_time, - mono_time_current_time_cb *current_time_callback, void *user_data); +non_null(1) nullable(2) +void mono_time_set_current_time_callback(Mono_Time *mono_time, const Tox_Time *tm); #ifdef __cplusplus } diff --git a/toxcore/mono_time_test.cc b/toxcore/mono_time_test.cc index 379b606c8e5..ffc6d42d553 100644 --- a/toxcore/mono_time_test.cc +++ b/toxcore/mono_time_test.cc @@ -2,12 +2,15 @@ #include +#include "os_memory.h" +#include "tox_time_impl.h" + namespace { TEST(MonoTime, UnixTimeIncreasesOverTime) { - const Memory *mem = system_memory(); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + const Memory *mem = os_memory(); + Mono_Time *mono_time = mono_time_new(mem, nullptr); ASSERT_NE(mono_time, nullptr); mono_time_update(mono_time); @@ -25,8 +28,8 @@ TEST(MonoTime, UnixTimeIncreasesOverTime) TEST(MonoTime, IsTimeout) { - const Memory *mem = system_memory(); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + const Memory *mem = os_memory(); + Mono_Time *mono_time = mono_time_new(mem, nullptr); ASSERT_NE(mono_time, nullptr); uint64_t const start = mono_time_get(mono_time); @@ -43,14 +46,17 @@ TEST(MonoTime, IsTimeout) TEST(MonoTime, CustomTime) { - const Memory *mem = system_memory(); - Mono_Time *mono_time = mono_time_new(mem, nullptr, nullptr); + const Memory *mem = os_memory(); + Mono_Time *mono_time = mono_time_new(mem, nullptr); ASSERT_NE(mono_time, nullptr); uint64_t test_time = current_time_monotonic(mono_time) + 42137; - mono_time_set_current_time_callback( - mono_time, [](void *user_data) { return *static_cast(user_data); }, &test_time); + constexpr Tox_Time_Funcs mock_time_funcs = { + [](void *user_data) { return *static_cast(user_data); }, + }; + Tox_Time *tm = tox_time_new(&mock_time_funcs, &test_time, mem); + mono_time_set_current_time_callback(mono_time, tm); mono_time_update(mono_time); EXPECT_EQ(current_time_monotonic(mono_time), test_time); @@ -65,6 +71,7 @@ TEST(MonoTime, CustomTime) EXPECT_EQ(current_time_monotonic(mono_time), test_time); mono_time_free(mem, mono_time); + tox_time_free(tm); } } // namespace diff --git a/toxcore/net_crypto.c b/toxcore/net_crypto.c index 7fb4b3a8139..20759b09152 100644 --- a/toxcore/net_crypto.c +++ b/toxcore/net_crypto.c @@ -128,7 +128,7 @@ static const Crypto_Connection empty_crypto_connection = {{0}}; struct Net_Crypto { const Logger *log; const Memory *mem; - const Random *rng; + const Tox_Random *rng; Mono_Time *mono_time; const Network *ns; @@ -247,7 +247,7 @@ static int create_cookie_request(const Net_Crypto *c, uint8_t *packet, const uin * @retval 0 on success. */ non_null() -static int create_cookie(const Random *rng, const Mono_Time *mono_time, uint8_t *cookie, const uint8_t *bytes, +static int create_cookie(const Tox_Random *rng, const Mono_Time *mono_time, uint8_t *cookie, const uint8_t *bytes, const uint8_t *encryption_key) { uint8_t contents[COOKIE_CONTENTS_LENGTH]; @@ -3108,7 +3108,7 @@ void load_secret_key(Net_Crypto *c, const uint8_t *sk) /** @brief Create new instance of Net_Crypto. * Sets all the global connection variables to their default values. */ -Net_Crypto *new_net_crypto(const Logger *log, const Memory *mem, const Random *rng, const Network *ns, +Net_Crypto *new_net_crypto(const Logger *log, const Memory *mem, const Tox_Random *rng, const Network *ns, Mono_Time *mono_time, DHT *dht, const TCP_Proxy_Info *proxy_info) { if (dht == nullptr) { diff --git a/toxcore/net_crypto.h b/toxcore/net_crypto.h index ac6a0b59cbd..38b58ffe61b 100644 --- a/toxcore/net_crypto.h +++ b/toxcore/net_crypto.h @@ -398,7 +398,7 @@ void load_secret_key(Net_Crypto *c, const uint8_t *sk); * Sets all the global connection variables to their default values. */ non_null() -Net_Crypto *new_net_crypto(const Logger *log, const Memory *mem, const Random *rng, const Network *ns, +Net_Crypto *new_net_crypto(const Logger *log, const Memory *mem, const Tox_Random *rng, const Network *ns, Mono_Time *mono_time, DHT *dht, const TCP_Proxy_Info *proxy_info); /** return the optimal interval in ms for running do_net_crypto. */ diff --git a/toxcore/network.c b/toxcore/network.c index 5ccf068f53c..9b2d2146fde 100644 --- a/toxcore/network.c +++ b/toxcore/network.c @@ -37,12 +37,6 @@ #include "network.h" -#ifdef PLAN9 -#include // Plan 9 requires this is imported first -// Comment line here to avoid reordering by source code formatters. -#include -#endif - #ifdef OS_WIN32 // Put win32 includes here // The mingw32/64 Windows library warns about including winsock2.h after // windows.h even though with the above it's a valid thing to do. So, to make @@ -53,11 +47,6 @@ #include #endif -#ifdef __APPLE__ -#include -#include -#endif - #if !defined(OS_WIN32) #include #include @@ -87,21 +76,12 @@ #include #include -#ifndef VANILLA_NACL -// Used for sodium_init() -#include -#endif - #include "ccompat.h" #include "logger.h" #include "mono_time.h" +#include "os_network_impl.h" #include "util.h" -// Disable MSG_NOSIGNAL on systems not supporting it, e.g. Windows, FreeBSD -#if !defined(MSG_NOSIGNAL) -#define MSG_NOSIGNAL 0 -#endif - #ifndef IPV6_ADD_MEMBERSHIP #ifdef IPV6_JOIN_GROUP #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP @@ -377,47 +357,47 @@ IP6 get_ip6_loopback(void) const Socket net_invalid_socket = { (int)INVALID_SOCKET }; -Family net_family_unspec() +Family net_family_unspec(void) { return family_unspec; } -Family net_family_ipv4() +Family net_family_ipv4(void) { return family_ipv4; } -Family net_family_ipv6() +Family net_family_ipv6(void) { return family_ipv6; } -Family net_family_tcp_server() +Family net_family_tcp_server(void) { return family_tcp_server; } -Family net_family_tcp_client() +Family net_family_tcp_client(void) { return family_tcp_client; } -Family net_family_tcp_ipv4() +Family net_family_tcp_ipv4(void) { return family_tcp_ipv4; } -Family net_family_tcp_ipv6() +Family net_family_tcp_ipv6(void) { return family_tcp_ipv6; } -Family net_family_tox_tcp_ipv4() +Family net_family_tox_tcp_ipv4(void) { return family_tox_tcp_ipv4; } -Family net_family_tox_tcp_ipv6() +Family net_family_tox_tcp_ipv6(void) { return family_tox_tcp_ipv6; } @@ -472,147 +452,9 @@ bool sock_valid(Socket sock) return sock.sock != net_invalid_socket.sock; } -struct Network_Addr { - struct sockaddr_storage addr; - size_t size; -}; - -non_null() -static int sys_close(void *obj, int sock) -{ -#if defined(OS_WIN32) - return closesocket(sock); -#else // !OS_WIN32 - return close(sock); -#endif -} - -non_null() -static int sys_accept(void *obj, int sock) -{ - return accept(sock, nullptr, nullptr); -} - -non_null() -static int sys_bind(void *obj, int sock, const Network_Addr *addr) -{ - return bind(sock, (const struct sockaddr *)&addr->addr, addr->size); -} - -non_null() -static int sys_listen(void *obj, int sock, int backlog) -{ - return listen(sock, backlog); -} - -non_null() -static int sys_recvbuf(void *obj, int sock) -{ -#ifdef OS_WIN32 - u_long count = 0; - ioctlsocket(sock, FIONREAD, &count); -#else - int count = 0; - ioctl(sock, FIONREAD, &count); -#endif - - return count; -} - -non_null() -static int sys_recv(void *obj, int sock, uint8_t *buf, size_t len) -{ - return recv(sock, (char *)buf, len, MSG_NOSIGNAL); -} - -non_null() -static int sys_send(void *obj, int sock, const uint8_t *buf, size_t len) -{ - return send(sock, (const char *)buf, len, MSG_NOSIGNAL); -} - -non_null() -static int sys_sendto(void *obj, int sock, const uint8_t *buf, size_t len, const Network_Addr *addr) { - return sendto(sock, (const char *)buf, len, 0, (const struct sockaddr *)&addr->addr, addr->size); -} - -non_null() -static int sys_recvfrom(void *obj, int sock, uint8_t *buf, size_t len, Network_Addr *addr) { - socklen_t size = addr->size; - const int ret = recvfrom(sock, (char *)buf, len, 0, (struct sockaddr *)&addr->addr, &size); - addr->size = size; - return ret; -} - -non_null() -static int sys_socket(void *obj, int domain, int type, int proto) -{ - return (int)socket(domain, type, proto); -} - -non_null() -static int sys_socket_nonblock(void *obj, int sock, bool nonblock) -{ -#ifdef OS_WIN32 - u_long mode = nonblock ? 1 : 0; - return ioctlsocket(sock, FIONBIO, &mode); -#else - return fcntl(sock, F_SETFL, O_NONBLOCK, nonblock ? 1 : 0); -#endif /* OS_WIN32 */ -} - -non_null() -static int sys_getsockopt(void *obj, int sock, int level, int optname, void *optval, size_t *optlen) -{ - socklen_t len = *optlen; - const int ret = getsockopt(sock, level, optname, optval, &len); - *optlen = len; - return ret; -} - -non_null() -static int sys_setsockopt(void *obj, int sock, int level, int optname, const void *optval, size_t optlen) -{ - return setsockopt(sock, level, optname, optval, optlen); -} - -static const Network_Funcs system_network_funcs = { - sys_close, - sys_accept, - sys_bind, - sys_listen, - sys_recvbuf, - sys_recv, - sys_recvfrom, - sys_send, - sys_sendto, - sys_socket, - sys_socket_nonblock, - sys_getsockopt, - sys_setsockopt, -}; -static const Network system_network_obj = {&system_network_funcs}; - -const Network *system_network(void) -{ -#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - if ((true)) { - return nullptr; - } -#endif -#ifdef OS_WIN32 - WSADATA wsaData; - - if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR) { - return nullptr; - } -#endif - return &system_network_obj; -} - #if 0 -/* TODO(iphydf): Call this from functions that use `system_network()`. */ -void system_network_deinit(const Network *ns) +/* TODO(iphydf): Call this from functions that use `os_network()`. */ +void os_network_deinit(const Network *ns) { #ifdef OS_WIN32 WSACleanup(); @@ -623,13 +465,13 @@ void system_network_deinit(const Network *ns) non_null() static int net_setsockopt(const Network *ns, Socket sock, int level, int optname, const void *optval, size_t optlen) { - return ns->funcs->setsockopt(ns->obj, sock.sock, level, optname, optval, optlen); + return tox_network_setsockopt(ns, sock.sock, level, optname, optval, optlen); } non_null() static int net_getsockopt(const Network *ns, Socket sock, int level, int optname, void *optval, size_t *optlen) { - return ns->funcs->getsockopt(ns->obj, sock.sock, level, optname, optval, optlen); + return tox_network_getsockopt(ns, sock.sock, level, optname, optval, optlen); } non_null() @@ -804,7 +646,7 @@ static void loglogdata(const Logger *log, const char *message, const uint8_t *bu int net_send(const Network *ns, const Logger *log, Socket sock, const uint8_t *buf, size_t len, const IP_Port *ip_port) { - const int res = ns->funcs->send(ns->obj, sock.sock, buf, len); + const int res = tox_network_send(ns, sock.sock, buf, len); loglogdata(log, "T=>", buf, len, ip_port, res); return res; } @@ -814,13 +656,13 @@ static int net_sendto( const Network *ns, Socket sock, const uint8_t *buf, size_t len, const Network_Addr *addr, const IP_Port *ip_port) { - return ns->funcs->sendto(ns->obj, sock.sock, buf, len, addr); + return tox_network_sendto(ns, sock.sock, buf, len, addr); } int net_recv(const Network *ns, const Logger *log, Socket sock, uint8_t *buf, size_t len, const IP_Port *ip_port) { - const int res = ns->funcs->recv(ns->obj, sock.sock, buf, len); + const int res = tox_network_recv(ns, sock.sock, buf, len); loglogdata(log, "=>T", buf, len, ip_port, res); return res; } @@ -829,35 +671,35 @@ non_null() static int net_recvfrom(const Network *ns, Socket sock, uint8_t *buf, size_t len, Network_Addr *addr) { - return ns->funcs->recvfrom(ns->obj, sock.sock, buf, len, addr); + return tox_network_recvfrom(ns, sock.sock, buf, len, addr); } int net_listen(const Network *ns, Socket sock, int backlog) { - return ns->funcs->listen(ns->obj, sock.sock, backlog); + return tox_network_listen(ns, sock.sock, backlog); } non_null() static int net_bind(const Network *ns, Socket sock, const Network_Addr *addr) { - return ns->funcs->bind(ns->obj, sock.sock, addr); + return tox_network_bind(ns, sock.sock, addr); } Socket net_accept(const Network *ns, Socket sock) { - const Socket newsock = {ns->funcs->accept(ns->obj, sock.sock)}; + const Socket newsock = {tox_network_accept(ns, sock.sock)}; return newsock; } /** Close the socket. */ void kill_sock(const Network *ns, Socket sock) { - ns->funcs->close(ns->obj, sock.sock); + tox_network_close(ns, sock.sock); } bool set_socket_nonblock(const Network *ns, Socket sock) { - return ns->funcs->socket_nonblock(ns->obj, sock.sock, true) == 0; + return tox_network_socket_nonblock(ns, sock.sock, true) == 0; } bool set_socket_nosigpipe(const Network *ns, Socket sock) @@ -962,34 +804,41 @@ int send_packet(const Networking_Core *net, const IP_Port *ip_port, Packet packe ipp_copy.ip.ip.v6 = ip6; } - Network_Addr addr; + Network_Addr *addr; if (net_family_is_ipv4(ipp_copy.ip.family)) { - struct sockaddr_in *const addr4 = (struct sockaddr_in *)&addr.addr; + struct sockaddr_in addr4 = {0}; - addr.size = sizeof(struct sockaddr_in); - addr4->sin_family = AF_INET; - addr4->sin_port = ipp_copy.port; - fill_addr4(&ipp_copy.ip.ip.v4, &addr4->sin_addr); + addr4.sin_family = AF_INET; + addr4.sin_port = ipp_copy.port; + fill_addr4(&ipp_copy.ip.ip.v4, &addr4.sin_addr); + + addr = net_addr_new(&addr4, sizeof(addr4), net->mem); } else if (net_family_is_ipv6(ipp_copy.ip.family)) { - struct sockaddr_in6 *const addr6 = (struct sockaddr_in6 *)&addr.addr; + struct sockaddr_in6 addr6 = {0}; - addr.size = sizeof(struct sockaddr_in6); - addr6->sin6_family = AF_INET6; - addr6->sin6_port = ipp_copy.port; - fill_addr6(&ipp_copy.ip.ip.v6, &addr6->sin6_addr); + addr6.sin6_family = AF_INET6; + addr6.sin6_port = ipp_copy.port; + fill_addr6(&ipp_copy.ip.ip.v6, &addr6.sin6_addr); - addr6->sin6_flowinfo = 0; - addr6->sin6_scope_id = 0; + addr6.sin6_flowinfo = 0; + addr6.sin6_scope_id = 0; + + addr = net_addr_new(&addr6, sizeof(addr6), net->mem); } else { LOGGER_ERROR(net->log, "unknown address type: %d", ipp_copy.ip.family.value); return -1; } - const long res = net_sendto(net->ns, net->sock, packet.data, packet.length, &addr, &ipp_copy); + if (addr == nullptr) { + return -1; + } + + const long res = net_sendto(net->ns, net->sock, packet.data, packet.length, addr, &ipp_copy); loglogdata(net->log, "O=>", packet.data, packet.length, ip_port, res); assert(res <= INT_MAX); + net_addr_free(addr, net->mem); return (int)res; } @@ -1013,11 +862,14 @@ non_null() static int receivepacket(const Network *ns, const Memory *mem, const Logger *log, Socket sock, IP_Port *ip_port, uint8_t *data, uint32_t *length) { memset(ip_port, 0, sizeof(IP_Port)); - Network_Addr addr = {{0}}; - addr.size = sizeof(addr.addr); + Network_Addr *addr = net_addr_new(nullptr, 0, mem); *length = 0; - const int fail_or_len = net_recvfrom(ns, sock, data, MAX_UDP_PACKET_SIZE, &addr); + if (addr == nullptr) { + return -1; + } + + const int fail_or_len = net_recvfrom(ns, sock, data, MAX_UDP_PACKET_SIZE, addr); if (fail_or_len < 0) { const int error = net_error(); @@ -1028,30 +880,33 @@ static int receivepacket(const Network *ns, const Memory *mem, const Logger *log net_kill_strerror(strerror); } + net_addr_free(addr, mem); return -1; /* Nothing received. */ } *length = (uint32_t)fail_or_len; - if (addr.addr.ss_family == AF_INET) { - const struct sockaddr_in *addr_in = (const struct sockaddr_in *)&addr.addr; + if (net_addr_is_ipv4(addr)) { + const struct sockaddr_in *addr_in = (const struct sockaddr_in *)net_addr_get_addr(addr); const Family *const family = make_tox_family(addr_in->sin_family); assert(family != nullptr); if (family == nullptr) { + net_addr_free(addr, mem); return -1; } ip_port->ip.family = *family; get_ip4(&ip_port->ip.ip.v4, &addr_in->sin_addr); ip_port->port = addr_in->sin_port; - } else if (addr.addr.ss_family == AF_INET6) { - const struct sockaddr_in6 *addr_in6 = (const struct sockaddr_in6 *)&addr.addr; + } else if (net_addr_is_ipv6(addr)) { + const struct sockaddr_in6 *addr_in6 = (const struct sockaddr_in6 *)net_addr_get_addr(addr); const Family *const family = make_tox_family(addr_in6->sin6_family); assert(family != nullptr); if (family == nullptr) { + net_addr_free(addr, mem); return -1; } @@ -1064,11 +919,13 @@ static int receivepacket(const Network *ns, const Memory *mem, const Logger *log ip_port->ip.ip.v4.uint32 = ip_port->ip.ip.v6.uint32[3]; } } else { + net_addr_free(addr, mem); return -1; } loglogdata(log, "=>O", data, MAX_UDP_PACKET_SIZE, ip_port, *length); + net_addr_free(addr, mem); return 0; } @@ -1222,23 +1079,31 @@ Networking_Core *new_networking_ex( /* Bind our socket to port PORT and the given IP address (usually 0.0.0.0 or ::) */ uint16_t *portptr = nullptr; - Network_Addr addr; + Network_Addr *addr = net_addr_new(nullptr, 0, mem); - memset(&addr.addr, 0, sizeof(struct sockaddr_storage)); + if (addr == nullptr) { + kill_networking(temp); + + if (error != nullptr) { + *error = 2; + } + + return nullptr; + } if (net_family_is_ipv4(temp->family)) { - struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr.addr; + struct sockaddr_in *addr4 = (struct sockaddr_in *)net_addr_mut_addr(addr); - addr.size = sizeof(struct sockaddr_in); + net_addr_set_size(addr, sizeof(struct sockaddr_in)); addr4->sin_family = AF_INET; addr4->sin_port = 0; fill_addr4(&ip->ip.v4, &addr4->sin_addr); portptr = &addr4->sin_port; } else if (net_family_is_ipv6(temp->family)) { - struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr.addr; + struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)net_addr_mut_addr(addr); - addr.size = sizeof(struct sockaddr_in6); + net_addr_set_size(addr, sizeof(struct sockaddr_in6)); addr6->sin6_family = AF_INET6; addr6->sin6_port = 0; fill_addr6(&ip->ip.v6, &addr6->sin6_addr); @@ -1249,6 +1114,7 @@ Networking_Core *new_networking_ex( portptr = &addr6->sin6_port; } else { mem_delete(mem, temp); + net_addr_free(addr, mem); return nullptr; } @@ -1305,7 +1171,7 @@ Networking_Core *new_networking_ex( *portptr = net_htons(port_to_try); for (uint16_t tries = port_from; tries <= port_to; ++tries) { - const int res = net_bind(ns, temp->sock, &addr); + const int res = net_bind(ns, temp->sock, addr); if (res == 0) { temp->port = *portptr; @@ -1325,6 +1191,7 @@ Networking_Core *new_networking_ex( *error = 0; } + net_addr_free(addr, mem); return temp; } @@ -1349,6 +1216,7 @@ Networking_Core *new_networking_ex( *error = 1; } + net_addr_free(addr, mem); return nullptr; } @@ -1777,6 +1645,7 @@ int32_t net_getipport(const Memory *mem, const char *node, IP_Port **res, int to IP_Port *tmp = (IP_Port *)mem_alloc(mem, sizeof(IP_Port)); if (tmp == nullptr) { + *res = nullptr; return -1; } @@ -1788,7 +1657,11 @@ int32_t net_getipport(const Memory *mem, const char *node, IP_Port **res, int to #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION if ((true)) { *res = (IP_Port *)mem_alloc(mem, sizeof(IP_Port)); - assert(*res != nullptr); + + if (*res == nullptr) { + return -1; + } + IP_Port *ip_port = *res; ip_port->ip.ip.v4.uint32 = net_htonl(0x7F000003); // 127.0.0.3 ip_port->ip.family = *make_tox_family(AF_INET); @@ -1877,27 +1750,31 @@ void net_freeipport(const Memory *mem, IP_Port *ip_ports) mem_delete(mem, ip_ports); } -bool bind_to_port(const Network *ns, Socket sock, Family family, uint16_t port) +bool bind_to_port(const Network *ns, const Memory *mem, Socket sock, Family family, uint16_t port) { - Network_Addr addr = {{0}}; + Network_Addr *addr; if (net_family_is_ipv4(family)) { - struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr.addr; + struct sockaddr_in addr4 = {0}; - addr.size = sizeof(struct sockaddr_in); - addr4->sin_family = AF_INET; - addr4->sin_port = net_htons(port); + addr4.sin_family = AF_INET; + addr4.sin_port = net_htons(port); + + addr = net_addr_new(&addr4, sizeof(addr4), mem); } else if (net_family_is_ipv6(family)) { - struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr.addr; + struct sockaddr_in6 addr6 = {0}; - addr.size = sizeof(struct sockaddr_in6); - addr6->sin6_family = AF_INET6; - addr6->sin6_port = net_htons(port); + addr6.sin6_family = AF_INET6; + addr6.sin6_port = net_htons(port); + + addr = net_addr_new(&addr6, sizeof(addr6), mem); } else { return false; } - return net_bind(ns, sock, &addr) == 0; + const bool ok = net_bind(ns, sock, addr) == 0; + net_addr_free(addr, mem); + return ok; } Socket net_socket(const Network *ns, Family domain, int type, int protocol) @@ -1905,13 +1782,13 @@ Socket net_socket(const Network *ns, Family domain, int type, int protocol) const int platform_domain = make_family(domain); const int platform_type = make_socktype(type); const int platform_prot = make_proto(protocol); - const Socket sock = {ns->funcs->socket(ns->obj, platform_domain, platform_type, platform_prot)}; + const Socket sock = {tox_network_socket(ns, platform_domain, platform_type, platform_prot)}; return sock; } uint16_t net_socket_data_recv_buffer(const Network *ns, Socket sock) { - const int count = ns->funcs->recvbuf(ns->obj, sock.sock); + const int count = tox_network_recvbuf(ns, sock.sock); return (uint16_t)max_s32(0, min_s32(count, UINT16_MAX)); } diff --git a/toxcore/network.h b/toxcore/network.h index 2f518c1d910..59b4a10a019 100644 --- a/toxcore/network.h +++ b/toxcore/network.h @@ -15,62 +15,12 @@ #include "logger.h" #include "mem.h" +#include "tox_network.h" #ifdef __cplusplus extern "C" { #endif -/** - * @brief Wrapper for sockaddr_storage and size. - */ -typedef struct Network_Addr Network_Addr; - -typedef int net_close_cb(void *obj, int sock); -typedef int net_accept_cb(void *obj, int sock); -typedef int net_bind_cb(void *obj, int sock, const Network_Addr *addr); -typedef int net_listen_cb(void *obj, int sock, int backlog); -typedef int net_recvbuf_cb(void *obj, int sock); -typedef int net_recv_cb(void *obj, int sock, uint8_t *buf, size_t len); -typedef int net_recvfrom_cb(void *obj, int sock, uint8_t *buf, size_t len, Network_Addr *addr); -typedef int net_send_cb(void *obj, int sock, const uint8_t *buf, size_t len); -typedef int net_sendto_cb(void *obj, int sock, const uint8_t *buf, size_t len, const Network_Addr *addr); -typedef int net_socket_cb(void *obj, int domain, int type, int proto); -typedef int net_socket_nonblock_cb(void *obj, int sock, bool nonblock); -typedef int net_getsockopt_cb(void *obj, int sock, int level, int optname, void *optval, size_t *optlen); -typedef int net_setsockopt_cb(void *obj, int sock, int level, int optname, const void *optval, size_t optlen); -typedef int net_getaddrinfo_cb(void *obj, int family, Network_Addr **addrs); -typedef int net_freeaddrinfo_cb(void *obj, Network_Addr *addrs); - -/** @brief Functions wrapping POSIX network functions. - * - * Refer to POSIX man pages for documentation of what these functions are - * expected to do when providing alternative Network implementations. - */ -typedef struct Network_Funcs { - net_close_cb *close; - net_accept_cb *accept; - net_bind_cb *bind; - net_listen_cb *listen; - net_recvbuf_cb *recvbuf; - net_recv_cb *recv; - net_recvfrom_cb *recvfrom; - net_send_cb *send; - net_sendto_cb *sendto; - net_socket_cb *socket; - net_socket_nonblock_cb *socket_nonblock; - net_getsockopt_cb *getsockopt; - net_setsockopt_cb *setsockopt; - net_getaddrinfo_cb *getaddrinfo; - net_freeaddrinfo_cb *freeaddrinfo; -} Network_Funcs; - -typedef struct Network { - const Network_Funcs *funcs; - void *obj; -} Network; - -const Network *system_network(void); - typedef struct Family { uint8_t value; } Family; @@ -267,6 +217,8 @@ typedef struct Socket { int sock; } Socket; +typedef Tox_Network Network; + non_null() Socket net_socket(const Network *ns, Family domain, int type, int protocol); @@ -560,7 +512,7 @@ void net_freeipport(const Memory *mem, IP_Port *ip_ports); * @return true on success, false on failure. */ non_null() -bool bind_to_port(const Network *ns, Socket sock, Family family, uint16_t port); +bool bind_to_port(const Network *ns, const Memory *mem, Socket sock, Family family, uint16_t port); /** @brief Get the last networking error code. * diff --git a/toxcore/onion.c b/toxcore/onion.c index d7ec8bfd788..fafb21d0fb0 100644 --- a/toxcore/onion.c +++ b/toxcore/onion.c @@ -113,7 +113,7 @@ static int ipport_unpack(IP_Port *target, const uint8_t *data, unsigned int data * return -1 on failure. * return 0 on success. */ -int create_onion_path(const Random *rng, const DHT *dht, Onion_Path *new_path, const Node_format *nodes) +int create_onion_path(const Tox_Random *rng, const DHT *dht, Onion_Path *new_path, const Node_format *nodes) { if (new_path == nullptr || nodes == nullptr) { return -1; @@ -176,7 +176,7 @@ int onion_path_to_nodes(Node_format *nodes, unsigned int num_nodes, const Onion_ * return -1 on failure. * return length of created packet on success. */ -int create_onion_packet(const Random *rng, uint8_t *packet, uint16_t max_packet_length, +int create_onion_packet(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, const IP_Port *dest, const uint8_t *data, uint16_t length) { @@ -236,7 +236,7 @@ int create_onion_packet(const Random *rng, uint8_t *packet, uint16_t max_packet_ * return -1 on failure. * return length of created packet on success. */ -int create_onion_packet_tcp(const Random *rng, uint8_t *packet, uint16_t max_packet_length, +int create_onion_packet_tcp(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, const IP_Port *dest, const uint8_t *data, uint16_t length) { @@ -668,7 +668,7 @@ void set_callback_handle_recv_1(Onion *onion, onion_recv_1_cb *function, void *o onion->callback_object = object; } -Onion *new_onion(const Logger *log, const Memory *mem, const Mono_Time *mono_time, const Random *rng, DHT *dht) +Onion *new_onion(const Logger *log, const Memory *mem, const Mono_Time *mono_time, const Tox_Random *rng, DHT *dht) { if (dht == nullptr) { return nullptr; diff --git a/toxcore/onion.h b/toxcore/onion.h index 7f71c2493d3..93a472c21e7 100644 --- a/toxcore/onion.h +++ b/toxcore/onion.h @@ -19,7 +19,7 @@ typedef int onion_recv_1_cb(void *object, const IP_Port *dest, const uint8_t *da typedef struct Onion { const Logger *log; const Mono_Time *mono_time; - const Random *rng; + const Tox_Random *rng; const Memory *mem; DHT *dht; Networking_Core *net; @@ -81,7 +81,7 @@ typedef struct Onion_Path { * return 0 on success. */ non_null() -int create_onion_path(const Random *rng, const DHT *dht, Onion_Path *new_path, const Node_format *nodes); +int create_onion_path(const Tox_Random *rng, const DHT *dht, Onion_Path *new_path, const Node_format *nodes); /** @brief Dump nodes in onion path to nodes of length num_nodes. * @@ -101,7 +101,7 @@ int onion_path_to_nodes(Node_format *nodes, unsigned int num_nodes, const Onion_ * return length of created packet on success. */ non_null() -int create_onion_packet(const Random *rng, uint8_t *packet, uint16_t max_packet_length, +int create_onion_packet(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, const IP_Port *dest, const uint8_t *data, uint16_t length); @@ -116,7 +116,7 @@ int create_onion_packet(const Random *rng, uint8_t *packet, uint16_t max_packet_ * return length of created packet on success. */ non_null() -int create_onion_packet_tcp(const Random *rng, uint8_t *packet, uint16_t max_packet_length, +int create_onion_packet_tcp(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, const IP_Port *dest, const uint8_t *data, uint16_t length); @@ -148,7 +148,7 @@ non_null(1) nullable(2, 3) void set_callback_handle_recv_1(Onion *onion, onion_recv_1_cb *function, void *object); non_null() -Onion *new_onion(const Logger *log, const Memory *mem, const Mono_Time *mono_time, const Random *rng, DHT *dht); +Onion *new_onion(const Logger *log, const Memory *mem, const Mono_Time *mono_time, const Tox_Random *rng, DHT *dht); nullable(1) void kill_onion(Onion *onion); diff --git a/toxcore/onion_announce.c b/toxcore/onion_announce.c index 551e7b1fae9..4c72000b474 100644 --- a/toxcore/onion_announce.c +++ b/toxcore/onion_announce.c @@ -50,7 +50,7 @@ typedef struct Onion_Announce_Entry { struct Onion_Announce { const Logger *log; const Mono_Time *mono_time; - const Random *rng; + const Tox_Random *rng; const Memory *mem; DHT *dht; Networking_Core *net; @@ -97,7 +97,7 @@ void onion_announce_entry_set_time(Onion_Announce *onion_a, uint32_t entry, uint * return -1 on failure. * return packet length on success. */ -int create_announce_request(const Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, +int create_announce_request(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id, const uint8_t *data_public_key, uint64_t sendback_data) { @@ -140,7 +140,7 @@ int create_announce_request(const Random *rng, uint8_t *packet, uint16_t max_pac * return -1 on failure. * return 0 on success. */ -int create_data_request(const Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *public_key, +int create_data_request(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *public_key, const uint8_t *encrypt_public_key, const uint8_t *nonce, const uint8_t *data, uint16_t length) { if (DATA_REQUEST_MIN_SIZE + length > max_packet_length) { @@ -186,7 +186,7 @@ int create_data_request(const Random *rng, uint8_t *packet, uint16_t max_packet_ * return -1 on failure. * return 0 on success. */ -int send_announce_request(const Networking_Core *net, const Random *rng, +int send_announce_request(const Networking_Core *net, const Tox_Random *rng, const Onion_Path *path, const Node_format *dest, const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id, @@ -230,7 +230,7 @@ int send_announce_request(const Networking_Core *net, const Random *rng, * return -1 on failure. * return 0 on success. */ -int send_data_request(const Networking_Core *net, const Random *rng, const Onion_Path *path, const IP_Port *dest, +int send_data_request(const Networking_Core *net, const Tox_Random *rng, const Onion_Path *path, const IP_Port *dest, const uint8_t *public_key, const uint8_t *encrypt_public_key, const uint8_t *nonce, const uint8_t *data, uint16_t length) { @@ -642,7 +642,7 @@ static int handle_data_request(void *object, const IP_Port *source, const uint8_ return 0; } -Onion_Announce *new_onion_announce(const Logger *log, const Memory *mem, const Random *rng, const Mono_Time *mono_time, DHT *dht) +Onion_Announce *new_onion_announce(const Logger *log, const Memory *mem, const Tox_Random *rng, const Mono_Time *mono_time, DHT *dht) { if (dht == nullptr) { return nullptr; diff --git a/toxcore/onion_announce.h b/toxcore/onion_announce.h index 857f4706ace..97372e26f62 100644 --- a/toxcore/onion_announce.h +++ b/toxcore/onion_announce.h @@ -59,7 +59,7 @@ void onion_announce_entry_set_time(Onion_Announce *onion_a, uint32_t entry, uint * return packet length on success. */ non_null() -int create_announce_request(const Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, +int create_announce_request(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id, const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id, const uint8_t *data_public_key, uint64_t sendback_data); @@ -76,7 +76,7 @@ int create_announce_request(const Random *rng, uint8_t *packet, uint16_t max_pac * return 0 on success. */ non_null() -int create_data_request(const Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *public_key, +int create_data_request(const Tox_Random *rng, uint8_t *packet, uint16_t max_packet_length, const uint8_t *public_key, const uint8_t *encrypt_public_key, const uint8_t *nonce, const uint8_t *data, uint16_t length); /** @brief Create and send an onion announce request packet. @@ -94,7 +94,7 @@ int create_data_request(const Random *rng, uint8_t *packet, uint16_t max_packet_ * return 0 on success. */ non_null() -int send_announce_request(const Networking_Core *net, const Random *rng, +int send_announce_request(const Networking_Core *net, const Tox_Random *rng, const Onion_Path *path, const Node_format *dest, const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id, @@ -117,7 +117,7 @@ int send_announce_request(const Networking_Core *net, const Random *rng, * return 0 on success. */ non_null() -int send_data_request(const Networking_Core *net, const Random *rng, const Onion_Path *path, const IP_Port *dest, +int send_data_request(const Networking_Core *net, const Tox_Random *rng, const Onion_Path *path, const IP_Port *dest, const uint8_t *public_key, const uint8_t *encrypt_public_key, const uint8_t *nonce, const uint8_t *data, uint16_t length); @@ -131,7 +131,7 @@ void onion_announce_extra_data_callback(Onion_Announce *onion_a, uint16_t extra_ pack_extra_data_cb *extra_data_callback, void *extra_data_object); non_null() -Onion_Announce *new_onion_announce(const Logger *log, const Memory *mem, const Random *rng, const Mono_Time *mono_time, DHT *dht); +Onion_Announce *new_onion_announce(const Logger *log, const Memory *mem, const Tox_Random *rng, const Mono_Time *mono_time, DHT *dht); nullable(1) void kill_onion_announce(Onion_Announce *onion_a); diff --git a/toxcore/onion_client.c b/toxcore/onion_client.c index 6aef15ec3a8..8e46c16fab0 100644 --- a/toxcore/onion_client.c +++ b/toxcore/onion_client.c @@ -105,7 +105,7 @@ typedef struct Onion_Data_Handler { struct Onion_Client { const Mono_Time *mono_time; const Logger *logger; - const Random *rng; + const Tox_Random *rng; const Memory *mem; DHT *dht; @@ -2075,7 +2075,7 @@ void do_onion_client(Onion_Client *onion_c) onion_c->last_run = mono_time_get(onion_c->mono_time); } -Onion_Client *new_onion_client(const Logger *logger, const Memory *mem, const Random *rng, const Mono_Time *mono_time, Net_Crypto *c) +Onion_Client *new_onion_client(const Logger *logger, const Memory *mem, const Tox_Random *rng, const Mono_Time *mono_time, Net_Crypto *c) { if (c == nullptr) { return nullptr; diff --git a/toxcore/onion_client.h b/toxcore/onion_client.h index 6498f8c5c39..f6db95a6a51 100644 --- a/toxcore/onion_client.h +++ b/toxcore/onion_client.h @@ -208,7 +208,7 @@ non_null() void do_onion_client(Onion_Client *onion_c); non_null() -Onion_Client *new_onion_client(const Logger *logger, const Memory *mem, const Random *rng, const Mono_Time *mono_time, Net_Crypto *c); +Onion_Client *new_onion_client(const Logger *logger, const Memory *mem, const Tox_Random *rng, const Mono_Time *mono_time, Net_Crypto *c); nullable(1) void kill_onion_client(Onion_Client *onion_c); diff --git a/toxcore/os_logger.c b/toxcore/os_logger.c new file mode 100644 index 00000000000..8c425777a66 --- /dev/null +++ b/toxcore/os_logger.c @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "os_logger.h" + +#include "ccompat.h" +#include "tox_logger_impl.h" + +non_null() +static void os_logger_log( + void *self, Tox_Log_Level level, + const char *file, uint32_t line, const char *func, + const char *message) +{ + // Do nothing with the log message by default. + return; +} + +static const Tox_Logger_Funcs os_logger_funcs = { + os_logger_log, +}; + +static const Tox_Logger os_logger_obj = {&os_logger_funcs}; + +const Tox_Logger *os_logger(void) +{ + return &os_logger_obj; +} diff --git a/toxcore/os_logger.h b/toxcore/os_logger.h new file mode 100644 index 00000000000..ff3b61100a8 --- /dev/null +++ b/toxcore/os_logger.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_OS_LOGGER_H +#define C_TOXCORE_TOXCORE_OS_LOGGER_H + +#include "tox_logger.h" + +#ifdef __cplusplus +extern "C" { +#endif + +const Tox_Logger *os_logger(void); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_OS_LOGGER_H diff --git a/toxcore/os_memory.c b/toxcore/os_memory.c new file mode 100644 index 00000000000..36fd5d3c540 --- /dev/null +++ b/toxcore/os_memory.c @@ -0,0 +1,52 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "os_memory.h" + +#include + +#include "ccompat.h" +#include "tox_memory_impl.h" + +non_null() +static void *os_malloc(void *self, uint32_t size) +{ + return malloc(size); +} + +non_null() +static void *os_calloc(void *self, uint32_t nmemb, uint32_t size) +{ + return calloc(nmemb, size); +} + +non_null(1) nullable(2) +static void *os_vrealloc(void *self, void *ptr, uint32_t nmemb, uint32_t size) +{ + const uint32_t bytes = nmemb * size; + + if (size != 0 && bytes / size != nmemb) { + return nullptr; + } + + return realloc(ptr, bytes); +} + +non_null(1) nullable(2) +static void os_free(void *self, void *ptr) +{ + free(ptr); +} + +static const Tox_Memory_Funcs os_memory_funcs = { + os_malloc, + os_calloc, + os_vrealloc, + os_free, +}; +static const Tox_Memory os_memory_obj = {&os_memory_funcs}; + +const Tox_Memory *os_memory(void) +{ + return &os_memory_obj; +} diff --git a/toxcore/os_memory.h b/toxcore/os_memory.h new file mode 100644 index 00000000000..8cd728e2399 --- /dev/null +++ b/toxcore/os_memory.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_OS_MEMORY_H +#define C_TOXCORE_TOXCORE_OS_MEMORY_H + +#include "tox_memory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +const Tox_Memory *os_memory(void); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_OS_MEMORY_H diff --git a/toxcore/os_network.c b/toxcore/os_network.c new file mode 100644 index 00000000000..81ea6f57d37 --- /dev/null +++ b/toxcore/os_network.c @@ -0,0 +1,288 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#ifdef __APPLE__ +#define _DARWIN_C_SOURCE +#endif + +// For Solaris. +#ifdef __sun +#define __EXTENSIONS__ 1 +#endif + +// For Linux (and some BSDs). +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 700 +#endif + +#if defined(_WIN32) && _WIN32_WINNT >= _WIN32_WINNT_WINXP +#undef _WIN32_WINNT +#define _WIN32_WINNT 0x501 +#endif + +#if !defined(OS_WIN32) && (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) +#define OS_WIN32 +#endif + +#if defined(OS_WIN32) && !defined(WINVER) +// Windows XP +#define WINVER 0x0501 +#endif + +#include "os_network.h" + +#ifdef OS_WIN32 // Put win32 includes here +// The mingw32/64 Windows library warns about including winsock2.h after +// windows.h even though with the above it's a valid thing to do. So, to make +// mingw32 headers happy, we include winsock2.h first. +#include +// Comment line here to avoid reordering by source code formatters. +#include +#include +#endif + +#if !defined(OS_WIN32) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __sun +#include +#include +#endif + +#else +#ifndef IPV6_V6ONLY +#define IPV6_V6ONLY 27 +#endif +#endif + +#include +#include // memcpy + +#include "ccompat.h" +#include "os_network_impl.h" +#include "tox_network_impl.h" + +// Disable MSG_NOSIGNAL on systems not supporting it, e.g. Windows, FreeBSD +#if !defined(MSG_NOSIGNAL) +#define MSG_NOSIGNAL 0 +#endif + +non_null() +static int os_close(void *self, int sock) +{ +#if defined(OS_WIN32) + return closesocket(sock); +#else // !OS_WIN32 + return close(sock); +#endif +} + +struct Network_Addr { + struct sockaddr_storage addr; + size_t size; +}; + +Network_Addr *net_addr_new(const void *data, size_t size, const Tox_Memory *mem) +{ + Network_Addr *addr = (Network_Addr *)tox_memory_calloc(mem, 1, sizeof(Network_Addr)); + + if (addr == nullptr) { + return nullptr; + } + + if (data != nullptr) { + net_addr_set(addr, data, size); + } else { + addr->size = sizeof(struct sockaddr_storage); + } + + return addr; +} + +void net_addr_free(Network_Addr *addr, const Tox_Memory *mem) +{ + tox_memory_dealloc(mem, addr); +} + +void net_addr_set(Network_Addr *addr, const void *data, size_t size) +{ + assert(size <= sizeof(struct sockaddr_storage)); + memcpy(&addr->addr, data, size); + addr->size = size; +} + +void *net_addr_mut_addr(Network_Addr *addr) +{ + return &addr->addr; +} + +const void *net_addr_get_addr(const Network_Addr *addr) +{ + return &addr->addr; +} + +void net_addr_set_size(Network_Addr *addr, size_t size) +{ + addr->size = size; +} + +size_t net_addr_get_size(const Network_Addr *addr) +{ + return addr->size; +} + +bool net_addr_is_ipv4(const Network_Addr *addr) +{ + return addr->addr.ss_family == AF_INET; +} + +bool net_addr_is_ipv6(const Network_Addr *addr) +{ + return addr->addr.ss_family == AF_INET6; +} + +uint16_t net_addr_get_port(const Network_Addr *addr) +{ + const int family = addr->addr.ss_family; + if (family == AF_INET6) { + const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)&addr->addr; + return addr6->sin6_port; + } else { + assert(family == AF_INET); + const struct sockaddr_in *addr4 = (const struct sockaddr_in *)&addr->addr; + return addr4->sin_port; + } +} + + +non_null() +static int os_accept(void *self, int sock) +{ + return accept(sock, nullptr, nullptr); +} + +non_null() +static int os_bind(void *self, int sock, const Network_Addr *addr) +{ + return bind(sock, (const struct sockaddr *)net_addr_get_addr(addr), net_addr_get_size(addr)); +} + +non_null() +static int os_listen(void *self, int sock, int backlog) +{ + return listen(sock, backlog); +} + +non_null() +static int os_recvbuf(void *self, int sock) +{ +#ifdef OS_WIN32 + u_long count = 0; + ioctlsocket(sock, FIONREAD, &count); +#else + int count = 0; + ioctl(sock, FIONREAD, &count); +#endif + + return count; +} + +non_null() +static int os_recv(void *self, int sock, uint8_t *buf, size_t len) +{ + return recv(sock, (char *)buf, len, MSG_NOSIGNAL); +} + +non_null() +static int os_send(void *self, int sock, const uint8_t *buf, size_t len) +{ + return send(sock, (const char *)buf, len, MSG_NOSIGNAL); +} + +non_null() +static int os_sendto(void *self, int sock, const uint8_t *buf, size_t len, const Network_Addr *addr) { + return sendto(sock, (const char *)buf, len, 0, (const struct sockaddr *)&addr->addr, addr->size); +} + +non_null() +static int os_recvfrom(void *self, int sock, uint8_t *buf, size_t len, Network_Addr *addr) { + socklen_t size = addr->size; + const int ret = recvfrom(sock, (char *)buf, len, 0, (struct sockaddr *)&addr->addr, &size); + addr->size = size; + return ret; +} + +non_null() +static int os_socket(void *self, int domain, int type, int proto) +{ + return (int)socket(domain, type, proto); +} + +non_null() +static int os_socket_nonblock(void *self, int sock, bool nonblock) +{ +#ifdef OS_WIN32 + u_long mode = nonblock ? 1 : 0; + return ioctlsocket(sock, FIONBIO, &mode); +#else + return fcntl(sock, F_SETFL, O_NONBLOCK, nonblock ? 1 : 0); +#endif /* OS_WIN32 */ +} + +non_null() +static int os_getsockopt(void *self, int sock, int level, int optname, void *optval, size_t *optlen) +{ + socklen_t len = *optlen; + const int ret = getsockopt(sock, level, optname, optval, &len); + *optlen = len; + return ret; +} + +non_null() +static int os_setsockopt(void *self, int sock, int level, int optname, const void *optval, size_t optlen) +{ + return setsockopt(sock, level, optname, optval, optlen); +} + +static const Tox_Network_Funcs os_network_funcs = { + os_close, + os_accept, + os_bind, + os_listen, + os_recvbuf, + os_recv, + os_recvfrom, + os_send, + os_sendto, + os_socket, + os_socket_nonblock, + os_getsockopt, + os_setsockopt, +}; +static const Tox_Network os_network_obj = {&os_network_funcs}; + +const Tox_Network *os_network(void) +{ +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + if ((true)) { + return nullptr; + } +#endif +#ifdef OS_WIN32 + WSADATA wsaData; + + if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR) { + return nullptr; + } +#endif + return &os_network_obj; +} diff --git a/toxcore/os_network.h b/toxcore/os_network.h new file mode 100644 index 00000000000..fd144e65917 --- /dev/null +++ b/toxcore/os_network.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_OS_NETWORK_H +#define C_TOXCORE_TOXCORE_OS_NETWORK_H + +#include "tox_network.h" + +#ifdef __cplusplus +extern "C" { +#endif + +const Tox_Network *os_network(void); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_OS_NETWORK_H diff --git a/toxcore/os_network_impl.h b/toxcore/os_network_impl.h new file mode 100644 index 00000000000..26cacf6b410 --- /dev/null +++ b/toxcore/os_network_impl.h @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_OS_NETWORK_IMPL_H +#define C_TOXCORE_TOXCORE_OS_NETWORK_IMPL_H + +#include "tox_network.h" + +#ifdef __cplusplus +extern "C" { +#endif + +non_null() Network_Addr *net_addr_new(const void *data, size_t size, const Tox_Memory *mem); +non_null() void net_addr_free(Network_Addr *addr, const Tox_Memory *mem); + +non_null() void net_addr_set(Network_Addr *addr, const void *data, size_t size); + +non_null() void *net_addr_mut_addr(Network_Addr *addr); +non_null() const void *net_addr_get_addr(const Network_Addr *addr); + +non_null() void net_addr_set_size(Network_Addr *addr, size_t size); +non_null() size_t net_addr_get_size(const Network_Addr *addr); + +non_null() bool net_addr_is_ipv4(const Network_Addr *addr); +non_null() bool net_addr_is_ipv6(const Network_Addr *addr); + +non_null() uint16_t net_addr_get_port(const Network_Addr *addr); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_OS_NETWORK_IMPL_H diff --git a/toxcore/os_random.c b/toxcore/os_random.c new file mode 100644 index 00000000000..66a8c5244a7 --- /dev/null +++ b/toxcore/os_random.c @@ -0,0 +1,60 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "os_random.h" + +#ifndef VANILLA_NACL +// We use libsodium by default. +#include +#else +#include +#endif + +#include "ccompat.h" +#include "tox_random_impl.h" + +non_null() +static void os_random_bytes(void *self, uint8_t *bytes, uint32_t length) +{ + randombytes(bytes, length); +} + +non_null() +static uint32_t os_random_uniform(void *self, uint32_t upper_bound) +{ +#ifdef VANILLA_NACL + if (upper_bound == 0) { + return 0; + } + + uint32_t randnum; + os_random_bytes(self, (uint8_t *)&randnum, sizeof(randnum)); + return randnum % upper_bound; +#else + return randombytes_uniform(upper_bound); +#endif +} + +static const Tox_Random_Funcs os_random_funcs = { + os_random_bytes, + os_random_uniform, +}; + +static const Tox_Random os_random_obj = {&os_random_funcs}; + +const Tox_Random *os_random(void) +{ +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + if ((true)) { + return nullptr; + } +#endif +#ifndef VANILLA_NACL + // It is safe to call this function more than once and from different + // threads -- subsequent calls won't have any effects. + if (sodium_init() == -1) { + return nullptr; + } +#endif + return &os_random_obj; +} diff --git a/toxcore/os_random.h b/toxcore/os_random.h new file mode 100644 index 00000000000..d265a2d26d4 --- /dev/null +++ b/toxcore/os_random.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_OS_RANDOM_H +#define C_TOXCORE_TOXCORE_OS_RANDOM_H + +#include "tox_random.h" + +#ifdef __cplusplus +extern "C" { +#endif + +const Tox_Random *os_random(void); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_OS_RANDOM_H diff --git a/toxcore/os_system.c b/toxcore/os_system.c new file mode 100644 index 00000000000..f79edbc2002 --- /dev/null +++ b/toxcore/os_system.c @@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "os_system.h" + +#include "ccompat.h" +#include "os_logger.h" +#include "os_memory.h" +#include "os_network.h" +#include "os_random.h" +#include "tox_system_impl.h" + +Tox_System os_system(const Tox_Logger *log, const Tox_Memory *mem, const Tox_Network *ns, const Tox_Random *rng, const Tox_Time *tm) +{ + const Tox_System sys = { + log != nullptr ? log : os_logger(), + mem != nullptr ? mem : os_memory(), + ns != nullptr ? ns : os_network(), + rng != nullptr ? rng : os_random(), + tm, // no os_time, mono_time has it. + }; + + return sys; +} diff --git a/toxcore/os_system.h b/toxcore/os_system.h new file mode 100644 index 00000000000..c3fe96262ca --- /dev/null +++ b/toxcore/os_system.h @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_OS_SYSTEM_H +#define C_TOXCORE_TOXCORE_OS_SYSTEM_H + +#include "tox_system.h" +#include "tox_system_impl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief Default operating-system-backed `Tox_System`. + * + * If any of the parameters are NULL, they are set to the OS instance of that + * subsystem. Only `Tox_Time` does not have a subsystem here, and instead is + * created in `mono_time`. + * + * This function, and by extension all the subsystem functions, does not + * allocate any dynamic memory. + */ +nullable(1, 2, 3, 4, 5) +Tox_System os_system(const Tox_Logger *log, const Tox_Memory *mem, const Tox_Network *ns, const Tox_Random *rng, const Tox_Time *tm); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_OS_SYSTEM_H diff --git a/toxcore/ping.c b/toxcore/ping.c index f8a96edfb96..48d6babdae5 100644 --- a/toxcore/ping.c +++ b/toxcore/ping.c @@ -30,7 +30,7 @@ struct Ping { const Mono_Time *mono_time; - const Random *rng; + const Tox_Random *rng; DHT *dht; Ping_Array *ping_array; @@ -336,7 +336,7 @@ void ping_iterate(Ping *ping) } -Ping *ping_new(const Memory *mem, const Mono_Time *mono_time, const Random *rng, DHT *dht) +Ping *ping_new(const Memory *mem, const Mono_Time *mono_time, const Tox_Random *rng, DHT *dht) { Ping *ping = (Ping *)mem_alloc(mem, sizeof(Ping)); diff --git a/toxcore/ping.h b/toxcore/ping.h index c5613459916..ee2d1d8cbac 100644 --- a/toxcore/ping.h +++ b/toxcore/ping.h @@ -18,7 +18,7 @@ typedef struct Ping Ping; non_null() -Ping *ping_new(const Memory *mem, const Mono_Time *mono_time, const Random *rng, DHT *dht); +Ping *ping_new(const Memory *mem, const Mono_Time *mono_time, const Tox_Random *rng, DHT *dht); non_null(1) nullable(2) void ping_kill(const Memory *mem, Ping *ping); diff --git a/toxcore/ping_array.c b/toxcore/ping_array.c index f303d802158..f475fb161dc 100644 --- a/toxcore/ping_array.c +++ b/toxcore/ping_array.c @@ -105,7 +105,7 @@ static void ping_array_clear_timedout(Ping_Array *array, const Mono_Time *mono_t } } -uint64_t ping_array_add(Ping_Array *array, const Mono_Time *mono_time, const Random *rng, +uint64_t ping_array_add(Ping_Array *array, const Mono_Time *mono_time, const Tox_Random *rng, const uint8_t *data, uint32_t length) { ping_array_clear_timedout(array, mono_time); diff --git a/toxcore/ping_array.h b/toxcore/ping_array.h index 5fc04017357..cdadcfe4b40 100644 --- a/toxcore/ping_array.h +++ b/toxcore/ping_array.h @@ -45,7 +45,7 @@ void ping_array_kill(Ping_Array *array); * @return ping_id on success, 0 on failure. */ non_null() -uint64_t ping_array_add(Ping_Array *array, const Mono_Time *mono_time, const Random *rng, +uint64_t ping_array_add(Ping_Array *array, const Mono_Time *mono_time, const Tox_Random *rng, const uint8_t *data, uint32_t length); /** diff --git a/toxcore/ping_array_test.cc b/toxcore/ping_array_test.cc index 8ce557092e4..1924de0f39d 100644 --- a/toxcore/ping_array_test.cc +++ b/toxcore/ping_array_test.cc @@ -5,6 +5,8 @@ #include #include "mono_time.h" +#include "os_memory.h" +#include "os_random.h" namespace { @@ -29,21 +31,21 @@ using Mono_Time_Ptr = std::unique_ptr; TEST(PingArray, MinimumTimeoutIsOne) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); EXPECT_EQ(ping_array_new(mem, 1, 0), nullptr); EXPECT_NE(Ping_Array_Ptr(ping_array_new(mem, 1, 1)), nullptr); } TEST(PingArray, MinimumArraySizeIsOne) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); EXPECT_EQ(ping_array_new(mem, 0, 1), nullptr); EXPECT_NE(Ping_Array_Ptr(ping_array_new(mem, 1, 1)), nullptr); } TEST(PingArray, ArraySizeMustBePowerOfTwo) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); Ping_Array_Ptr arr; arr.reset(ping_array_new(mem, 2, 1)); @@ -59,12 +61,12 @@ TEST(PingArray, ArraySizeMustBePowerOfTwo) TEST(PingArray, StoredDataCanBeRetrieved) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); Ping_Array_Ptr const arr(ping_array_new(mem, 2, 1)); - Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr, nullptr), mem); + Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr), mem); ASSERT_NE(mono_time, nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); uint64_t const ping_id = ping_array_add( @@ -78,12 +80,12 @@ TEST(PingArray, StoredDataCanBeRetrieved) TEST(PingArray, RetrievingDataWithTooSmallOutputBufferHasNoEffect) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); Ping_Array_Ptr const arr(ping_array_new(mem, 2, 1)); - Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr, nullptr), mem); + Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr), mem); ASSERT_NE(mono_time, nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); uint64_t const ping_id = ping_array_add( @@ -101,12 +103,12 @@ TEST(PingArray, RetrievingDataWithTooSmallOutputBufferHasNoEffect) TEST(PingArray, ZeroLengthDataCanBeAdded) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); Ping_Array_Ptr const arr(ping_array_new(mem, 2, 1)); - Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr, nullptr), mem); + Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr), mem); ASSERT_NE(mono_time, nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); uint8_t c = 0; @@ -118,10 +120,10 @@ TEST(PingArray, ZeroLengthDataCanBeAdded) TEST(PingArray, PingId0IsInvalid) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); Ping_Array_Ptr const arr(ping_array_new(mem, 2, 1)); - Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr, nullptr), mem); + Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr), mem); ASSERT_NE(mono_time, nullptr); uint8_t c = 0; @@ -131,12 +133,12 @@ TEST(PingArray, PingId0IsInvalid) // Protection against replay attacks. TEST(PingArray, DataCanOnlyBeRetrievedOnce) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); Ping_Array_Ptr const arr(ping_array_new(mem, 2, 1)); - Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr, nullptr), mem); + Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr), mem); ASSERT_NE(mono_time, nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); uint8_t c = 0; @@ -149,12 +151,12 @@ TEST(PingArray, DataCanOnlyBeRetrievedOnce) TEST(PingArray, PingIdMustMatchOnCheck) { - const Memory *mem = system_memory(); + const Memory *mem = os_memory(); Ping_Array_Ptr const arr(ping_array_new(mem, 1, 1)); - Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr, nullptr), mem); + Mono_Time_Ptr const mono_time(mono_time_new(mem, nullptr), mem); ASSERT_NE(mono_time, nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); uint8_t c = 0; diff --git a/toxcore/tox.c b/toxcore/tox.c index d17e61b70f2..c61c3c9fdd6 100644 --- a/toxcore/tox.c +++ b/toxcore/tox.c @@ -25,6 +25,7 @@ #include "mem.h" #include "mono_time.h" #include "network.h" +#include "os_system.h" #include "tox_private.h" #include "tox_struct.h" @@ -649,7 +650,7 @@ Tox *tox_new(const struct Tox_Options *options, Tox_Err_New *error) assert(opts != nullptr); const Tox_System *sys = tox_options_get_operating_system(opts); - const Tox_System default_system = tox_default_system(); + const Tox_System default_system = os_system(nullptr, nullptr, nullptr, nullptr, nullptr); if (sys == nullptr) { sys = &default_system; @@ -777,7 +778,7 @@ Tox *tox_new(const struct Tox_Options *options, Tox_Err_New *error) m_options.proxy_info.ip_port.port = net_htons(tox_options_get_proxy_port(opts)); } - tox->mono_time = mono_time_new(tox->sys.mem, sys->mono_time_callback, sys->mono_time_user_data); + tox->mono_time = mono_time_new(tox->sys.mem, sys->tm); if (tox->mono_time == nullptr) { SET_ERROR_PARAMETER(error, TOX_ERR_NEW_MALLOC); diff --git a/toxcore/tox.h b/toxcore/tox.h index d03e2b19b9b..f5fd4239f68 100644 --- a/toxcore/tox.h +++ b/toxcore/tox.h @@ -104,6 +104,8 @@ #include #include +#include "tox_system.h" + #ifdef __cplusplus extern "C" { #endif @@ -445,42 +447,8 @@ typedef enum Tox_Savedata_Type { } Tox_Savedata_Type; - -/** - * @brief Severity level of log messages. - */ -typedef enum Tox_Log_Level { - - /** - * Very detailed traces including all network activity. - */ - TOX_LOG_LEVEL_TRACE, - - /** - * Debug messages such as which port we bind to. - */ - TOX_LOG_LEVEL_DEBUG, - - /** - * Informational log messages such as video call status changes. - */ - TOX_LOG_LEVEL_INFO, - - /** - * Warnings about events_alloc inconsistency or logic errors. - */ - TOX_LOG_LEVEL_WARNING, - - /** - * Severe unexpected errors caused by external or events_alloc inconsistency. - */ - TOX_LOG_LEVEL_ERROR, - -} Tox_Log_Level; - - /** - * @brief This event is triggered when the toxcore library logs an events_alloc message. + * @brief This event is triggered when the toxcore library logs a message. * * This is mostly useful for debugging. This callback can be called from any * function, not just tox_iterate. This means the user data lifetime must at @@ -500,17 +468,6 @@ typedef enum Tox_Log_Level { typedef void tox_log_cb(Tox *tox, Tox_Log_Level level, const char *file, uint32_t line, const char *func, const char *message, void *user_data); - -/** - * @brief Operating system functions used by Tox. - * - * This struct is opaque and generally shouldn't be used in clients, but in - * combination with tox_private.h, it allows tests to inject non-IO (hermetic) - * versions of low level network, RNG, and time keeping functions. - */ -typedef struct Tox_System Tox_System; - - /** * @brief This struct contains all the startup options for Tox. * diff --git a/toxcore/tox_api.c b/toxcore/tox_api.c index 61c248c30d7..3163ff308c0 100644 --- a/toxcore/tox_api.c +++ b/toxcore/tox_api.c @@ -161,7 +161,7 @@ ACCESSORS(void *, log_, user_data) ACCESSORS(bool,, local_discovery_enabled) ACCESSORS(bool,, dht_announcements_enabled) ACCESSORS(bool,, experimental_thread_safety) -ACCESSORS(const Tox_System *,, operating_system) +ACCESSORS(const struct Tox_System *,, operating_system) //!TOKSTYLE+ diff --git a/toxcore/tox_attributes.h b/toxcore/tox_attributes.h new file mode 100644 index 00000000000..7200763a883 --- /dev/null +++ b/toxcore/tox_attributes.h @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +/** + * printf and nonnull attributes for GCC/Clang and Cimple. + */ +#ifndef C_TOXCORE_TOXCORE_TOX_ATTRIBUTES_H +#define C_TOXCORE_TOXCORE_TOX_ATTRIBUTES_H + +/* No declarations here. */ + +//!TOKSTYLE- + +#ifdef __GNUC__ +#define GNU_PRINTF(f, a) __attribute__((__format__(__printf__, f, a))) +#else +#define GNU_PRINTF(f, a) +#endif + +#if defined(__GNUC__) && defined(_DEBUG) && !defined(__OPTIMIZE__) +#define non_null(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else +#define non_null(...) +#endif + +#define nullable(...) + +//!TOKSTYLE+ + +#endif // C_TOXCORE_TOXCORE_TOX_ATTRIBUTES_H diff --git a/toxcore/tox_events.c b/toxcore/tox_events.c index cae662e58ef..490c1b6871f 100644 --- a/toxcore/tox_events.c +++ b/toxcore/tox_events.c @@ -14,7 +14,7 @@ #include "events/events_alloc.h" #include "mem.h" #include "tox.h" -#include "tox_private.h" +#include "tox_system_impl.h" /***************************************************** diff --git a/toxcore/tox_events.h b/toxcore/tox_events.h index e868d89098a..8a0cd8a7d8d 100644 --- a/toxcore/tox_events.h +++ b/toxcore/tox_events.h @@ -343,9 +343,9 @@ void tox_events_free(Tox_Events *events); uint32_t tox_events_bytes_size(const Tox_Events *events); void tox_events_get_bytes(const Tox_Events *events, uint8_t *bytes); -Tox_Events *tox_events_load(const Tox_System *sys, const uint8_t *bytes, uint32_t bytes_size); +Tox_Events *tox_events_load(const struct Tox_System *sys, const uint8_t *bytes, uint32_t bytes_size); -bool tox_events_equal(const Tox_System *sys, const Tox_Events *a, const Tox_Events *b); +bool tox_events_equal(const struct Tox_System *sys, const Tox_Events *a, const Tox_Events *b); #ifdef __cplusplus } diff --git a/toxcore/tox_events_test.cc b/toxcore/tox_events_test.cc index 5de29b5e483..0c58e20323d 100644 --- a/toxcore/tox_events_test.cc +++ b/toxcore/tox_events_test.cc @@ -6,13 +6,15 @@ #include #include "crypto_core.h" +#include "os_system.h" #include "tox_private.h" +#include "tox_system_impl.h" namespace { TEST(ToxEvents, UnpackRandomDataDoesntCrash) { - const Tox_System sys = tox_default_system(); + const Tox_System sys = os_system(nullptr, nullptr, nullptr, nullptr, nullptr); ASSERT_NE(sys.rng, nullptr); std::array data; random_bytes(sys.rng, data.data(), data.size()); @@ -21,7 +23,7 @@ TEST(ToxEvents, UnpackRandomDataDoesntCrash) TEST(ToxEvents, UnpackEmptyDataFails) { - const Tox_System sys = tox_default_system(); + const Tox_System sys = os_system(nullptr, nullptr, nullptr, nullptr, nullptr); std::array data; Tox_Events *events = tox_events_load(&sys, data.end(), 0); EXPECT_EQ(events, nullptr); @@ -29,7 +31,7 @@ TEST(ToxEvents, UnpackEmptyDataFails) TEST(ToxEvents, UnpackEmptyArrayCreatesEmptyEvents) { - const Tox_System sys = tox_default_system(); + const Tox_System sys = os_system(nullptr, nullptr, nullptr, nullptr, nullptr); std::array data{0x90}; // empty msgpack array Tox_Events *events = tox_events_load(&sys, data.data(), data.size()); ASSERT_NE(events, nullptr); @@ -47,7 +49,7 @@ TEST(ToxEvents, NullEventsPacksToEmptyArray) TEST(ToxEvents, PackedEventsCanBeUnpacked) { - const Tox_System sys = tox_default_system(); + const Tox_System sys = os_system(nullptr, nullptr, nullptr, nullptr, nullptr); // [[0, 1]] == Tox_Self_Connection_Status { .connection_status = TOX_CONNECTION_TCP } std::array packed{0x91, 0x92, 0xcc, 0x00, 0xcc, 0x01}; Tox_Events *events = tox_events_load(&sys, packed.data(), packed.size()); @@ -61,7 +63,7 @@ TEST(ToxEvents, PackedEventsCanBeUnpacked) TEST(ToxEvents, DealsWithHugeMsgpackArrays) { - const Tox_System sys = tox_default_system(); + const Tox_System sys = os_system(nullptr, nullptr, nullptr, nullptr, nullptr); std::vector data{0xdd, 0xff, 0xff, 0xff, 0xff}; EXPECT_EQ(tox_events_load(&sys, data.data(), data.size()), nullptr); } diff --git a/toxcore/tox_logger.c b/toxcore/tox_logger.c new file mode 100644 index 00000000000..0a9f8034a4f --- /dev/null +++ b/toxcore/tox_logger.c @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "tox_logger.h" + +#include "ccompat.h" +#include "tox_logger_impl.h" + +Tox_Logger *tox_logger_new(const Tox_Logger_Funcs *funcs, void *user_data, const Tox_Memory *mem) +{ + Tox_Logger *log = (Tox_Logger *)tox_memory_calloc(mem, 1, sizeof(Tox_Logger)); + + if (log == nullptr) { + return nullptr; + } + + log->funcs = funcs; + log->user_data = user_data; + + log->mem = mem; + + return log; +} + +void tox_logger_free(Tox_Logger *log) +{ + tox_memory_dealloc(log->mem, log); +} + +void tox_logger_log( + const Tox_Logger *log, Tox_Log_Level level, + const char *file, uint32_t line, const char *func, + const char *message) +{ + log->funcs->log_callback(log->user_data, level, file, line, func, message); +} diff --git a/toxcore/tox_logger.h b/toxcore/tox_logger.h new file mode 100644 index 00000000000..015aca55e64 --- /dev/null +++ b/toxcore/tox_logger.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_LOGGER_H +#define C_TOXCORE_TOXCORE_TOX_LOGGER_H + +#include "tox_memory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Severity level of log messages. + */ +typedef enum Tox_Log_Level { + + /** + * Very detailed traces including all network activity. + */ + TOX_LOG_LEVEL_TRACE, + + /** + * Debug messages such as which port we bind to. + */ + TOX_LOG_LEVEL_DEBUG, + + /** + * Informational log messages such as video call status changes. + */ + TOX_LOG_LEVEL_INFO, + + /** + * Warnings about events_alloc inconsistency or logic errors. + */ + TOX_LOG_LEVEL_WARNING, + + /** + * Severe unexpected errors caused by external or events_alloc inconsistency. + */ + TOX_LOG_LEVEL_ERROR, + +} Tox_Log_Level; + + +typedef struct Tox_Logger_Funcs Tox_Logger_Funcs; + +typedef struct Tox_Logger Tox_Logger; + +non_null(1, 3) nullable(2) +Tox_Logger *tox_logger_new(const Tox_Logger_Funcs *funcs, void *user_data, const Tox_Memory *mem); + +nullable(1) void tox_logger_free(Tox_Logger *log); + +non_null() void tox_logger_log( + const Tox_Logger *log, Tox_Log_Level level, + const char *file, uint32_t line, const char *func, + const char *message); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_LOGGER_H diff --git a/toxcore/tox_logger_impl.h b/toxcore/tox_logger_impl.h new file mode 100644 index 00000000000..9d3795a91ac --- /dev/null +++ b/toxcore/tox_logger_impl.h @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_LOGGER_IMPL_H +#define C_TOXCORE_TOXCORE_TOX_LOGGER_IMPL_H + +#include "tox_logger.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief This event is triggered when the toxcore library logs a message. + * + * This is mostly useful for debugging. This callback can be called from any + * function, not just tox_iterate. This means the user data lifetime must at + * least extend between registering and unregistering it or tox_kill. + * + * Other toxcore modules such as toxav may concurrently call this callback at + * any time. Thus, user code must make sure it is equipped to handle concurrent + * execution, e.g. by employing appropriate mutex locking. + * + * @param self The user data pointer passed to `tox_logger_new`. + * @param level The severity of the log message. + * @param file The source file from which the message originated. + * @param line The source line from which the message originated. + * @param func The function from which the message originated. + * @param message The log message. + */ +typedef void tox_logger_log_cb( + void *self, Tox_Log_Level level, + const char *file, uint32_t line, const char *func, + const char *message); + + +struct Tox_Logger_Funcs { + tox_logger_log_cb *log_callback; +}; + +struct Tox_Logger { + const Tox_Logger_Funcs *funcs; + void *user_data; + + const Tox_Memory *mem; +}; + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_LOGGER_IMPL_H diff --git a/toxcore/tox_memory.c b/toxcore/tox_memory.c new file mode 100644 index 00000000000..8c31fb089bf --- /dev/null +++ b/toxcore/tox_memory.c @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2016-2018 The TokTok team. + * Copyright © 2013 Tox project. + */ +#include "tox_memory.h" + +#include "ccompat.h" +#include "tox_memory_impl.h" + +Tox_Memory *tox_memory_new(const Tox_Memory_Funcs *funcs, void *user_data) +{ + const Tox_Memory bootstrap = {funcs, user_data}; + + Tox_Memory *mem = tox_memory_calloc(&bootstrap, 1, sizeof(Tox_Memory)); + + if (mem == nullptr) { + return nullptr; + } + + *mem = bootstrap; + + return mem; +} + +void tox_memory_free(Tox_Memory *mem) +{ + if (mem == nullptr) { + return; + } + + tox_memory_dealloc(mem, mem); +} + +void *tox_memory_malloc(const Tox_Memory *mem, uint32_t size) +{ + void *const ptr = mem->funcs->malloc_callback(mem->user_data, size); + return ptr; +} + +void *tox_memory_calloc(const Tox_Memory *mem, uint32_t nmemb, uint32_t size) +{ + void *const ptr = mem->funcs->calloc_callback(mem->user_data, nmemb, size); + return ptr; +} + +void *tox_memory_vrealloc(const Tox_Memory *mem, void *ptr, uint32_t nmemb, uint32_t size) +{ + void *const new_ptr = mem->funcs->realloc_callback(mem->user_data, ptr, nmemb, size); + return new_ptr; +} + +void tox_memory_dealloc(const Tox_Memory *mem, void *ptr) +{ + mem->funcs->dealloc_callback(mem->user_data, ptr); +} diff --git a/toxcore/tox_memory.h b/toxcore/tox_memory.h new file mode 100644 index 00000000000..9185f1f6e57 --- /dev/null +++ b/toxcore/tox_memory.h @@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2016-2018 The TokTok team. + * Copyright © 2013 Tox project. + */ + +/** + * Memory allocation and deallocation functions. + */ +#ifndef C_TOXCORE_TOXCORE_TOX_MEMORY_H +#define C_TOXCORE_TOXCORE_TOX_MEMORY_H + +#include // uint*_t + +#include "tox_attributes.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief Functions wrapping standard C memory allocation functions. */ +typedef struct Tox_Memory_Funcs Tox_Memory_Funcs; + +/** + * @brief A dynamic memory allocator. + */ +typedef struct Tox_Memory Tox_Memory; + +/** + * @brief Allocates a new allocator using itself to allocate its own memory. + * + * The passed `user_data` is stored and passed to allocator callbacks. It must + * outlive the `Tox_Memory` object, since it may be used by the callback invoked + * in `tox_memory_free`. + * + * @return NULL if allocation fails. + */ +non_null(1) nullable(2) +Tox_Memory *tox_memory_new(const Tox_Memory_Funcs *funcs, void *user_data); + +/** + * @brief Destroys the allocator using its own deallocation function. + * + * The stored `user_data` will not be deallocated. + */ +nullable(1) void tox_memory_free(Tox_Memory *mem); + +/** + * @brief Allocate an array of a given size for built-in types. + * + * The array will not be initialised. Supported built-in types are + * `uint8_t`, `int8_t`, and `int16_t`. + */ +non_null() void *tox_memory_malloc(const Tox_Memory *mem, uint32_t size); + +/** + * @brief Allocate a vector (array) of zero-initialised objects. + * + * Always use as `(T *)tox_memory_calloc(mem, N, sizeof(T))`. + * + * @param mem The memory allocator. + * @param nmemb Number of array elements (can be 1 to allocate a single object). + * @param size Size in bytes of each element. + */ +non_null() void *tox_memory_calloc(const Tox_Memory *mem, uint32_t nmemb, uint32_t size); + +/** + * @brief Resize an object vector. + * + * Changes the size of (and possibly moves) the memory block pointed to by + * @p ptr to be large enough for an array of @p nmemb elements, each of which + * is @p size bytes. It is similar to the call + * + * @code + * realloc(ptr, nmemb * size); + * @endcode + * + * However, unlike that `realloc()` call, `mem_vrealloc()` fails safely in the + * case where the multiplication would overflow. If such an overflow occurs, + * `mem_vrealloc()` returns `nullptr`. + */ +non_null(1) nullable(2) void *tox_memory_vrealloc(const Tox_Memory *mem, void *ptr, uint32_t nmemb, uint32_t size); + +/** @brief Free an array, object, or object vector. */ +non_null(1) nullable(2) void tox_memory_dealloc(const Tox_Memory *mem, void *ptr); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_MEMORY_H diff --git a/toxcore/tox_memory_impl.h b/toxcore/tox_memory_impl.h new file mode 100644 index 00000000000..e369df115f8 --- /dev/null +++ b/toxcore/tox_memory_impl.h @@ -0,0 +1,52 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2016-2018 The TokTok team. + * Copyright © 2013 Tox project. + */ + +/** + * Datatypes, functions and includes for the core networking. + */ +#ifndef C_TOXCORE_TOXCORE_TOX_MEMORY_IMPL_H +#define C_TOXCORE_TOXCORE_TOX_MEMORY_IMPL_H + +#include // uint*_t + +#include "tox_memory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief Allocate a byte array, similar to malloc. */ +typedef void *tox_memory_malloc_cb(void *self, uint32_t size); +/** @brief Allocate a zero-initialised object array, similar to calloc. */ +typedef void *tox_memory_calloc_cb(void *self, uint32_t nmemb, uint32_t size); +/** @brief Reallocate an object array, similar to realloc. */ +typedef void *tox_memory_vrealloc_cb(void *self, void *ptr, uint32_t nmemb, uint32_t size); +/** + * @brief Deallocate a byte or object array, similar to free. + * + * Note that `tox_memory_free` will use this callback to deallocate itself, so + * once the deallocation is done, the allocator data structures can no longer be + * referenced. + */ +typedef void tox_memory_dealloc_cb(void *self, void *ptr); + +/** @brief Functions wrapping standard C memory allocation functions. */ +struct Tox_Memory_Funcs { + tox_memory_malloc_cb *malloc_callback; + tox_memory_calloc_cb *calloc_callback; + tox_memory_vrealloc_cb *realloc_callback; + tox_memory_dealloc_cb *dealloc_callback; +}; + +struct Tox_Memory { + const Tox_Memory_Funcs *funcs; + void *user_data; +}; + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_MEMORY_IMPL_H diff --git a/toxcore/tox_network.c b/toxcore/tox_network.c new file mode 100644 index 00000000000..f96a75f6c00 --- /dev/null +++ b/toxcore/tox_network.c @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "tox_network.h" + +#include "ccompat.h" +#include "tox_network_impl.h" + +Tox_Network *tox_network_new(const Tox_Network_Funcs *funcs, void *user_data, const Tox_Memory *mem) +{ + Tox_Network *ns = (Tox_Network *)tox_memory_calloc(mem, 1, sizeof(Tox_Network)); + + if (ns == nullptr) { + return nullptr; + } + + ns->funcs = funcs; + ns->user_data = user_data; + + ns->mem = mem; + + return ns; +} + +void tox_network_free(Tox_Network *ns) +{ + tox_memory_dealloc(ns->mem, ns); +} + +int tox_network_close(const Tox_Network *ns, int sock) +{ + return ns->funcs->close_callback(ns->user_data, sock); +} + +int tox_network_accept(const Tox_Network *ns, int sock) +{ + return ns->funcs->accept_callback(ns->user_data, sock); +} + +int tox_network_bind(const Tox_Network *ns, int sock, const Network_Addr *addr) +{ + return ns->funcs->bind_callback(ns->user_data, sock, addr); +} + +int tox_network_listen(const Tox_Network *ns, int sock, int backlog) +{ + return ns->funcs->listen_callback(ns->user_data, sock, backlog); +} + +int tox_network_recvbuf(const Tox_Network *ns, int sock) +{ + return ns->funcs->recvbuf_callback(ns->user_data, sock); +} + +int tox_network_recv(const Tox_Network *ns, int sock, uint8_t *buf, size_t len) +{ + return ns->funcs->recv_callback(ns->user_data, sock, buf, len); +} + +int tox_network_recvfrom(const Tox_Network *ns, int sock, uint8_t *buf, size_t len, Network_Addr *addr) +{ + return ns->funcs->recvfrom_callback(ns->user_data, sock, buf, len, addr); +} + +int tox_network_send(const Tox_Network *ns, int sock, const uint8_t *buf, size_t len) +{ + return ns->funcs->send_callback(ns->user_data, sock, buf, len); +} + +int tox_network_sendto(const Tox_Network *ns, int sock, const uint8_t *buf, size_t len, const Network_Addr *addr) +{ + return ns->funcs->sendto_callback(ns->user_data, sock, buf, len, addr); +} + +int tox_network_socket(const Tox_Network *ns, int domain, int type, int proto) +{ + return ns->funcs->socket_callback(ns->user_data, domain, type, proto); +} + +int tox_network_socket_nonblock(const Tox_Network *ns, int sock, bool nonblock) +{ + return ns->funcs->socket_nonblock_callback(ns->user_data, sock, nonblock); +} + +int tox_network_getsockopt(const Tox_Network *ns, int sock, int level, int optname, void *optval, size_t *optlen) +{ + return ns->funcs->getsockopt_callback(ns->user_data, sock, level, optname, optval, optlen); +} + +int tox_network_setsockopt(const Tox_Network *ns, int sock, int level, int optname, const void *optval, size_t optlen) +{ + return ns->funcs->setsockopt_callback(ns->user_data, sock, level, optname, optval, optlen); +} + +int tox_network_getaddrinfo(const Tox_Network *ns, int family, Network_Addr **addrs) +{ + return ns->funcs->getaddrinfo_callback(ns->user_data, family, addrs); +} + +int tox_network_freeaddrinfo(const Tox_Network *ns, Network_Addr *addrs) +{ + return ns->funcs->freeaddrinfo_callback(ns->user_data, addrs); +} diff --git a/toxcore/tox_network.h b/toxcore/tox_network.h new file mode 100644 index 00000000000..bb8f879ed2d --- /dev/null +++ b/toxcore/tox_network.h @@ -0,0 +1,51 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_NETWORK_H +#define C_TOXCORE_TOXCORE_TOX_NETWORK_H + +#include +#include // size_t + +#include "tox_memory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Tox_Network_Funcs Tox_Network_Funcs; + +typedef struct Tox_Network Tox_Network; + +non_null(1, 3) nullable(2) +Tox_Network *tox_network_new(const Tox_Network_Funcs *funcs, void *user_data, const Tox_Memory *mem); + +nullable(1) void tox_network_free(Tox_Network *ns); + +/** + * @brief Wrapper for sockaddr_storage and size. + */ +typedef struct Network_Addr Network_Addr; + +non_null() int tox_network_close(const Tox_Network *ns, int sock); +non_null() int tox_network_accept(const Tox_Network *ns, int sock); +non_null() int tox_network_bind(const Tox_Network *ns, int sock, const Network_Addr *addr); +non_null() int tox_network_listen(const Tox_Network *ns, int sock, int backlog); +non_null() int tox_network_recvbuf(const Tox_Network *ns, int sock); +non_null() int tox_network_recv(const Tox_Network *ns, int sock, uint8_t *buf, size_t len); +non_null() int tox_network_recvfrom(const Tox_Network *ns, int sock, uint8_t *buf, size_t len, Network_Addr *addr); +non_null() int tox_network_send(const Tox_Network *ns, int sock, const uint8_t *buf, size_t len); +non_null() int tox_network_sendto(const Tox_Network *ns, int sock, const uint8_t *buf, size_t len, const Network_Addr *addr); +non_null() int tox_network_socket(const Tox_Network *ns, int domain, int type, int proto); +non_null() int tox_network_socket_nonblock(const Tox_Network *ns, int sock, bool nonblock); +non_null() int tox_network_getsockopt(const Tox_Network *ns, int sock, int level, int optname, void *optval, size_t *optlen); +non_null() int tox_network_setsockopt(const Tox_Network *ns, int sock, int level, int optname, const void *optval, size_t optlen); +non_null() int tox_network_getaddrinfo(const Tox_Network *ns, int family, Network_Addr **addrs); +non_null() int tox_network_freeaddrinfo(const Tox_Network *ns, Network_Addr *addrs); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_NETWORK_H diff --git a/toxcore/tox_network_impl.h b/toxcore/tox_network_impl.h new file mode 100644 index 00000000000..bc0217b7210 --- /dev/null +++ b/toxcore/tox_network_impl.h @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_NETWORK_IMPL_H +#define C_TOXCORE_TOXCORE_TOX_NETWORK_IMPL_H + +#include "tox_network.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef int tox_network_close_cb(void *self, int sock); +typedef int tox_network_accept_cb(void *self, int sock); +typedef int tox_network_bind_cb(void *self, int sock, const Network_Addr *addr); +typedef int tox_network_listen_cb(void *self, int sock, int backlog); +typedef int tox_network_recvbuf_cb(void *self, int sock); +typedef int tox_network_recv_cb(void *self, int sock, uint8_t *buf, size_t len); +typedef int tox_network_recvfrom_cb(void *self, int sock, uint8_t *buf, size_t len, Network_Addr *addr); +typedef int tox_network_send_cb(void *self, int sock, const uint8_t *buf, size_t len); +typedef int tox_network_sendto_cb(void *self, int sock, const uint8_t *buf, size_t len, const Network_Addr *addr); +typedef int tox_network_socket_cb(void *self, int domain, int type, int proto); +typedef int tox_network_socket_nonblock_cb(void *self, int sock, bool nonblock); +typedef int tox_network_getsockopt_cb(void *self, int sock, int level, int optname, void *optval, size_t *optlen); +typedef int tox_network_setsockopt_cb(void *self, int sock, int level, int optname, const void *optval, size_t optlen); +typedef int tox_network_getaddrinfo_cb(void *self, int family, Network_Addr **addrs); +typedef int tox_network_freeaddrinfo_cb(void *self, Network_Addr *addrs); + +/** @brief Functions wrapping POSIX network functions. + * + * Refer to POSIX man pages for documentation of what these functions are + * expected to do when providing alternative Network implementations. + */ +struct Tox_Network_Funcs { + tox_network_close_cb *close_callback; + tox_network_accept_cb *accept_callback; + tox_network_bind_cb *bind_callback; + tox_network_listen_cb *listen_callback; + tox_network_recvbuf_cb *recvbuf_callback; + tox_network_recv_cb *recv_callback; + tox_network_recvfrom_cb *recvfrom_callback; + tox_network_send_cb *send_callback; + tox_network_sendto_cb *sendto_callback; + tox_network_socket_cb *socket_callback; + tox_network_socket_nonblock_cb *socket_nonblock_callback; + tox_network_getsockopt_cb *getsockopt_callback; + tox_network_setsockopt_cb *setsockopt_callback; + tox_network_getaddrinfo_cb *getaddrinfo_callback; + tox_network_freeaddrinfo_cb *freeaddrinfo_callback; +}; + +struct Tox_Network { + const Tox_Network_Funcs *funcs; + void *user_data; + + const Tox_Memory *mem; +}; + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_NETWORK_IMPL_H diff --git a/toxcore/tox_private.c b/toxcore/tox_private.c index 72a93358a5b..cebdd502fd3 100644 --- a/toxcore/tox_private.c +++ b/toxcore/tox_private.c @@ -22,18 +22,6 @@ } \ } while (0) -Tox_System tox_default_system(void) -{ - const Tox_System sys = { - nullptr, // mono_time_callback - nullptr, // mono_time_user_data - system_random(), - system_network(), - system_memory(), - }; - return sys; -} - void tox_lock(const Tox *tox) { if (tox->mutex != nullptr) { diff --git a/toxcore/tox_private.h b/toxcore/tox_private.h index c82357170e6..ba6c8a27eb7 100644 --- a/toxcore/tox_private.h +++ b/toxcore/tox_private.h @@ -16,18 +16,6 @@ extern "C" { #endif -typedef uint64_t tox_mono_time_cb(void *user_data); - -struct Tox_System { - tox_mono_time_cb *mono_time_callback; - void *mono_time_user_data; - const struct Random *rng; - const struct Network *ns; - const struct Memory *mem; -}; - -Tox_System tox_default_system(void); - void tox_lock(const Tox *tox); void tox_unlock(const Tox *tox); diff --git a/toxcore/tox_random.c b/toxcore/tox_random.c new file mode 100644 index 00000000000..ee014fdfd46 --- /dev/null +++ b/toxcore/tox_random.c @@ -0,0 +1,38 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "tox_random.h" + +#include "ccompat.h" +#include "tox_random_impl.h" + +Tox_Random *tox_random_new(const Tox_Random_Funcs *funcs, void *user_data, const Tox_Memory *mem) +{ + Tox_Random *rng = (Tox_Random *)tox_memory_calloc(mem, 1, sizeof(Tox_Random)); + + if (rng == nullptr) { + return nullptr; + } + + rng->funcs = funcs; + rng->user_data = user_data; + + rng->mem = mem; + + return rng; +} + +void tox_random_free(Tox_Random *rng) +{ + tox_memory_dealloc(rng->mem, rng); +} + +void tox_random_bytes(const Tox_Random *rng, uint8_t *bytes, uint32_t length) +{ + rng->funcs->bytes_callback(rng->user_data, bytes, length); +} + +uint32_t tox_random_uniform(const Tox_Random *rng, uint32_t upper_bound) +{ + return rng->funcs->uniform_callback(rng->user_data, upper_bound); +} diff --git a/toxcore/tox_random.h b/toxcore/tox_random.h new file mode 100644 index 00000000000..82e3acbcd71 --- /dev/null +++ b/toxcore/tox_random.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_RANDOM_H +#define C_TOXCORE_TOXCORE_TOX_RANDOM_H + +#include +#include + +#include "tox_memory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Tox_Random_Funcs Tox_Random_Funcs; + +typedef struct Tox_Random Tox_Random; + +non_null(1, 3) nullable(2) +Tox_Random *tox_random_new(const Tox_Random_Funcs *funcs, void *user_data, const Tox_Memory *mem); + +nullable(1) void tox_random_free(Tox_Random *rng); + +non_null() void tox_random_bytes(const Tox_Random *rng, uint8_t *bytes, uint32_t length); +non_null() uint32_t tox_random_uniform(const Tox_Random *rng, uint32_t upper_bound); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_RANDOM_H diff --git a/toxcore/tox_random_impl.h b/toxcore/tox_random_impl.h new file mode 100644 index 00000000000..f11d2f26d6a --- /dev/null +++ b/toxcore/tox_random_impl.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_RANDOM_IMPL_H +#define C_TOXCORE_TOXCORE_TOX_RANDOM_IMPL_H + +#include "tox_random.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void tox_random_bytes_cb(void *self, uint8_t *bytes, uint32_t length); +typedef uint32_t tox_random_uniform_cb(void *self, uint32_t upper_bound); + +struct Tox_Random_Funcs { + tox_random_bytes_cb *bytes_callback; + tox_random_uniform_cb *uniform_callback; +}; + +struct Tox_Random { + const Tox_Random_Funcs *funcs; + void *user_data; + + const Tox_Memory *mem; +}; + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_RANDOM_IMPL_H diff --git a/toxcore/tox_struct.h b/toxcore/tox_struct.h index b298269af95..ec1db247a7c 100644 --- a/toxcore/tox_struct.h +++ b/toxcore/tox_struct.h @@ -10,6 +10,7 @@ #include "mem.h" #include "tox.h" #include "tox_private.h" +#include "tox_system_impl.h" #ifdef __cplusplus extern "C" { diff --git a/toxcore/tox_system.c b/toxcore/tox_system.c new file mode 100644 index 00000000000..686b6f9484c --- /dev/null +++ b/toxcore/tox_system.c @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "tox_system.h" + +#include "ccompat.h" +#include "tox_system_impl.h" + +Tox_System *tox_system_new(const Tox_Logger *log, const Tox_Memory *mem, const Tox_Network *ns, const Tox_Random *rng, const Tox_Time *tm) +{ + Tox_System *sys = (Tox_System *)tox_memory_calloc(mem, 1, sizeof(Tox_System)); + + if (sys == nullptr) { + return nullptr; + } + + sys->log = log; + sys->mem = mem; + sys->ns = ns; + sys->rng = rng; + sys->tm = tm; + + return sys; +} + +void tox_system_free(Tox_System *sys) +{ + tox_memory_dealloc(sys->mem, sys); +} diff --git a/toxcore/tox_system.h b/toxcore/tox_system.h new file mode 100644 index 00000000000..49934017ff5 --- /dev/null +++ b/toxcore/tox_system.h @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_SYSTEM_H +#define C_TOXCORE_TOXCORE_TOX_SYSTEM_H + +#include "tox_logger.h" +#include "tox_memory.h" +#include "tox_network.h" +#include "tox_random.h" +#include "tox_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Operating system functions used by Tox. + * + * This struct is opaque and generally shouldn't be used in clients, but in + * combination with tox_private.h, it allows tests to inject non-IO (hermetic) + * versions of low level network, RNG, and time keeping functions. + */ +typedef struct Tox_System Tox_System; + +non_null() Tox_System *tox_system_new(const Tox_Logger *log, const Tox_Memory *mem, const Tox_Network *ns, const Tox_Random *rng, const Tox_Time *tm); +nullable(1) void tox_system_free(Tox_System *sys); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_SYSTEM_H diff --git a/toxcore/tox_system_impl.h b/toxcore/tox_system_impl.h new file mode 100644 index 00000000000..bd74fd6e32a --- /dev/null +++ b/toxcore/tox_system_impl.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_SYSTEM_IMPL_H +#define C_TOXCORE_TOXCORE_TOX_SYSTEM_IMPL_H + +#include "tox_system.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct Tox_System { + const Tox_Logger *log; + const Tox_Memory *mem; + const Tox_Network *ns; + const Tox_Random *rng; + const Tox_Time *tm; +}; + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_SYSTEM_IMPL_H diff --git a/toxcore/tox_test.cc b/toxcore/tox_test.cc index 530c1390a1f..2848a4fa2e6 100644 --- a/toxcore/tox_test.cc +++ b/toxcore/tox_test.cc @@ -6,6 +6,7 @@ #include #include "crypto_core.h" +#include "os_random.h" #include "tox_private.h" namespace { @@ -94,7 +95,7 @@ TEST(Tox, OneTest) Tox *tox1 = tox_new(options, nullptr); ASSERT_NE(tox1, nullptr); - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); set_random_name_and_status_message(tox1, rng, name.data(), status_message.data()); Tox *tox2 = tox_new(options, nullptr); diff --git a/toxcore/tox_time.c b/toxcore/tox_time.c new file mode 100644 index 00000000000..637e17f8f00 --- /dev/null +++ b/toxcore/tox_time.c @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ +#include "tox_time.h" + +#include "ccompat.h" +#include "tox_time_impl.h" + +Tox_Time *tox_time_new(const Tox_Time_Funcs *funcs, void *user_data, const Tox_Memory *mem) +{ + Tox_Time *tm = (Tox_Time *)tox_memory_calloc(mem, 1, sizeof(Tox_Time)); + + if (tm == nullptr) { + return nullptr; + } + + tm->funcs = funcs; + tm->user_data = user_data; + + tm->mem = mem; + + return tm; +} + +void tox_time_free(Tox_Time *tm) +{ + tox_memory_dealloc(tm->mem, tm); +} + +uint64_t tox_time_monotonic(const Tox_Time *tm) +{ + return tm->funcs->monotonic_callback(tm->user_data); +} diff --git a/toxcore/tox_time.h b/toxcore/tox_time.h new file mode 100644 index 00000000000..b8dd5c2cb6b --- /dev/null +++ b/toxcore/tox_time.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_TIME_H +#define C_TOXCORE_TOXCORE_TOX_TIME_H + +#include +#include +#include + +#include "tox_memory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Tox_Time_Funcs Tox_Time_Funcs; + +typedef struct Tox_Time Tox_Time; + +non_null(1, 3) nullable(2) +Tox_Time *tox_time_new(const Tox_Time_Funcs *funcs, void *user_data, const Tox_Memory *mem); + +nullable(1) void tox_time_free(Tox_Time *tm); + +non_null() uint64_t tox_time_monotonic(const Tox_Time *tm); + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_TIME_H diff --git a/toxcore/tox_time_impl.h b/toxcore/tox_time_impl.h new file mode 100644 index 00000000000..300bc12b1f8 --- /dev/null +++ b/toxcore/tox_time_impl.h @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later + * Copyright © 2022-2023 The TokTok team. + */ + +#ifndef C_TOXCORE_TOXCORE_TOX_TIME_IMPL_H +#define C_TOXCORE_TOXCORE_TOX_TIME_IMPL_H + +#include "tox_time.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef uint64_t tox_time_monotonic_cb(void *self); + +struct Tox_Time_Funcs { + tox_time_monotonic_cb *monotonic_callback; +}; + +struct Tox_Time { + const Tox_Time_Funcs *funcs; + void *user_data; + + const Tox_Memory *mem; +}; + +#ifdef __cplusplus +} +#endif + +#endif // C_TOXCORE_TOXCORE_TOX_TIME_IMPL_H diff --git a/toxcore/tox_unpack.h b/toxcore/tox_unpack.h index 5f0b18ad1b8..c07fe49445d 100644 --- a/toxcore/tox_unpack.h +++ b/toxcore/tox_unpack.h @@ -5,7 +5,7 @@ #ifndef C_TOXCORE_TOXCORE_TOX_UNPACK_H #define C_TOXCORE_TOXCORE_TOX_UNPACK_H -#include "attributes.h" +#include "tox_attributes.h" #include "bin_unpack.h" #include "tox.h" diff --git a/toxcore/util.h b/toxcore/util.h index 44091b36227..e8067dbf77b 100644 --- a/toxcore/util.h +++ b/toxcore/util.h @@ -15,7 +15,7 @@ #include #include -#include "attributes.h" +#include "tox_attributes.h" #include "mem.h" #ifdef __cplusplus diff --git a/toxcore/util_test.cc b/toxcore/util_test.cc index 47bf258766b..3a31ce39363 100644 --- a/toxcore/util_test.cc +++ b/toxcore/util_test.cc @@ -3,12 +3,13 @@ #include #include "crypto_core.h" +#include "os_random.h" namespace { TEST(Util, TwoRandomIdsAreNotEqual) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); uint8_t pk1[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t sk1[CRYPTO_SECRET_KEY_SIZE]; @@ -23,7 +24,7 @@ TEST(Util, TwoRandomIdsAreNotEqual) TEST(Util, IdCopyMakesKeysEqual) { - const Random *rng = system_random(); + const Random *rng = os_random(); ASSERT_NE(rng, nullptr); uint8_t pk1[CRYPTO_PUBLIC_KEY_SIZE]; uint8_t sk1[CRYPTO_SECRET_KEY_SIZE]; diff --git a/toxencryptsave.h b/toxencryptsave.h new file mode 100644 index 00000000000..15e6502939d --- /dev/null +++ b/toxencryptsave.h @@ -0,0 +1 @@ +#include "toxencryptsave/toxencryptsave.h" diff --git a/toxencryptsave/BUILD.bazel b/toxencryptsave/BUILD.bazel index bbd5e0ee88c..78312bd6cc3 100644 --- a/toxencryptsave/BUILD.bazel +++ b/toxencryptsave/BUILD.bazel @@ -22,6 +22,7 @@ cc_library( ":defines", "//c-toxcore/toxcore:ccompat", "//c-toxcore/toxcore:crypto_core", + "//c-toxcore/toxcore:os_random", "@libsodium", ], ) @@ -36,6 +37,7 @@ cc_library( deps = [ "//c-toxcore/toxcore:ccompat", "//c-toxcore/toxcore:crypto_core", + "//c-toxcore/toxcore:os_random", "@libsodium", ], ) diff --git a/toxencryptsave/toxencryptsave.c b/toxencryptsave/toxencryptsave.c index 45003055f42..343dde38cf6 100644 --- a/toxencryptsave/toxencryptsave.c +++ b/toxencryptsave/toxencryptsave.c @@ -15,6 +15,7 @@ #include "../toxcore/ccompat.h" #include "../toxcore/crypto_core.h" +#include "../toxcore/os_random.h" #include "defines.h" static_assert(TOX_PASS_SALT_LENGTH == crypto_pwhash_scryptsalsa208sha256_SALTBYTES, @@ -115,7 +116,7 @@ bool tox_get_salt(const uint8_t *ciphertext, uint8_t *salt, Tox_Err_Get_Salt *er Tox_Pass_Key *tox_pass_key_derive(const uint8_t *passphrase, size_t passphrase_len, Tox_Err_Key_Derivation *error) { - const Random *rng = system_random(); + const Random *rng = os_random(); if (rng == nullptr) { SET_ERROR_PARAMETER(error, TOX_ERR_KEY_DERIVATION_FAILED); @@ -192,7 +193,7 @@ Tox_Pass_Key *tox_pass_key_derive_with_salt(const uint8_t *passphrase, size_t pa bool tox_pass_key_encrypt(const Tox_Pass_Key *key, const uint8_t *plaintext, size_t plaintext_len, uint8_t *ciphertext, Tox_Err_Encryption *error) { - const Random *rng = system_random(); + const Random *rng = os_random(); if (rng == nullptr) { SET_ERROR_PARAMETER(error, TOX_ERR_ENCRYPTION_FAILED);