├── src ├── utils │ ├── mod.rs │ └── cpu_affinity.rs ├── protocol │ ├── mod.rs │ ├── communication.rs │ └── messaging.rs ├── stream │ ├── mod.rs │ ├── tcp.rs │ └── udp.rs ├── main.rs ├── server.rs └── client.rs ├── Cargo.toml ├── README.md ├── test.py └── COPYING /src/utils/mod.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | pub mod cpu_affinity; 22 | -------------------------------------------------------------------------------- /src/protocol/mod.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | pub mod communication; 22 | pub mod messaging; 23 | pub mod results; 24 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rperf" 3 | version = "0.1.8" 4 | description = "validates network throughput capacity and reliability" 5 | authors = ["Neil Tallim "] 6 | edition = "2021" 7 | repository = "https://github.com/opensource-3d-p/rperf" 8 | license = "GPLv3" 9 | keywords = ["network", "performance", "tcp", "udp"] 10 | categories = ["network-utilities"] 11 | readme = "README.md" 12 | 13 | [dependencies] 14 | chrono = "0.4" 15 | clap = "~2.33.3" 16 | core_affinity = "0.5" 17 | ctrlc = "3.1" 18 | env_logger = "0.8" 19 | log = {version = "0.4", features = ["std"]} 20 | mio = "0.6" 21 | nix = "0.20" 22 | serde = {version = "1.0", features = ["derive"]} 23 | serde_json = "1.0" 24 | simple-error = "0.2" 25 | uuid = {version = "0.8", features = ["v4"]} 26 | 27 | #configuration for cargo-deb 28 | #install with "cargo install cargo-deb" 29 | #then "cargo deb" to build simple Debian packages for this project 30 | [package.metadata.deb] 31 | copyright = "(C) 2022 Evtech Solutions, Ltd., dba 3D-P" 32 | license-file = ["COPYING", "0"] 33 | extended-description = """ 34 | Rust-based iperf clone with a number of behavioural fixes and corrections, plus 35 | a feature-set aimed at continuous monitoring in an IoT-like environment. 36 | """ 37 | section = "net" 38 | priority = "optional" 39 | 40 | [package.metadata.deb.systemd-units] 41 | #don't enable the service by default 42 | enable = false 43 | start = false 44 | -------------------------------------------------------------------------------- /src/stream/mod.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | pub mod tcp; 22 | pub mod udp; 23 | 24 | use std::error::Error; 25 | type BoxResult = Result>; 26 | 27 | pub const INTERVAL:std::time::Duration = std::time::Duration::from_secs(1); 28 | 29 | /// tests in this system are self-contained iterator-likes, where run_interval() may be invoked multiple times 30 | /// until it returns None, indicating that the test has run its course; each invocation blocks for up to approximately 31 | /// INTERVAL while gathering data. 32 | pub trait TestStream { 33 | /// gather data; returns None when the test is over 34 | fn run_interval(&mut self) -> Option>>; 35 | /// return the port associated with the test-stream; this may vary over the test's lifetime 36 | fn get_port(&self) -> BoxResult; 37 | /// returns the index of the test, used to match client and server data 38 | fn get_idx(&self) -> u8; 39 | /// stops a running test 40 | fn stop(&mut self); 41 | } 42 | 43 | fn parse_port_spec(port_spec:String) -> Vec { 44 | let mut ports = Vec::::new(); 45 | if !port_spec.is_empty() { 46 | for range in port_spec.split(',') { 47 | if range.contains('-') { 48 | let mut range_spec = range.split('-'); 49 | let range_first = range_spec.next().unwrap().parse::().unwrap(); 50 | let range_last = range_spec.last().unwrap().parse::().unwrap(); 51 | 52 | for port in range_first..=range_last { 53 | ports.push(port); 54 | } 55 | } else { 56 | ports.push(range.parse::().unwrap()); 57 | } 58 | } 59 | 60 | ports.sort(); 61 | } 62 | 63 | return ports; 64 | } 65 | -------------------------------------------------------------------------------- /src/utils/cpu_affinity.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | extern crate core_affinity; 22 | 23 | use std::error::Error; 24 | type BoxResult = Result>; 25 | 26 | pub struct CpuAffinityManager { 27 | enabled_cores: Vec, 28 | last_core_pointer: usize, 29 | } 30 | impl CpuAffinityManager { 31 | pub fn new(cores:&str) -> BoxResult { 32 | let core_ids = core_affinity::get_core_ids().unwrap_or_default(); 33 | log::debug!("enumerated CPU cores: {:?}", core_ids.iter().map(|c| c.id).collect::>()); 34 | 35 | let mut enabled_cores = Vec::new(); 36 | for cid in cores.split(',') { 37 | if cid.is_empty() { 38 | continue; 39 | } 40 | let cid_usize:usize = cid.parse()?; 41 | let mut cid_valid = false; 42 | for core_id in &core_ids { 43 | if core_id.id == cid_usize { 44 | enabled_cores.push(core_id.clone()); 45 | cid_valid = true; 46 | } 47 | } 48 | if !cid_valid { 49 | log::warn!("unrecognised CPU core: {}", cid_usize); 50 | } 51 | } 52 | if enabled_cores.len() > 0 { 53 | log::debug!("selecting from CPU cores {:?}", enabled_cores); 54 | } else { 55 | log::debug!("not applying CPU core affinity"); 56 | } 57 | 58 | Ok(CpuAffinityManager{ 59 | enabled_cores: enabled_cores, 60 | last_core_pointer: 0, 61 | }) 62 | } 63 | 64 | pub fn set_affinity(&mut self) { 65 | if self.enabled_cores.len() > 0 { 66 | let core_id = self.enabled_cores[self.last_core_pointer]; 67 | log::debug!("setting CPU affinity to {}", core_id.id); 68 | core_affinity::set_for_current(core_id); 69 | //cycle to the next option in a round-robin order 70 | if self.last_core_pointer == self.enabled_cores.len() - 1 { 71 | self.last_core_pointer = 0; 72 | } else { 73 | self.last_core_pointer += 1; 74 | } 75 | } else { 76 | log::debug!("CPU affinity is not configured; not doing anything"); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/protocol/communication.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | use std::io::{self, Read, Write}; 22 | use std::time::Duration; 23 | 24 | use mio::{Events, Ready, Poll, PollOpt, Token}; 25 | use mio::net::{TcpStream}; 26 | 27 | use std::error::Error; 28 | type BoxResult = Result>; 29 | 30 | /// how long to wait for keepalive events 31 | // the communications channels typically exchange data every second, so 2s is reasonable to avoid excess noise 32 | pub const KEEPALIVE_DURATION:Duration = Duration::from_secs(2); 33 | 34 | /// how long to block on polling operations 35 | const POLL_TIMEOUT:Duration = Duration::from_millis(50); 36 | 37 | /// sends JSON data over a client-server communications stream 38 | pub fn send(stream:&mut TcpStream, message:&serde_json::Value) -> BoxResult<()> { 39 | let serialised_message = serde_json::to_vec(message)?; 40 | 41 | log::debug!("sending message of length {}, {:?}, to {}...", serialised_message.len(), message, stream.peer_addr()?); 42 | let mut output_buffer = vec![0_u8; (serialised_message.len() + 2).into()]; 43 | output_buffer[..2].copy_from_slice(&(serialised_message.len() as u16).to_be_bytes()); 44 | output_buffer[2..].copy_from_slice(serialised_message.as_slice()); 45 | Ok(stream.write_all(&output_buffer)?) 46 | } 47 | 48 | /// receives the length-count of a pending message over a client-server communications stream 49 | fn receive_length(stream:&mut TcpStream, alive_check:fn() -> bool, results_handler:&mut dyn FnMut() -> BoxResult<()>) -> BoxResult { 50 | let mut cloned_stream = stream.try_clone()?; 51 | 52 | let mio_token = Token(0); 53 | let poll = Poll::new()?; 54 | poll.register( 55 | &cloned_stream, 56 | mio_token, 57 | Ready::readable(), 58 | PollOpt::edge(), 59 | )?; 60 | let mut events = Events::with_capacity(1); //only interacting with one stream 61 | 62 | let mut length_bytes_read = 0; 63 | let mut length_spec:[u8; 2] = [0; 2]; 64 | while alive_check() { //waiting to find out how long the next message is 65 | results_handler()?; //send any outstanding results between cycles 66 | poll.poll(&mut events, Some(POLL_TIMEOUT))?; 67 | for event in events.iter() { 68 | match event.token() { 69 | _ => loop { 70 | match cloned_stream.read(&mut length_spec[length_bytes_read..]) { 71 | Ok(size) => { 72 | if size == 0 { 73 | if alive_check() { 74 | return Err(Box::new(simple_error::simple_error!("connection lost"))); 75 | } else { //shutting down; a disconnect is expected 76 | return Err(Box::new(simple_error::simple_error!("local shutdown requested"))); 77 | } 78 | } 79 | 80 | length_bytes_read += size; 81 | if length_bytes_read == 2 { 82 | let length = u16::from_be_bytes(length_spec); 83 | log::debug!("received length-spec of {} from {}", length, stream.peer_addr()?); 84 | return Ok(length); 85 | } else { 86 | log::debug!("received partial length-spec from {}", stream.peer_addr()?); 87 | } 88 | }, 89 | Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { //nothing left to process 90 | break; 91 | }, 92 | Err(e) => { 93 | return Err(Box::new(e)); 94 | }, 95 | } 96 | }, 97 | } 98 | } 99 | } 100 | Err(Box::new(simple_error::simple_error!("system shutting down"))) 101 | } 102 | /// receives the data-value of a pending message over a client-server communications stream 103 | fn receive_payload(stream:&mut TcpStream, alive_check:fn() -> bool, results_handler:&mut dyn FnMut() -> BoxResult<()>, length:u16) -> BoxResult { 104 | let mut cloned_stream = stream.try_clone()?; 105 | 106 | let mio_token = Token(0); 107 | let poll = Poll::new()?; 108 | poll.register( 109 | &cloned_stream, 110 | mio_token, 111 | Ready::readable(), 112 | PollOpt::edge(), 113 | )?; 114 | let mut events = Events::with_capacity(1); //only interacting with one stream 115 | 116 | let mut bytes_read = 0; 117 | let mut buffer = vec![0_u8; length.into()]; 118 | while alive_check() { //waiting to receive the payload 119 | results_handler()?; //send any outstanding results between cycles 120 | poll.poll(&mut events, Some(POLL_TIMEOUT))?; 121 | for event in events.iter() { 122 | match event.token() { 123 | _ => loop { 124 | match cloned_stream.read(&mut buffer[bytes_read..]) { 125 | Ok(size) => { 126 | if size == 0 { 127 | if alive_check() { 128 | return Err(Box::new(simple_error::simple_error!("connection lost"))); 129 | } else { //shutting down; a disconnect is expected 130 | return Err(Box::new(simple_error::simple_error!("local shutdown requested"))); 131 | } 132 | } 133 | 134 | bytes_read += size; 135 | if bytes_read == length as usize { 136 | match serde_json::from_slice(&buffer) { 137 | Ok(v) => { 138 | log::debug!("received {:?} from {}", v, stream.peer_addr()?); 139 | return Ok(v); 140 | }, 141 | Err(e) => { 142 | return Err(Box::new(e)); 143 | }, 144 | } 145 | } else { 146 | log::debug!("received partial payload from {}", stream.peer_addr()?); 147 | } 148 | }, 149 | Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { //nothing left to process 150 | break; 151 | }, 152 | Err(e) => { 153 | return Err(Box::new(e)); 154 | }, 155 | } 156 | }, 157 | } 158 | } 159 | } 160 | Err(Box::new(simple_error::simple_error!("system shutting down"))) 161 | } 162 | /// handles the full process of retrieving a message from a client-server communications stream 163 | pub fn receive(mut stream:&mut TcpStream, alive_check:fn() -> bool, results_handler:&mut dyn FnMut() -> BoxResult<()>) -> BoxResult { 164 | log::debug!("awaiting length-value from {}...", stream.peer_addr()?); 165 | let length = receive_length(&mut stream, alive_check, results_handler)?; 166 | log::debug!("awaiting payload from {}...", stream.peer_addr()?); 167 | receive_payload(&mut stream, alive_check, results_handler, length) 168 | } 169 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rperf 2 | 3 | _rperf_ is a Rust-based [_iperf_](https://github.com/esnet/iperf) alternative 4 | developed by [3D-P](https://3d-p.com/), aiming to avoid some reliability and 5 | consistency issues found in _iperf3_, while simultaneously providing richer 6 | metrics data, with a focus on operation in a loss-tolerant, more IoT-like 7 | environment. While it can be used as a near-drop-in replacement for _iperf_, and 8 | there may be benefits to doing so, its focus is on periodic data-collection in a 9 | monitoring capacity in a closed network, meaning it is not suitable for all 10 | domains that _iperf_ can serve. 11 | 12 | ## development ## 13 | 14 | _rperf_ is an independent implementation, referencing the algorithms of _iperf3_ 15 | and [_zapwireless_](https://github.com/ryanchapman/zapwireless) to assess 16 | correctness and derive suitable corrections, but copying no code from either. 17 | 18 | 19 | In particular, the most significant issues addressed from _iperf3_ follow: 20 | 21 | * Multiple concurrent clients are supported by any given server. 22 | 23 | * _rperf_'s implementation of 24 | [RFC 1889](https://tools.ietf.org/html/rfc1889#appendix-A.8) for streaming 25 | jitter calculation starts by assuming a delta between the first and second 26 | packets in a sequence and gaps in a sequence trigger a reset of the count. 27 | Comparatively, _iperf3_ begins with 0, which creates artificially low values, 28 | and in case of a gap, it just continues naively, which creates artificially 29 | high values. 30 | 31 | * Duplicate packets are accounted for in UDP exchanges and out-of-order packets 32 | are counted as independent events. 33 | 34 | * All traffic can be emitted proportionally at regular sub-second intervals, 35 | allowing for configurations that more accurately reflect real data 36 | transmission and sending algorithms. 37 | 38 | * This addresses a commonly seen case in embedded-like systems where a piece 39 | of equipment has a very small send- or receive-buffer that the OS does not 40 | know about and it will just drop packets when receiving a huge mass of 41 | data in a single burst, incorrectly under-reporting network capacity. 42 | 43 | * Stream-configuration and results are exchanged via a dedicated connection and 44 | every data-path has clearly defined timeout, completion and failure semantics, 45 | so execution doesn't hang indefinitely on either side of a test when key 46 | packets are lost. 47 | 48 | * _rperf_'s JSON output is structurally legal. No unquoted strings, repeated 49 | keys, or dangling commas, all of which require pre-processing before 50 | consumption or cause unexpected errors. 51 | 52 | 53 | In contrast to _zapwireless_, the following improvements are realised: 54 | 55 | * _rperf_ uses a classic client-server architecture, so there's no need to 56 | maintain a running process on devices that waits for a test-execution request. 57 | 58 | * Jitter is calculated. 59 | 60 | * IPv6 is supported. 61 | 62 | * Multiple streams may be run in parallel as part of a test. 63 | 64 | * An `omit` option is available to discard TCP ramp-up time from results. 65 | 66 | * Output is available in JSON for easier telemetry-harvesting. 67 | 68 | ## platforms ## 69 | 70 | _rperf_ should build and work on all major platforms, though its development and 71 | usage focus is on Linux-based systems, so that is where it will be most 72 | feature-complete. 73 | 74 | Pull-requests for implementations of equivalent features for other systems are 75 | welcome. 76 | 77 | 78 | ## usage 79 | 80 | Everything is outlined in the output of `--help` and most users familiar with similar tools should feel comfortable immediately. 81 | 82 | _rperf_ works much like _iperf3_, sharing a lot of concepts and even command-line flags. One key area where it differs is that the client drives all of the configuration process while the server just complies to the best of its ability and provides a stream of results. This means that the server will not present test-results directly via its interface and also that TCP and UDP tests can be run against the same instance, potentially by many clients simultaneously. 83 | 84 | In its normal mode of operation, the client will upload data to the server; when the `reverse` flag is set, the client will receive data. 85 | 86 | Unlike _iperf3_, _rperf_ does not make use of a reserved port-range by default. This is so it can support an arbitrary number of clients in parallel without resource contention on what can only practically be a small number of contiguous ports. In its intended capacity, this shouldn't be a problem, but where non-permissive firewalls and NAT setups are concerned, the `--tcp[6]-port-pool` and `--udp[6]-port-pool` options may be used to allocate non-continguous ports to the set that will be used to receive traffic. 87 | 88 | There also isn't a concept of testing throughput relative to a fixed quantity of data. Rather, the sole focus is on measuring throughput over a roughly known period of time. 89 | 90 | Also of relevance is that, if the server is running in IPv6 mode and its host supports IPv4-mapping in a dual-stack configuration, both IPv4 and IPv6 clients can connect to the same instance. 91 | 92 | 93 | ## building 94 | 95 | _rperf_ uses [_cargo_](https://doc.rust-lang.org/cargo/). 96 | The typical process will simply be `cargo build --release`. 97 | 98 | [_cargo-deb_](https://github.com/mmstick/cargo-deb) is also supported and will 99 | produce a usable Debian package that installs a disabled-by-default `rperf` 100 | _systemd_ service. When started, it runs as `nobody:nogroup`, assuming IPv6 101 | support by default. 102 | 103 | 104 | ## theory of operation 105 | 106 | Like its contemporaries, _rperf_'s core concept is firing a stream of TCP or 107 | UDP data at an IP target at a pre-arranged target speed. The amount of data 108 | actually received is observed and used to gauge the capacity of a network link. 109 | 110 | Within those domains, additional data about the quality of the exchange is 111 | gathered and made available for review. 112 | 113 | Architecturally, _rperf_ has clients establish a TCP connection to the server, 114 | after which the client sends details about the test to be performed and the 115 | server obliges, reporting observation results to the client during the entire 116 | testing process. 117 | 118 | The client may request that multiple parallel streams be used for testing, which 119 | is facilitated by establishing multiple TCP connections or UDP sockets with 120 | their own dedicated thread on either side, which may be further pinned to a 121 | single logical CPU core to reduce the impact of page-faults on the 122 | data-exchange. 123 | 124 | 125 | ### implementation details 126 | 127 | The client-server relationship is treated as a very central aspect of this 128 | design, in contrast to _iperf3_, where they're more like peers, and 129 | _zapwireless_, where each participant runs its own daemon and a third process 130 | orchestrates communication. 131 | 132 | Notably, all data-gathering, calculation, and display happens client-side, with 133 | the server simply returning what it observed. This can lead to some drift in 134 | recordings, particularly where time is concerned (server intervals being a 135 | handful of milliseconds longer than their corresponding client values is not 136 | at all uncommon). Assuming the connection wasn't lost, however, totals for data 137 | observed will match up in all modes of operation. 138 | 139 | The server uses three layers of threading: one for the main thread, one for each 140 | client being served, and one more for each stream that communicates with the 141 | client. On the client side, the main thread is used to communicate with the 142 | server and it spawns an additional thread for each stream that communicates with 143 | the server. 144 | 145 | When the server receives a request from a client, it spawns a thread that 146 | handles that client's specific request; internally, each stream for the test 147 | produces an iterator-like handler on either side. Both the client and server run 148 | these iterator-analogues against each other asynchronously until the test period 149 | ends, at which point the sender indicates completion within its stream. 150 | 151 | To reliably handle the possibility of disconnects at the stream level, a 152 | keepalive mechanism in the client-server stream, over which test-results are 153 | sent from the server at regular intervals, will terminate outstanding 154 | connections after a few seconds of inactivity. 155 | 156 | The host OS's TCP and UDP mechanisms are used for all actual traffic exchanged, 157 | with some tuning parameters exposed. This approach was chosen over a userspace 158 | implementation on top of layer-2 or layer-3 because it most accurately 159 | represents the way real-world applications will behave. 160 | 161 | #### considerations #### 162 | 163 | The "timestamp" values visible in JSON-serialised interval data are 164 | host-relative, so unless your environment has very high system-clock accuracy, 165 | send-timestamps should only be compared to other send-timestamps and likewise 166 | for receive-timestamps. In general, this data is not useful outside of 167 | correctness-validation, however. 168 | 169 | During each exchange interval, an attempt is made to send `length` bytes at a 170 | time, until the amount written to the stream meets or exceeds the bandwdith 171 | target, at which point the sender goes silent until the start of the next 172 | interval; the data sent within an interval should be uniformly distributed over 173 | the period. 174 | 175 | Stream indexes start at `0`, not `1`. This probably won't surprise anyone, but 176 | seeing "stream 0" in a report is not cause for concern. 177 | 178 | 179 | ## copyright and distribution ## 180 | 181 | _rperf_ is distributed by Evtech Solutions, Ltd., dba 3D-P, under the 182 | [GNU GPL version 3](https://www.gnu.org/licenses/gpl-3.0.en.html), the text of 183 | which may be found in `COPYING`. 184 | 185 | Authorship details, copyright specifics, and transferability notes are present 186 | within the source code itself. 187 | -------------------------------------------------------------------------------- /src/protocol/messaging.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | use std::error::Error; 22 | type BoxResult = Result>; 23 | 24 | /// prepares a message used to tell the server to begin operations 25 | pub fn prepare_begin() -> serde_json::Value { 26 | serde_json::json!({ 27 | "kind": "begin", 28 | }) 29 | } 30 | 31 | /// prepares a message used to tell the client to connect its test-streams 32 | pub fn prepare_connect(stream_ports:&[u16]) -> serde_json::Value { 33 | serde_json::json!({ 34 | "kind": "connect", 35 | 36 | "stream_ports": stream_ports, 37 | }) 38 | } 39 | 40 | /// prepares a message used to tell the client that the server is ready to connect to its test-streams 41 | pub fn prepare_connect_ready() -> serde_json::Value { 42 | serde_json::json!({ 43 | "kind": "connect-ready", 44 | }) 45 | } 46 | 47 | /// prepares a message used to tell the server that testing is finished 48 | pub fn prepare_end() -> serde_json::Value { 49 | serde_json::json!({ 50 | "kind": "end", 51 | }) 52 | } 53 | 54 | 55 | 56 | 57 | /// prepares a message used to describe the upload role of a TCP test 58 | fn prepare_configuration_tcp_upload(test_id:&[u8; 16], streams:u8, bandwidth:u64, seconds:f32, length:usize, send_interval:f32, send_buffer:u32, no_delay:bool) -> serde_json::Value { 59 | serde_json::json!({ 60 | "kind": "configuration", 61 | 62 | "family": "tcp", 63 | "role": "upload", 64 | 65 | "test_id": test_id, 66 | "streams": validate_streams(streams), 67 | 68 | "bandwidth": validate_bandwidth(bandwidth), 69 | "duration": seconds, 70 | "length": calculate_length_tcp(length), 71 | "send_interval": validate_send_interval(send_interval), 72 | 73 | "send_buffer": send_buffer, 74 | "no_delay": no_delay, 75 | }) 76 | } 77 | 78 | /// prepares a message used to describe the download role of a TCP test 79 | fn prepare_configuration_tcp_download(test_id:&[u8; 16], streams:u8, length:usize, receive_buffer:u32) -> serde_json::Value { 80 | serde_json::json!({ 81 | "kind": "configuration", 82 | 83 | "family": "tcp", 84 | "role": "download", 85 | 86 | "test_id": test_id, 87 | "streams": validate_streams(streams), 88 | 89 | "length": calculate_length_tcp(length), 90 | "receive_buffer": receive_buffer, 91 | }) 92 | } 93 | 94 | /// prepares a message used to describe the upload role of a UDP test 95 | fn prepare_configuration_udp_upload(test_id:&[u8; 16], streams:u8, bandwidth:u64, seconds:f32, length:u16, send_interval:f32, send_buffer:u32) -> serde_json::Value { 96 | serde_json::json!({ 97 | "kind": "configuration", 98 | 99 | "family": "udp", 100 | "role": "upload", 101 | 102 | "test_id": test_id, 103 | "streams": validate_streams(streams), 104 | 105 | "bandwidth": validate_bandwidth(bandwidth), 106 | "duration": seconds, 107 | "length": calculate_length_udp(length), 108 | "send_interval": validate_send_interval(send_interval), 109 | 110 | "send_buffer": send_buffer, 111 | }) 112 | } 113 | 114 | /// prepares a message used to describe the download role of a UDP test 115 | fn prepare_configuration_udp_download(test_id:&[u8; 16], streams:u8, length:u16, receive_buffer:u32) -> serde_json::Value { 116 | serde_json::json!({ 117 | "kind": "configuration", 118 | 119 | "family": "udp", 120 | "role": "download", 121 | 122 | "test_id": test_id, 123 | "streams": validate_streams(streams), 124 | 125 | "length": calculate_length_udp(length), 126 | "receive_buffer": receive_buffer, 127 | }) 128 | } 129 | 130 | 131 | 132 | 133 | fn validate_streams(streams:u8) -> u8 { 134 | if streams > 0 { 135 | streams 136 | } else { 137 | log::warn!("parallel streams not specified; defaulting to 1"); 138 | 1 139 | } 140 | } 141 | 142 | fn validate_bandwidth(bandwidth:u64) -> u64 { 143 | if bandwidth > 0 { 144 | bandwidth 145 | } else { 146 | log::warn!("bandwidth was not specified; defaulting to 1024 bytes/second"); 147 | 1024 148 | } 149 | } 150 | 151 | fn validate_send_interval(send_interval:f32) -> f32 { 152 | if send_interval > 0.0 && send_interval <= 1.0 { 153 | send_interval 154 | } else { 155 | log::warn!("send-interval was invalid or not specified; defaulting to once per second"); 156 | 1.0 157 | } 158 | } 159 | 160 | fn calculate_length_tcp(length:usize) -> usize { 161 | if length < crate::stream::tcp::TEST_HEADER_SIZE { //length must be at least enough to hold the test data 162 | crate::stream::tcp::TEST_HEADER_SIZE 163 | } else { 164 | length 165 | } 166 | } 167 | fn calculate_length_udp(length:u16) -> u16 { 168 | if length < crate::stream::udp::TEST_HEADER_SIZE { //length must be at least enough to hold the test data 169 | crate::stream::udp::TEST_HEADER_SIZE 170 | } else { 171 | length 172 | } 173 | } 174 | 175 | 176 | /// prepares a message used to describe the upload role in a test 177 | pub fn prepare_upload_configuration(args:&clap::ArgMatches, test_id:&[u8; 16]) -> BoxResult { 178 | let parallel_streams:u8 = args.value_of("parallel").unwrap().parse()?; 179 | let mut seconds:f32 = args.value_of("time").unwrap().parse()?; 180 | let mut send_interval:f32 = args.value_of("send_interval").unwrap().parse()?; 181 | let mut length:u32 = args.value_of("length").unwrap().parse()?; 182 | 183 | let mut send_buffer:u32 = args.value_of("send_buffer").unwrap().parse()?; 184 | 185 | let mut bandwidth_string = args.value_of("bandwidth").unwrap(); 186 | let bandwidth:u64; 187 | let bandwidth_multiplier:f64; 188 | match bandwidth_string.chars().last() { 189 | Some(v) => { 190 | match v { 191 | 'k' => { //kilobits 192 | bandwidth_multiplier = 1000.0 / 8.0; 193 | }, 194 | 'K' => { //kilobytes 195 | bandwidth_multiplier = 1000.0; 196 | }, 197 | 'm' => { //megabits 198 | bandwidth_multiplier = 1000.0 * 1000.0 / 8.0; 199 | }, 200 | 'M' => { //megabytes 201 | bandwidth_multiplier = 1000.0 * 1000.0; 202 | }, 203 | 'g' => { //gigabits 204 | bandwidth_multiplier = 1000.0 * 1000.0 * 1000.0 / 8.0; 205 | }, 206 | 'G' => { //gigabytes 207 | bandwidth_multiplier = 1000.0 * 1000.0 * 1000.0; 208 | }, 209 | _ => { 210 | bandwidth_multiplier = 1.0; 211 | }, 212 | } 213 | 214 | if bandwidth_multiplier != 1.0 { //the value uses a suffix 215 | bandwidth_string = &bandwidth_string[0..(bandwidth_string.len() - 1)]; 216 | } 217 | 218 | match bandwidth_string.parse::() { 219 | Ok(v2) => { 220 | bandwidth = (v2 * bandwidth_multiplier) as u64; 221 | }, 222 | Err(_) => { //invalid input; fall back to 1mbps 223 | log::warn!("invalid bandwidth: {}; setting value to 1mbps", args.value_of("bandwidth").unwrap()); 224 | bandwidth = 125000; 225 | }, 226 | } 227 | }, 228 | None => { //invalid input; fall back to 1mbps 229 | log::warn!("invalid bandwidth: {}; setting value to 1mbps", args.value_of("bandwidth").unwrap()); 230 | bandwidth = 125000; 231 | }, 232 | } 233 | 234 | if seconds <= 0.0 { 235 | log::warn!("time was not in an acceptable range and has been set to 0.0"); 236 | seconds = 0.0 237 | } 238 | 239 | if send_interval > 1.0 || send_interval <= 0.0 { 240 | log::warn!("send-interval was not in an acceptable range and has been set to 0.05"); 241 | send_interval = 0.05 242 | } 243 | 244 | if args.is_present("udp") { 245 | log::debug!("preparing UDP upload config..."); 246 | if length == 0 { 247 | length = 1024; 248 | } 249 | if send_buffer != 0 && send_buffer < length { 250 | log::warn!("requested send-buffer, {}, is too small to hold the data to be exchanged; it will be increased to {}", send_buffer, length * 2); 251 | send_buffer = length * 2; 252 | } 253 | Ok(prepare_configuration_udp_upload(test_id, parallel_streams, bandwidth, seconds, length as u16, send_interval, send_buffer)) 254 | } else { 255 | log::debug!("preparing TCP upload config..."); 256 | if length == 0 { 257 | length = 32 * 1024; 258 | } 259 | if send_buffer != 0 && send_buffer < length { 260 | log::warn!("requested send-buffer, {}, is too small to hold the data to be exchanged; it will be increased to {}", send_buffer, length * 2); 261 | send_buffer = length * 2; 262 | } 263 | 264 | let no_delay:bool = args.is_present("no_delay"); 265 | 266 | Ok(prepare_configuration_tcp_upload(test_id, parallel_streams, bandwidth, seconds, length as usize, send_interval, send_buffer, no_delay)) 267 | } 268 | } 269 | /// prepares a message used to describe the download role in a test 270 | pub fn prepare_download_configuration(args:&clap::ArgMatches, test_id:&[u8; 16]) -> BoxResult { 271 | let parallel_streams:u8 = args.value_of("parallel").unwrap().parse()?; 272 | let mut length:u32 = args.value_of("length").unwrap().parse()?; 273 | let mut receive_buffer:u32 = args.value_of("receive_buffer").unwrap().parse()?; 274 | 275 | if args.is_present("udp") { 276 | log::debug!("preparing UDP download config..."); 277 | if length == 0 { 278 | length = 1024; 279 | } 280 | if receive_buffer != 0 && receive_buffer < length { 281 | log::warn!("requested receive-buffer, {}, is too small to hold the data to be exchanged; it will be increased to {}", receive_buffer, length * 2); 282 | receive_buffer = length * 2; 283 | } 284 | Ok(prepare_configuration_udp_download(test_id, parallel_streams, length as u16, receive_buffer)) 285 | } else { 286 | log::debug!("preparing TCP download config..."); 287 | if length == 0 { 288 | length = 32 * 1024; 289 | } 290 | if receive_buffer != 0 && receive_buffer < length { 291 | log::warn!("requested receive-buffer, {}, is too small to hold the data to be exchanged; it will be increased to {}", receive_buffer, length * 2); 292 | receive_buffer = length * 2; 293 | } 294 | Ok(prepare_configuration_tcp_download(test_id, parallel_streams, length as usize, receive_buffer)) 295 | } 296 | } 297 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | extern crate log; 22 | extern crate env_logger; 23 | 24 | use clap::{App, Arg}; 25 | 26 | mod protocol; 27 | mod stream; 28 | mod utils; 29 | mod client; 30 | mod server; 31 | 32 | fn main() { 33 | let args = App::new("rperf") 34 | .about(clap::crate_description!()) 35 | .author("https://github.com/opensource-3d-p/rperf") 36 | .name(clap::crate_name!()) 37 | .version(clap::crate_version!()) 38 | .arg( 39 | Arg::with_name("port") 40 | .help("the port used for client-server interactions") 41 | .takes_value(true) 42 | .long("port") 43 | .short("p") 44 | .required(false) 45 | .default_value("5199") 46 | ) 47 | 48 | .arg( 49 | Arg::with_name("affinity") 50 | .help("specify logical CPUs, delimited by commas, across which to round-robin affinity; not supported on all systems") 51 | .takes_value(true) 52 | .long("affinity") 53 | .short("A") 54 | .required(false) 55 | .multiple(true) 56 | .default_value("") 57 | ) 58 | .arg( 59 | Arg::with_name("debug") 60 | .help("emit debug-level logging on stderr; default is info and above") 61 | .takes_value(false) 62 | .long("debug") 63 | .short("d") 64 | .required(false) 65 | ) 66 | 67 | 68 | .arg( 69 | Arg::with_name("server") 70 | .help("run in server mode") 71 | .takes_value(false) 72 | .long("server") 73 | .short("s") 74 | .required(false) 75 | ) 76 | .arg( 77 | Arg::with_name("version6") 78 | .help("enable IPv6 on the server (on most hosts, this will allow both IPv4 and IPv6, but it might limit to just IPv6 on some)") 79 | .takes_value(false) 80 | .long("version6") 81 | .short("6") 82 | .required(false) 83 | ) 84 | .arg( 85 | Arg::with_name("client_limit") 86 | .help("limit the number of concurrent clients that can be processed by a server; any over this count will be immediately disconnected") 87 | .takes_value(true) 88 | .long("client-limit") 89 | .required(false) 90 | .default_value("0") 91 | ) 92 | 93 | .arg( 94 | Arg::with_name("client") 95 | .help("run in client mode; value is the server's address") 96 | .takes_value(true) 97 | .long("client") 98 | .short("c") 99 | .required(false) 100 | ) 101 | .arg( 102 | Arg::with_name("reverse") 103 | .help("run in reverse-mode (server sends, client receives)") 104 | .takes_value(false) 105 | .long("reverse") 106 | .short("R") 107 | .required(false) 108 | ) 109 | .arg( 110 | Arg::with_name("format") 111 | .help("the format in which to deplay information (json, megabit/sec, megabyte/sec)") 112 | .takes_value(true) 113 | .long("format") 114 | .short("f") 115 | .required(false) 116 | .default_value("megabit") 117 | .possible_values(&["json", "megabit", "megabyte"]) 118 | ) 119 | .arg( 120 | Arg::with_name("udp") 121 | .help("use UDP rather than TCP") 122 | .takes_value(false) 123 | .long("udp") 124 | .short("u") 125 | .required(false) 126 | ) 127 | .arg( 128 | Arg::with_name("bandwidth") 129 | .help("target bandwidth in bytes/sec; this value is applied to each stream, with a default target of 1 megabit/second for all protocols (note: megabit, not mebibit); the suffixes kKmMgG can also be used for xbit and xbyte, respectively") 130 | .takes_value(true) 131 | .long("bandwidth") 132 | .short("b") 133 | .required(false) 134 | .default_value("125000") 135 | ) 136 | .arg( 137 | Arg::with_name("time") 138 | .help("the time in seconds for which to transmit") 139 | .takes_value(true) 140 | .long("time") 141 | .short("t") 142 | .required(false) 143 | .default_value("10.0") 144 | ) 145 | .arg( 146 | Arg::with_name("send_interval") 147 | .help("the interval at which to send batches of data, in seconds, between [0.0 and 1.0); this is used to evenly spread packets out over time") 148 | .takes_value(true) 149 | .long("send-interval") 150 | .required(false) 151 | .default_value("0.05") 152 | ) 153 | .arg( 154 | Arg::with_name("length") 155 | .help("length of the buffer to exchange; for TCP, this defaults to 32 kibibytes; for UDP, it's 1024 bytes") 156 | .takes_value(true) 157 | .long("length") 158 | .short("l") 159 | .required(false) 160 | .default_value("0") 161 | ) 162 | .arg( 163 | Arg::with_name("send_buffer") 164 | .help("send_buffer, in bytes (only supported on some platforms; if set too small, a 'resource unavailable' error may occur; affects TCP window-size)") 165 | .takes_value(true) 166 | .long("send-buffer") 167 | .required(false) 168 | .default_value("0") 169 | ) 170 | .arg( 171 | Arg::with_name("receive_buffer") 172 | .help("receive_buffer, in bytes (only supported on some platforms; if set too small, a 'resource unavailable' error may occur; affects TCP window-size)") 173 | .takes_value(true) 174 | .long("receive-buffer") 175 | .required(false) 176 | .default_value("0") 177 | ) 178 | .arg( 179 | Arg::with_name("parallel") 180 | .help("the number of parallel data-streams to use") 181 | .takes_value(true) 182 | .long("parallel") 183 | .short("P") 184 | .required(false) 185 | .default_value("1") 186 | ) 187 | .arg( 188 | Arg::with_name("omit") 189 | .help("omit a number of seconds from the start of calculations, primarily to avoid including TCP ramp-up in averages; using this option may result in disagreement between bytes sent and received, since data can be in-flight across time-boundaries") 190 | .takes_value(true) 191 | .long("omit") 192 | .short("O") 193 | .default_value("0") 194 | .required(false) 195 | ) 196 | .arg( 197 | Arg::with_name("no_delay") 198 | .help("use no-delay mode for TCP tests, disabling Nagle's Algorithm") 199 | .takes_value(false) 200 | .long("no-delay") 201 | .short("N") 202 | .required(false) 203 | ) 204 | .arg( 205 | Arg::with_name("tcp_port_pool") 206 | .help("an optional pool of IPv4 TCP ports over which data will be accepted; if omitted, any OS-assignable port is used; format: 1-10,19,21") 207 | .takes_value(true) 208 | .long("tcp-port-pool") 209 | .required(false) 210 | .default_value("") 211 | ) 212 | .arg( 213 | Arg::with_name("tcp6_port_pool") 214 | .help("an optional pool of IPv6 TCP ports over which data will be accepted; if omitted, any OS-assignable port is used; format: 1-10,19,21") 215 | .takes_value(true) 216 | .long("tcp6-port-pool") 217 | .required(false) 218 | .default_value("") 219 | ) 220 | .arg( 221 | Arg::with_name("udp_port_pool") 222 | .help("an optional pool of IPv4 UDP ports over which data will be accepted; if omitted, any OS-assignable port is used; format: 1-10,19,21") 223 | .takes_value(true) 224 | .long("udp-port-pool") 225 | .required(false) 226 | .default_value("") 227 | ) 228 | .arg( 229 | Arg::with_name("udp6_port_pool") 230 | .help("an optional pool of IPv6 UDP ports over which data will be accepted; if omitted, any OS-assignable port is used; format: 1-10,19,21") 231 | .takes_value(true) 232 | .long("udp6-port-pool") 233 | .required(false) 234 | .default_value("") 235 | ) 236 | .get_matches(); 237 | 238 | let mut env = env_logger::Env::default() 239 | .filter_or("RUST_LOG", "info"); 240 | if args.is_present("debug") { 241 | env = env.filter_or("RUST_LOG", "debug"); 242 | } 243 | env_logger::init_from_env(env); 244 | 245 | if args.is_present("server") { 246 | log::debug!("registering SIGINT handler..."); 247 | ctrlc::set_handler(move || { 248 | if server::kill() { 249 | log::warn!("shutdown requested; please allow a moment for any in-progress tests to stop"); 250 | } else { 251 | log::warn!("forcing shutdown immediately"); 252 | std::process::exit(3); 253 | } 254 | }).expect("unable to set SIGINT handler"); 255 | 256 | log::debug!("beginning normal operation..."); 257 | let service = server::serve(args); 258 | if service.is_err() { 259 | log::error!("unable to run server: {}", service.unwrap_err()); 260 | std::process::exit(4); 261 | } 262 | } else if args.is_present("client") { 263 | log::debug!("registering SIGINT handler..."); 264 | ctrlc::set_handler(move || { 265 | if client::kill() { 266 | log::warn!("shutdown requested; please allow a moment for any in-progress tests to stop"); 267 | } else { 268 | log::warn!("forcing shutdown immediately"); 269 | std::process::exit(3); 270 | } 271 | }).expect("unable to set SIGINT handler"); 272 | 273 | log::debug!("connecting to server..."); 274 | let execution = client::execute(args); 275 | if execution.is_err() { 276 | log::error!("unable to run client: {}", execution.unwrap_err()); 277 | std::process::exit(4); 278 | } 279 | } else { 280 | std::println!("{}", args.usage()); 281 | std::process::exit(2); 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 4 | Copyright (C) 2021 Neil Tallim 5 | 6 | This file is part of rperf. 7 | 8 | rperf is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | rperf is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with rperf. If not, see . 20 | """ 21 | """ 22 | This is a simple testing script to ensure basic correctness of rperf behaviour. 23 | 24 | It doesn't test off-host connectivity (unless you've got a very unusual setup) 25 | and it isn't concerned with probing limits. It just makes sure TCP, UDP, and 26 | common options are functioning as expected. 27 | """ 28 | 29 | import argparse 30 | import concurrent.futures 31 | import json 32 | import subprocess 33 | import unittest 34 | 35 | _RPERF_BINARY = "./target/release/rperf" 36 | _DISPLAY_LOGS = False #whether to display rperf's logs on stderr while testing 37 | 38 | def _run_rperf_client(address, args): 39 | full_args = [_RPERF_BINARY, '-c', address, '-f', 'json',] 40 | full_args.extend(args) 41 | if _DISPLAY_LOGS: 42 | result = subprocess.check_output(full_args) 43 | else: 44 | result = subprocess.check_output(full_args, stderr=subprocess.DEVNULL) 45 | return json.loads(result) 46 | 47 | def _run_rperf_client_hostname(args): 48 | return _run_rperf_client('localhost', args) 49 | 50 | def _run_rperf_client_ipv4(args): 51 | return _run_rperf_client('127.0.0.1', args) 52 | 53 | def _run_rperf_client_ipv6(args): 54 | return _run_rperf_client('::1', args) 55 | 56 | 57 | 58 | 59 | class TestIpv4(unittest.TestCase): 60 | def setUp(self): 61 | if _DISPLAY_LOGS: 62 | self.server = subprocess.Popen((_RPERF_BINARY, '-s',)) 63 | else: 64 | self.server = subprocess.Popen((_RPERF_BINARY, '-s',), stderr=subprocess.DEVNULL) 65 | 66 | def tearDown(self): 67 | self.server.terminate() 68 | self.server.wait() 69 | 70 | def test_tcp_forward(self): 71 | result = _run_rperf_client_ipv4(( 72 | '-b', '500000', #keep it light, at 500kBps per stream 73 | '-l', '4096', #try to send 4k of data at a time 74 | '-O', '1', #omit the first second of data from summaries 75 | '-P', '2', #two parallel streams 76 | '-t', '2', #run for two seconds 77 | )) 78 | self.assertTrue(result['success']) 79 | self.assertEqual(result['config']['common']['family'], 'tcp') 80 | self.assertEqual(result['config']['common']['streams'], 2) 81 | self.assertEqual(result['config']['additional']['reverse'], False) 82 | self.assertEqual(result['config']['additional']['ip_version'], 4) 83 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 84 | self.assertAlmostEqual(result['summary']['bytes_received'], 1000000, delta=50000) 85 | self.assertAlmostEqual(result['summary']['duration_receive'], 2.0, delta=0.1) 86 | 87 | def test_tcp_reverse(self): 88 | result = _run_rperf_client_ipv4(( 89 | '-R', #run in reverse mode 90 | '-b', '500000', #keep it light, at 500kBps per stream 91 | '-l', '4096', #try to send 4k of data at a time 92 | '-O', '1', #omit the first second of data from summaries 93 | '-P', '2', #two parallel streams 94 | '-t', '2', #run for two seconds 95 | )) 96 | self.assertTrue(result['success']) 97 | self.assertEqual(result['config']['common']['family'], 'tcp') 98 | self.assertEqual(result['config']['common']['streams'], 2) 99 | self.assertEqual(result['config']['additional']['reverse'], True) 100 | self.assertEqual(result['config']['additional']['ip_version'], 4) 101 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 102 | self.assertAlmostEqual(result['summary']['bytes_received'], 1000000, delta=50000) 103 | self.assertAlmostEqual(result['summary']['duration_receive'], 2.0, delta=0.1) 104 | 105 | def test_udp_forward(self): 106 | result = _run_rperf_client_ipv4(( 107 | '-u', #run UDP test 108 | '-b', '500000', #keep it light, at 500kBps per stream 109 | '-l', '1200', #try to send 1200 bytes of data at a time 110 | '-O', '1', #omit the first second of data from summaries 111 | '-P', '2', #two parallel streams 112 | '-t', '2', #run for two seconds 113 | )) 114 | self.assertTrue(result['success']) 115 | self.assertEqual(result['config']['common']['family'], 'udp') 116 | self.assertEqual(result['config']['common']['streams'], 2) 117 | self.assertEqual(result['config']['additional']['reverse'], False) 118 | self.assertEqual(result['config']['additional']['ip_version'], 4) 119 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 120 | self.assertEqual(result['summary']['packets_received'], result['summary']['packets_sent']) 121 | self.assertEqual(result['summary']['framed_packet_size'], 1228) 122 | self.assertEqual(result['summary']['packets_duplicate'], 0) 123 | self.assertEqual(result['summary']['packets_lost'], 0) 124 | self.assertEqual(result['summary']['packets_out_of_order'], 0) 125 | self.assertAlmostEqual(result['summary']['bytes_received'], 1000000, delta=50000) 126 | self.assertAlmostEqual(result['summary']['duration_receive'], 2.0, delta=0.1) 127 | 128 | def test_udp_reverse(self): 129 | result = _run_rperf_client_ipv4(( 130 | '-u', #run UDP test 131 | '-R', #run in reverse mode 132 | '-b', '500000', #keep it light, at 500kBps per stream 133 | '-l', '1200', #try to send 1200 bytes of data at a time 134 | '-O', '1', #omit the first second of data from summaries 135 | '-P', '2', #two parallel streams 136 | '-t', '2', #run for two seconds 137 | )) 138 | self.assertTrue(result['success']) 139 | self.assertEqual(result['config']['common']['family'], 'udp') 140 | self.assertEqual(result['config']['common']['streams'], 2) 141 | self.assertEqual(result['config']['additional']['reverse'], True) 142 | self.assertEqual(result['config']['additional']['ip_version'], 4) 143 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 144 | self.assertEqual(result['summary']['packets_received'], result['summary']['packets_sent']) 145 | self.assertEqual(result['summary']['framed_packet_size'], 1228) 146 | self.assertEqual(result['summary']['packets_duplicate'], 0) 147 | self.assertEqual(result['summary']['packets_lost'], 0) 148 | self.assertEqual(result['summary']['packets_out_of_order'], 0) 149 | self.assertAlmostEqual(result['summary']['bytes_received'], 1000000, delta=50000) 150 | self.assertAlmostEqual(result['summary']['duration_receive'], 2.0, delta=0.1) 151 | 152 | 153 | 154 | 155 | class TestIpv6(unittest.TestCase): 156 | def setUp(self): 157 | if _DISPLAY_LOGS: 158 | self.server = subprocess.Popen((_RPERF_BINARY, '-s', '-6',)) 159 | else: 160 | self.server = subprocess.Popen((_RPERF_BINARY, '-s', '-6'), stderr=subprocess.DEVNULL) 161 | 162 | def tearDown(self): 163 | self.server.terminate() 164 | self.server.wait() 165 | 166 | def test_tcp_forward(self): 167 | result = _run_rperf_client_ipv6(( 168 | '-b', '500000', #keep it light, at 500kBps per stream 169 | '-l', '4096', #try to send 4k of data at a time 170 | '-O', '1', #omit the first second of data from summaries 171 | '-t', '2', #run for two seconds 172 | )) 173 | self.assertTrue(result['success']) 174 | self.assertEqual(result['config']['common']['family'], 'tcp') 175 | self.assertEqual(result['config']['common']['streams'], 1) 176 | self.assertEqual(result['config']['additional']['reverse'], False) 177 | self.assertEqual(result['config']['additional']['ip_version'], 6) 178 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 179 | self.assertAlmostEqual(result['summary']['bytes_received'], 500000, delta=25000) 180 | self.assertAlmostEqual(result['summary']['duration_receive'], 1.0, delta=0.1) 181 | 182 | def test_tcp_reverse(self): 183 | result = _run_rperf_client_ipv6(( 184 | '-R', #run in reverse mode 185 | '-b', '500000', #keep it light, at 500kBps per stream 186 | '-l', '4096', #try to send 4k of data at a time 187 | '-O', '1', #omit the first second of data from summaries 188 | '-t', '2', #run for two seconds 189 | )) 190 | self.assertTrue(result['success']) 191 | self.assertEqual(result['config']['common']['family'], 'tcp') 192 | self.assertEqual(result['config']['common']['streams'], 1) 193 | self.assertEqual(result['config']['additional']['reverse'], True) 194 | self.assertEqual(result['config']['additional']['ip_version'], 6) 195 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 196 | self.assertAlmostEqual(result['summary']['bytes_received'], 500000, delta=25000) 197 | self.assertAlmostEqual(result['summary']['duration_receive'], 1.0, delta=0.1) 198 | 199 | def test_udp_forward(self): 200 | result = _run_rperf_client_ipv6(( 201 | '-u', #run UDP test 202 | '-b', '500000', #keep it light, at 500kBps per stream 203 | '-l', '1200', #try to send 1200 bytes of data at a time 204 | '-t', '1', #run for one second 205 | )) 206 | self.assertTrue(result['success']) 207 | self.assertEqual(result['config']['common']['family'], 'udp') 208 | self.assertEqual(result['config']['common']['streams'], 1) 209 | self.assertEqual(result['config']['additional']['reverse'], False) 210 | self.assertEqual(result['config']['additional']['ip_version'], 6) 211 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 212 | self.assertEqual(result['summary']['packets_received'], result['summary']['packets_sent']) 213 | self.assertEqual(result['summary']['framed_packet_size'], 1228) 214 | self.assertEqual(result['summary']['packets_duplicate'], 0) 215 | self.assertEqual(result['summary']['packets_lost'], 0) 216 | self.assertEqual(result['summary']['packets_out_of_order'], 0) 217 | self.assertAlmostEqual(result['summary']['bytes_received'], 500000, delta=25000) 218 | self.assertAlmostEqual(result['summary']['duration_receive'], 1.0, delta=0.1) 219 | 220 | def test_udp_reverse(self): 221 | result = _run_rperf_client_ipv6(( 222 | '-u', #run UDP test 223 | '-R', #run in reverse mode 224 | '-b', '500000', #keep it light, at 500kBps per stream 225 | '-l', '1200', #try to send 1200 bytes of data at a time 226 | '-t', '1', #run for one seconds 227 | )) 228 | self.assertTrue(result['success']) 229 | self.assertEqual(result['config']['common']['family'], 'udp') 230 | self.assertEqual(result['config']['common']['streams'], 1) 231 | self.assertEqual(result['config']['additional']['reverse'], True) 232 | self.assertEqual(result['config']['additional']['ip_version'], 6) 233 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 234 | self.assertEqual(result['summary']['packets_received'], result['summary']['packets_sent']) 235 | self.assertEqual(result['summary']['framed_packet_size'], 1228) 236 | self.assertEqual(result['summary']['packets_duplicate'], 0) 237 | self.assertEqual(result['summary']['packets_lost'], 0) 238 | self.assertEqual(result['summary']['packets_out_of_order'], 0) 239 | self.assertAlmostEqual(result['summary']['bytes_received'], 500000, delta=25000) 240 | self.assertAlmostEqual(result['summary']['duration_receive'], 1.0, delta=0.1) 241 | 242 | 243 | 244 | 245 | class TestMisc(unittest.TestCase): 246 | def setUp(self): 247 | if _DISPLAY_LOGS: 248 | self.server = subprocess.Popen((_RPERF_BINARY, '-s', '-6', '-A', '0,1')) 249 | else: 250 | self.server = subprocess.Popen((_RPERF_BINARY, '-s', '-6', '-A', '0,1'), stderr=subprocess.DEVNULL) 251 | 252 | def tearDown(self): 253 | self.server.terminate() 254 | self.server.wait() 255 | 256 | def test_hostname(self): 257 | result = _run_rperf_client_hostname(( 258 | '-N', #disable Nagle's algorithm 259 | '-b', '500000', #keep it light, at 500kBps per stream 260 | '-l', '4096', #try to send 4k of data at a time 261 | '-O', '1', #omit the first second of data from summaries 262 | '-t', '2', #run for two seconds 263 | )) 264 | self.assertTrue(result['success']) 265 | self.assertEqual(result['config']['common']['family'], 'tcp') 266 | self.assertEqual(result['config']['common']['streams'], 1) 267 | self.assertEqual(result['config']['additional']['reverse'], False) 268 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 269 | self.assertAlmostEqual(result['summary']['bytes_received'], 500000, delta=25000) 270 | self.assertAlmostEqual(result['summary']['duration_receive'], 1.0, delta=0.1) 271 | 272 | def test_hostname_reverse(self): 273 | result = _run_rperf_client_hostname(( 274 | '-N', #disable Nagle's algorithm 275 | '-R', #run in reverse mode 276 | '-b', '500000', #keep it light, at 500kBps per stream 277 | '-l', '4096', #try to send 4k of data at a time 278 | '-O', '1', #omit the first second of data from summaries 279 | '-t', '2', #run for two seconds 280 | )) 281 | self.assertTrue(result['success']) 282 | self.assertEqual(result['config']['common']['family'], 'tcp') 283 | self.assertEqual(result['config']['common']['streams'], 1) 284 | self.assertEqual(result['config']['additional']['reverse'], True) 285 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 286 | self.assertAlmostEqual(result['summary']['bytes_received'], 500000, delta=25000) 287 | self.assertAlmostEqual(result['summary']['duration_receive'], 1.0, delta=0.1) 288 | 289 | def test_ipv4_mapped_with_core_affinity(self): 290 | result = _run_rperf_client_ipv4(( 291 | '-A', '2,3', #set CPU core-affinity to 2 and 3 292 | '-b', '500000', #keep it light, at 500kBps per stream 293 | '-l', '4096', #try to send 4k of data at a time 294 | '-O', '1', #omit the first second of data from summaries 295 | '-P', '2', #two parallel streams 296 | '-t', '2', #run for two seconds 297 | )) 298 | self.assertTrue(result['success']) 299 | self.assertEqual(result['config']['common']['family'], 'tcp') 300 | self.assertEqual(result['config']['common']['streams'], 2) 301 | self.assertEqual(result['config']['additional']['reverse'], False) 302 | self.assertEqual(result['config']['additional']['ip_version'], 4) 303 | self.assertEqual(result['summary']['bytes_received'], result['summary']['bytes_sent']) 304 | self.assertAlmostEqual(result['summary']['bytes_received'], 1000000, delta=50000) 305 | self.assertAlmostEqual(result['summary']['duration_receive'], 2.0, delta=0.1) 306 | 307 | def test_multiple_simultaneous_clients(self): 308 | with concurrent.futures.ThreadPoolExecutor() as executor: 309 | tcp_1_ipv4 = executor.submit(_run_rperf_client_ipv4, ( 310 | '-b', '100000', #keep it light, at 100kBps per stream 311 | '-l', '4096', #try to send 4k of data at a time 312 | '-t', '2', #run for two seconds 313 | )) 314 | tcp_2_ipv6_reverse = executor.submit(_run_rperf_client_ipv6, ( 315 | '-R', #run in reverse mode 316 | '-b', '100000', #keep it light, at 100kBps per stream 317 | '-l', '4096', #try to send 4k of data at a time 318 | '-t', '2', #run for two seconds 319 | )) 320 | udp_1_ipv6 = executor.submit(_run_rperf_client_ipv6, ( 321 | '-u', #run UDP test 322 | '-b', '100000', #keep it light, at 100kBps per stream 323 | '-l', '1200', #try to send 1200 bytes of data at a time 324 | '-t', '2', #run for two seconds 325 | )) 326 | udp_2_hostname_reverse = executor.submit(_run_rperf_client_hostname, ( 327 | '-u', #run UDP test 328 | '-R', #run in reverse mode 329 | '-b', '100000', #keep it light, at 100kBps per stream 330 | '-l', '1200', #try to send 1200 bytes of data at a time 331 | '-t', '2', #run for two seconds 332 | )) 333 | 334 | self.assertTrue(tcp_1_ipv4.result()['success']) 335 | self.assertTrue(tcp_2_ipv6_reverse.result()['success']) 336 | self.assertTrue(udp_1_ipv6.result()['success']) 337 | self.assertTrue(udp_2_hostname_reverse.result()['success']) 338 | 339 | 340 | 341 | 342 | if __name__ == '__main__': 343 | unittest.main() 344 | 345 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | use std::error::Error; 22 | use std::io; 23 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; 24 | use std::sync::atomic::{AtomicBool, AtomicU16, Ordering}; 25 | use std::sync::{Arc, Mutex}; 26 | use std::sync::mpsc::channel; 27 | use std::thread; 28 | use std::time::{Duration}; 29 | 30 | use clap::ArgMatches; 31 | 32 | use mio::net::{TcpListener, TcpStream}; 33 | use mio::{Events, Ready, Poll, PollOpt, Token}; 34 | 35 | use crate::protocol::communication::{receive, send, KEEPALIVE_DURATION}; 36 | 37 | use crate::protocol::messaging::{ 38 | prepare_connect, prepare_connect_ready, 39 | }; 40 | 41 | use crate::stream::TestStream; 42 | use crate::stream::tcp; 43 | use crate::stream::udp; 44 | 45 | type BoxResult = Result>; 46 | 47 | const POLL_TIMEOUT:Duration = Duration::from_millis(500); 48 | 49 | /// when false, the system is shutting down 50 | static ALIVE:AtomicBool = AtomicBool::new(true); 51 | 52 | /// a count of connected clients 53 | static CLIENTS:AtomicU16 = AtomicU16::new(0); 54 | 55 | 56 | fn handle_client( 57 | stream:&mut TcpStream, 58 | cpu_affinity_manager:Arc>, 59 | tcp_port_pool:Arc>, 60 | udp_port_pool:Arc>, 61 | ) -> BoxResult<()> { 62 | let mut started = false; 63 | let peer_addr = stream.peer_addr()?; 64 | 65 | 66 | //scaffolding to track and relay the streams and stream-results associated with this client 67 | let mut parallel_streams:Vec>> = Vec::new(); 68 | let mut parallel_streams_joinhandles = Vec::new(); 69 | let (results_tx, results_rx):(std::sync::mpsc::Sender>, std::sync::mpsc::Receiver>) = channel(); 70 | 71 | //a closure used to pass results from stream-handlers to the client-communication stream 72 | let mut forwarding_send_stream = stream.try_clone()?; 73 | let mut results_handler = || -> BoxResult<()> { 74 | loop { //drain all results every time this closer is invoked 75 | match results_rx.try_recv() { //if there's something to forward, write it to the client 76 | Ok(result) => { 77 | send(&mut forwarding_send_stream, &result.to_json())?; 78 | }, 79 | Err(_) => break, //whether it's empty or disconnected, there's nothing to do 80 | } 81 | } 82 | Ok(()) 83 | }; 84 | 85 | 86 | //server operations are entirely driven by client-signalling, making this a (simple) state-machine 87 | while is_alive() { 88 | let payload = receive(stream, is_alive, &mut results_handler)?; 89 | match payload.get("kind") { 90 | Some(kind) => { 91 | match kind.as_str().unwrap() { 92 | "configuration" => { //we either need to connect streams to the client or prepare to receive connections 93 | if payload.get("role").unwrap_or(&serde_json::json!("download")).as_str().unwrap() == "download" { 94 | log::info!("[{}] running in forward-mode: server will be receiving data", &peer_addr); 95 | 96 | let stream_count = payload.get("streams").unwrap_or(&serde_json::json!(1)).as_i64().unwrap(); 97 | //since we're receiving data, we're also responsible for letting the client know where to send it 98 | let mut stream_ports = Vec::with_capacity(stream_count as usize); 99 | 100 | if payload.get("family").unwrap_or(&serde_json::json!("tcp")).as_str().unwrap() == "udp" { 101 | log::info!("[{}] preparing for UDP test with {} streams...", &peer_addr, stream_count); 102 | 103 | let mut c_udp_port_pool = udp_port_pool.lock().unwrap(); 104 | 105 | let test_definition = udp::UdpTestDefinition::new(&payload)?; 106 | for stream_idx in 0..stream_count { 107 | log::debug!("[{}] preparing UDP-receiver for stream {}...", &peer_addr, stream_idx); 108 | let test = udp::receiver::UdpReceiver::new( 109 | test_definition.clone(), &(stream_idx as u8), 110 | &mut c_udp_port_pool, 111 | &peer_addr.ip(), 112 | &(payload["receive_buffer"].as_i64().unwrap() as usize), 113 | )?; 114 | stream_ports.push(test.get_port()?); 115 | parallel_streams.push(Arc::new(Mutex::new(test))); 116 | } 117 | } else { //TCP 118 | log::info!("[{}] preparing for TCP test with {} streams...", &peer_addr, stream_count); 119 | 120 | let mut c_tcp_port_pool = tcp_port_pool.lock().unwrap(); 121 | 122 | let test_definition = tcp::TcpTestDefinition::new(&payload)?; 123 | for stream_idx in 0..stream_count { 124 | log::debug!("[{}] preparing TCP-receiver for stream {}...", &peer_addr, stream_idx); 125 | let test = tcp::receiver::TcpReceiver::new( 126 | test_definition.clone(), &(stream_idx as u8), 127 | &mut c_tcp_port_pool, 128 | &peer_addr.ip(), 129 | &(payload["receive_buffer"].as_i64().unwrap() as usize), 130 | )?; 131 | stream_ports.push(test.get_port()?); 132 | parallel_streams.push(Arc::new(Mutex::new(test))); 133 | } 134 | } 135 | 136 | //let the client know we're ready to receive the connection; stream-ports are in stream-index order 137 | send(stream, &prepare_connect(&stream_ports))?; 138 | } else { //upload 139 | log::info!("[{}] running in reverse-mode: server will be uploading data", &peer_addr); 140 | 141 | let stream_ports = payload.get("stream_ports").unwrap().as_array().unwrap(); 142 | 143 | if payload.get("family").unwrap_or(&serde_json::json!("tcp")).as_str().unwrap() == "udp" { 144 | log::info!("[{}] preparing for UDP test with {} streams...", &peer_addr, stream_ports.len()); 145 | 146 | let test_definition = udp::UdpTestDefinition::new(&payload)?; 147 | for (stream_idx, port) in stream_ports.iter().enumerate() { 148 | log::debug!("[{}] preparing UDP-sender for stream {}...", &peer_addr, stream_idx); 149 | let test = udp::sender::UdpSender::new( 150 | test_definition.clone(), &(stream_idx as u8), 151 | &0, &peer_addr.ip(), &(port.as_i64().unwrap_or(0) as u16), 152 | &(payload.get("duration").unwrap_or(&serde_json::json!(0.0)).as_f64().unwrap() as f32), 153 | &(payload.get("send_interval").unwrap_or(&serde_json::json!(1.0)).as_f64().unwrap() as f32), 154 | &(payload["send_buffer"].as_i64().unwrap() as usize), 155 | )?; 156 | parallel_streams.push(Arc::new(Mutex::new(test))); 157 | } 158 | } else { //TCP 159 | log::info!("[{}] preparing for TCP test with {} streams...", &peer_addr, stream_ports.len()); 160 | 161 | let test_definition = tcp::TcpTestDefinition::new(&payload)?; 162 | for (stream_idx, port) in stream_ports.iter().enumerate() { 163 | log::debug!("[{}] preparing TCP-sender for stream {}...", &peer_addr, stream_idx); 164 | let test = tcp::sender::TcpSender::new( 165 | test_definition.clone(), &(stream_idx as u8), 166 | &peer_addr.ip(), &(port.as_i64().unwrap() as u16), 167 | &(payload["duration"].as_f64().unwrap() as f32), 168 | &(payload["send_interval"].as_f64().unwrap() as f32), 169 | &(payload["send_buffer"].as_i64().unwrap() as usize), 170 | &(payload["no_delay"].as_bool().unwrap()), 171 | )?; 172 | parallel_streams.push(Arc::new(Mutex::new(test))); 173 | } 174 | } 175 | 176 | //let the client know we're ready to begin 177 | send(stream, &prepare_connect_ready())?; 178 | } 179 | }, 180 | "begin" => { //the client has indicated that testing can begin 181 | if !started { //a simple guard to protect against reinitialisaion 182 | for (stream_idx, parallel_stream) in parallel_streams.iter_mut().enumerate() { 183 | log::info!("[{}] beginning execution of stream {}...", &peer_addr, stream_idx); 184 | let c_ps = Arc::clone(¶llel_stream); 185 | let c_results_tx = results_tx.clone(); 186 | let c_cam = cpu_affinity_manager.clone(); 187 | let handle = thread::spawn(move || { 188 | { //set CPU affinity, if enabled 189 | c_cam.lock().unwrap().set_affinity(); 190 | } 191 | loop { 192 | let mut test = c_ps.lock().unwrap(); 193 | log::debug!("[{}] beginning test-interval for stream {}", &peer_addr, test.get_idx()); 194 | match test.run_interval() { 195 | Some(interval_result) => match interval_result { 196 | Ok(ir) => match c_results_tx.send(ir) { 197 | Ok(_) => (), 198 | Err(e) => { 199 | log::error!("[{}] unable to process interval-result: {}", &peer_addr, e); 200 | break 201 | }, 202 | }, 203 | Err(e) => { 204 | log::error!("[{}] unable to process stream: {}", peer_addr, e); 205 | match c_results_tx.send(Box::new(crate::protocol::results::ServerFailedResult{stream_idx: test.get_idx()})) { 206 | Ok(_) => (), 207 | Err(e) => log::error!("[{}] unable to report interval-failed-result: {}", &peer_addr, e), 208 | } 209 | break; 210 | }, 211 | }, 212 | None => { 213 | match c_results_tx.send(Box::new(crate::protocol::results::ServerDoneResult{stream_idx: test.get_idx()})) { 214 | Ok(_) => (), 215 | Err(e) => log::error!("[{}] unable to report interval-done-result: {}", &peer_addr, e), 216 | } 217 | break; 218 | }, 219 | } 220 | } 221 | }); 222 | parallel_streams_joinhandles.push(handle); 223 | } 224 | started = true; 225 | } else { //this can only happen in case of malicious action 226 | log::error!("[{}] duplicate begin-signal", &peer_addr); 227 | break; 228 | } 229 | }, 230 | "end" => { //the client has indicated that testing is done; stop cleanly 231 | log::info!("[{}] end of testing signaled", &peer_addr); 232 | break; 233 | }, 234 | _ => { 235 | log::error!("[{}] invalid data", &peer_addr); 236 | break; 237 | }, 238 | } 239 | }, 240 | None => { 241 | log::error!("[{}] invalid data", &peer_addr); 242 | break; 243 | }, 244 | } 245 | } 246 | 247 | log::debug!("[{}] stopping any still-in-progress streams", &peer_addr); 248 | for ps in parallel_streams.iter_mut() { 249 | let mut stream = match (*ps).lock() { 250 | Ok(guard) => guard, 251 | Err(poisoned) => { 252 | log::error!("[{}] a stream-handler was poisoned; this indicates some sort of logic error", &peer_addr); 253 | poisoned.into_inner() 254 | }, 255 | }; 256 | stream.stop(); 257 | } 258 | log::debug!("[{}] waiting for all streams to end", &peer_addr); 259 | for jh in parallel_streams_joinhandles { 260 | match jh.join() { 261 | Ok(_) => (), 262 | Err(e) => log::error!("[{}] error in parallel stream: {:?}", &peer_addr, e), 263 | } 264 | } 265 | 266 | Ok(()) 267 | } 268 | 269 | /// a panic-tolerant means of indicating that a client has been disconnected 270 | struct ClientThreadMonitor { 271 | client_address: String, 272 | } 273 | impl Drop for ClientThreadMonitor { 274 | fn drop(&mut self) { 275 | CLIENTS.fetch_sub(1, Ordering::Relaxed); 276 | if thread::panicking(){ 277 | log::warn!("{} disconnecting due to panic", self.client_address); 278 | } else { 279 | log::info!("{} disconnected", self.client_address); 280 | } 281 | } 282 | } 283 | 284 | pub fn serve(args:ArgMatches) -> BoxResult<()> { 285 | //config-parsing and pre-connection setup 286 | let tcp_port_pool = Arc::new(Mutex::new(tcp::receiver::TcpPortPool::new( 287 | args.value_of("tcp_port_pool").unwrap().to_string(), 288 | args.value_of("tcp6_port_pool").unwrap().to_string(), 289 | ))); 290 | let udp_port_pool = Arc::new(Mutex::new(udp::receiver::UdpPortPool::new( 291 | args.value_of("udp_port_pool").unwrap().to_string(), 292 | args.value_of("udp6_port_pool").unwrap().to_string(), 293 | ))); 294 | 295 | let cpu_affinity_manager = Arc::new(Mutex::new(crate::utils::cpu_affinity::CpuAffinityManager::new(args.value_of("affinity").unwrap())?)); 296 | 297 | let client_limit:u16 = args.value_of("client_limit").unwrap().parse()?; 298 | if client_limit > 0 { 299 | log::debug!("limiting service to {} concurrent clients", client_limit); 300 | } 301 | 302 | //start listening for connections 303 | let port:u16 = args.value_of("port").unwrap().parse()?; 304 | let mut listener:TcpListener; 305 | if args.is_present("version6") { 306 | listener = TcpListener::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port)).expect(format!("failed to bind TCP socket, port {}", port).as_str()); 307 | } else { 308 | listener = TcpListener::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port)).expect(format!("failed to bind TCP socket, port {}", port).as_str()); 309 | } 310 | log::info!("server listening on {}", listener.local_addr()?); 311 | 312 | let mio_token = Token(0); 313 | let poll = Poll::new()?; 314 | poll.register( 315 | &mut listener, 316 | mio_token, 317 | Ready::readable(), 318 | PollOpt::edge(), 319 | )?; 320 | let mut events = Events::with_capacity(32); 321 | 322 | while is_alive() { 323 | poll.poll(&mut events, Some(POLL_TIMEOUT))?; 324 | for event in events.iter() { 325 | match event.token() { 326 | _ => loop { 327 | match listener.accept() { 328 | Ok((mut stream, address)) => { 329 | log::info!("connection from {}", address); 330 | 331 | stream.set_nodelay(true).expect("cannot disable Nagle's algorithm"); 332 | stream.set_keepalive(Some(KEEPALIVE_DURATION)).expect("unable to set TCP keepalive"); 333 | 334 | let client_count = CLIENTS.fetch_add(1, Ordering::Relaxed) + 1; 335 | if client_limit > 0 && client_count > client_limit { 336 | log::warn!("client-limit ({}) reached; disconnecting {}...", client_limit, address.to_string()); 337 | stream.shutdown(Shutdown::Both).unwrap_or_default(); 338 | CLIENTS.fetch_sub(1, Ordering::Relaxed); 339 | } else { 340 | let c_cam = cpu_affinity_manager.clone(); 341 | let c_tcp_port_pool = tcp_port_pool.clone(); 342 | let c_udp_port_pool = udp_port_pool.clone(); 343 | let thread_builder = thread::Builder::new() 344 | .name(address.to_string().into()); 345 | thread_builder.spawn(move || { 346 | //ensure the client is accounted-for even if the handler panics 347 | let _client_thread_monitor = ClientThreadMonitor{ 348 | client_address: address.to_string(), 349 | }; 350 | 351 | match handle_client(&mut stream, c_cam, c_tcp_port_pool, c_udp_port_pool) { 352 | Ok(_) => (), 353 | Err(e) => log::error!("error in client-handler: {}", e), 354 | } 355 | 356 | //in the event of panic, this will happen when the stream is dropped 357 | stream.shutdown(Shutdown::Both).unwrap_or_default(); 358 | })?; 359 | } 360 | }, 361 | Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { //nothing to do 362 | break; 363 | }, 364 | Err(e) => { 365 | return Err(Box::new(e)); 366 | }, 367 | } 368 | }, 369 | } 370 | } 371 | } 372 | 373 | //wait until all clients have been disconnected 374 | loop { 375 | let clients_count = CLIENTS.load(Ordering::Relaxed); 376 | if clients_count > 0 { 377 | log::info!("waiting for {} clients to finish...", clients_count); 378 | thread::sleep(POLL_TIMEOUT); 379 | } else { 380 | break; 381 | } 382 | } 383 | Ok(()) 384 | } 385 | 386 | pub fn kill() -> bool { 387 | ALIVE.swap(false, Ordering::Relaxed) 388 | } 389 | fn is_alive() -> bool { 390 | ALIVE.load(Ordering::Relaxed) 391 | } 392 | -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | use std::net::{IpAddr, Shutdown, ToSocketAddrs}; 22 | use std::sync::atomic::{AtomicBool, Ordering}; 23 | use std::sync::{Arc, Mutex}; 24 | use std::sync::mpsc::channel; 25 | use std::thread; 26 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; 27 | 28 | use clap::ArgMatches; 29 | 30 | use mio::net::{TcpStream}; 31 | 32 | use crate::protocol::communication::{receive, send, KEEPALIVE_DURATION}; 33 | 34 | use crate::protocol::messaging::{ 35 | prepare_begin, prepare_end, 36 | prepare_upload_configuration, prepare_download_configuration, 37 | }; 38 | 39 | use crate::protocol::results::{IntervalResult, IntervalResultKind, TestResults, TcpTestResults, UdpTestResults}; 40 | 41 | use crate::stream::TestStream; 42 | use crate::stream::tcp; 43 | use crate::stream::udp; 44 | 45 | use std::error::Error; 46 | type BoxResult = Result>; 47 | 48 | /// when false, the system is shutting down 49 | static ALIVE:AtomicBool = AtomicBool::new(true); 50 | 51 | /// a deferred kill-switch to handle shutdowns a bit more gracefully in the event of a probable disconnect 52 | static mut KILL_TIMER_RELATIVE_START_TIME:f64 = 0.0; //the time at which the kill-timer was started 53 | const KILL_TIMEOUT:f64 = 5.0; //once testing finishes, allow a few seconds for the server to respond 54 | 55 | const CONNECT_TIMEOUT:Duration = Duration::from_secs(2); 56 | 57 | fn connect_to_server(address:&str, port:&u16) -> BoxResult { 58 | let destination = format!("{}:{}", address, port); 59 | log::info!("connecting to server at {}...", destination); 60 | 61 | let server_addr = destination.to_socket_addrs()?.next(); 62 | if server_addr.is_none() { 63 | return Err(Box::new(simple_error::simple_error!("unable to resolve {}", address))); 64 | } 65 | let raw_stream = match std::net::TcpStream::connect_timeout(&server_addr.unwrap(), CONNECT_TIMEOUT) { 66 | Ok(s) => s, 67 | Err(e) => return Err(Box::new(simple_error::simple_error!("unable to connect: {}", e))), 68 | }; 69 | let stream = match TcpStream::from_stream(raw_stream) { 70 | Ok(s) => s, 71 | Err(e) => return Err(Box::new(simple_error::simple_error!("unable to prepare TCP control-channel: {}", e))), 72 | }; 73 | log::info!("connected to server"); 74 | 75 | stream.set_nodelay(true).expect("cannot disable Nagle's algorithm"); 76 | stream.set_keepalive(Some(KEEPALIVE_DURATION)).expect("unable to set TCP keepalive"); 77 | 78 | Ok(stream) 79 | } 80 | 81 | fn prepare_test_results(is_udp:bool, stream_count:u8) -> Mutex> { 82 | if is_udp { //UDP 83 | let mut udp_test_results = UdpTestResults::new(); 84 | for i in 0..stream_count { 85 | udp_test_results.prepare_index(&i); 86 | } 87 | Mutex::new(Box::new(udp_test_results)) 88 | } else { //TCP 89 | let mut tcp_test_results = TcpTestResults::new(); 90 | for i in 0..stream_count { 91 | tcp_test_results.prepare_index(&i); 92 | } 93 | Mutex::new(Box::new(tcp_test_results)) 94 | } 95 | } 96 | 97 | 98 | pub fn execute(args:ArgMatches) -> BoxResult<()> { 99 | let mut complete = false; 100 | 101 | //config-parsing and pre-connection setup 102 | let mut tcp_port_pool = tcp::receiver::TcpPortPool::new( 103 | args.value_of("tcp_port_pool").unwrap().to_string(), 104 | args.value_of("tcp6_port_pool").unwrap().to_string(), 105 | ); 106 | let mut udp_port_pool = udp::receiver::UdpPortPool::new( 107 | args.value_of("udp_port_pool").unwrap().to_string(), 108 | args.value_of("udp6_port_pool").unwrap().to_string(), 109 | ); 110 | 111 | let cpu_affinity_manager = Arc::new(Mutex::new(crate::utils::cpu_affinity::CpuAffinityManager::new(args.value_of("affinity").unwrap())?)); 112 | 113 | let display_json:bool; 114 | let display_bit:bool; 115 | match args.value_of("format").unwrap() { 116 | "json" => { 117 | display_json = true; 118 | display_bit = false; 119 | }, 120 | "megabit" => { 121 | display_json = false; 122 | display_bit = true; 123 | }, 124 | "megabyte" => { 125 | display_json = false; 126 | display_bit = false; 127 | }, 128 | _ => { 129 | log::error!("unsupported display-mode; defaulting to JSON"); 130 | display_json = true; 131 | display_bit = false; 132 | }, 133 | } 134 | 135 | let is_udp = args.is_present("udp"); 136 | 137 | let test_id = uuid::Uuid::new_v4(); 138 | let mut upload_config = prepare_upload_configuration(&args, test_id.as_bytes())?; 139 | let mut download_config = prepare_download_configuration(&args, test_id.as_bytes())?; 140 | 141 | 142 | //connect to the server 143 | let mut stream = connect_to_server(&args.value_of("client").unwrap(), &(args.value_of("port").unwrap().parse()?))?; 144 | let server_addr = stream.peer_addr()?; 145 | 146 | 147 | //scaffolding to track and relay the streams and stream-results associated with this test 148 | let stream_count = download_config.get("streams").unwrap().as_i64().unwrap() as usize; 149 | let mut parallel_streams:Vec>> = Vec::with_capacity(stream_count); 150 | let mut parallel_streams_joinhandles = Vec::with_capacity(stream_count); 151 | let (results_tx, results_rx):(std::sync::mpsc::Sender>, std::sync::mpsc::Receiver>) = channel(); 152 | 153 | let test_results:Mutex> = prepare_test_results(is_udp, stream_count as u8); 154 | 155 | //a closure used to pass results from stream-handlers to the test-result structure 156 | let mut results_handler = || -> BoxResult<()> { 157 | loop { //drain all results every time this closer is invoked 158 | match results_rx.try_recv() { //see if there's a result to pass on 159 | Ok(result) => { 160 | if !display_json { //since this runs in the main thread, which isn't involved in any testing, render things immediately 161 | println!("{}", result.to_string(display_bit)); 162 | } 163 | 164 | //update the test-results accordingly 165 | let mut tr = test_results.lock().unwrap(); 166 | match result.kind() { 167 | IntervalResultKind::ClientDone | IntervalResultKind::ClientFailed => { 168 | if result.kind() == IntervalResultKind::ClientDone { 169 | log::info!("stream {} is done", result.get_stream_idx()); 170 | } else { 171 | log::warn!("stream {} failed", result.get_stream_idx()); 172 | } 173 | tr.mark_stream_done(&result.get_stream_idx(), result.kind() == IntervalResultKind::ClientDone); 174 | if tr.count_in_progress_streams() == 0 { 175 | complete = true; 176 | 177 | if tr.count_in_progress_streams_server() > 0 { 178 | log::info!("giving the server a few seconds to report results..."); 179 | start_kill_timer(); 180 | } else { //all data gathered from both sides 181 | kill(); 182 | } 183 | } 184 | }, 185 | _ => { 186 | tr.update_from_json(result.to_json())?; 187 | } 188 | } 189 | }, 190 | Err(_) => break, //whether it's empty or disconnected, there's nothing to do 191 | } 192 | } 193 | Ok(()) 194 | }; 195 | 196 | //depending on whether this is a forward- or reverse-test, the order of configuring test-streams will differ 197 | if args.is_present("reverse") { 198 | log::debug!("running in reverse-mode: server will be uploading data"); 199 | 200 | //when we're receiving data, we're also responsible for letting the server know where to send it 201 | let mut stream_ports = Vec::with_capacity(stream_count); 202 | 203 | if is_udp { //UDP 204 | log::info!("preparing for reverse-UDP test with {} streams...", stream_count); 205 | 206 | let test_definition = udp::UdpTestDefinition::new(&download_config)?; 207 | for stream_idx in 0..stream_count { 208 | log::debug!("preparing UDP-receiver for stream {}...", stream_idx); 209 | let test = udp::receiver::UdpReceiver::new( 210 | test_definition.clone(), &(stream_idx as u8), 211 | &mut udp_port_pool, 212 | &server_addr.ip(), 213 | &(download_config["receive_buffer"].as_i64().unwrap() as usize), 214 | )?; 215 | stream_ports.push(test.get_port()?); 216 | parallel_streams.push(Arc::new(Mutex::new(test))); 217 | } 218 | } else { //TCP 219 | log::info!("preparing for reverse-TCP test with {} streams...", stream_count); 220 | 221 | let test_definition = tcp::TcpTestDefinition::new(&download_config)?; 222 | for stream_idx in 0..stream_count { 223 | log::debug!("preparing TCP-receiver for stream {}...", stream_idx); 224 | let test = tcp::receiver::TcpReceiver::new( 225 | test_definition.clone(), &(stream_idx as u8), 226 | &mut tcp_port_pool, 227 | &server_addr.ip(), 228 | &(download_config["receive_buffer"].as_i64().unwrap() as usize), 229 | )?; 230 | stream_ports.push(test.get_port()?); 231 | parallel_streams.push(Arc::new(Mutex::new(test))); 232 | } 233 | } 234 | 235 | //add the port-list to the upload-config that the server will receive; this is in stream-index order 236 | upload_config["stream_ports"] = serde_json::json!(stream_ports); 237 | 238 | //let the server know what we're expecting 239 | send(&mut stream, &upload_config)?; 240 | } else { 241 | log::debug!("running in forward-mode: server will be receiving data"); 242 | 243 | //let the server know to prepare for us to connect 244 | send(&mut stream, &download_config)?; 245 | //NOTE: we don't prepare to send data at this point; that happens in the loop below, after the server signals that it's ready 246 | } 247 | 248 | 249 | //now that the server knows what we need to do, we have to wait for its response 250 | let connection_payload = receive(&mut stream, is_alive, &mut results_handler)?; 251 | match connection_payload.get("kind") { 252 | Some(kind) => { 253 | match kind.as_str().unwrap_or_default() { 254 | "connect" => { //we need to connect to the server 255 | if is_udp { //UDP 256 | log::info!("preparing for UDP test with {} streams...", stream_count); 257 | 258 | let test_definition = udp::UdpTestDefinition::new(&upload_config)?; 259 | for (stream_idx, port) in connection_payload.get("stream_ports").unwrap().as_array().unwrap().iter().enumerate() { 260 | log::debug!("preparing UDP-sender for stream {}...", stream_idx); 261 | let test = udp::sender::UdpSender::new( 262 | test_definition.clone(), &(stream_idx as u8), 263 | &0, &server_addr.ip(), &(port.as_i64().unwrap() as u16), 264 | &(upload_config["duration"].as_f64().unwrap() as f32), 265 | &(upload_config["send_interval"].as_f64().unwrap() as f32), 266 | &(upload_config["send_buffer"].as_i64().unwrap() as usize), 267 | )?; 268 | parallel_streams.push(Arc::new(Mutex::new(test))); 269 | } 270 | } else { //TCP 271 | log::info!("preparing for TCP test with {} streams...", stream_count); 272 | 273 | let test_definition = tcp::TcpTestDefinition::new(&upload_config)?; 274 | for (stream_idx, port) in connection_payload.get("stream_ports").unwrap().as_array().unwrap().iter().enumerate() { 275 | log::debug!("preparing TCP-sender for stream {}...", stream_idx); 276 | let test = tcp::sender::TcpSender::new( 277 | test_definition.clone(), &(stream_idx as u8), 278 | &server_addr.ip(), &(port.as_i64().unwrap() as u16), 279 | &(upload_config["duration"].as_f64().unwrap() as f32), 280 | &(upload_config["send_interval"].as_f64().unwrap() as f32), 281 | &(upload_config["send_buffer"].as_i64().unwrap() as usize), 282 | &(upload_config["no_delay"].as_bool().unwrap()), 283 | )?; 284 | parallel_streams.push(Arc::new(Mutex::new(test))); 285 | } 286 | } 287 | }, 288 | "connect-ready" => { //server is ready to connect to us 289 | //nothing more to do in this flow 290 | }, 291 | _ => { 292 | log::error!("invalid data from {}: {}", stream.peer_addr()?, serde_json::to_string(&connection_payload)?); 293 | kill(); 294 | }, 295 | } 296 | }, 297 | None => { 298 | log::error!("invalid data from {}: {}", stream.peer_addr()?, serde_json::to_string(&connection_payload)?); 299 | kill(); 300 | }, 301 | } 302 | 303 | 304 | if is_alive() { //if interrupted while waiting for the server to respond, there's no reason to continue 305 | log::info!("informing server that testing can begin..."); 306 | //tell the server to start 307 | send(&mut stream, &prepare_begin())?; 308 | 309 | log::debug!("spawning stream-threads"); 310 | //begin the test-streams 311 | for (stream_idx, parallel_stream) in parallel_streams.iter_mut().enumerate() { 312 | log::info!("beginning execution of stream {}...", stream_idx); 313 | let c_ps = Arc::clone(¶llel_stream); 314 | let c_results_tx = results_tx.clone(); 315 | let c_cam = cpu_affinity_manager.clone(); 316 | let handle = thread::spawn(move || { 317 | { //set CPU affinity, if enabled 318 | c_cam.lock().unwrap().set_affinity(); 319 | } 320 | loop { 321 | let mut test = c_ps.lock().unwrap(); 322 | log::debug!("beginning test-interval for stream {}", test.get_idx()); 323 | match test.run_interval() { 324 | Some(interval_result) => match interval_result { 325 | Ok(ir) => match c_results_tx.send(ir) { 326 | Ok(_) => (), 327 | Err(e) => { 328 | log::error!("unable to report interval-result: {}", e); 329 | break 330 | }, 331 | }, 332 | Err(e) => { 333 | log::error!("unable to process stream: {}", e); 334 | match c_results_tx.send(Box::new(crate::protocol::results::ClientFailedResult{stream_idx: test.get_idx()})) { 335 | Ok(_) => (), 336 | Err(e) => log::error!("unable to report interval-failed-result: {}", e), 337 | } 338 | break; 339 | }, 340 | }, 341 | None => { 342 | match c_results_tx.send(Box::new(crate::protocol::results::ClientDoneResult{stream_idx: test.get_idx()})) { 343 | Ok(_) => (), 344 | Err(e) => log::error!("unable to report interval-done-result: {}", e), 345 | } 346 | break; 347 | }, 348 | } 349 | } 350 | }); 351 | parallel_streams_joinhandles.push(handle); 352 | } 353 | 354 | //watch for events from the server 355 | while is_alive() { 356 | match receive(&mut stream, is_alive, &mut results_handler) { 357 | Ok(payload) => { 358 | match payload.get("kind") { 359 | Some(kind) => { 360 | match kind.as_str().unwrap_or_default() { 361 | "receive" | "send" => { //receive/send-results from the server 362 | if !display_json { 363 | let result = crate::protocol::results::interval_result_from_json(payload.clone())?; 364 | println!("{}", result.to_string(display_bit)); 365 | } 366 | let mut tr = test_results.lock().unwrap(); 367 | tr.update_from_json(payload)?; 368 | }, 369 | "done" | "failed" => match payload.get("stream_idx") { //completion-result from the server 370 | Some(stream_idx) => match stream_idx.as_i64() { 371 | Some(idx64) => { 372 | let mut tr = test_results.lock().unwrap(); 373 | match kind.as_str().unwrap() { 374 | "done" => { 375 | log::info!("server reported completion of stream {}", idx64); 376 | }, 377 | "failed" => { 378 | log::warn!("server reported failure with stream {}", idx64); 379 | tr.mark_stream_done(&(idx64 as u8), false); 380 | }, 381 | _ => (), //not possible 382 | } 383 | tr.mark_stream_done_server(&(idx64 as u8)); 384 | 385 | if tr.count_in_progress_streams() == 0 && tr.count_in_progress_streams_server() == 0 { //all data gathered from both sides 386 | kill(); 387 | } 388 | }, 389 | None => log::error!("completion from server did not include a valid stream_idx"), 390 | }, 391 | None => log::error!("completion from server did not include stream_idx"), 392 | }, 393 | _ => { 394 | log::error!("invalid data from {}: {}", stream.peer_addr()?, serde_json::to_string(&connection_payload)?); 395 | break; 396 | }, 397 | } 398 | }, 399 | None => { 400 | log::error!("invalid data from {}: {}", stream.peer_addr()?, serde_json::to_string(&connection_payload)?); 401 | break; 402 | }, 403 | } 404 | }, 405 | Err(e) => { 406 | if !complete { //when complete, this also occurs 407 | return Err(e); 408 | } 409 | break; 410 | }, 411 | } 412 | } 413 | } 414 | 415 | //assume this is a controlled shutdown; if it isn't, this is just a very slight waste of time 416 | send(&mut stream, &prepare_end()).unwrap_or_default(); 417 | thread::sleep(Duration::from_millis(250)); //wait a moment for the "end" message to be queued for delivery to the server 418 | stream.shutdown(Shutdown::Both).unwrap_or_default(); 419 | 420 | log::debug!("stopping any still-in-progress streams"); 421 | for ps in parallel_streams.iter_mut() { 422 | let mut stream = match (*ps).lock() { 423 | Ok(guard) => guard, 424 | Err(poisoned) => { 425 | log::error!("a stream-handler was poisoned; this indicates some sort of logic error"); 426 | poisoned.into_inner() 427 | }, 428 | }; 429 | stream.stop(); 430 | } 431 | log::debug!("waiting for all streams to end"); 432 | for jh in parallel_streams_joinhandles { 433 | match jh.join() { 434 | Ok(_) => (), 435 | Err(e) => log::error!("error in parallel stream: {:?}", e), 436 | } 437 | } 438 | 439 | let common_config:serde_json::Value; 440 | //sanitise the config structures for export 441 | { 442 | let upload_config_map = upload_config.as_object_mut().unwrap(); 443 | let cc_family = upload_config_map.remove("family"); 444 | upload_config_map.remove("kind"); 445 | let cc_length = upload_config_map.remove("length"); 446 | upload_config_map.remove("role"); 447 | let cc_streams = upload_config_map.remove("streams"); 448 | upload_config_map.remove("test_id"); 449 | upload_config_map.remove("stream_ports"); 450 | if upload_config_map["send_buffer"].as_i64().unwrap() == 0 { 451 | upload_config_map.remove("send_buffer"); 452 | } 453 | 454 | let download_config_map = download_config.as_object_mut().unwrap(); 455 | download_config_map.remove("family"); 456 | download_config_map.remove("kind"); 457 | download_config_map.remove("length"); 458 | download_config_map.remove("role"); 459 | download_config_map.remove("streams"); 460 | download_config_map.remove("test_id"); 461 | if download_config_map["receive_buffer"].as_i64().unwrap() == 0 { 462 | download_config_map.remove("receive_buffer"); 463 | } 464 | 465 | common_config = serde_json::json!({ 466 | "family": cc_family, 467 | "length": cc_length, 468 | "streams": cc_streams, 469 | }); 470 | } 471 | 472 | log::debug!("displaying test results"); 473 | let omit_seconds:usize = args.value_of("omit").unwrap().parse()?; 474 | { 475 | let tr = test_results.lock().unwrap(); 476 | if display_json { 477 | println!("{}", tr.to_json_string(omit_seconds, upload_config, download_config, common_config, serde_json::json!({ 478 | "omit_seconds": omit_seconds, 479 | "ip_version": match server_addr.ip() { 480 | IpAddr::V4(_) => 4, 481 | IpAddr::V6(_) => 6, 482 | }, 483 | "reverse": args.is_present("reverse"), 484 | }))); 485 | } else { 486 | println!("{}", tr.to_string(display_bit, omit_seconds)); 487 | } 488 | } 489 | 490 | Ok(()) 491 | } 492 | 493 | pub fn kill() -> bool { 494 | ALIVE.swap(false, Ordering::Relaxed) 495 | } 496 | fn start_kill_timer() { 497 | unsafe { 498 | KILL_TIMER_RELATIVE_START_TIME = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs_f64(); 499 | } 500 | } 501 | fn is_alive() -> bool { 502 | unsafe { 503 | if KILL_TIMER_RELATIVE_START_TIME != 0.0 { //initialised 504 | if SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs_f64() - KILL_TIMER_RELATIVE_START_TIME >= KILL_TIMEOUT { 505 | return false; 506 | } 507 | } 508 | } 509 | ALIVE.load(Ordering::Relaxed) 510 | } 511 | -------------------------------------------------------------------------------- /src/stream/tcp.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | extern crate nix; 22 | 23 | use nix::sys::socket::{setsockopt, sockopt::RcvBuf, sockopt::SndBuf}; 24 | 25 | use crate::protocol::results::{IntervalResult, TcpReceiveResult, TcpSendResult, get_unix_timestamp}; 26 | 27 | use super::{INTERVAL, TestStream, parse_port_spec}; 28 | 29 | use std::error::Error; 30 | type BoxResult = Result>; 31 | 32 | pub const TEST_HEADER_SIZE:usize = 16; 33 | 34 | #[derive(Clone)] 35 | pub struct TcpTestDefinition { 36 | //a UUID used to identify packets associated with this test 37 | pub test_id: [u8; 16], 38 | //bandwidth target, in bytes/sec 39 | pub bandwidth: u64, 40 | //the length of the buffer to exchange 41 | pub length: usize, 42 | } 43 | impl TcpTestDefinition { 44 | pub fn new(details:&serde_json::Value) -> super::BoxResult { 45 | let mut test_id_bytes = [0_u8; 16]; 46 | for (i, v) in details.get("test_id").unwrap_or(&serde_json::json!([])).as_array().unwrap().iter().enumerate() { 47 | if i >= 16 { //avoid out-of-bounds if given malicious data 48 | break; 49 | } 50 | test_id_bytes[i] = v.as_i64().unwrap_or(0) as u8; 51 | } 52 | 53 | let length = details.get("length").unwrap_or(&serde_json::json!(TEST_HEADER_SIZE)).as_i64().unwrap() as usize; 54 | if length < TEST_HEADER_SIZE { 55 | return Err(Box::new(simple_error::simple_error!(std::format!("{} is too short of a length to satisfy testing requirements", length)))); 56 | } 57 | 58 | Ok(TcpTestDefinition{ 59 | test_id: test_id_bytes, 60 | bandwidth: details.get("bandwidth").unwrap_or(&serde_json::json!(0.0)).as_f64().unwrap() as u64, 61 | length: length, 62 | }) 63 | } 64 | } 65 | 66 | 67 | pub mod receiver { 68 | use std::io::Read; 69 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; 70 | use std::os::unix::io::AsRawFd; 71 | use std::sync::{Mutex}; 72 | use std::time::{Duration, Instant}; 73 | 74 | use mio::net::{TcpListener, TcpStream}; 75 | use mio::{Events, Ready, Poll, PollOpt, Token}; 76 | 77 | const POLL_TIMEOUT:Duration = Duration::from_millis(250); 78 | const RECEIVE_TIMEOUT:Duration = Duration::from_secs(3); 79 | 80 | pub struct TcpPortPool { 81 | pub ports_ip4: Vec, 82 | pub ports_ip6: Vec, 83 | pos_ip4: usize, 84 | pos_ip6: usize, 85 | lock_ip4: Mutex, 86 | lock_ip6: Mutex, 87 | } 88 | impl TcpPortPool { 89 | pub fn new(port_spec:String, port_spec6:String) -> TcpPortPool { 90 | let ports = super::parse_port_spec(port_spec); 91 | if !ports.is_empty() { 92 | log::debug!("configured IPv4 TCP port pool: {:?}", ports); 93 | } else { 94 | log::debug!("using OS assignment for IPv4 TCP ports"); 95 | } 96 | 97 | let ports6 = super::parse_port_spec(port_spec6); 98 | if !ports.is_empty() { 99 | log::debug!("configured IPv6 TCP port pool: {:?}", ports6); 100 | } else { 101 | log::debug!("using OS assignment for IPv6 TCP ports"); 102 | } 103 | 104 | TcpPortPool { 105 | ports_ip4: ports, 106 | pos_ip4: 0, 107 | lock_ip4: Mutex::new(0), 108 | 109 | ports_ip6: ports6, 110 | pos_ip6: 0, 111 | lock_ip6: Mutex::new(0), 112 | } 113 | } 114 | 115 | pub fn bind(&mut self, peer_ip:&IpAddr) -> super::BoxResult { 116 | match peer_ip { 117 | IpAddr::V6(_) => { 118 | if self.ports_ip6.is_empty() { 119 | return Ok(TcpListener::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0)).expect(format!("failed to bind OS-assigned IPv6 TCP socket").as_str())); 120 | } else { 121 | let _guard = self.lock_ip6.lock().unwrap(); 122 | 123 | for port_idx in (self.pos_ip6 + 1)..self.ports_ip6.len() { //iterate to the end of the pool; this will skip the first element in the pool initially, but that's fine 124 | let listener_result = TcpListener::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), self.ports_ip6[port_idx])); 125 | if listener_result.is_ok() { 126 | self.pos_ip6 = port_idx; 127 | return Ok(listener_result.unwrap()); 128 | } else { 129 | log::warn!("unable to bind IPv6 TCP port {}", self.ports_ip6[port_idx]); 130 | } 131 | } 132 | for port_idx in 0..=self.pos_ip6 { //circle back to where the search started 133 | let listener_result = TcpListener::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), self.ports_ip6[port_idx])); 134 | if listener_result.is_ok() { 135 | self.pos_ip6 = port_idx; 136 | return Ok(listener_result.unwrap()); 137 | } else { 138 | log::warn!("unable to bind IPv6 TCP port {}", self.ports_ip6[port_idx]); 139 | } 140 | } 141 | } 142 | return Err(Box::new(simple_error::simple_error!("unable to allocate IPv6 TCP port"))); 143 | }, 144 | IpAddr::V4(_) => { 145 | if self.ports_ip4.is_empty() { 146 | return Ok(TcpListener::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)).expect(format!("failed to bind OS-assigned IPv4 TCP socket").as_str())); 147 | } else { 148 | let _guard = self.lock_ip4.lock().unwrap(); 149 | 150 | for port_idx in (self.pos_ip4 + 1)..self.ports_ip4.len() { //iterate to the end of the pool; this will skip the first element in the pool initially, but that's fine 151 | let listener_result = TcpListener::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), self.ports_ip4[port_idx])); 152 | if listener_result.is_ok() { 153 | self.pos_ip4 = port_idx; 154 | return Ok(listener_result.unwrap()); 155 | } else { 156 | log::warn!("unable to bind IPv4 TCP port {}", self.ports_ip4[port_idx]); 157 | } 158 | } 159 | for port_idx in 0..=self.pos_ip4 { //circle back to where the search started 160 | let listener_result = TcpListener::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), self.ports_ip4[port_idx])); 161 | if listener_result.is_ok() { 162 | self.pos_ip4 = port_idx; 163 | return Ok(listener_result.unwrap()); 164 | } else { 165 | log::warn!("unable to bind IPv4 TCP port {}", self.ports_ip4[port_idx]); 166 | } 167 | } 168 | } 169 | return Err(Box::new(simple_error::simple_error!("unable to allocate IPv4 TCP port"))); 170 | }, 171 | }; 172 | } 173 | } 174 | 175 | pub struct TcpReceiver { 176 | active: bool, 177 | test_definition: super::TcpTestDefinition, 178 | stream_idx: u8, 179 | 180 | listener: Option, 181 | stream: Option, 182 | mio_poll_token: Token, 183 | mio_poll: Poll, 184 | 185 | receive_buffer: usize, 186 | } 187 | impl TcpReceiver { 188 | pub fn new(test_definition:super::TcpTestDefinition, stream_idx:&u8, port_pool:&mut TcpPortPool, peer_ip:&IpAddr, receive_buffer:&usize) -> super::BoxResult { 189 | log::debug!("binding TCP listener for stream {}...", stream_idx); 190 | let listener:TcpListener = port_pool.bind(peer_ip).expect(format!("failed to bind TCP socket").as_str()); 191 | log::debug!("bound TCP listener for stream {}: {}", stream_idx, listener.local_addr()?); 192 | 193 | let mio_poll_token = Token(0); 194 | let mio_poll = Poll::new()?; 195 | 196 | Ok(TcpReceiver{ 197 | active: true, 198 | test_definition: test_definition, 199 | stream_idx: stream_idx.to_owned(), 200 | 201 | listener: Some(listener), 202 | stream: None, 203 | mio_poll_token: mio_poll_token, 204 | mio_poll: mio_poll, 205 | 206 | receive_buffer: receive_buffer.to_owned(), 207 | }) 208 | } 209 | 210 | fn process_connection(&mut self) -> super::BoxResult { 211 | log::debug!("preparing to receive TCP stream {} connection...", self.stream_idx); 212 | 213 | let listener = self.listener.as_mut().unwrap(); 214 | let mio_token = Token(0); 215 | let poll = Poll::new()?; 216 | poll.register( 217 | listener, 218 | mio_token, 219 | Ready::readable(), 220 | PollOpt::edge(), 221 | )?; 222 | let mut events = Events::with_capacity(1); 223 | 224 | let start = Instant::now(); 225 | 226 | while self.active { 227 | if start.elapsed() >= RECEIVE_TIMEOUT { 228 | return Err(Box::new(simple_error::simple_error!("TCP listening for stream {} timed out", self.stream_idx))); 229 | } 230 | 231 | poll.poll(&mut events, Some(POLL_TIMEOUT))?; 232 | for event in events.iter() { 233 | match event.token() { 234 | _ => loop { 235 | match listener.accept() { 236 | Ok((stream, address)) => { 237 | log::debug!("received TCP stream {} connection from {}", self.stream_idx, address); 238 | 239 | let mut verification_stream = stream.try_clone()?; 240 | let mio_token2 = Token(0); 241 | let poll2 = Poll::new()?; 242 | poll2.register( 243 | &verification_stream, 244 | mio_token2, 245 | Ready::readable(), 246 | PollOpt::edge(), 247 | )?; 248 | 249 | let mut buffer = [0_u8; 16]; 250 | let mut events2 = Events::with_capacity(1); 251 | poll2.poll(&mut events2, Some(RECEIVE_TIMEOUT))?; 252 | for event2 in events2.iter() { 253 | match event2.token() { 254 | _ => match verification_stream.read(&mut buffer) { 255 | Ok(_) => { 256 | if buffer == self.test_definition.test_id { 257 | log::debug!("validated TCP stream {} connection from {}", self.stream_idx, address); 258 | if !cfg!(windows) { //NOTE: features unsupported on Windows 259 | if self.receive_buffer != 0 { 260 | log::debug!("setting receive-buffer to {}...", self.receive_buffer); 261 | super::setsockopt(stream.as_raw_fd(), super::RcvBuf, &self.receive_buffer)?; 262 | } 263 | } 264 | 265 | self.mio_poll.register( 266 | &stream, 267 | self.mio_poll_token, 268 | Ready::readable(), 269 | PollOpt::edge(), 270 | )?; 271 | return Ok(stream); 272 | } 273 | }, 274 | Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => { //client didn't provide anything 275 | break; 276 | }, 277 | Err(e) => { 278 | return Err(Box::new(e)); 279 | }, 280 | } 281 | } 282 | } 283 | log::warn!("could not validate TCP stream {} connection from {}", self.stream_idx, address); 284 | }, 285 | Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => { //nothing to do 286 | break; 287 | }, 288 | Err(e) => { 289 | return Err(Box::new(e)); 290 | }, 291 | } 292 | }, 293 | } 294 | } 295 | } 296 | Err(Box::new(simple_error::simple_error!("did not receive a connection"))) 297 | } 298 | } 299 | impl super::TestStream for TcpReceiver { 300 | fn run_interval(&mut self) -> Option>> { 301 | let mut bytes_received:u64 = 0; 302 | 303 | if self.stream.is_none() { //if still in the setup phase, receive the sender 304 | match self.process_connection() { 305 | Ok(stream) => { 306 | self.stream = Some(stream); 307 | //NOTE: the connection process consumes the test-header; account for those bytes 308 | bytes_received += super::TEST_HEADER_SIZE as u64; 309 | }, 310 | Err(e) => { 311 | return Some(Err(e)); 312 | }, 313 | } 314 | self.listener = None; //drop it, closing the socket 315 | } 316 | let stream = self.stream.as_mut().unwrap(); 317 | 318 | let mut events = Events::with_capacity(1); //only watching one socket 319 | let mut buf = vec![0_u8; self.test_definition.length]; 320 | 321 | let peer_addr = match stream.peer_addr() { 322 | Ok(pa) => pa, 323 | Err(e) => return Some(Err(Box::new(e))), 324 | }; 325 | let start = Instant::now(); 326 | 327 | while self.active { 328 | if start.elapsed() >= RECEIVE_TIMEOUT { 329 | return Some(Err(Box::new(simple_error::simple_error!("TCP reception for stream {} from {} timed out", self.stream_idx, peer_addr)))); 330 | } 331 | 332 | log::trace!("awaiting TCP stream {} from {}...", self.stream_idx, peer_addr); 333 | let poll_result = self.mio_poll.poll(&mut events, Some(POLL_TIMEOUT)); 334 | if poll_result.is_err() { 335 | return Some(Err(Box::new(poll_result.unwrap_err()))); 336 | } 337 | for event in events.iter() { 338 | if event.token() == self.mio_poll_token { 339 | loop { 340 | match stream.read(&mut buf) { 341 | Ok(packet_size) => { 342 | log::trace!("received {} bytes in TCP stream {} from {}", packet_size, self.stream_idx, peer_addr); 343 | if packet_size == 0 { //test's over 344 | self.active = false; //HACK: can't call self.stop() because it's a double-borrow due to the unwrapped stream 345 | break; 346 | } 347 | 348 | bytes_received += packet_size as u64; 349 | 350 | let elapsed_time = start.elapsed(); 351 | if elapsed_time >= super::INTERVAL { 352 | return Some(Ok(Box::new(super::TcpReceiveResult{ 353 | timestamp: super::get_unix_timestamp(), 354 | 355 | stream_idx: self.stream_idx, 356 | 357 | duration: elapsed_time.as_secs_f32(), 358 | 359 | bytes_received: bytes_received, 360 | }))) 361 | } 362 | }, 363 | Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { //receive timeout 364 | break; 365 | }, 366 | Err(e) => { 367 | return Some(Err(Box::new(e))); 368 | }, 369 | } 370 | } 371 | } else { 372 | log::warn!("got event for unbound token: {:?}", event); 373 | } 374 | } 375 | } 376 | if bytes_received > 0 { 377 | Some(Ok(Box::new(super::TcpReceiveResult{ 378 | timestamp: super::get_unix_timestamp(), 379 | 380 | stream_idx: self.stream_idx, 381 | 382 | duration: start.elapsed().as_secs_f32(), 383 | 384 | bytes_received: bytes_received, 385 | }))) 386 | } else { 387 | None 388 | } 389 | } 390 | 391 | fn get_port(&self) -> super::BoxResult { 392 | match &self.listener { 393 | Some(listener) => Ok(listener.local_addr()?.port()), 394 | None => match &self.stream { 395 | Some(stream) => Ok(stream.local_addr()?.port()), 396 | None => Err(Box::new(simple_error::simple_error!("no port currently bound"))), 397 | } 398 | } 399 | } 400 | 401 | fn get_idx(&self) -> u8 { 402 | self.stream_idx.to_owned() 403 | } 404 | 405 | fn stop(&mut self) { 406 | self.active = false; 407 | } 408 | } 409 | } 410 | 411 | 412 | 413 | pub mod sender { 414 | use std::io::Write; 415 | use std::net::{IpAddr, SocketAddr}; 416 | use std::os::unix::io::AsRawFd; 417 | use std::time::{Duration, Instant}; 418 | 419 | use mio::net::TcpStream; 420 | 421 | use std::thread::{sleep}; 422 | 423 | const CONNECT_TIMEOUT:Duration = Duration::from_secs(2); 424 | const WRITE_TIMEOUT:Duration = Duration::from_millis(50); 425 | const BUFFER_FULL_TIMEOUT:Duration = Duration::from_millis(1); 426 | 427 | pub struct TcpSender { 428 | active: bool, 429 | test_definition: super::TcpTestDefinition, 430 | stream_idx: u8, 431 | 432 | socket_addr: SocketAddr, 433 | stream: Option, 434 | 435 | //the interval, in seconds, at which to send data 436 | send_interval: f32, 437 | 438 | remaining_duration: f32, 439 | staged_buffer: Vec, 440 | 441 | send_buffer:usize, 442 | no_delay:bool, 443 | } 444 | impl TcpSender { 445 | pub fn new(test_definition:super::TcpTestDefinition, stream_idx:&u8, receiver_ip:&IpAddr, receiver_port:&u16, send_duration:&f32, send_interval:&f32, send_buffer:&usize, no_delay:&bool) -> super::BoxResult { 446 | let mut staged_buffer = vec![0_u8; test_definition.length]; 447 | for i in super::TEST_HEADER_SIZE..(staged_buffer.len()) { //fill the packet with a fixed sequence 448 | staged_buffer[i] = (i % 256) as u8; 449 | } 450 | //embed the test ID 451 | staged_buffer[0..16].copy_from_slice(&test_definition.test_id); 452 | 453 | Ok(TcpSender{ 454 | active: true, 455 | test_definition: test_definition, 456 | stream_idx: stream_idx.to_owned(), 457 | 458 | socket_addr: SocketAddr::new(*receiver_ip, *receiver_port), 459 | stream: None, 460 | 461 | send_interval: send_interval.to_owned(), 462 | 463 | remaining_duration: send_duration.to_owned(), 464 | staged_buffer: staged_buffer, 465 | 466 | send_buffer: send_buffer.to_owned(), 467 | no_delay: no_delay.to_owned(), 468 | }) 469 | } 470 | 471 | fn process_connection(&mut self) -> super::BoxResult { 472 | log::debug!("preparing to connect TCP stream {}...", self.stream_idx); 473 | 474 | let raw_stream = match std::net::TcpStream::connect_timeout(&self.socket_addr, CONNECT_TIMEOUT) { 475 | Ok(s) => s, 476 | Err(e) => return Err(Box::new(simple_error::simple_error!("unable to connect stream {}: {}", self.stream_idx, e))), 477 | }; 478 | raw_stream.set_write_timeout(Some(WRITE_TIMEOUT))?; 479 | let stream = match TcpStream::from_stream(raw_stream) { 480 | Ok(s) => s, 481 | Err(e) => return Err(Box::new(simple_error::simple_error!("unable to prepare TCP stream {}: {}", self.stream_idx, e))), 482 | }; 483 | log::debug!("connected TCP stream {} to {}", self.stream_idx, stream.peer_addr()?); 484 | 485 | if self.no_delay { 486 | log::debug!("setting no-delay..."); 487 | stream.set_nodelay(true)?; 488 | } 489 | if !cfg!(windows) { //NOTE: features unsupported on Windows 490 | if self.send_buffer != 0 { 491 | log::debug!("setting send-buffer to {}...", self.send_buffer); 492 | super::setsockopt(stream.as_raw_fd(), super::SndBuf, &self.send_buffer)?; 493 | } 494 | } 495 | Ok(stream) 496 | } 497 | } 498 | impl super::TestStream for TcpSender { 499 | fn run_interval(&mut self) -> Option>> { 500 | if self.stream.is_none() { //if still in the setup phase, connect to the receiver 501 | match self.process_connection() { 502 | Ok(stream) => { 503 | self.stream = Some(stream); 504 | }, 505 | Err(e) => { 506 | return Some(Err(e)); 507 | }, 508 | } 509 | } 510 | let stream = self.stream.as_mut().unwrap(); 511 | 512 | 513 | let interval_duration = Duration::from_secs_f32(self.send_interval); 514 | let mut interval_iteration = 0; 515 | let bytes_to_send = ((self.test_definition.bandwidth as f32) * super::INTERVAL.as_secs_f32()) as i64; 516 | let mut bytes_to_send_remaining = bytes_to_send; 517 | let bytes_to_send_per_interval_slice = ((bytes_to_send as f32) * self.send_interval) as i64; 518 | let mut bytes_to_send_per_interval_slice_remaining = bytes_to_send_per_interval_slice; 519 | 520 | let mut sends_blocked:u64 = 0; 521 | let mut bytes_sent:u64 = 0; 522 | 523 | let peer_addr = match stream.peer_addr() { 524 | Ok(pa) => pa, 525 | Err(e) => return Some(Err(Box::new(e))), 526 | }; 527 | let cycle_start = Instant::now(); 528 | 529 | while self.active && self.remaining_duration > 0.0 && bytes_to_send_remaining > 0 { 530 | log::trace!("writing {} bytes in TCP stream {} to {}...", self.staged_buffer.len(), self.stream_idx, peer_addr); 531 | let packet_start = Instant::now(); 532 | 533 | match stream.write(&self.staged_buffer) { //it doesn't matter if the whole thing couldn't be written, since it's just garbage data 534 | Ok(packet_size) => { 535 | log::trace!("wrote {} bytes in TCP stream {} to {}", packet_size, self.stream_idx, peer_addr); 536 | 537 | let bytes_written = packet_size as i64; 538 | bytes_sent += bytes_written as u64; 539 | bytes_to_send_remaining -= bytes_written; 540 | bytes_to_send_per_interval_slice_remaining -= bytes_written; 541 | 542 | let elapsed_time = cycle_start.elapsed(); 543 | if elapsed_time >= super::INTERVAL { 544 | self.remaining_duration -= packet_start.elapsed().as_secs_f32(); 545 | 546 | return Some(Ok(Box::new(super::TcpSendResult{ 547 | timestamp: super::get_unix_timestamp(), 548 | 549 | stream_idx: self.stream_idx, 550 | 551 | duration: elapsed_time.as_secs_f32(), 552 | 553 | bytes_sent: bytes_sent, 554 | sends_blocked: sends_blocked, 555 | }))) 556 | } 557 | }, 558 | Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { //send-buffer is full 559 | //nothing to do, but avoid burning CPU cycles 560 | sleep(BUFFER_FULL_TIMEOUT); 561 | sends_blocked += 1; 562 | }, 563 | Err(e) => { 564 | return Some(Err(Box::new(e))); 565 | }, 566 | } 567 | 568 | if bytes_to_send_remaining <= 0 { //interval's target is exhausted, so sleep until the end 569 | let elapsed_time = cycle_start.elapsed(); 570 | if super::INTERVAL > elapsed_time { 571 | sleep(super::INTERVAL - elapsed_time); 572 | } 573 | } else if bytes_to_send_per_interval_slice_remaining <= 0 { // interval subsection exhausted 574 | interval_iteration += 1; 575 | bytes_to_send_per_interval_slice_remaining = bytes_to_send_per_interval_slice; 576 | let elapsed_time = cycle_start.elapsed(); 577 | let interval_endtime = interval_iteration * interval_duration; 578 | if interval_endtime > elapsed_time { 579 | sleep(interval_endtime - elapsed_time); 580 | } 581 | } 582 | self.remaining_duration -= packet_start.elapsed().as_secs_f32(); 583 | } 584 | if bytes_sent > 0 { 585 | Some(Ok(Box::new(super::TcpSendResult{ 586 | timestamp: super::get_unix_timestamp(), 587 | 588 | stream_idx: self.stream_idx, 589 | 590 | duration: cycle_start.elapsed().as_secs_f32(), 591 | 592 | bytes_sent: bytes_sent, 593 | sends_blocked: sends_blocked, 594 | }))) 595 | } else { 596 | //indicate that the test is over by dropping the stream 597 | self.stream = None; 598 | None 599 | } 600 | } 601 | 602 | fn get_port(&self) -> super::BoxResult { 603 | match &self.stream { 604 | Some(stream) => Ok(stream.local_addr()?.port()), 605 | None => Err(Box::new(simple_error::simple_error!("no stream currently exists"))), 606 | } 607 | } 608 | 609 | fn get_idx(&self) -> u8 { 610 | self.stream_idx.to_owned() 611 | } 612 | 613 | fn stop(&mut self) { 614 | self.active = false; 615 | } 616 | } 617 | } 618 | -------------------------------------------------------------------------------- /src/stream/udp.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2021 Evtech Solutions, Ltd., dba 3D-P 3 | * Copyright (C) 2021 Neil Tallim 4 | * 5 | * This file is part of rperf. 6 | * 7 | * rperf is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * rperf is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with rperf. If not, see . 19 | */ 20 | 21 | extern crate log; 22 | extern crate nix; 23 | 24 | use std::error::Error; 25 | 26 | use nix::sys::socket::{setsockopt, sockopt::RcvBuf, sockopt::SndBuf}; 27 | 28 | use crate::protocol::results::{IntervalResult, UdpReceiveResult, UdpSendResult, get_unix_timestamp}; 29 | 30 | use super::{INTERVAL, TestStream, parse_port_spec}; 31 | 32 | type BoxResult = Result>; 33 | 34 | pub const TEST_HEADER_SIZE:u16 = 36; 35 | const UDP_HEADER_SIZE:u16 = 8; 36 | 37 | #[derive(Clone)] 38 | pub struct UdpTestDefinition { 39 | //a UUID used to identify packets associated with this test 40 | pub test_id: [u8; 16], 41 | //bandwidth target, in bytes/sec 42 | pub bandwidth: u64, 43 | //the length of the buffer to exchange 44 | pub length: u16, 45 | } 46 | impl UdpTestDefinition { 47 | pub fn new(details:&serde_json::Value) -> super::BoxResult { 48 | let mut test_id_bytes = [0_u8; 16]; 49 | for (i, v) in details.get("test_id").unwrap_or(&serde_json::json!([])).as_array().unwrap().iter().enumerate() { 50 | if i >= 16 { //avoid out-of-bounds if given malicious data 51 | break; 52 | } 53 | test_id_bytes[i] = v.as_i64().unwrap_or(0) as u8; 54 | } 55 | 56 | let length = details.get("length").unwrap_or(&serde_json::json!(TEST_HEADER_SIZE)).as_i64().unwrap() as u16; 57 | if length < TEST_HEADER_SIZE { 58 | return Err(Box::new(simple_error::simple_error!(std::format!("{} is too short of a length to satisfy testing requirements", length)))); 59 | } 60 | 61 | Ok(UdpTestDefinition{ 62 | test_id: test_id_bytes, 63 | bandwidth: details.get("bandwidth").unwrap_or(&serde_json::json!(0.0)).as_f64().unwrap() as u64, 64 | length: length, 65 | }) 66 | } 67 | } 68 | 69 | pub mod receiver { 70 | use std::convert::TryInto; 71 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; 72 | use std::os::unix::io::AsRawFd; 73 | use std::sync::{Mutex}; 74 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 75 | 76 | use chrono::{NaiveDateTime}; 77 | 78 | use std::net::UdpSocket; 79 | 80 | const READ_TIMEOUT:Duration = Duration::from_millis(50); 81 | const RECEIVE_TIMEOUT:Duration = Duration::from_secs(3); 82 | 83 | pub struct UdpPortPool { 84 | pub ports_ip4: Vec, 85 | pos_ip4: usize, 86 | lock_ip4: Mutex, 87 | 88 | pub ports_ip6: Vec, 89 | pos_ip6: usize, 90 | lock_ip6: Mutex, 91 | } 92 | impl UdpPortPool { 93 | pub fn new(port_spec:String, port_spec6:String) -> UdpPortPool { 94 | let ports = super::parse_port_spec(port_spec); 95 | if !ports.is_empty() { 96 | log::debug!("configured IPv4 UDP port pool: {:?}", ports); 97 | } else { 98 | log::debug!("using OS assignment for IPv4 UDP ports"); 99 | } 100 | 101 | let ports6 = super::parse_port_spec(port_spec6); 102 | if !ports.is_empty() { 103 | log::debug!("configured IPv6 UDP port pool: {:?}", ports6); 104 | } else { 105 | log::debug!("using OS assignment for IPv6 UDP ports"); 106 | } 107 | 108 | UdpPortPool { 109 | ports_ip4: ports, 110 | pos_ip4: 0, 111 | lock_ip4: Mutex::new(0), 112 | 113 | ports_ip6: ports6, 114 | pos_ip6: 0, 115 | lock_ip6: Mutex::new(0), 116 | } 117 | } 118 | 119 | pub fn bind(&mut self, peer_ip:&IpAddr) -> super::BoxResult { 120 | match peer_ip { 121 | IpAddr::V6(_) => { 122 | if self.ports_ip6.is_empty() { 123 | return Ok(UdpSocket::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0)).expect(format!("failed to bind OS-assigned IPv6 UDP socket").as_str())); 124 | } else { 125 | let _guard = self.lock_ip6.lock().unwrap(); 126 | 127 | for port_idx in (self.pos_ip6 + 1)..self.ports_ip6.len() { //iterate to the end of the pool; this will skip the first element in the pool initially, but that's fine 128 | let listener_result = UdpSocket::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), self.ports_ip6[port_idx])); 129 | if listener_result.is_ok() { 130 | self.pos_ip6 = port_idx; 131 | return Ok(listener_result.unwrap()); 132 | } else { 133 | log::warn!("unable to bind IPv6 UDP port {}", self.ports_ip6[port_idx]); 134 | } 135 | } 136 | for port_idx in 0..=self.pos_ip6 { //circle back to where the search started 137 | let listener_result = UdpSocket::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), self.ports_ip6[port_idx])); 138 | if listener_result.is_ok() { 139 | self.pos_ip6 = port_idx; 140 | return Ok(listener_result.unwrap()); 141 | } else { 142 | log::warn!("unable to bind IPv6 UDP port {}", self.ports_ip6[port_idx]); 143 | } 144 | } 145 | } 146 | return Err(Box::new(simple_error::simple_error!("unable to allocate IPv6 UDP port"))); 147 | }, 148 | IpAddr::V4(_) => { 149 | if self.ports_ip4.is_empty() { 150 | return Ok(UdpSocket::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)).expect(format!("failed to bind OS-assigned IPv4 UDP socket").as_str())); 151 | } else { 152 | let _guard = self.lock_ip4.lock().unwrap(); 153 | 154 | for port_idx in (self.pos_ip4 + 1)..self.ports_ip4.len() { //iterate to the end of the pool; this will skip the first element in the pool initially, but that's fine 155 | let listener_result = UdpSocket::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), self.ports_ip4[port_idx])); 156 | if listener_result.is_ok() { 157 | self.pos_ip4 = port_idx; 158 | return Ok(listener_result.unwrap()); 159 | } else { 160 | log::warn!("unable to bind IPv4 UDP port {}", self.ports_ip4[port_idx]); 161 | } 162 | } 163 | for port_idx in 0..=self.pos_ip4 { //circle back to where the search started 164 | let listener_result = UdpSocket::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), self.ports_ip4[port_idx])); 165 | if listener_result.is_ok() { 166 | self.pos_ip4 = port_idx; 167 | return Ok(listener_result.unwrap()); 168 | } else { 169 | log::warn!("unable to bind IPv4 UDP port {}", self.ports_ip4[port_idx]); 170 | } 171 | } 172 | } 173 | return Err(Box::new(simple_error::simple_error!("unable to allocate IPv4 UDP port"))); 174 | }, 175 | }; 176 | } 177 | } 178 | 179 | struct UdpReceiverIntervalHistory { 180 | packets_received: u64, 181 | 182 | packets_lost: i64, 183 | packets_out_of_order: u64, 184 | packets_duplicated: u64, 185 | 186 | unbroken_sequence: u64, 187 | jitter_seconds: Option, 188 | longest_unbroken_sequence: u64, 189 | longest_jitter_seconds: Option, 190 | previous_time_delta_nanoseconds: i64, 191 | } 192 | 193 | pub struct UdpReceiver { 194 | active: bool, 195 | test_definition: super::UdpTestDefinition, 196 | stream_idx: u8, 197 | next_packet_id: u64, 198 | 199 | socket: UdpSocket, 200 | } 201 | impl UdpReceiver { 202 | pub fn new(test_definition:super::UdpTestDefinition, stream_idx:&u8, port_pool:&mut UdpPortPool, peer_ip:&IpAddr, receive_buffer:&usize) -> super::BoxResult { 203 | log::debug!("binding UDP receive socket for stream {}...", stream_idx); 204 | let socket:UdpSocket = port_pool.bind(peer_ip).expect(format!("failed to bind UDP socket").as_str()); 205 | socket.set_read_timeout(Some(READ_TIMEOUT))?; 206 | if !cfg!(windows) { //NOTE: features unsupported on Windows 207 | if *receive_buffer != 0 { 208 | log::debug!("setting receive-buffer to {}...", receive_buffer); 209 | super::setsockopt(socket.as_raw_fd(), super::RcvBuf, receive_buffer)?; 210 | } 211 | } 212 | log::debug!("bound UDP receive socket for stream {}: {}", stream_idx, socket.local_addr()?); 213 | 214 | Ok(UdpReceiver{ 215 | active: true, 216 | test_definition: test_definition, 217 | stream_idx: stream_idx.to_owned(), 218 | 219 | next_packet_id: 0, 220 | 221 | socket: socket, 222 | }) 223 | } 224 | 225 | fn process_packets_ordering(&mut self, packet_id:u64, mut history:&mut UdpReceiverIntervalHistory) -> bool { 226 | /* the algorithm from iperf3 provides a pretty decent approximation 227 | * for tracking lost and out-of-order packets efficiently, so it's 228 | * been minimally reimplemented here, with corrections. 229 | * 230 | * returns true if packet-ordering is as-expected 231 | */ 232 | if packet_id == self.next_packet_id { //expected sequential-ordering case 233 | self.next_packet_id += 1; 234 | return true; 235 | } else if packet_id > self.next_packet_id { //something was either lost or there's an ordering problem 236 | let lost_packet_count = (packet_id - self.next_packet_id) as i64; 237 | log::debug!("UDP reception for stream {} observed a gap of {} packets", self.stream_idx, lost_packet_count); 238 | history.packets_lost += lost_packet_count; //assume everything in-between has been lost 239 | self.next_packet_id = packet_id + 1; //anticipate that ordered receipt will resume 240 | } else { //a packet with a previous ID was received; this is either a duplicate or an ordering issue 241 | //CAUTION: this is where the approximation part of the algorithm comes into play 242 | if history.packets_lost > 0 { //assume it's an ordering issue in the common case 243 | history.packets_lost -= 1; 244 | history.packets_out_of_order += 1; 245 | } else { //the only other thing it could be is a duplicate; in practice, duplicates don't tend to show up alongside losses; non-zero is always bad, though 246 | history.packets_duplicated += 1; 247 | } 248 | } 249 | return false; 250 | } 251 | 252 | fn process_jitter(&mut self, timestamp:&NaiveDateTime, history:&mut UdpReceiverIntervalHistory) { 253 | /* this is a pretty straightforward implementation of RFC 1889, Appendix 8 254 | * it works on an assumption that the timestamp delta between sender and receiver 255 | * will remain effectively constant during the testing window 256 | */ 257 | let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before UNIX epoch"); 258 | let current_timestamp = NaiveDateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos()); 259 | 260 | let time_delta = current_timestamp - *timestamp; 261 | 262 | let time_delta_nanoseconds = match time_delta.num_nanoseconds() { 263 | Some(ns) => ns, 264 | None => { 265 | log::warn!("sender and receiver clocks are too out-of-sync to calculate jitter"); 266 | return; 267 | }, 268 | }; 269 | 270 | if history.unbroken_sequence > 1 { //do jitter calculation 271 | let delta_seconds = (time_delta_nanoseconds - history.previous_time_delta_nanoseconds).abs() as f32 / 1_000_000_000.00; 272 | 273 | if history.unbroken_sequence > 2 { //normal jitter-calculation, per the RFC 274 | let mut jitter_seconds = history.jitter_seconds.unwrap(); //since we have a chain, this won't be None 275 | jitter_seconds += (delta_seconds - jitter_seconds) / 16.0; 276 | history.jitter_seconds = Some(jitter_seconds); 277 | } else { //first observed transition; use this as the calibration baseline 278 | history.jitter_seconds = Some(delta_seconds); 279 | } 280 | } 281 | //update time-delta 282 | history.previous_time_delta_nanoseconds = time_delta_nanoseconds; 283 | } 284 | 285 | fn process_packet(&mut self, packet:&[u8], mut history:&mut UdpReceiverIntervalHistory) -> bool { 286 | //the first sixteen bytes are the test's ID 287 | if packet[0..16] != self.test_definition.test_id { 288 | return false 289 | } 290 | 291 | //the next eight bytes are the packet's ID, in big-endian order 292 | let packet_id = u64::from_be_bytes(packet[16..24].try_into().unwrap()); 293 | 294 | //except for the timestamp, nothing else in the packet actually matters 295 | 296 | history.packets_received += 1; 297 | if self.process_packets_ordering(packet_id, &mut history) { 298 | //the second eight are the number of seconds since the UNIX epoch, in big-endian order 299 | let origin_seconds = i64::from_be_bytes(packet[24..32].try_into().unwrap()); 300 | //and the following four are the number of nanoseconds since the UNIX epoch 301 | let origin_nanoseconds = u32::from_be_bytes(packet[32..36].try_into().unwrap()); 302 | let source_timestamp = NaiveDateTime::from_timestamp(origin_seconds, origin_nanoseconds); 303 | 304 | history.unbroken_sequence += 1; 305 | self.process_jitter(&source_timestamp, &mut history); 306 | 307 | if history.unbroken_sequence > history.longest_unbroken_sequence { 308 | history.longest_unbroken_sequence = history.unbroken_sequence; 309 | history.longest_jitter_seconds = history.jitter_seconds; 310 | } 311 | } else { 312 | history.unbroken_sequence = 0; 313 | history.jitter_seconds = None; 314 | } 315 | return true; 316 | } 317 | } 318 | impl super::TestStream for UdpReceiver { 319 | fn run_interval(&mut self) -> Option>> { 320 | let mut buf = vec![0_u8; self.test_definition.length.into()]; 321 | 322 | let mut bytes_received:u64 = 0; 323 | 324 | let mut history = UdpReceiverIntervalHistory{ 325 | packets_received: 0, 326 | 327 | packets_lost: 0, 328 | packets_out_of_order: 0, 329 | packets_duplicated: 0, 330 | 331 | unbroken_sequence: 0, 332 | jitter_seconds: None, 333 | longest_unbroken_sequence: 0, 334 | longest_jitter_seconds: None, 335 | previous_time_delta_nanoseconds: 0, 336 | }; 337 | 338 | let start = Instant::now(); 339 | 340 | while self.active { 341 | if start.elapsed() >= RECEIVE_TIMEOUT { 342 | return Some(Err(Box::new(simple_error::simple_error!("UDP reception for stream {} timed out, likely because the end-signal was lost", self.stream_idx)))); 343 | } 344 | 345 | log::trace!("awaiting UDP packets on stream {}...", self.stream_idx); 346 | loop { 347 | match self.socket.recv_from(&mut buf) { 348 | Ok((packet_size, peer_addr)) => { 349 | log::trace!("received {} bytes in UDP packet {} from {}", packet_size, self.stream_idx, peer_addr); 350 | if packet_size == 16 { //possible end-of-test message 351 | if &buf[0..16] == self.test_definition.test_id { //test's over 352 | self.stop(); 353 | break; 354 | } 355 | } 356 | if packet_size < super::TEST_HEADER_SIZE as usize { 357 | log::warn!("received malformed packet with size {} for UDP stream {} from {}", packet_size, self.stream_idx, peer_addr); 358 | continue; 359 | } 360 | 361 | if self.process_packet(&buf, &mut history) { 362 | //NOTE: duplicate packets increase this count; this is intentional because the stack still processed data 363 | bytes_received += packet_size as u64 + super::UDP_HEADER_SIZE as u64; 364 | 365 | let elapsed_time = start.elapsed(); 366 | if elapsed_time >= super::INTERVAL { 367 | return Some(Ok(Box::new(super::UdpReceiveResult{ 368 | timestamp: super::get_unix_timestamp(), 369 | 370 | stream_idx: self.stream_idx, 371 | 372 | duration: elapsed_time.as_secs_f32(), 373 | 374 | bytes_received: bytes_received, 375 | packets_received: history.packets_received, 376 | packets_lost: history.packets_lost, 377 | packets_out_of_order: history.packets_out_of_order, 378 | packets_duplicated: history.packets_duplicated, 379 | 380 | unbroken_sequence: history.longest_unbroken_sequence, 381 | jitter_seconds: history.longest_jitter_seconds, 382 | }))) 383 | } 384 | } else { 385 | log::warn!("received packet unrelated to UDP stream {} from {}", self.stream_idx, peer_addr); 386 | continue; 387 | } 388 | }, 389 | Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { //receive timeout 390 | break; 391 | }, 392 | Err(e) => { 393 | return Some(Err(Box::new(e))); 394 | }, 395 | } 396 | } 397 | } 398 | if bytes_received > 0 { 399 | Some(Ok(Box::new(super::UdpReceiveResult{ 400 | timestamp: super::get_unix_timestamp(), 401 | 402 | stream_idx: self.stream_idx, 403 | 404 | duration: start.elapsed().as_secs_f32(), 405 | 406 | bytes_received: bytes_received, 407 | packets_received: history.packets_received, 408 | packets_lost: history.packets_lost, 409 | packets_out_of_order: history.packets_out_of_order, 410 | packets_duplicated: history.packets_duplicated, 411 | 412 | unbroken_sequence: history.longest_unbroken_sequence, 413 | jitter_seconds: history.longest_jitter_seconds, 414 | }))) 415 | } else { 416 | None 417 | } 418 | } 419 | 420 | fn get_port(&self) -> super::BoxResult { 421 | let socket_addr = self.socket.local_addr()?; 422 | Ok(socket_addr.port()) 423 | } 424 | 425 | fn get_idx(&self) -> u8 { 426 | self.stream_idx.to_owned() 427 | } 428 | 429 | fn stop(&mut self) { 430 | self.active = false; 431 | } 432 | } 433 | } 434 | 435 | 436 | 437 | pub mod sender { 438 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; 439 | use std::os::unix::io::AsRawFd; 440 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 441 | 442 | use std::net::UdpSocket; 443 | 444 | use std::thread::{sleep}; 445 | 446 | const WRITE_TIMEOUT:Duration = Duration::from_millis(50); 447 | const BUFFER_FULL_TIMEOUT:Duration = Duration::from_millis(1); 448 | 449 | pub struct UdpSender { 450 | active: bool, 451 | test_definition: super::UdpTestDefinition, 452 | stream_idx: u8, 453 | 454 | socket: UdpSocket, 455 | 456 | //the interval, in seconds, at which to send data 457 | send_interval: f32, 458 | 459 | remaining_duration: f32, 460 | next_packet_id: u64, 461 | staged_packet: Vec, 462 | } 463 | impl UdpSender { 464 | pub fn new(test_definition:super::UdpTestDefinition, stream_idx:&u8, port:&u16, receiver_ip:&IpAddr, receiver_port:&u16, send_duration:&f32, send_interval:&f32, send_buffer:&usize) -> super::BoxResult { 465 | log::debug!("preparing to connect UDP stream {}...", stream_idx); 466 | let socket_addr_receiver = SocketAddr::new(*receiver_ip, *receiver_port); 467 | let socket = match receiver_ip { 468 | IpAddr::V6(_) => UdpSocket::bind(&SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), *port)).expect(format!("failed to bind UDP socket, port {}", port).as_str()), 469 | IpAddr::V4(_) => UdpSocket::bind(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), *port)).expect(format!("failed to bind UDP socket, port {}", port).as_str()), 470 | }; 471 | socket.set_write_timeout(Some(WRITE_TIMEOUT))?; 472 | if !cfg!(windows) { //NOTE: features unsupported on Windows 473 | if *send_buffer != 0 { 474 | log::debug!("setting send-buffer to {}...", send_buffer); 475 | super::setsockopt(socket.as_raw_fd(), super::SndBuf, send_buffer)?; 476 | } 477 | } 478 | socket.connect(socket_addr_receiver)?; 479 | log::debug!("connected UDP stream {} to {}", stream_idx, socket_addr_receiver); 480 | 481 | let mut staged_packet = vec![0_u8; test_definition.length.into()]; 482 | for i in super::TEST_HEADER_SIZE..(staged_packet.len() as u16) { //fill the packet with a fixed sequence 483 | staged_packet[i as usize] = (i % 256) as u8; 484 | } 485 | //embed the test ID 486 | staged_packet[0..16].copy_from_slice(&test_definition.test_id); 487 | 488 | Ok(UdpSender{ 489 | active: true, 490 | test_definition: test_definition, 491 | stream_idx: stream_idx.to_owned(), 492 | 493 | socket: socket, 494 | 495 | send_interval: send_interval.to_owned(), 496 | 497 | remaining_duration: send_duration.to_owned(), 498 | next_packet_id: 0, 499 | staged_packet: staged_packet, 500 | }) 501 | } 502 | 503 | fn prepare_packet(&mut self) { 504 | let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before UNIX epoch"); 505 | 506 | //eight bytes after the test ID are the packet's ID, in big-endian order 507 | self.staged_packet[16..24].copy_from_slice(&self.next_packet_id.to_be_bytes()); 508 | 509 | //the next eight are the seconds part of the UNIX timestamp and the following four are the nanoseconds 510 | self.staged_packet[24..32].copy_from_slice(&now.as_secs().to_be_bytes()); 511 | self.staged_packet[32..36].copy_from_slice(&now.subsec_nanos().to_be_bytes()); 512 | } 513 | } 514 | impl super::TestStream for UdpSender { 515 | fn run_interval(&mut self) -> Option>> { 516 | let interval_duration = Duration::from_secs_f32(self.send_interval); 517 | let mut interval_iteration = 0; 518 | let bytes_to_send = ((self.test_definition.bandwidth as f32) * super::INTERVAL.as_secs_f32()) as i64; 519 | let mut bytes_to_send_remaining = bytes_to_send; 520 | let bytes_to_send_per_interval_slice = ((bytes_to_send as f32) * self.send_interval) as i64; 521 | let mut bytes_to_send_per_interval_slice_remaining = bytes_to_send_per_interval_slice; 522 | 523 | let mut packets_sent:u64 = 0; 524 | let mut sends_blocked:u64 = 0; 525 | let mut bytes_sent:u64 = 0; 526 | 527 | let cycle_start = Instant::now(); 528 | 529 | while self.active && self.remaining_duration > 0.0 && bytes_to_send_remaining > 0 { 530 | log::trace!("writing {} bytes in UDP stream {}...", self.staged_packet.len(), self.stream_idx); 531 | let packet_start = Instant::now(); 532 | 533 | self.prepare_packet(); 534 | match self.socket.send(&self.staged_packet) { 535 | Ok(packet_size) => { 536 | log::trace!("wrote {} bytes in UDP stream {}", packet_size, self.stream_idx); 537 | 538 | packets_sent += 1; 539 | //reflect that a packet is in-flight 540 | self.next_packet_id += 1; 541 | 542 | let bytes_written = packet_size as i64 + super::UDP_HEADER_SIZE as i64; 543 | bytes_sent += bytes_written as u64; 544 | bytes_to_send_remaining -= bytes_written; 545 | bytes_to_send_per_interval_slice_remaining -= bytes_written; 546 | 547 | let elapsed_time = cycle_start.elapsed(); 548 | if elapsed_time >= super::INTERVAL { 549 | self.remaining_duration -= packet_start.elapsed().as_secs_f32(); 550 | 551 | return Some(Ok(Box::new(super::UdpSendResult{ 552 | timestamp: super::get_unix_timestamp(), 553 | 554 | stream_idx: self.stream_idx, 555 | 556 | duration: elapsed_time.as_secs_f32(), 557 | 558 | bytes_sent: bytes_sent, 559 | packets_sent: packets_sent, 560 | sends_blocked: sends_blocked, 561 | }))) 562 | } 563 | }, 564 | Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { //send-buffer is full 565 | //nothing to do, but avoid burning CPU cycles 566 | sleep(BUFFER_FULL_TIMEOUT); 567 | sends_blocked += 1; 568 | }, 569 | Err(e) => { 570 | return Some(Err(Box::new(e))); 571 | }, 572 | } 573 | 574 | if bytes_to_send_remaining <= 0 { //interval's target is exhausted, so sleep until the end 575 | let elapsed_time = cycle_start.elapsed(); 576 | if super::INTERVAL > elapsed_time { 577 | sleep(super::INTERVAL - elapsed_time); 578 | } 579 | } else if bytes_to_send_per_interval_slice_remaining <= 0 { // interval subsection exhausted 580 | interval_iteration += 1; 581 | bytes_to_send_per_interval_slice_remaining = bytes_to_send_per_interval_slice; 582 | let elapsed_time = cycle_start.elapsed(); 583 | let interval_endtime = interval_iteration * interval_duration; 584 | if interval_endtime > elapsed_time { 585 | sleep(interval_endtime - elapsed_time); 586 | } 587 | } 588 | self.remaining_duration -= packet_start.elapsed().as_secs_f32(); 589 | } 590 | if bytes_sent > 0 { 591 | Some(Ok(Box::new(super::UdpSendResult{ 592 | timestamp: super::get_unix_timestamp(), 593 | 594 | stream_idx: self.stream_idx, 595 | 596 | duration: cycle_start.elapsed().as_secs_f32(), 597 | 598 | bytes_sent: bytes_sent, 599 | packets_sent: packets_sent, 600 | sends_blocked: sends_blocked, 601 | }))) 602 | } else { 603 | //indicate that the test is over by sending the test ID by itself 604 | let mut remaining_announcements = 5; 605 | while remaining_announcements > 0 { //do it a few times in case of loss 606 | match self.socket.send(&self.staged_packet[0..16]) { 607 | Ok(packet_size) => { 608 | log::trace!("wrote {} bytes of test-end signal in UDP stream {}", packet_size, self.stream_idx); 609 | remaining_announcements -= 1; 610 | }, 611 | Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { //send-buffer is full 612 | //wait to try again and avoid burning CPU cycles 613 | sleep(BUFFER_FULL_TIMEOUT); 614 | }, 615 | Err(e) => { 616 | return Some(Err(Box::new(e))); 617 | }, 618 | } 619 | } 620 | None 621 | } 622 | } 623 | 624 | fn get_port(&self) -> super::BoxResult { 625 | let socket_addr = self.socket.local_addr()?; 626 | Ok(socket_addr.port()) 627 | } 628 | 629 | fn get_idx(&self) -> u8 { 630 | self.stream_idx.to_owned() 631 | } 632 | 633 | fn stop(&mut self) { 634 | self.active = false; 635 | } 636 | } 637 | } 638 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | --------------------------------------------------------------------------------