├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── virtualnet ├── .gitignore ├── Cargo.toml ├── README.md └── src ├── interface.rs ├── lib.rs ├── middleware.rs └── vnet.rs /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Nikita Baksalyar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Low-Level Academy WebAssembly modules 2 | 3 | This repository contains the back-end code used in [Low-Level Academy](https://lowlvl.org). 4 | 5 | Currently, there is only one project. 6 | 7 | ## virtualnet 8 | 9 | This module implements a virtual network for the "TCP/IP Fundamentals" course. 10 | It is based on [smoltcp](https://github.com/smoltcp-rs), a pure Rust implementation of the TCP/IP stack. 11 | 12 | ## License 13 | 14 | Licensed under either of 15 | 16 | - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 17 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 18 | 19 | at your option. 20 | -------------------------------------------------------------------------------- /virtualnet/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /virtualnet/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "virtualnet" 3 | version = "0.1.0" 4 | authors = ["Nikita Baksalyar "] 5 | edition = "2018" 6 | license = "MIT OR Apache-2.0" 7 | 8 | [lib] 9 | crate-type = ["cdylib"] 10 | 11 | [dependencies] 12 | smoltcp = { git = "https://github.com/nbaksalyar/smoltcp.git", branch = "lowlvl", default-features = false, features = [ "std", "socket-udp", "proto-ipv4", "ethernet" ] } 13 | -------------------------------------------------------------------------------- /virtualnet/README.md: -------------------------------------------------------------------------------- 1 | ## Building the project 2 | 3 | `cargo build --release --target wasm32-unknown-unknown` 4 | -------------------------------------------------------------------------------- /virtualnet/src/interface.rs: -------------------------------------------------------------------------------- 1 | //! This module contains structs & functions that are used by user's code in the course. 2 | //! It's almost entirely copied from smoltcp with a small number of changes, and it's not 3 | //! actually compiled in the target virtual network module - this part of code is here only 4 | //! for testing purposes. In production, it's a part of the front-end code base. 5 | 6 | #![allow(unused)] 7 | 8 | use std::convert::TryInto; 9 | use std::io::ErrorKind; 10 | use std::net::Ipv4Addr; 11 | 12 | type Result = std::io::Result; 13 | 14 | pub type Ipv4Packet = Packet<[u8; 20]>; 15 | 16 | pub mod checksum { 17 | use super::*; 18 | 19 | fn propagate_carries(word: u32) -> u16 { 20 | let sum = (word >> 16) + (word & 0xffff); 21 | ((sum >> 16) as u16) + (sum as u16) 22 | } 23 | 24 | /// Compute an RFC 1071 compliant checksum (without the final complement). 25 | pub fn data(mut data: &[u8]) -> u16 { 26 | let mut accum = 0; 27 | 28 | // For each 32-byte chunk... 29 | const CHUNK_SIZE: usize = 32; 30 | while data.len() >= CHUNK_SIZE { 31 | let mut d = &data[..CHUNK_SIZE]; 32 | // ... take by 2 bytes and sum them. 33 | while d.len() >= 2 { 34 | accum += NetworkEndian::read_u16(d) as u32; 35 | d = &d[2..]; 36 | } 37 | 38 | data = &data[CHUNK_SIZE..]; 39 | } 40 | 41 | // Sum the rest that does not fit the last 32-byte chunk, 42 | // taking by 2 bytes. 43 | while data.len() >= 2 { 44 | accum += NetworkEndian::read_u16(data) as u32; 45 | data = &data[2..]; 46 | } 47 | 48 | // Add the last remaining odd byte, if any. 49 | if let Some(&value) = data.first() { 50 | accum += (value as u32) << 8; 51 | } 52 | 53 | propagate_carries(accum) 54 | } 55 | 56 | /// Combine several RFC 1071 compliant checksums. 57 | pub fn combine(checksums: &[u16]) -> u16 { 58 | let mut accum: u32 = 0; 59 | for &word in checksums { 60 | accum += word as u32; 61 | } 62 | propagate_carries(accum) 63 | } 64 | 65 | /// Compute an IP pseudo header checksum. 66 | pub fn pseudo_header( 67 | src_addr: &Ipv4Addr, 68 | dst_addr: &Ipv4Addr, 69 | protocol: Protocol, 70 | length: u32, 71 | ) -> u16 { 72 | let mut proto_len = [0u8; 4]; 73 | proto_len[1] = protocol.into(); 74 | NetworkEndian::write_u16(&mut proto_len[2..4], length as u16); 75 | 76 | combine(&[ 77 | data(&src_addr.octets()), 78 | data(&dst_addr.octets()), 79 | data(&proto_len[..]), 80 | ]) 81 | } 82 | } 83 | 84 | pub enum Protocol { 85 | HopByHop, 86 | Icmp, 87 | Igmp, 88 | Tcp, 89 | Udp, 90 | Unknown(u8), 91 | } 92 | 93 | impl From for Protocol { 94 | fn from(value: u8) -> Self { 95 | match value { 96 | 0x00 => Protocol::HopByHop, 97 | 0x01 => Protocol::Icmp, 98 | 0x02 => Protocol::Igmp, 99 | 0x06 => Protocol::Tcp, 100 | 0x11 => Protocol::Udp, 101 | other => Protocol::Unknown(other), 102 | } 103 | } 104 | } 105 | 106 | impl From for u8 { 107 | fn from(value: Protocol) -> Self { 108 | match value { 109 | Protocol::HopByHop => 0x00, 110 | Protocol::Icmp => 0x01, 111 | Protocol::Igmp => 0x02, 112 | Protocol::Tcp => 0x06, 113 | Protocol::Udp => 0x11, 114 | Protocol::Unknown(other) => other, 115 | } 116 | } 117 | } 118 | 119 | struct NetworkEndian {} 120 | 121 | impl NetworkEndian { 122 | fn read_u16(input: &[u8]) -> u16 { 123 | let (int_bytes, rest) = input.split_at(std::mem::size_of::()); 124 | u16::from_be_bytes(int_bytes.try_into().unwrap()) 125 | } 126 | 127 | fn read_u32(input: &[u8]) -> u32 { 128 | let (int_bytes, rest) = input.split_at(std::mem::size_of::()); 129 | u32::from_be_bytes(int_bytes.try_into().unwrap()) 130 | } 131 | 132 | fn write_u16(input: &mut [u8], value: u16) { 133 | let bytes = value.to_be_bytes(); 134 | let (int_bytes, rest) = input.split_at_mut(std::mem::size_of::()); 135 | int_bytes.copy_from_slice(&bytes); 136 | } 137 | 138 | fn write_u32(input: &mut [u8], value: u32) { 139 | let bytes = value.to_be_bytes(); 140 | let (int_bytes, rest) = input.split_at_mut(std::mem::size_of::()); 141 | int_bytes.copy_from_slice(&bytes); 142 | } 143 | } 144 | 145 | /// A read/write wrapper around an Internet Protocol version 4 packet buffer. 146 | #[derive(Debug, PartialEq, Clone)] 147 | pub struct Packet> { 148 | buffer: T, 149 | } 150 | 151 | mod field { 152 | pub type Field = ::core::ops::Range; 153 | 154 | pub const VER_IHL: usize = 0; 155 | pub const DSCP_ECN: usize = 1; 156 | pub const LENGTH: Field = 2..4; 157 | pub const IDENT: Field = 4..6; 158 | pub const FLG_OFF: Field = 6..8; 159 | pub const TTL: usize = 8; 160 | pub const PROTOCOL: usize = 9; 161 | pub const CHECKSUM: Field = 10..12; 162 | pub const SRC_ADDR: Field = 12..16; 163 | pub const DST_ADDR: Field = 16..20; 164 | } 165 | 166 | impl> Packet { 167 | /// Imbue a raw octet buffer with IPv4 packet structure. 168 | pub fn new_unchecked(buffer: T) -> Packet { 169 | Packet { buffer } 170 | } 171 | 172 | /// Shorthand for a combination of [new_unchecked] and [check_len]. 173 | /// 174 | /// [new_unchecked]: #method.new_unchecked 175 | /// [check_len]: #method.check_len 176 | pub fn new_checked(buffer: T) -> Result> { 177 | let packet = Self::new_unchecked(buffer); 178 | packet.check_len()?; 179 | Ok(packet) 180 | } 181 | 182 | /// Ensure that no accessor method will panic if called. 183 | pub fn check_len(&self) -> Result<()> { 184 | let len = self.buffer.as_ref().len(); 185 | if len < field::DST_ADDR.end { 186 | Err(std::io::Error::new(ErrorKind::Other, "Truncated")) 187 | } else if len < self.header_len() as usize { 188 | Err(std::io::Error::new(ErrorKind::Other, "Truncated")) 189 | } else if self.header_len() as u16 > self.total_len() { 190 | Err(std::io::Error::new(ErrorKind::Other, "Malformed")) 191 | } else if len < self.total_len() as usize { 192 | Err(std::io::Error::new(ErrorKind::Other, "Truncated")) 193 | } else { 194 | Ok(()) 195 | } 196 | } 197 | 198 | /// Consume the packet, returning the underlying buffer. 199 | pub fn into_inner(self) -> T { 200 | self.buffer 201 | } 202 | 203 | /// Return the version field. 204 | #[inline] 205 | pub fn version(&self) -> u8 { 206 | let data = self.buffer.as_ref(); 207 | data[field::VER_IHL] >> 4 208 | } 209 | 210 | /// Return the header length, in octets. 211 | #[inline] 212 | pub fn header_len(&self) -> u8 { 213 | let data = self.buffer.as_ref(); 214 | (data[field::VER_IHL] & 0x0f) * 4 215 | } 216 | 217 | /// Return the Differential Services Code Point field. 218 | pub fn dscp(&self) -> u8 { 219 | let data = self.buffer.as_ref(); 220 | data[field::DSCP_ECN] >> 2 221 | } 222 | 223 | /// Return the Explicit Congestion Notification field. 224 | pub fn ecn(&self) -> u8 { 225 | let data = self.buffer.as_ref(); 226 | data[field::DSCP_ECN] & 0x03 227 | } 228 | 229 | /// Return the total length field. 230 | #[inline] 231 | pub fn total_len(&self) -> u16 { 232 | let data = self.buffer.as_ref(); 233 | NetworkEndian::read_u16(&data[field::LENGTH]) 234 | } 235 | 236 | /// Return the fragment identification field. 237 | #[inline] 238 | pub fn ident(&self) -> u16 { 239 | let data = self.buffer.as_ref(); 240 | NetworkEndian::read_u16(&data[field::IDENT]) 241 | } 242 | 243 | /// Return the "don't fragment" flag. 244 | #[inline] 245 | pub fn dont_frag(&self) -> bool { 246 | let data = self.buffer.as_ref(); 247 | NetworkEndian::read_u16(&data[field::FLG_OFF]) & 0x4000 != 0 248 | } 249 | 250 | /// Return the "more fragments" flag. 251 | #[inline] 252 | pub fn more_frags(&self) -> bool { 253 | let data = self.buffer.as_ref(); 254 | NetworkEndian::read_u16(&data[field::FLG_OFF]) & 0x2000 != 0 255 | } 256 | 257 | /// Return the fragment offset, in octets. 258 | #[inline] 259 | pub fn frag_offset(&self) -> u16 { 260 | let data = self.buffer.as_ref(); 261 | NetworkEndian::read_u16(&data[field::FLG_OFF]) << 3 262 | } 263 | 264 | /// Return the time to live field. 265 | #[inline] 266 | pub fn hop_limit(&self) -> u8 { 267 | let data = self.buffer.as_ref(); 268 | data[field::TTL] 269 | } 270 | 271 | /// Return the protocol field. 272 | #[inline] 273 | pub fn protocol(&self) -> Protocol { 274 | let data = self.buffer.as_ref(); 275 | Protocol::from(data[field::PROTOCOL]) 276 | } 277 | 278 | /// Return the header checksum field. 279 | #[inline] 280 | pub fn checksum(&self) -> u16 { 281 | let data = self.buffer.as_ref(); 282 | NetworkEndian::read_u16(&data[field::CHECKSUM]) 283 | } 284 | 285 | /// Return the source address field. 286 | #[inline] 287 | pub fn src_addr(&self) -> Ipv4Addr { 288 | let data = self.buffer.as_ref(); 289 | Ipv4Addr::from(NetworkEndian::read_u32(&data[field::SRC_ADDR])) 290 | } 291 | 292 | /// Return the destination address field. 293 | #[inline] 294 | pub fn dst_addr(&self) -> Ipv4Addr { 295 | let data = self.buffer.as_ref(); 296 | Ipv4Addr::from(NetworkEndian::read_u32(&data[field::DST_ADDR])) 297 | } 298 | 299 | /// Validate the header checksum. 300 | /// 301 | /// # Fuzzing 302 | /// This function always returns `true` when fuzzing. 303 | pub fn verify_checksum(&self) -> bool { 304 | if cfg!(fuzzing) { 305 | return true; 306 | } 307 | 308 | let data = self.buffer.as_ref(); 309 | checksum::data(&data[..self.header_len() as usize]) == !0 310 | } 311 | } 312 | 313 | impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> { 314 | /// Return a pointer to the payload. 315 | #[inline] 316 | pub fn payload(&self) -> &'a [u8] { 317 | let range = self.header_len() as usize..self.total_len() as usize; 318 | let data = self.buffer.as_ref(); 319 | &data[range] 320 | } 321 | } 322 | 323 | impl + AsMut<[u8]>> Packet { 324 | /// Set the version field. 325 | #[inline] 326 | pub fn set_version(&mut self, value: u8) { 327 | let data = self.buffer.as_mut(); 328 | data[field::VER_IHL] = (data[field::VER_IHL] & !0xf0) | (value << 4); 329 | } 330 | 331 | /// Set the header length, in octets. 332 | #[inline] 333 | pub fn set_header_len(&mut self, value: u8) { 334 | let data = self.buffer.as_mut(); 335 | data[field::VER_IHL] = (data[field::VER_IHL] & !0x0f) | ((value / 4) & 0x0f); 336 | } 337 | 338 | /// Set the Differential Services Code Point field. 339 | pub fn set_dscp(&mut self, value: u8) { 340 | let data = self.buffer.as_mut(); 341 | data[field::DSCP_ECN] = (data[field::DSCP_ECN] & !0xfc) | (value << 2) 342 | } 343 | 344 | /// Set the Explicit Congestion Notification field. 345 | pub fn set_ecn(&mut self, value: u8) { 346 | let data = self.buffer.as_mut(); 347 | data[field::DSCP_ECN] = (data[field::DSCP_ECN] & !0x03) | (value & 0x03) 348 | } 349 | 350 | /// Set the total length field. 351 | #[inline] 352 | pub fn set_total_len(&mut self, value: u16) { 353 | let data = self.buffer.as_mut(); 354 | NetworkEndian::write_u16(&mut data[field::LENGTH], value) 355 | } 356 | 357 | /// Set the fragment identification field. 358 | #[inline] 359 | pub fn set_ident(&mut self, value: u16) { 360 | let data = self.buffer.as_mut(); 361 | NetworkEndian::write_u16(&mut data[field::IDENT], value) 362 | } 363 | 364 | /// Clear the entire flags field. 365 | #[inline] 366 | pub fn clear_flags(&mut self) { 367 | let data = self.buffer.as_mut(); 368 | let raw = NetworkEndian::read_u16(&data[field::FLG_OFF]); 369 | let raw = raw & !0xe000; 370 | NetworkEndian::write_u16(&mut data[field::FLG_OFF], raw); 371 | } 372 | 373 | /// Set the "don't fragment" flag. 374 | #[inline] 375 | pub fn set_dont_frag(&mut self, value: bool) { 376 | let data = self.buffer.as_mut(); 377 | let raw = NetworkEndian::read_u16(&data[field::FLG_OFF]); 378 | let raw = if value { raw | 0x4000 } else { raw & !0x4000 }; 379 | NetworkEndian::write_u16(&mut data[field::FLG_OFF], raw); 380 | } 381 | 382 | /// Set the "more fragments" flag. 383 | #[inline] 384 | pub fn set_more_frags(&mut self, value: bool) { 385 | let data = self.buffer.as_mut(); 386 | let raw = NetworkEndian::read_u16(&data[field::FLG_OFF]); 387 | let raw = if value { raw | 0x2000 } else { raw & !0x2000 }; 388 | NetworkEndian::write_u16(&mut data[field::FLG_OFF], raw); 389 | } 390 | 391 | /// Set the fragment offset, in octets. 392 | #[inline] 393 | pub fn set_frag_offset(&mut self, value: u16) { 394 | let data = self.buffer.as_mut(); 395 | let raw = NetworkEndian::read_u16(&data[field::FLG_OFF]); 396 | let raw = (raw & 0xe000) | (value >> 3); 397 | NetworkEndian::write_u16(&mut data[field::FLG_OFF], raw); 398 | } 399 | 400 | /// Set the time to live field. 401 | #[inline] 402 | pub fn set_hop_limit(&mut self, value: u8) { 403 | let data = self.buffer.as_mut(); 404 | data[field::TTL] = value 405 | } 406 | 407 | /// Set the protocol field. 408 | #[inline] 409 | pub fn set_protocol(&mut self, value: Protocol) { 410 | let data = self.buffer.as_mut(); 411 | data[field::PROTOCOL] = value.into() 412 | } 413 | 414 | /// Set the header checksum field. 415 | #[inline] 416 | pub fn set_checksum(&mut self, value: u16) { 417 | let data = self.buffer.as_mut(); 418 | NetworkEndian::write_u16(&mut data[field::CHECKSUM], value) 419 | } 420 | 421 | /// Set the source address field. 422 | #[inline] 423 | pub fn set_src_addr(&mut self, value: Ipv4Addr) { 424 | let data = self.buffer.as_mut(); 425 | data[field::SRC_ADDR].copy_from_slice(&value.octets()) 426 | } 427 | 428 | /// Set the destination address field. 429 | #[inline] 430 | pub fn set_dst_addr(&mut self, value: Ipv4Addr) { 431 | let data = self.buffer.as_mut(); 432 | data[field::DST_ADDR].copy_from_slice(&value.octets()) 433 | } 434 | 435 | /// Compute and fill in the header checksum. 436 | pub fn fill_checksum(&mut self) { 437 | self.set_checksum(0); 438 | let checksum = { 439 | let data = self.buffer.as_ref(); 440 | !checksum::data(&data[..self.header_len() as usize]) 441 | }; 442 | self.set_checksum(checksum) 443 | } 444 | 445 | /// Return a mutable pointer to the payload. 446 | #[inline] 447 | pub fn payload_mut(&mut self) -> &mut [u8] { 448 | let range = self.header_len() as usize..self.total_len() as usize; 449 | let data = self.buffer.as_mut(); 450 | &mut data[range] 451 | } 452 | } 453 | 454 | impl> AsRef<[u8]> for Packet { 455 | fn as_ref(&self) -> &[u8] { 456 | self.buffer.as_ref() 457 | } 458 | } 459 | 460 | mod udp { 461 | use super::{NetworkEndian, Protocol as IpProtocol}; 462 | use std::io::ErrorKind; 463 | use std::net::Ipv4Addr; 464 | 465 | type Result = std::io::Result; 466 | 467 | #[derive(Debug, PartialEq, Clone)] 468 | pub struct Packet> { 469 | buffer: T, 470 | } 471 | 472 | mod field { 473 | #![allow(non_snake_case)] 474 | 475 | pub type Field = ::core::ops::Range; 476 | 477 | pub const SRC_PORT: Field = 0..2; 478 | pub const DST_PORT: Field = 2..4; 479 | pub const LENGTH: Field = 4..6; 480 | pub const CHECKSUM: Field = 6..8; 481 | 482 | pub fn PAYLOAD(length: u16) -> Field { 483 | CHECKSUM.end..(length as usize) 484 | } 485 | } 486 | 487 | impl> Packet { 488 | pub fn new_unchecked(buffer: T) -> Packet { 489 | Packet { buffer } 490 | } 491 | 492 | pub fn new_checked(buffer: T) -> Result> { 493 | let packet = Self::new_unchecked(buffer); 494 | packet.check_len()?; 495 | Ok(packet) 496 | } 497 | 498 | pub fn check_len(&self) -> Result<()> { 499 | let buffer_len = self.buffer.as_ref().len(); 500 | if buffer_len < field::CHECKSUM.end { 501 | Err(std::io::Error::new(ErrorKind::Other, "Truncated")) 502 | } else { 503 | let field_len = self.len() as usize; 504 | if buffer_len < field_len { 505 | Err(std::io::Error::new(ErrorKind::Other, "Truncated")) 506 | } else if field_len < field::CHECKSUM.end { 507 | Err(std::io::Error::new(ErrorKind::Other, "Malformed")) 508 | } else { 509 | Ok(()) 510 | } 511 | } 512 | } 513 | 514 | pub fn into_inner(self) -> T { 515 | self.buffer 516 | } 517 | 518 | #[inline] 519 | pub fn src_port(&self) -> u16 { 520 | let data = self.buffer.as_ref(); 521 | NetworkEndian::read_u16(&data[field::SRC_PORT]) 522 | } 523 | 524 | #[inline] 525 | pub fn dst_port(&self) -> u16 { 526 | let data = self.buffer.as_ref(); 527 | NetworkEndian::read_u16(&data[field::DST_PORT]) 528 | } 529 | 530 | #[inline] 531 | pub fn len(&self) -> u16 { 532 | let data = self.buffer.as_ref(); 533 | NetworkEndian::read_u16(&data[field::LENGTH]) 534 | } 535 | 536 | #[inline] 537 | pub fn checksum(&self) -> u16 { 538 | let data = self.buffer.as_ref(); 539 | NetworkEndian::read_u16(&data[field::CHECKSUM]) 540 | } 541 | 542 | pub fn verify_checksum(&self, src_addr: &Ipv4Addr, dst_addr: &Ipv4Addr) -> bool { 543 | let data = self.buffer.as_ref(); 544 | super::checksum::combine(&[ 545 | super::checksum::pseudo_header( 546 | src_addr, 547 | dst_addr, 548 | IpProtocol::Udp, 549 | self.len() as u32, 550 | ), 551 | super::checksum::data(&data[..self.len() as usize]), 552 | ]) == !0 553 | } 554 | } 555 | 556 | impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> { 557 | #[inline] 558 | pub fn payload(&self) -> &'a [u8] { 559 | let length = self.len(); 560 | let data = self.buffer.as_ref(); 561 | &data[field::PAYLOAD(length)] 562 | } 563 | } 564 | 565 | impl + AsMut<[u8]>> Packet { 566 | #[inline] 567 | pub fn set_src_port(&mut self, value: u16) { 568 | let data = self.buffer.as_mut(); 569 | NetworkEndian::write_u16(&mut data[field::SRC_PORT], value) 570 | } 571 | 572 | #[inline] 573 | pub fn set_dst_port(&mut self, value: u16) { 574 | let data = self.buffer.as_mut(); 575 | NetworkEndian::write_u16(&mut data[field::DST_PORT], value) 576 | } 577 | 578 | #[inline] 579 | pub fn set_len(&mut self, value: u16) { 580 | let data = self.buffer.as_mut(); 581 | NetworkEndian::write_u16(&mut data[field::LENGTH], value) 582 | } 583 | 584 | #[inline] 585 | pub fn set_checksum(&mut self, value: u16) { 586 | let data = self.buffer.as_mut(); 587 | NetworkEndian::write_u16(&mut data[field::CHECKSUM], value) 588 | } 589 | 590 | pub fn fill_checksum(&mut self, src_addr: &Ipv4Addr, dst_addr: &Ipv4Addr) { 591 | self.set_checksum(0); 592 | let checksum = { 593 | let data = self.buffer.as_ref(); 594 | !super::checksum::combine(&[ 595 | super::checksum::pseudo_header( 596 | src_addr, 597 | dst_addr, 598 | IpProtocol::Udp, 599 | self.len() as u32, 600 | ), 601 | super::checksum::data(&data[..self.len() as usize]), 602 | ]) 603 | }; 604 | self.set_checksum(if checksum == 0 { 0xffff } else { checksum }) 605 | } 606 | 607 | #[inline] 608 | pub fn payload_mut(&mut self) -> &mut [u8] { 609 | let length = self.len(); 610 | let data = self.buffer.as_mut(); 611 | &mut data[field::PAYLOAD(length)] 612 | } 613 | } 614 | 615 | impl> AsRef<[u8]> for Packet { 616 | fn as_ref(&self) -> &[u8] { 617 | self.buffer.as_ref() 618 | } 619 | } 620 | } 621 | 622 | mod test { 623 | use super::*; 624 | 625 | #[test] 626 | fn create_udp_header() { 627 | type UdpDatagram = super::udp::Packet<[u8; 8]>; 628 | type Ipv4Packet = super::Packet<[u8; 28]>; 629 | 630 | let our_own_address = Ipv4Addr::new(10, 0, 0, 1); 631 | let dns_server_address = Ipv4Addr::new(1, 2, 3, 4); 632 | 633 | let udp_header_data = [0u8; 8]; 634 | let mut udp_packet = UdpDatagram::new_unchecked(udp_header_data); 635 | 636 | udp_packet.set_src_port(1000); 637 | udp_packet.set_dst_port(53); 638 | udp_packet.set_len(0); 639 | 640 | let mut ip_data = [0u8; 20 + 8]; 641 | let mut ip_packet = Ipv4Packet::new_unchecked(ip_data); 642 | 643 | ip_packet.set_src_addr(our_own_address); 644 | ip_packet.set_dst_addr(dns_server_address); 645 | 646 | udp_packet.fill_checksum(&our_own_address, &dns_server_address); 647 | 648 | ip_packet.set_header_len(20); 649 | ip_packet.set_total_len(28); 650 | 651 | ip_packet 652 | .payload_mut() 653 | .copy_from_slice(&udp_packet.into_inner()); 654 | 655 | ip_packet.fill_checksum(); 656 | 657 | assert_ne!(ip_packet.into_inner(), [0u8; 28]); 658 | } 659 | 660 | #[test] 661 | fn create_header() { 662 | let mut header_data = [0u8; 20]; 663 | let mut ip_packet = Ipv4Packet::new_unchecked(header_data); 664 | 665 | let our_own_address = Ipv4Addr::new(10, 0, 0, 1); 666 | 667 | ip_packet.set_src_addr(our_own_address); 668 | 669 | let dns_server_address = Ipv4Addr::new(1, 2, 3, 4); 670 | ip_packet.set_dst_addr(dns_server_address); 671 | 672 | ip_packet.set_protocol(Protocol::Udp); 673 | 674 | ip_packet.set_version(4); 675 | ip_packet.set_header_len(20); 676 | ip_packet.set_total_len(20); 677 | 678 | ip_packet.fill_checksum(); 679 | 680 | assert_ne!(ip_packet.into_inner(), [0; 20]); 681 | } 682 | } 683 | -------------------------------------------------------------------------------- /virtualnet/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate implements the virtual network for the 'TCP/IP Fundamentals' course on lowlvl.org 2 | //! It is based on smoltcp, the pure Rust TCP/IP stack implementation. 3 | 4 | #[cfg(test)] 5 | mod interface; 6 | 7 | mod middleware; 8 | mod vnet; 9 | 10 | use std::alloc::{alloc, dealloc, realloc, Layout}; 11 | use std::mem; 12 | 13 | pub use vnet::*; 14 | 15 | #[cfg(test)] 16 | mod test { 17 | #[no_mangle] 18 | unsafe fn print_log(src: *const u8, len: usize) { 19 | let str = String::from_utf8_lossy(std::slice::from_raw_parts(src, len)); 20 | println!("{}", str); 21 | } 22 | 23 | #[no_mangle] 24 | fn notify_rx(_packet: *const u8, _len: usize) {} 25 | 26 | #[no_mangle] 27 | fn notify_tx(_packet: *const u8, _len: usize) {} 28 | 29 | #[no_mangle] 30 | fn test_completed(_test_num: u8) {} 31 | 32 | #[cfg(test)] 33 | #[test] 34 | fn test_vnet() { 35 | use std::net::Ipv4Addr; 36 | 37 | let src_ip = Ipv4Addr::new(10, 0, 0, 1).octets(); 38 | let dst_ip = Ipv4Addr::new(10, 0, 0, 99).octets(); 39 | // let dst_ip = Ipv4Addr::new(1, 2, 3, 4).octets(); 40 | let data = b"Alice"; 41 | 42 | unsafe { 43 | crate::setup_network(false); 44 | 45 | let sock = crate::udp_bind(u32::from_be_bytes(src_ip), 1000); 46 | crate::udp_send_to( 47 | sock, 48 | data.as_ptr(), 49 | data.len() as u16, 50 | u32::from_be_bytes(dst_ip), 51 | 1000, 52 | // 53, 53 | ); 54 | 55 | let mut polls = 0; 56 | 57 | while polls < 3 { 58 | crate::poll_network(); 59 | polls += 1; 60 | } 61 | } 62 | } 63 | } 64 | 65 | /// Allocate memory in the virtual network module. 66 | #[no_mangle] 67 | pub extern "C" fn __wbindgen_malloc(size: usize) -> *mut u8 { 68 | let align = mem::align_of::(); 69 | if let Ok(layout) = Layout::from_size_align(size, align) { 70 | unsafe { 71 | if layout.size() > 0 { 72 | let ptr = alloc(layout); 73 | if !ptr.is_null() { 74 | return ptr; 75 | } 76 | } else { 77 | return align as *mut u8; 78 | } 79 | } 80 | } 81 | 82 | malloc_failure(); 83 | } 84 | 85 | /// Reallocate memory in the virtual network module. 86 | #[no_mangle] 87 | pub unsafe extern "C" fn __wbindgen_realloc( 88 | ptr: *mut u8, 89 | old_size: usize, 90 | new_size: usize, 91 | ) -> *mut u8 { 92 | let align = mem::align_of::(); 93 | debug_assert!(old_size > 0); 94 | debug_assert!(new_size > 0); 95 | if let Ok(layout) = Layout::from_size_align(old_size, align) { 96 | let ptr = realloc(ptr, layout, new_size); 97 | if !ptr.is_null() { 98 | return ptr; 99 | } 100 | } 101 | malloc_failure(); 102 | } 103 | 104 | #[cold] 105 | fn malloc_failure() -> ! { 106 | if cfg!(debug_assertions) { 107 | panic!("invalid malloc request") 108 | // throw_str("invalid malloc request") 109 | } else { 110 | std::process::abort(); 111 | } 112 | } 113 | 114 | /// Deallocate memory in the virtual network module. 115 | #[no_mangle] 116 | pub unsafe extern "C" fn __wbindgen_free(ptr: *mut u8, size: usize) { 117 | // This happens for zero-length slices, and in that case `ptr` is 118 | // likely bogus so don't actually send this to the system allocator 119 | if size == 0 { 120 | return; 121 | } 122 | let align = mem::align_of::(); 123 | let layout = Layout::from_size_align_unchecked(size, align); 124 | dealloc(ptr, layout); 125 | } 126 | -------------------------------------------------------------------------------- /virtualnet/src/middleware.rs: -------------------------------------------------------------------------------- 1 | //! This module implements a virtual device middleware for smoltcp. 2 | //! It wraps a 'real' device (`Loopback` in our case) and calls `notify_tx` and `notify_rx` 3 | //! for each transmitted packet. Both functions are externally-defined; they are implemented 4 | //! as a part of the JavaScript API. 5 | 6 | use smoltcp::phy::{self, Device, DeviceCapabilities}; 7 | use smoltcp::time::Instant; 8 | use smoltcp::Result; 9 | 10 | extern "C" { 11 | /// Notifies the JS API about a new outgoing packet. 12 | /// `packet` is a pointer to the packet contents. 13 | /// `len` is the size of a packet. 14 | fn notify_rx(packet: *const u8, len: usize); 15 | 16 | /// Notifies the JS API about a new incoming packet. 17 | /// `packet` is a pointer to the packet contents. 18 | /// `len` is the size of a packet. 19 | fn notify_tx(packet: *const u8, len: usize); 20 | } 21 | pub struct WasmMiddleware Device<'a>> { 22 | inner: D, 23 | } 24 | 25 | impl Device<'a>> WasmMiddleware { 26 | pub fn new(inner: D) -> WasmMiddleware { 27 | Self { inner } 28 | } 29 | 30 | /// Get a reference to the underlying device. 31 | /// 32 | /// Even if the device offers reading through a standard reference, it is inadvisable to 33 | /// directly read from the device as doing so will circumvent the tracing. 34 | #[allow(unused)] 35 | pub fn get_ref(&self) -> &D { 36 | &self.inner 37 | } 38 | 39 | /// Get a mutable reference to the underlying device. 40 | /// 41 | /// It is inadvisable to directly read from the device as doing so will circumvent the tracing. 42 | #[allow(unused)] 43 | pub fn get_mut(&mut self) -> &mut D { 44 | &mut self.inner 45 | } 46 | 47 | /// Return the underlying device, consuming the tracer. 48 | #[allow(unused)] 49 | pub fn into_inner(self) -> D { 50 | self.inner 51 | } 52 | } 53 | 54 | impl<'a, D> Device<'a> for WasmMiddleware 55 | where 56 | D: for<'b> Device<'b>, 57 | { 58 | type RxToken = RxToken<>::RxToken>; 59 | type TxToken = TxToken<>::TxToken>; 60 | 61 | fn capabilities(&self) -> DeviceCapabilities { 62 | self.inner.capabilities() 63 | } 64 | 65 | fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> { 66 | let &mut Self { ref mut inner } = self; 67 | inner.receive().map(|(rx_token, tx_token)| { 68 | let rx = RxToken { token: rx_token }; 69 | let tx = TxToken { token: tx_token }; 70 | (rx, tx) 71 | }) 72 | } 73 | 74 | fn transmit(&'a mut self) -> Option { 75 | let &mut Self { ref mut inner } = self; 76 | inner.transmit().map(|tx_token| TxToken { token: tx_token }) 77 | } 78 | } 79 | 80 | pub struct RxToken { 81 | token: Rx, 82 | } 83 | 84 | impl phy::RxToken for RxToken { 85 | fn consume(self, timestamp: Instant, f: F) -> Result 86 | where 87 | F: FnOnce(&mut [u8]) -> Result, 88 | { 89 | let Self { token } = self; 90 | token.consume(timestamp, |buffer| { 91 | unsafe { 92 | notify_rx(buffer.as_ptr(), buffer.len()); 93 | } 94 | f(buffer) 95 | }) 96 | } 97 | } 98 | 99 | pub struct TxToken { 100 | token: Tx, 101 | } 102 | 103 | impl phy::TxToken for TxToken { 104 | fn consume(self, timestamp: Instant, len: usize, f: F) -> Result 105 | where 106 | F: FnOnce(&mut [u8]) -> Result, 107 | { 108 | let Self { token } = self; 109 | token.consume(timestamp, len, |buffer| { 110 | let result = f(buffer); 111 | unsafe { 112 | notify_tx(buffer.as_ptr(), buffer.len()); 113 | } 114 | result 115 | }) 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /virtualnet/src/vnet.rs: -------------------------------------------------------------------------------- 1 | //! This module implements the virtual network functions used from JavaScript API. 2 | 3 | use smoltcp::iface::{EthernetInterface, EthernetInterfaceBuilder, NeighborCache}; 4 | use smoltcp::phy::Loopback; 5 | use smoltcp::socket::{SocketHandle, SocketSet, UdpPacketMetadata, UdpSocket, UdpSocketBuffer}; 6 | use smoltcp::time::Duration; 7 | use smoltcp::wire::*; 8 | 9 | use std::collections::hash_map::DefaultHasher; 10 | use std::collections::BTreeMap; 11 | use std::hash::{Hash, Hasher}; 12 | use std::{cell::RefCell, slice}; 13 | 14 | use crate::middleware::WasmMiddleware; 15 | 16 | /// Test: has the reader sent a DNS request for Alice's IP address? 17 | const TEST_ASKED_ALICE_IP: u8 = 1; 18 | /// Test: has the reader contacted 'Alice'? 19 | const TEST_CONTACTED_ALICE: u8 = 2; 20 | 21 | extern "C" { 22 | /// Prints out a message to JS console. 23 | fn print_log(s: *const u8, s_len: usize); 24 | 25 | /// Function that is triggered each time a test condition is met. 26 | fn test_completed(num: u8); 27 | } 28 | 29 | fn log(s: &str) { 30 | use std::ffi::CString; 31 | 32 | let len = s.len(); 33 | let c_str = CString::new(s).unwrap(); 34 | unsafe { 35 | print_log(c_str.as_ptr() as *const _, len); 36 | } 37 | } 38 | 39 | // List of lessons with different behaviours. 40 | enum Lesson { 41 | ExchangingMessages, 42 | Fragmentation, 43 | } 44 | 45 | /// This struct holds the entire state of the virtual network, including sockets, interfaces, etc. 46 | pub struct NetworkState<'a> { 47 | /// Ethernet interface for the virtual network with the WebAssembly middleware. 48 | iface: EthernetInterface<'static, 'a, 'a, WasmMiddleware>, 49 | clock: mock::Clock, 50 | /// Socket set that holds all sockets used in the virtual network. 51 | socket_set: SocketSet<'a, 'a, 'a>, 52 | /// Socket for the name server. 53 | dns_socket: Option, 54 | /// If this server runs in a 'mock' DNS mode, it will not return 'real' IP addresses 55 | /// used in the virtual network, but rather a hash converted into a mock IP address. 56 | is_mock_dns: bool, 57 | /// Socket for the 'Alice' server. 58 | alice_socket: Option, 59 | /// Socket for the easter egg server. ;) 60 | easter_socket: Option, 61 | /// Lesson ID 62 | lesson: Lesson, 63 | } 64 | 65 | // There's only one thread in the wasm runtime, so we use thread_locals for global state storage. 66 | thread_local! { 67 | pub static NETWORK: RefCell>> = RefCell::new(None); 68 | } 69 | 70 | mod mock { 71 | use core::cell::Cell; 72 | use smoltcp::time::{Duration, Instant}; 73 | 74 | pub struct Clock(Cell); 75 | 76 | impl Clock { 77 | pub fn new() -> Clock { 78 | Clock(Cell::new(Instant::from_millis(0))) 79 | } 80 | 81 | pub fn advance(&self, duration: Duration) { 82 | self.0.set(self.0.get() + duration) 83 | } 84 | 85 | pub fn elapsed(&self) -> Instant { 86 | self.0.get() 87 | } 88 | } 89 | } 90 | 91 | /// Setup a UDP socket for the domain name service. 92 | fn setup_dns_socket(socket_set: &mut SocketSet) -> SocketHandle { 93 | let mut socket = { 94 | let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 4], vec![0; 1024]); 95 | let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 4], vec![0; 1024]); 96 | UdpSocket::new(udp_rx_buffer, udp_tx_buffer) 97 | }; 98 | 99 | socket 100 | .bind(IpEndpoint::new(IpAddress::v4(1, 2, 3, 4), 53)) 101 | .unwrap(); 102 | 103 | socket_set.add(socket) 104 | } 105 | 106 | /// Setup UDP socket for Alice. 107 | fn setup_alice_socket(socket_set: &mut SocketSet, net_buffer_size: usize) -> Option { 108 | let mut socket = { 109 | let udp_rx_buffer = UdpSocketBuffer::new( 110 | vec![ 111 | UdpPacketMetadata::EMPTY; 112 | net_buffer_size / std::mem::size_of::() 113 | ], 114 | vec![0; net_buffer_size], 115 | ); 116 | let udp_tx_buffer = UdpSocketBuffer::new( 117 | vec![ 118 | UdpPacketMetadata::EMPTY; 119 | net_buffer_size / std::mem::size_of::() 120 | ], 121 | vec![0; net_buffer_size], 122 | ); 123 | UdpSocket::new(udp_rx_buffer, udp_tx_buffer) 124 | }; 125 | socket 126 | .bind(IpEndpoint::new(IpAddress::v4(10, 0, 0, 42), 1000)) 127 | .unwrap(); 128 | 129 | let alice_socket = socket_set.add(socket); 130 | 131 | return Some(alice_socket); 132 | } 133 | 134 | /// Setup UDP socket for the easter egg server. 135 | fn setup_easter_egg_socket(socket_set: &mut SocketSet) -> Option { 136 | let mut socket = { 137 | let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 4], vec![0; 1024]); 138 | let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 4], vec![0; 1024]); 139 | UdpSocket::new(udp_rx_buffer, udp_tx_buffer) 140 | }; 141 | socket 142 | .bind(IpEndpoint::new(IpAddress::v4(10, 0, 0, 99), 1000)) 143 | .unwrap(); 144 | 145 | let easter_egg_socket = socket_set.add(socket); 146 | 147 | return Some(easter_egg_socket); 148 | } 149 | 150 | /// Handle DNS requests. 151 | fn poll_dns(socket: SocketHandle, network: &mut NetworkState) { 152 | let mut dns_sock = network.socket_set.get::(socket); 153 | 154 | match dns_sock.recv() { 155 | Ok((data, sender_endpoint)) => { 156 | // Decode a DNS request. 157 | log(&format!("{:?}, {:?}", data, sender_endpoint)); 158 | 159 | if network.is_mock_dns { 160 | // Hash the request and return it as a faux IP address. 161 | let mut hasher = DefaultHasher::new(); 162 | data.hash(&mut hasher); 163 | 164 | let res = hasher.finish().to_be_bytes(); 165 | log(&format!("DNS response: {:?}", &res[0..4])); 166 | 167 | dns_sock.send_slice(&res[0..4], sender_endpoint).unwrap(); // fixme: properly report errors 168 | } else { 169 | let response = match &data.to_ascii_lowercase()[..] { 170 | b"alice" => { 171 | unsafe { test_completed(TEST_ASKED_ALICE_IP) }; 172 | [10, 0, 0, 42] 173 | } 174 | b"lobste.rs" 175 | | b"google.com" 176 | | b"duckduckgo.com" 177 | | b"rust-lang.org" 178 | | b"users.rust-lang.org" 179 | | b"news.ycombinator.com" 180 | | b"youtube.com" 181 | | b"youtu.be" 182 | | b"reddit.com" => [10, 0, 0, 99], 183 | _ => [0, 0, 0, 0], 184 | }; 185 | log(&format!("DNS response: {:?}", &response[0..4])); 186 | 187 | dns_sock.send_slice(&response, sender_endpoint).unwrap(); // fixme: properly report errors 188 | } 189 | } 190 | Err(smoltcp::Error::Exhausted) => { 191 | // Buffer is empty, ignore 192 | return; 193 | } 194 | Err(e) => { 195 | // TODO: properly report this error 196 | log(&format!("{:?}", e)); 197 | return; 198 | } 199 | } 200 | } 201 | 202 | /// Handle requests to Alice's server. 203 | fn poll_alice(network: &mut NetworkState) { 204 | let mut sock = network 205 | .socket_set 206 | .get::(network.alice_socket.as_ref().cloned().unwrap()); 207 | 208 | match sock.recv() { 209 | Ok((_, sender_endpoint)) => { 210 | // Send a response, but only for the 1st lesson. 211 | if let Lesson::ExchangingMessages = network.lesson { 212 | unsafe { test_completed(TEST_CONTACTED_ALICE) }; 213 | 214 | sock.send_slice(b"Hello from Alice!", sender_endpoint) 215 | .unwrap(); // fixme: properly report errors 216 | } 217 | } 218 | Err(smoltcp::Error::Exhausted) => { 219 | // buffer is empty, ignore 220 | return; 221 | } 222 | Err(e) => { 223 | // todo: properly report this error 224 | log(&format!("{:?}", e)); 225 | return; 226 | } 227 | } 228 | } 229 | 230 | fn poll_easter(network: &mut NetworkState) { 231 | let mut sock = network 232 | .socket_set 233 | .get::(network.easter_socket.as_ref().cloned().unwrap()); 234 | 235 | match sock.recv() { 236 | Ok((_, sender_endpoint)) => { 237 | sock.send_slice( 238 | b"301 Moved Permanently\nLocation: https://youtu.be/dQw4w9WgXcQ\n", 239 | sender_endpoint, 240 | ) 241 | .unwrap(); // FIXME: properly report errors 242 | } 243 | Err(smoltcp::Error::Exhausted) => { 244 | // Buffer is empty, ignore 245 | return; 246 | } 247 | Err(e) => { 248 | // TODO: properly report this error 249 | log(&format!("{:?}", e)); 250 | return; 251 | } 252 | } 253 | } 254 | 255 | fn poll_services(network: &mut NetworkState) { 256 | if let Some(socket) = network.dns_socket { 257 | poll_dns(socket, network); 258 | } 259 | 260 | if network.alice_socket.is_some() { 261 | poll_alice(network); 262 | } 263 | 264 | if network.easter_socket.is_some() { 265 | poll_easter(network); 266 | } 267 | } 268 | 269 | /// Initialise the virtual network, setup sockets, etc. 270 | /// If `mock_dns` is true, only a 'fake' name server will be initialised. 271 | /// The fake name server will return IP addresses that don't exist in the virtual network. 272 | #[no_mangle] 273 | pub fn setup_network(is_mock_dns: bool) { 274 | let clock = mock::Clock::new(); 275 | 276 | let loopback = Loopback::new(); 277 | let device = WasmMiddleware::new(loopback); 278 | 279 | let neighbor_cache = NeighborCache::new(BTreeMap::new()); 280 | 281 | let iface = EthernetInterfaceBuilder::new(device) 282 | .ethernet_addr(EthernetAddress::default()) 283 | .neighbor_cache(neighbor_cache) 284 | .ip_addrs([ 285 | IpCidr::new(IpAddress::v4(1, 2, 3, 4), 8), // DNS 286 | IpCidr::new(IpAddress::v4(10, 0, 0, 1), 8), // User's IP 287 | IpCidr::new(IpAddress::v4(10, 0, 0, 42), 8), // Alice 288 | IpCidr::new(IpAddress::v4(10, 0, 0, 99), 8), // Hidden service 289 | ]) 290 | .finalize(); 291 | 292 | let mut socket_set = SocketSet::new(vec![]); 293 | 294 | let dns_socket = Some(setup_dns_socket(&mut socket_set)); 295 | 296 | let (alice_socket, easter_socket) = if is_mock_dns { 297 | (None, None) 298 | } else { 299 | let alice = setup_alice_socket(&mut socket_set, 1024); 300 | let easter = setup_easter_egg_socket(&mut socket_set); 301 | (alice, easter) 302 | }; 303 | 304 | let network = NetworkState { 305 | iface, 306 | clock, 307 | socket_set, 308 | dns_socket, 309 | alice_socket, 310 | easter_socket, 311 | is_mock_dns, 312 | lesson: Lesson::ExchangingMessages, 313 | }; 314 | 315 | NETWORK.with(|net| { 316 | *net.borrow_mut() = Some(network); 317 | }); 318 | } 319 | 320 | /// Initialise the virtual network, setup sockets, etc. 321 | /// This function is used for the 2nd lesson in the 'TCP/IP Fundamentals' series. 322 | #[no_mangle] 323 | pub fn setup_fragmentation_network() { 324 | let clock = mock::Clock::new(); 325 | 326 | let loopback = Loopback::new(); 327 | let device = WasmMiddleware::new(loopback); 328 | 329 | let neighbor_cache = NeighborCache::new(BTreeMap::new()); 330 | 331 | let iface = EthernetInterfaceBuilder::new(device) 332 | .ethernet_addr(EthernetAddress::default()) 333 | .neighbor_cache(neighbor_cache) 334 | .ip_addrs([ 335 | IpCidr::new(IpAddress::v4(10, 0, 0, 1), 8), // User's IP 336 | IpCidr::new(IpAddress::v4(10, 0, 0, 42), 8), // Alice 337 | ]) 338 | .finalize(); 339 | 340 | let mut socket_set = SocketSet::new(vec![]); 341 | 342 | let alice_socket = setup_alice_socket(&mut socket_set, 65536 * 4); 343 | 344 | let network = NetworkState { 345 | iface, 346 | clock, 347 | socket_set, 348 | dns_socket: None, 349 | alice_socket, 350 | easter_socket: None, 351 | is_mock_dns: false, 352 | lesson: Lesson::Fragmentation, 353 | }; 354 | 355 | NETWORK.with(|net| { 356 | *net.borrow_mut() = Some(network); 357 | }); 358 | } 359 | 360 | /// Polls all sockets in the virtual network and handles events. 361 | #[no_mangle] 362 | pub unsafe fn poll_network() { 363 | NETWORK.with(|net| { 364 | let net2 = &mut *net.borrow_mut(); // TODO: gracefully report error if None 365 | let mut network = net2.as_mut().unwrap(); 366 | 367 | let mut processed = true; 368 | 369 | while processed { 370 | processed = match network 371 | .iface 372 | .poll(&mut network.socket_set, network.clock.elapsed()) 373 | { 374 | Ok(processed) => processed, 375 | Err(_e) => { 376 | log(&format!("err: {:?}", _e)); 377 | true 378 | } 379 | }; 380 | 381 | match network 382 | .iface 383 | .poll_delay(&network.socket_set, network.clock.elapsed()) 384 | { 385 | Some(Duration { millis: 0 }) => {} 386 | Some(delay) => network.clock.advance(delay), 387 | None => network.clock.advance(Duration::from_millis(1)), 388 | } 389 | 390 | if processed { 391 | poll_services(&mut network); 392 | } 393 | } 394 | }); 395 | } 396 | 397 | /// Creates a new UDP socket on the virtual network and returns a handle. 398 | #[no_mangle] 399 | pub unsafe fn udp_bind(ip: u32, port: u16) -> usize { 400 | let mut socket = { 401 | let udp_rx_buffer = 402 | UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 128], vec![0; 65536]); 403 | let udp_tx_buffer = 404 | UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 128], vec![0; 65536 * 4]); 405 | UdpSocket::new(udp_rx_buffer, udp_tx_buffer) 406 | }; 407 | 408 | socket 409 | .bind(IpEndpoint::new( 410 | IpAddress::Ipv4(Ipv4Address(ip.to_be_bytes())), 411 | port, 412 | )) 413 | .unwrap(); 414 | 415 | NETWORK.with(|net| { 416 | let net2 = &mut *net.borrow_mut(); 417 | let network = net2.as_mut().unwrap(); // TODO: gracefully report error if None 418 | 419 | network.socket_set.add(socket).inner() 420 | }) 421 | } 422 | 423 | /// Sends data to a provided destination address. 424 | /// 425 | /// ## Arguments 426 | /// - `sock`: the source socket. 427 | /// - `buf`: pointer to the source data buffer. 428 | /// - `buf_len`: size of the source data buffer. 429 | /// - `dst_ip`: destination IP address. 430 | /// - `dst_port`: destination port number. 431 | #[no_mangle] 432 | pub unsafe fn udp_send_to(sock: usize, buf: *const u8, buf_len: u16, dst_ip: u32, dst_port: u16) { 433 | NETWORK.with(|net| { 434 | let net2 = &mut *net.borrow_mut(); 435 | let network = net2.as_mut().unwrap(); // TODO: gracefully report error if None 436 | 437 | let mut socket = network 438 | .socket_set 439 | .get::(SocketHandle::from(sock)); 440 | 441 | let endpoint = 442 | IpEndpoint::new(IpAddress::Ipv4(Ipv4Address(dst_ip.to_be_bytes())), dst_port); 443 | let buf_slice = slice::from_raw_parts(buf, buf_len as usize); 444 | 445 | let res = socket.send_slice(buf_slice, endpoint); 446 | 447 | log(&format!( 448 | "udp_send_to (sock {:?}), sending {:?} bytes to {:?}, res: {:?}", 449 | sock, buf_len, endpoint, res 450 | )); 451 | }) 452 | } 453 | 454 | /// Polls a given socket for new packets. 455 | /// Returns a number of bytes received. 456 | /// 457 | /// ## Arguments 458 | /// - `sock`: the source socket. 459 | /// - `buf`: pointer to the destination data buffer that needs to be pre-allocated. 460 | /// - `buf_len`: size of the destination data buffer. 461 | /// - `src_ip`: pointer to a memory region that will hold the sender's IP. 462 | /// - `src_port`: pointer to a memory region that will hold the sender's port number. 463 | #[no_mangle] 464 | pub unsafe fn udp_recv_from( 465 | sock: usize, 466 | buf: *mut u8, 467 | buf_len: u16, 468 | src_ip: *mut u32, 469 | src_port: *mut u16, 470 | ) -> u16 { 471 | NETWORK.with(|net| { 472 | let net2 = &mut *net.borrow_mut(); 473 | let network = net2.as_mut().unwrap(); // TODO: gracefully report error if None 474 | 475 | log(&format!("sock num: {:?}", sock)); 476 | 477 | let mut socket = network 478 | .socket_set 479 | .get::(SocketHandle::from(sock)); 480 | 481 | let mut dst_buf = slice::from_raw_parts_mut(buf, buf_len as usize); 482 | 483 | let (size, sender) = match socket.recv_slice(&mut dst_buf) { 484 | Ok(res) => res, 485 | Err(smoltcp::Error::Exhausted) => { 486 | // the buffer is empty 487 | return 0; 488 | } 489 | Err(e) => { 490 | // TODO: proper error reporting 491 | log(&format!("recv error: {:?}", e)); 492 | return 0; 493 | } 494 | }; 495 | 496 | log(&format!("udp_recv_from: {:?}, {:?}", size, sender)); 497 | 498 | if let IpAddress::Ipv4(ipv4) = sender.addr { 499 | *src_ip = u32::from_be_bytes(ipv4.0); 500 | } 501 | *src_port = sender.port; 502 | 503 | size as u16 504 | }) 505 | } 506 | 507 | /// Removes the given socket from the virtual network. 508 | #[no_mangle] 509 | pub fn udp_unbind(sock: usize) { 510 | NETWORK.with(|net| { 511 | let net2 = &mut *net.borrow_mut(); 512 | let network = net2.as_mut().unwrap(); // TODO: gracefully report error if None 513 | 514 | let _ = network.socket_set.remove(SocketHandle::from(sock)); 515 | }); 516 | } 517 | --------------------------------------------------------------------------------