/* * ping.c -- Buffered pinging using cyclic arrays. * * This file is donated to the Tox Project. * Copyright 2013 plutooo */ #include #include #include "DHT.h" #include "net_crypto.h" #include "packets.h" #include "network.h" #include "util.h" #define PING_NUM_MAX 256 #define PING_TIMEOUT 5 // 5s typedef struct { IP_Port ipp; uint64_t id; uint64_t timestamp; } pinged_t; static pinged_t pings[PING_NUM_MAX]; static size_t num_pings; static size_t pos_pings; static clientid_t* self_id = (clientid_t*) &self_public_key; extern uint8_t self_secret_key[crypto_box_SECRETKEYBYTES]; // DHT.c void init_ping() { num_pings = 0; pos_pings = 0; } static bool is_timeout(uint64_t time) { return (time + PING_TIMEOUT) < now(); } static void remove_timeouts() // O(n) { size_t i, id; size_t new_pos = pos_pings; size_t new_num = num_pings; // Loop through buffer, oldest first for (i=0; iclient_id, self_id)) return 1; // Decrypt ping_id rc = decrypt_data((uint8_t*) &p->client_id, self_secret_key, (uint8_t*) &p->nonce, (uint8_t*) &p->ping_id, sizeof(ping_id) + ENCRYPTION_PADDING, (uint8_t*) &ping_id); if (rc != sizeof(ping_id)) return 1; // Send response send_ping_response(source, &p->client_id, ping_id); send_ping_request(source, &p->client_id); // Make this smarter? return 0; } int handle_ping_response(uint8_t* packet, uint32_t length, IP_Port source) { pingres_t* p = (pingres_t*) packet; int rc; uint64_t ping_id; if (length != sizeof(pingres_t) || id_eq(&p->client_id, self_id)) return 1; // Decrypt ping_id rc = decrypt_data((uint8_t*) &p->client_id, self_secret_key, (uint8_t*) &p->nonce, (uint8_t*) &p->ping_id, sizeof(ping_id) + ENCRYPTION_PADDING, (uint8_t*) &ping_id); if (rc != sizeof(ping_id)) return 1; // Make sure ping_id is correct if(!is_pinging(source, ping_id)) return 1; // Associate source ip with client_id addto_lists(source, (uint8_t*) &p->client_id); return 0; }