├── include └── RUDP │ ├── library.hpp │ ├── utility.hpp │ ├── Peer.hpp │ ├── Packet.hpp │ ├── protocols.hpp │ ├── Socket.hpp │ └── impl │ └── Socket.tcc ├── README.md ├── examples └── basic │ ├── client.cpp │ └── server.cpp └── LICENSE.md /include/RUDP/library.hpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #ifndef RELIABLEUDP_LIBRARY_HPP 13 | #define RELIABLEUDP_LIBRARY_HPP 14 | 15 | #include "Packet.hpp" 16 | #include "Peer.hpp" 17 | #include "Socket.hpp" 18 | #include "protocols.hpp" 19 | #include "utility.hpp" 20 | 21 | // FIXME: beware endianness! 22 | 23 | #endif //RELIABLEUDP_LIBRARY_HPP 24 | -------------------------------------------------------------------------------- /include/RUDP/utility.hpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #ifndef RELIABLEUDP_UTILITY_HPP 13 | #define RELIABLEUDP_UTILITY_HPP 14 | 15 | #include 16 | #include // uint8_t, uint16_t, uint32_t 17 | #include // std::numeric_limits 18 | 19 | namespace rudp { 20 | 21 | template 22 | bool sequence_more_recent(T s1, T s2) { 23 | return (s1 > s2) && (s1 - s2 <= std::numeric_limits::max() / 2) 24 | || (s2 > s1) && (s2 - s1 > std::numeric_limits::max() / 2); 25 | } 26 | 27 | template 28 | void build_buffer(uint8_t* buffer, Header header, std::string message) { 29 | std::copy((uint8_t *) &header, (uint8_t *) &header + sizeof(header), buffer); 30 | std::copy(message.data(), message.data() + message.size(), buffer + sizeof(header)); 31 | } 32 | 33 | } 34 | 35 | #endif //RELIABLEUDP_UTILITY_HPP 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RUDP 2 | 3 | RUDP is a header only library aiming at providing various asynchronous UDP based sockets such as reliable UDP socket. 4 | 5 | Currently it only has a "connection" UDP socket (an UDP socket that handles connections). 6 | 7 | RUDP uses some C++14 features and boost libraries (mainly asio and uuid). 8 | 9 | [More explanations to come] 10 | 11 | ## Basic usage 12 | 13 | Minimal server code: 14 | ```C++ 15 | using boost::asio::ip::udp; 16 | 17 | boost::asio::io_service io_service; 18 | rudp::Socket socket(io_service, 512, { udp::v4(), 2000 }); 19 | 20 | io_service.run(); 21 | ``` 22 | 23 | Minimal client code: 24 | ```C++ 25 | using boost::asio::ip::udp; 26 | 27 | boost::asio::io_service io_service; 28 | rudp::Socket socket(io_service, 512); 29 | 30 | udp::resolver resolver(io_service); 31 | udp::resolver::query query(udp::v4(), "localhost", "2000"); 32 | udp::endpoint remote_endpoint = *resolver.resolve(query); 33 | socket.connect(remote_endpoint); 34 | 35 | io_service.run(); 36 | ``` 37 | 38 | To perform any useful task handlers shall be set. 39 | 40 | `rudp::BasicHeader` is the simplest header of RUDP. A `rudp::Socket` only provides a "connection" UDP socket. 41 | 42 | For more complete examples, check the [example folder](examples). 43 | 44 | ## License 45 | 46 | This work is under the [European Union Public License v1.1](LICENSE.md). 47 | 48 | You may get a copy of this license in your language from the European Commission [here](https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11). 49 | 50 | Extract of article 13 : 51 | 52 | All linguistic versions of this Licence, approved by the European Commission, have identical value. 53 | Parties can take advantage of the linguistic version of their choice. 54 | 55 | ## Planned 56 | 57 | - Add makefiles 58 | - Add doxygen documentation. 59 | - Add time critical protocol. 60 | - Add reliable order protocol. 61 | -------------------------------------------------------------------------------- /include/RUDP/Peer.hpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #ifndef RELIABLEUDP_PEER_HPP 13 | #define RELIABLEUDP_PEER_HPP 14 | 15 | #include 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | namespace rudp { 22 | 23 | struct Peer { 24 | Peer() {} 25 | 26 | Peer(boost::asio::ip::udp::endpoint endpoint) 27 | : uuid(boost::uuids::random_generator{}()) 28 | , endpoint(endpoint) 29 | {} 30 | 31 | Peer(boost::asio::ip::udp::endpoint endpoint, boost::uuids::uuid uuid) 32 | : uuid(uuid) 33 | , endpoint(endpoint) 34 | {} 35 | 36 | Peer(boost::asio::ip::udp::endpoint endpoint, boost::uuids::uuid uuid, std::chrono::seconds last_packet_timestamp) 37 | : uuid(uuid) 38 | , endpoint(endpoint) 39 | , last_packet_timestamp(last_packet_timestamp) 40 | {} 41 | 42 | boost::uuids::uuid uuid; 43 | boost::asio::ip::udp::endpoint endpoint; 44 | std::chrono::seconds last_packet_timestamp; 45 | }; 46 | 47 | } 48 | 49 | #endif //RELIABLEUDP_PEER_HPP 50 | -------------------------------------------------------------------------------- /include/RUDP/Packet.hpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #ifndef RELIABLEUDP_PACKET_HPP 13 | #define RELIABLEUDP_PACKET_HPP 14 | 15 | #include // uint8_t, uint16_t, uint32_t 16 | #include 17 | #include 18 | 19 | namespace rudp { 20 | 21 | struct bad_header_exception : std::runtime_error { 22 | bad_header_exception() : std::runtime_error("Bad header") {} 23 | }; 24 | 25 | struct bad_protocol_exception : std::runtime_error { 26 | bad_protocol_exception() : std::runtime_error("Bad protocol") {} 27 | }; 28 | 29 | template 30 | class Packet { 31 | public: 32 | Packet(std::vector packet_buffer) noexcept(false) { 33 | if (packet_buffer.size() < sizeof(Header)) { 34 | throw bad_header_exception(); 35 | } 36 | 37 | m_header = *reinterpret_cast(packet_buffer.data()); 38 | if (m_header.protocol != Header::PROTOCOL_ID) { 39 | throw bad_protocol_exception(); 40 | } 41 | 42 | m_message = std::vector(packet_buffer.begin() + sizeof(m_header), packet_buffer.end()); 43 | } 44 | 45 | const Header& get_header() const noexcept { 46 | return m_header; 47 | } 48 | 49 | const std::vector& get_message() const noexcept { 50 | return m_message; 51 | } 52 | 53 | private: 54 | Header m_header; 55 | std::vector m_message; 56 | }; 57 | 58 | } 59 | 60 | #endif //RELIABLEUDP_PACKET_HPP 61 | -------------------------------------------------------------------------------- /include/RUDP/protocols.hpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #ifndef RELIABLEUDP_PROTOCOLS_HPP 13 | #define RELIABLEUDP_PROTOCOLS_HPP 14 | 15 | #include // uint8_t, uint16_t, uint32_t 16 | 17 | #include 18 | 19 | namespace rudp { 20 | 21 | using protocol_type = uint32_t; 22 | 23 | struct BasicHeader { 24 | static protocol_type constexpr PROTOCOL_ID = 57986; 25 | 26 | BasicHeader() : protocol(PROTOCOL_ID) {} 27 | 28 | BasicHeader(boost::uuids::uuid uuid) 29 | : protocol(PROTOCOL_ID) 30 | , uuid(uuid) {} 31 | 32 | protocol_type protocol; 33 | boost::uuids::uuid uuid; 34 | }; 35 | 36 | struct TimeCriticalHeader { 37 | static protocol_type constexpr PROTOCOL_ID = 57987; 38 | 39 | TimeCriticalHeader() : protocol(PROTOCOL_ID) {} 40 | 41 | TimeCriticalHeader(boost::uuids::uuid uuid) 42 | : protocol(PROTOCOL_ID) 43 | , uuid(uuid) {} 44 | 45 | protocol_type protocol; 46 | uint16_t sequence; 47 | uint16_t ack; 48 | boost::uuids::uuid uuid; 49 | }; 50 | 51 | struct ReliableOrderHeader { 52 | static protocol_type constexpr PROTOCOL_ID = 57988; 53 | 54 | ReliableOrderHeader() : protocol(PROTOCOL_ID) {} 55 | 56 | ReliableOrderHeader(boost::uuids::uuid uuid) 57 | : protocol(PROTOCOL_ID) 58 | , uuid(uuid) {} 59 | 60 | protocol_type protocol; 61 | uint16_t sequence; 62 | uint16_t ack; 63 | uint32_t ack_bits; 64 | boost::uuids::uuid uuid; 65 | }; 66 | 67 | } 68 | 69 | #endif //RELIABLEUDP_PROTOCOLS_HPP 70 | -------------------------------------------------------------------------------- /examples/basic/client.cpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | #include 17 | #include 18 | 19 | #include "RUDP/Packet.hpp" 20 | #include "RUDP/protocols.hpp" 21 | #include "RUDP/utility.hpp" 22 | #include "RUDP/Peer.hpp" 23 | #include "RUDP/Socket.hpp" 24 | 25 | using boost::asio::ip::udp; 26 | 27 | using Header = rudp::BasicHeader; 28 | 29 | boost::asio::io_service io_service; 30 | rudp::Socket
sock(io_service, 512); 31 | 32 | void receive_handler(const rudp::Packet
& packet, 33 | size_t bytes_transferred, 34 | const rudp::Peer /*peer*/) { 35 | std::string message(packet.get_message().begin(), packet.get_message().begin() + bytes_transferred - sizeof(packet.get_header())); 36 | std::cout << message << std::endl; 37 | } 38 | 39 | void disconnection_timeout_handler(const rudp::Peer& peer) { 40 | std::cout << "Server connection has timed out!" << std::endl; 41 | } 42 | 43 | void disconnection_handler(const rudp::Peer& /*peer*/) { 44 | std::cout << "Disconnected from server!" << std::endl; 45 | } 46 | 47 | void connection_handler(const rudp::Peer& /*peer*/) { 48 | std::cout << "Connected to server!" << std::endl; 49 | } 50 | 51 | int main(int argc, char* argv[]) { 52 | if (argc != 2) { 53 | std::cerr << "Usage: client " << std::endl; 54 | return EXIT_FAILURE; 55 | } 56 | 57 | sock.set_receive_handler(receive_handler); 58 | sock.set_disconnection_timeout_handler(disconnection_timeout_handler); 59 | sock.set_disconnection_handler(disconnection_handler); 60 | sock.set_connection_handler(connection_handler); 61 | 62 | udp::resolver resolver(io_service); 63 | udp::resolver::query query(udp::v4(), argv[1], "2000"); 64 | udp::endpoint remote_endpoint = *resolver.resolve(query); 65 | sock.connect(remote_endpoint); 66 | 67 | std::thread thread([]() { io_service.run(); }); 68 | 69 | for (;;) { 70 | std::string message; 71 | std::getline(std::cin, message, '\n'); 72 | 73 | if (message == "/quit") { 74 | break; 75 | } 76 | 77 | Header header; 78 | header.uuid = sock.self().uuid; 79 | size_t packet_size = sizeof(header) + message.size(); 80 | uint8_t buffer[packet_size]; 81 | build_buffer(buffer, header, message); 82 | 83 | sock.async_send_to(buffer, packet_size, remote_endpoint); 84 | } 85 | 86 | sock.close(); 87 | io_service.stop(); 88 | thread.join(); 89 | 90 | return EXIT_SUCCESS; 91 | } 92 | -------------------------------------------------------------------------------- /examples/basic/server.cpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | 18 | #include "RUDP/Packet.hpp" 19 | #include "RUDP/protocols.hpp" 20 | #include "RUDP/utility.hpp" 21 | #include "RUDP/Peer.hpp" 22 | #include "RUDP/Socket.hpp" 23 | 24 | using boost::asio::ip::udp; 25 | 26 | using Header = rudp::BasicHeader; 27 | 28 | boost::asio::io_service io_service; 29 | rudp::Socket
sock(io_service, 512, { udp::v4(), 2000 }); 30 | 31 | void receive_handler(const rudp::Packet
& packet, 32 | size_t bytes_transferred, 33 | const rudp::Peer& peer) { 34 | std::string message(packet.get_message().begin(), packet.get_message().begin() + bytes_transferred - sizeof(packet.get_header())); 35 | std::cout << boost::uuids::to_string(peer.uuid) << ": " << message << std::endl; 36 | 37 | Header answer_header; 38 | answer_header.uuid = sock.self().uuid; 39 | std::string answer_message; 40 | bool stop_server = false; 41 | if (message == "/stop_server") { 42 | answer_message = "Server is stopping..."; 43 | stop_server = true; 44 | } else { 45 | answer_message = boost::uuids::to_string(peer.uuid) + ": " + message; 46 | } 47 | size_t packet_size = sizeof(answer_header) + answer_message.size(); 48 | uint8_t buffer[packet_size]; 49 | build_buffer(buffer, answer_header, answer_message); 50 | sock.async_send_to_all(buffer, packet_size); 51 | 52 | if (stop_server) { 53 | sock.close(); 54 | io_service.stop(); 55 | } 56 | } 57 | 58 | void disconnection_timeout_handler(const rudp::Peer& peer) { 59 | Header answer_header; 60 | answer_header.uuid = sock.self().uuid; 61 | std::string answer_message = boost::uuids::to_string(peer.uuid) + "'s connection has timed out!"; 62 | size_t packet_size = sizeof(answer_header) + answer_message.size(); 63 | uint8_t buffer[packet_size]; 64 | build_buffer(buffer, answer_header, answer_message); 65 | 66 | sock.async_send_to_all(buffer, packet_size); 67 | std::cout << answer_message << std::endl; 68 | } 69 | 70 | void disconnection_handler(const rudp::Peer& peer) { 71 | Header answer_header; 72 | answer_header.uuid = sock.self().uuid; 73 | std::string answer_message = boost::uuids::to_string(peer.uuid) + " disconnected!"; 74 | size_t packet_size = sizeof(answer_header) + answer_message.size(); 75 | uint8_t buffer[packet_size]; 76 | build_buffer(buffer, answer_header, answer_message); 77 | 78 | sock.async_send_to_all(buffer, packet_size); 79 | std::cout << answer_message << std::endl; 80 | } 81 | 82 | void connection_handler(const rudp::Peer& peer) { 83 | Header answer_header; 84 | answer_header.uuid = sock.self().uuid; 85 | std::string answer_message = boost::uuids::to_string(peer.uuid) + " connected!"; 86 | size_t packet_size = sizeof(answer_header) + answer_message.size(); 87 | uint8_t buffer[packet_size]; 88 | build_buffer(buffer, answer_header, answer_message); 89 | 90 | sock.async_send_to_all(buffer, packet_size); 91 | std::cout << answer_message << std::endl; 92 | } 93 | 94 | int main() { 95 | sock.set_receive_handler(receive_handler); 96 | sock.set_disconnection_timeout_handler(disconnection_timeout_handler); 97 | sock.set_disconnection_handler(disconnection_handler); 98 | sock.set_connection_handler(connection_handler); 99 | 100 | std::cout << "Starting server." << std::endl; 101 | io_service.run(); 102 | std::cout << "Closing server." << std::endl; 103 | 104 | return EXIT_SUCCESS; 105 | } 106 | -------------------------------------------------------------------------------- /include/RUDP/Socket.hpp: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #ifndef RELIABLEUDP_SOCKET_HPP 13 | #define RELIABLEUDP_SOCKET_HPP 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | #include "protocols.hpp" 24 | #include "Packet.hpp" 25 | #include "Peer.hpp" 26 | 27 | namespace rudp { 28 | 29 | const unsigned int DEFAULT_CONNECTION_TIMEOUT = 15; 30 | const unsigned int DEFAULT_KEEP_ALIVE_WAIT = 3; 31 | 32 | template 33 | class Socket { 34 | 35 | using receive_handler_type = std::function&, size_t, const rudp::Peer&)>; 36 | using connection_handler_type = std::function; 37 | using disconnection_handler_type = std::function; 38 | using disconnection_timeout_handler_type = std::function; 39 | 40 | public: 41 | Socket(boost::asio::io_service& io_service, const size_t buffer_size, 42 | const boost::asio::ip::udp::endpoint& endpoint); 43 | 44 | Socket(boost::asio::io_service& io_service, const size_t buffer_size); 45 | 46 | void set_receive_handler(const receive_handler_type& handler) noexcept { 47 | m_receive_handler = handler; 48 | } 49 | 50 | void set_connection_handler(const connection_handler_type& handler) noexcept { 51 | m_connection_handler = handler; 52 | } 53 | 54 | void set_disconnection_handler(const disconnection_handler_type& handler) noexcept { 55 | m_disconnection_handler = handler; 56 | } 57 | 58 | void set_disconnection_timeout_handler(const disconnection_timeout_handler_type& handler) noexcept { 59 | m_disconnection_timeout_handler = handler; 60 | } 61 | 62 | void open(const boost::asio::ip::udp& ip_protocol) { m_socket.open(ip_protocol); } 63 | 64 | void close() noexcept; 65 | 66 | void connect(boost::asio::ip::udp::endpoint& endpoint); 67 | 68 | void bind(boost::asio::ip::udp::endpoint endpoint) noexcept { m_socket.bind(endpoint); } 69 | 70 | void async_send_to(void* buffer, size_t buffer_size, boost::asio::ip::udp::endpoint& endpoint) { 71 | m_socket.async_send_to(boost::asio::buffer(buffer, buffer_size), 72 | endpoint, 73 | [](boost::system::error_code ec, size_t br) { } 74 | ); 75 | } 76 | 77 | void async_send_to_all(void* buffer, size_t buffer_size) { 78 | for (auto& peer : m_peers) { 79 | async_send_to(buffer, buffer_size, peer.endpoint); 80 | } 81 | } 82 | 83 | /*template 84 | void async_send_to(const SizedContainer& buffer, boost::asio::ip::udp::endpoint& endpoint) { 85 | m_socket.async_send_to(boost::asio::buffer(buffer), 86 | endpoint, 87 | [](boost::system::error_code ec, size_t br) { } 88 | ); 89 | } 90 | 91 | template 92 | void async_send_to_all(const SizedContainer& buffer, size_t buffer_size) { 93 | for (auto& peer : m_peers) { 94 | async_send_to(buffer, peer.endpoint); 95 | } 96 | }*/ 97 | 98 | const rudp::Peer& self() { return m_self; } 99 | 100 | private: 101 | void handle_async_receive_from(const boost::system::error_code &error_code, size_t bytes_transferred); 102 | 103 | void handle_keep_alive(); 104 | 105 | void start_receive(); 106 | 107 | void start_keep_alive(); 108 | 109 | unsigned int m_connection_timeout; 110 | bool m_listening; 111 | 112 | boost::asio::io_service& m_io_service; 113 | boost::asio::ip::udp::socket m_socket; 114 | boost::asio::ip::udp::endpoint m_remote_endpoint; 115 | boost::asio::deadline_timer m_timer; 116 | 117 | rudp::Peer m_self; 118 | std::vector m_recv_buf; 119 | std::vector m_peers; 120 | 121 | receive_handler_type m_receive_handler; 122 | connection_handler_type m_connection_handler; 123 | disconnection_handler_type m_disconnection_handler; 124 | disconnection_timeout_handler_type m_disconnection_timeout_handler; 125 | }; 126 | 127 | } 128 | 129 | #include "impl/Socket.tcc" 130 | 131 | #endif //RELIABLEUDP_SOCKET_HPP 132 | -------------------------------------------------------------------------------- /include/RUDP/impl/Socket.tcc: -------------------------------------------------------------------------------- 1 | /////////////////////////////////////////////////////////////////////////////////////////////////// 2 | // // 3 | // Copyright 2017 Benoît CORTIER // 4 | // // 5 | // This file is part of RUDP project which is released under the // 6 | // European Union Public License v1.1. If a copy of the EUPL was // 7 | // not distributed with this software, you can obtain one at : // 8 | // https://joinup.ec.europa.eu/community/eupl/og_page/european-union-public-licence-eupl-v11 // 9 | // // 10 | /////////////////////////////////////////////////////////////////////////////////////////////////// 11 | 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | #include "RUDP/Socket.hpp" 21 | 22 | namespace { 23 | template 24 | void erase_if(ContainerT& container, const PredicateT& predicate) { 25 | for (auto it = container.cbegin(); it != container.cend(); ) { 26 | if (predicate(*it)) { 27 | it = container.erase(it); 28 | } else { 29 | ++it; 30 | } 31 | } 32 | } 33 | 34 | template 35 | void is_valid_specialization() { 36 | static_assert(std::is_same::value, 37 | "'PROTOCOL_ID' static field should be of the same type as 'rudp::BasicHeader::PROTOCOL_ID'."); 38 | static_assert(std::is_same::value, 39 | "'protocol' field should be of the same type as 'rudp::BasicHeader::protocol'."); 40 | static_assert(std::is_same::value, 41 | "'uuid' field should be of the same type as 'rudp::BasicHeader::uuid'."); 42 | 43 | return; // Header type should have a field 'uuid', 'protocol' of the same type as 'rudp::BasicHeader::uuid' and 'rudp::BasicHeader::protocol' and a static field 'PROTOCOL_ID' of the same type as 'rudp::BasicHeader::PROTOCOL_ID'. 44 | } 45 | 46 | using lib_message_type = uint32_t; 47 | 48 | const lib_message_type KEEP_ALIVE_MESSAGE = 424967295; 49 | const lib_message_type CONNECTION_MESSAGE = 424967296; 50 | const lib_message_type DISCONNECTION_MESSAGE = 424967297; 51 | 52 | template 53 | struct LibMessage { 54 | Header header; 55 | lib_message_type message; 56 | }; 57 | 58 | template 59 | inline LibMessage
build_lib_message(boost::uuids::uuid self_uuid, const lib_message_type type) { 60 | LibMessage
lib_message; 61 | lib_message.header = Header(self_uuid); 62 | lib_message.message = type; 63 | return lib_message; 64 | } 65 | } 66 | 67 | template 68 | rudp::Socket
::Socket(boost::asio::io_service& io_service, size_t buffer_size, 69 | const boost::asio::ip::udp::endpoint& endpoint) 70 | : m_connection_timeout(DEFAULT_CONNECTION_TIMEOUT) 71 | , m_listening(true) 72 | , m_io_service(io_service) 73 | , m_socket(io_service, endpoint) 74 | , m_timer(io_service) 75 | , m_self(endpoint) 76 | , m_recv_buf(buffer_size) 77 | { 78 | is_valid_specialization
(); 79 | start_keep_alive(); 80 | start_receive(); 81 | } 82 | 83 | template 84 | rudp::Socket
::Socket(boost::asio::io_service& io_service, size_t buffer_size) 85 | : m_connection_timeout(DEFAULT_CONNECTION_TIMEOUT) 86 | , m_listening(false) 87 | , m_io_service(io_service) 88 | , m_socket(io_service) 89 | , m_timer(io_service) 90 | , m_self(boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4::loopback(), 0)) 91 | , m_recv_buf(buffer_size) 92 | { is_valid_specialization
(); } 93 | 94 | template 95 | void rudp::Socket
::close() noexcept { 96 | LibMessage
lib_message = build_lib_message
(m_self.uuid, DISCONNECTION_MESSAGE); 97 | async_send_to_all(reinterpret_cast(&lib_message), sizeof(lib_message)); 98 | 99 | m_listening = false; 100 | } 101 | 102 | template 103 | void rudp::Socket
::connect(boost::asio::ip::udp::endpoint& remote_endpoint) { 104 | m_socket.open(remote_endpoint.protocol()); 105 | 106 | LibMessage
lib_message = build_lib_message
(m_self.uuid, CONNECTION_MESSAGE); 107 | async_send_to(reinterpret_cast(&lib_message), sizeof(lib_message), remote_endpoint); 108 | 109 | m_listening = true; 110 | 111 | start_keep_alive(); 112 | start_receive(); 113 | } 114 | 115 | template 116 | void rudp::Socket
::handle_async_receive_from(const boost::system::error_code &error_code, size_t bytes_transferred) { 117 | if (!error_code) { 118 | try { 119 | rudp::Packet
packet(m_recv_buf); 120 | 121 | std::vector::iterator peer_it = std::find_if(m_peers.begin(), m_peers.end(), [this, &packet](rudp::Peer& peer) -> bool { 122 | if (peer.uuid == packet.get_header().uuid) { 123 | peer.last_packet_timestamp = 124 | std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); 125 | return true; 126 | } 127 | return false; 128 | }); 129 | 130 | if (peer_it == m_peers.end()) { // peer doesn't exist 131 | //BOOST_LOG_TRIVIAL(trace) << "New peer: " << boost::uuids::to_string(packet.get_header().uuid); 132 | 133 | m_peers.emplace_back(m_remote_endpoint, 134 | packet.get_header().uuid, 135 | std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch())); 136 | peer_it = m_peers.end() - 1; 137 | 138 | if (m_connection_handler) { 139 | m_connection_handler(*peer_it); 140 | 141 | LibMessage
lib_message = build_lib_message
(m_self.uuid, CONNECTION_MESSAGE); 142 | async_send_to(reinterpret_cast(&lib_message), sizeof(lib_message), peer_it->endpoint); 143 | } 144 | } 145 | 146 | bool is_a_user_message = true; 147 | if (bytes_transferred - sizeof(Header) == sizeof(lib_message_type)) { 148 | const lib_message_type lib_message = *reinterpret_cast(packet.get_message().data()); 149 | if (lib_message == CONNECTION_MESSAGE || lib_message == KEEP_ALIVE_MESSAGE) { 150 | is_a_user_message = false; 151 | } else if (lib_message == DISCONNECTION_MESSAGE) { 152 | is_a_user_message = false; 153 | if (m_disconnection_handler) { 154 | m_disconnection_handler(*peer_it); 155 | } 156 | 157 | m_peers.erase(std::remove_if(m_peers.begin(), m_peers.end(), [this, peer_it](const auto& other_peer) -> bool { 158 | if (peer_it->uuid == other_peer.uuid) 159 | return true; 160 | return false; 161 | }), m_peers.end()); 162 | } 163 | } 164 | 165 | if (is_a_user_message && m_receive_handler) { 166 | m_receive_handler(packet, bytes_transferred, *peer_it); 167 | } 168 | } catch (std::exception& e) { 169 | //BOOST_LOG_TRIVIAL(info) << "Received packet with a bad protocol."; 170 | m_socket.send_to(boost::asio::buffer("Bad protocol"), m_remote_endpoint); 171 | // FIXME: possible network loop... 172 | } 173 | 174 | if (m_listening) { 175 | start_receive(); 176 | } 177 | } 178 | } 179 | 180 | template 181 | void rudp::Socket
::handle_keep_alive() { 182 | //BOOST_LOG_TRIVIAL(trace) << "keep alive"; 183 | 184 | // check for timeouts 185 | std::chrono::seconds now = 186 | std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); 187 | m_peers.erase(std::remove_if(m_peers.begin(), m_peers.end(), [this, &now](const auto& peer) -> bool { 188 | if (peer.last_packet_timestamp + std::chrono::seconds(m_connection_timeout) < now) { 189 | if (m_disconnection_timeout_handler) { 190 | m_disconnection_timeout_handler(peer); 191 | } 192 | return true; 193 | } 194 | return false; 195 | }), m_peers.end()); 196 | 197 | if (m_listening) { 198 | // Keep alive. 199 | LibMessage
lib_message = build_lib_message
(m_self.uuid, KEEP_ALIVE_MESSAGE); 200 | async_send_to_all(reinterpret_cast(&lib_message), sizeof(lib_message)); 201 | 202 | start_keep_alive(); 203 | } 204 | } 205 | 206 | template 207 | void rudp::Socket::start_receive() { 208 | m_socket.async_receive_from( 209 | boost::asio::buffer(m_recv_buf), 210 | m_remote_endpoint, 211 | [this](auto ec, auto bytes_transfered) { 212 | this->handle_async_receive_from(ec, bytes_transfered); 213 | } 214 | ); 215 | } 216 | 217 | template 218 | void rudp::Socket::start_keep_alive() { 219 | m_timer.expires_from_now(boost::posix_time::seconds(DEFAULT_KEEP_ALIVE_WAIT)); 220 | m_timer.async_wait([this](auto ec) { 221 | this->handle_keep_alive(); 222 | }); 223 | } 224 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | # European Union Public Licence 3 | ### V. 1.1 4 | 5 | -------------------------- 6 | 7 | *EUPL © the European Community 2007* 8 | 9 | 10 | This European Union Public Licence (the “EUPL”) applies to the *Work* or *Software* (as defined below) which is provided under the terms of this Licence. Any use of the *Work*, other than as authorised under this Licence is prohibited (to the extent such use is covered by a right of the copyright holder of the Work). 11 | 12 | The *Original Work* is provided under the terms of this Licence when the *Licensor* (as defined below) has placed the following notice immediately following the copyright notice for the *Original Work*: 13 | 14 | Licensed under the EUPL V.1.1 15 | 16 | or has expressed by any other mean his willingness to license under the EUPL. 17 | 18 | 19 | ----------------- 20 | 21 | ## 1. Definitions 22 | 23 | 24 | In this Licence, the following terms have the following meaning: 25 | 26 | - *The Licence*: this Licence. 27 | 28 | - The *Original Work* or the *Software*: the software distributed and/or communicated by the *Licensor* under this Licence, available as *Source Code* and also as *Executable Code* as the case may be. 29 | 30 | - *Derivative Works*: the works or software that could be created by the *Licensee*, based upon the *Original Work* or modifications thereof. This Licence does not define the extent of modification or dependence on the *Original Work* required in order to classify a work as a *Derivative Work*; this extent is determined by copyright law applicable in the country mentioned in Article 15. 31 | 32 | - The *Work*: the *Original Work* and/or its *Derivative Works*. 33 | 34 | - The *Source Code*: the human-readable form of the *Work* which is the most convenient for people to study and modify. 35 | 36 | - The *Executable Code*: any code which has generally been compiled and which is meant to be interpreted by a computer as a program. 37 | 38 | - The *Licensor*: the natural or legal person that distributes and/or communicates the *Work* under the *Licence*. 39 | 40 | - *Contributor(s)*: any natural or legal person who modifies the *Work* under the *Licence*, or otherwise contributes to the creation of a *Derivative Work*. 41 | 42 | - The *Licensee* or “*You*”: any natural or legal person who makes any usage of the *Software* under the terms of the *Licence*. 43 | 44 | - *Distribution* and/or *Communication*: any act of selling, giving, lending, renting, distributing, communicating, transmitting, or otherwise making available, on-line or off-line, copies of the *Work* or providing access to its essential functionalities at the disposal of any other natural or legal person. 45 | 46 | 47 | ----------------------------------------------- 48 | 49 | ## 2. Scope of the rights granted by the *Licence* 50 | 51 | 52 | The *Licensor* hereby grants *You* a world-wide, royalty-free, non-exclusive, sub-licensable licence to do the following, for the duration of copyright vested in the *Original Work*: 53 | 54 | - use the *Work* in any circumstance and for all usage, 55 | - reproduce the *Work*, 56 | - modify the *Original Work*, and make *Derivative Works* based upon the *Work*, 57 | - communicate to the public, including the right to make available or display the *Work* or copies thereof to the public and perform publicly, as the case may be, the *Work*, 58 | - distribute the *Work* or copies thereof, 59 | - lend and rent the *Work* or copies thereof, 60 | - sub-license rights in the *Work* or copies thereof. 61 | 62 | Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the applicable law permits so. 63 | 64 | In the countries where moral rights apply, the *Licensor* waives his right to exercise his moral right to the extent allowed by law in order to make effective the licence of the economic rights here above listed. 65 | 66 | The *Licensor* grants to the *Licensee* royalty-free, non exclusive usage rights to any patents held by the *Licensor*, to the extent necessary to make use of the rights granted on the *Work* under this Licence. 67 | 68 | 69 | ----------------------------------- 70 | 71 | ## 3. *Communication* of the *Source Code* 72 | 73 | 74 | The *Licensor* may provide the *Work* either in its *Source Code* form, or as *Executable Code*. If the *Work* is provided as *Executable Code*, the *Licensor* provides in addition a machine-readable copy of the *Source Code* of the *Work* along with each copy of the *Work* that the *Licensor* distributes or indicates, in a notice following the copyright notice attached to the *Work*, a repository where the *Source Code* is easily and freely accessible for as long as the *Licensor* continues to distribute and/or communicate the *Work*. 75 | 76 | 77 | -------------------------- 78 | 79 | ## 4. Limitations on copyright 80 | 81 | 82 | Nothing in this Licence is intended to deprive the *Licensee* of the benefits from any exception or limitation to the exclusive rights of the rights owners in the *Original Work* or *Software*, of the exhaustion of those rights or of other applicable limitations thereto. 83 | 84 | 85 | ------------------------------ 86 | 87 | ## 5. Obligations of the *Licensee* 88 | 89 | 90 | The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the *Licensee*. Those obligations are the following: 91 | 92 | Attribution right: the *Licensee* shall keep intact all copyright, patent or trademarks notices and all notices that refer to the *Licence* and to the disclaimer of warranties. The *Licensee* must include a copy of such notices and a copy of the *Licence* with every copy of the *Work* he/she distributes and/or communicates. The *Licensee* must cause any *Derivative Work* to carry prominent notices stating that the *Work* has been modified and the date of modification. 93 | 94 | Copyleft clause: If the *Licensee* distributes and/or communicates copies of the *Original Works* or *Derivative Works* based upon the *Original Work*, this *Distribution* and/or *Communication* will be done under the terms of this Licence or of a later version of this Licence unless the *Original Work* is expressly distributed only under this version of the *Licence*. The *Licensee* (becoming *Licensor*) cannot offer or impose any additional terms or conditions on the *Work* or *Derivative Work* that alter or restrict the terms of the *Licence*. 95 | 96 | Compatibility clause: If the *Licensee* Distributes and/or Communicates *Derivative Works* or copies thereof based upon both the *Original Work* and another work licensed under a Compatible Licence, this *Distribution* and/or *Communication* can be done under the terms of this Compatible Licence. For the sake of this clause, “Compatible Licence” refers to the licences listed in the appendix attached to this Licence. Should the *Licensee*’s obligations under the Compatible Licence conflict with his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. 97 | 98 | Provision of *Source Code*: When distributing and/or communicating copies of the *Work*, the *Licensee* will provide a machine-readable copy of the *Source Code* or indicate a repository where this Source will be easily and freely available for as long as the *Licensee* continues to distribute and/or communicate the *Work*. 99 | 100 | Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names of the *Licensor*, except as required for reasonable and customary use in describing the origin of the *Work* and reproducing the content of the copyright notice. 101 | 102 | 103 | ---------------------- 104 | 105 | ## 6. Chain of Authorship 106 | 107 | 108 | The original *Licensor* warrants that the copyright in the *Original Work* granted hereunder is owned by him/her or licensed to him/her and that he/she has the power and authority to grant the *Licence*. 109 | 110 | Each *Contributor* warrants that the copyright in the modifications he/she brings to the *Work* are owned by him/her or licensed to him/her and that he/she has the power and authority to grant the *Licence*. 111 | 112 | Each time *You* accept the *Licence*, the original *Licensor* and subsequent *Contributor*s grant *You* a licence to their contributions to the *Work*, under the terms of this Licence. 113 | 114 | 115 | ------------------------- 116 | 117 | ## 7. Disclaimer of Warranty 118 | 119 | 120 | The *Work* is a work in progress, which is continuously improved by numerous contributors. It is not a finished work and may therefore contain defects or “bugs” inherent to this type of software development. 121 | 122 | For the above reason, the *Work* is provided under the *Licence* on an **“as is”** basis and **without warranties of any kind** concerning the *Work*, including without limitation merchantability, fitness for a particular purpose, absence of defects or errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this Licence. 123 | 124 | This disclaimer of warranty is an essential part of the *Licence* and a condition for the grant of any rights to the *Work*. 125 | 126 | 127 | -------------------------- 128 | 129 | ## 8. Disclaimer of Liability 130 | 131 | 132 | Except in the cases of wilful misconduct or damages directly caused to natural persons, the *Licensor* will in no event be liable for any direct or indirect, material or moral, damages of any kind, arising out of the *Licence* or of the use of the *Work*, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss of data or any commercial damage, even if the *Licensor* has been advised of the possibility of such damage. However, the *Licensor* will be liable under statutory product liability laws as far such laws apply to the *Work*. 133 | 134 | 135 | ------------------------ 136 | 137 | ## 9. Additional agreements 138 | 139 | 140 | While distributing the *Original Work* or *Derivative Works*, *You* may choose to conclude an additional agreement to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or services consistent with this Licence. However, in accepting such obligations, *You* may act only on your own behalf and on your sole responsibility, not on behalf of the original *Licensor* or any other *Contributor*, and only if *You* agree to indemnify, defend, and hold each *Contributor* harmless for any liability incurred by, or claims asserted against such *Contributor* by the fact *You* have accepted any such warranty or additional liability. 141 | 142 | 143 | -------------------------------- 144 | 145 | ## 10. Acceptance of the *Licence* 146 | 147 | 148 | The provisions of this Licence can be accepted by clicking on an icon “I agree” placed under the bottom of a window displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms and conditions. 149 | 150 | Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to *You* by Article 2 of this Licence, such as the use of the *Work*, the creation by *You* of a *Derivative Work* or the *Distribution* and/or *Communication* by *You* of the *Work* or copies thereof. 151 | 152 | 153 | 154 | ----------------------------- 155 | 156 | ## 11. Information to the public 157 | 158 | 159 | In case of any *Distribution* and/or *Communication* of the *Work* by means of electronic communication by *You* (for example, by offering to download the *Work* from a remote location) the distribution channel or media (for example, a website) must at least provide to the public the information requested by the applicable law regarding the *Licensor*, the *Licence* and the way it may be accessible, concluded, stored and reproduced by the *Licensee*. 160 | 161 | 162 | -------------------------------- 163 | 164 | ## 12. Termination of the *Licence* 165 | 166 | 167 | The *Licence* and the rights granted hereunder will terminate automatically upon any breach by the *Licensee* of the terms of the *Licence*. 168 | 169 | Such a termination will not terminate the licences of any person who has received the *Work* from the *Licensee* under the *Licence*, provided such persons remain in full compliance with the *Licence*. 170 | 171 | 172 | ----------------- 173 | 174 | ## 13. Miscellaneous 175 | 176 | 177 | Without prejudice of Article 9 above, the *Licence* represents the complete agreement between the Parties as to the *Work* licensed hereunder. 178 | 179 | If any provision of the *Licence* is invalid or unenforceable under applicable law, this will not affect the validity or enforceability of the *Licence* as a whole. Such provision will be construed and/or reformed so as necessary to make it valid and enforceable. 180 | 181 | The European Commission may publish other linguistic versions and/or new versions of this Licence, so far this is required and reasonable, without reducing the scope of the rights granted by the *Licence*. New versions of the *Licence* will be published with a unique version number. 182 | 183 | All linguistic versions of this *Licence*, approved by the European Commission, have identical value. Parties can take advantage of the linguistic version of their choice. 184 | 185 | 186 | ---------------- 187 | 188 | ## 14. Jurisdiction 189 | 190 | 191 | Any litigation resulting from the interpretation of this License, arising between the European Commission, as a *Licensor*, and any *Licensee*, will be subject to the jurisdiction of the Court of Justice of the European Communities, as laid down in article 238 of the Treaty establishing the European Community. 192 | 193 | Any litigation arising between Parties, other than the European Commission, and resulting from the interpretation of this License, will be subject to the exclusive jurisdiction of the competent court where the *Licensor* resides or conducts its primary business. 194 | 195 | 196 | ------------------ 197 | 198 | ## 15. Applicable Law 199 | 200 | 201 | This Licence shall be governed by the law of the European Union country where the *Licensor* resides or has his registered office. 202 | 203 | This licence shall be governed by the Belgian law if: 204 | 205 | - a litigation arises between the European Commission, as a *Licensor*, and any *Licensee*; 206 | - the *Licensor*, other than the European Commission, has no residence or registered office inside a European Union country. 207 | 208 | 209 | -------------------------------- 210 | 211 | 212 | # Appendix 213 | 214 | 215 | 216 | “Compatible Licences” according to article 5 EUPL are: 217 | 218 | 219 | - GNU General Public License (GNU GPL) v. 2 220 | 221 | - Open Software License (OSL) v. 2.1, v. 3.0 222 | 223 | - Common Public License v. 1.0 224 | 225 | - Eclipse Public License v. 1.0 226 | 227 | - Cecill v. 2.0 228 | --------------------------------------------------------------------------------