Basic packet handling and room data

This commit is contained in:
mars 2022-05-24 18:16:46 -06:00
parent a06ac08560
commit cebbf6a449
3 changed files with 481 additions and 15 deletions

261
Cargo.lock generated
View File

@ -2,18 +2,184 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "byteorder"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]]
name = "clap"
version = "3.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2dbdf4bdacb33466e854ce889eee8dfd5729abf7ccd7664d0a2d60cd384440b"
dependencies = [
"atty",
"bitflags",
"clap_derive",
"clap_lex",
"indexmap",
"lazy_static",
"strsim",
"termcolor",
"textwrap",
]
[[package]]
name = "clap_derive"
version = "3.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25320346e922cffe59c0bbc5410c8d8784509efb321488971081313cb1e1a33c"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213"
dependencies = [
"os_str_bytes",
]
[[package]]
name = "hashbrown"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]]
name = "heck"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
[[package]]
name = "hermit-abi"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
dependencies = [
"libc",
]
[[package]]
name = "indexmap"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.126"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836"
[[package]]
name = "num_enum"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf5395665662ef45796a4ff5486c5d41d29e0c09640af4c5f17fd94ee2c119c9"
dependencies = [
"num_enum_derive",
]
[[package]]
name = "num_enum_derive"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0498641e53dd6ac1a4f22547548caa6864cc4933784319cd1775271c5a46ce"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "os_str_bytes"
version = "6.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "029d8d0b2f198229de29dca79676f2738ff952edf3fde542eb8bf94d8c21b435"
[[package]]
name = "paste"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c520e05135d6e763148b6426a837e239041653ba7becd2e538c076c738025fc"
[[package]]
name = "proc-macro-crate"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a"
dependencies = [
"thiserror",
"toml",
]
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "1.0.39"
@ -48,6 +214,18 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1"
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "1.0.95"
@ -59,10 +237,56 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "termcolor"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
dependencies = [
"winapi-util",
]
[[package]]
name = "textwrap"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
[[package]]
name = "thiserror"
version = "1.0.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "toml"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7"
dependencies = [
"serde",
]
[[package]]
name = "udp-mud"
version = "0.1.0"
dependencies = [
"clap",
"num_enum",
"protocol",
"protocol-derive",
]
@ -72,3 +296,40 @@ name = "unicode-ident"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

View File

@ -10,5 +10,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "3", features = ["derive"] }
num_enum = "0.5"
protocol = { path = "./protocol" }
protocol-derive = { path = "./protocol-derive" }

View File

@ -1,23 +1,226 @@
use clap::Parser;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use protocol::*;
use protocol_derive::{Decode, Encode};
use std::collections::HashMap;
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
#[derive(Parser, Debug)]
#[clap(
author = "Marceline Cramer",
about = "Experimental distributed UDP chat."
)]
pub struct Args {
/// Name you appear as to other peers.
#[clap(short, long)]
pub username: String,
/// Address to bind to.
#[clap(short, long)]
pub bind_addr: SocketAddr,
/// Other address to initiate connection with.
#[clap(short, long)]
pub connect: Option<SocketAddr>,
}
#[derive(Debug, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
pub enum PacketKind {
Ping,
Pong,
RequestUserInfo,
RequestRoomInfo,
RequestRoomList,
UserInfo,
RoomInfo,
RoomList,
Message,
}
#[derive(Debug, Decode, Encode)]
struct TestData {
var_int: Var<u32>,
string: String,
pub struct Pronouns {
/// Non-zero for true, zero for false.
pub case_sensitive: u8, // TODO bitfield or bool protocol impl?
/// Ex. he, she, they, fae.
pub subject: String,
/// Ex. him, her, them, faer.
pub object: String,
/// Ex. his, her, their, faer.
pub possessive: String,
/// Ex. his, hers, theirs, faers.
pub possessive_pronoun: String,
/// Ex. himself, herself, themself, faerself.
pub reflexive: String,
}
#[derive(Debug, Decode, Encode)]
pub struct UserInfo {
pub id: String,
pub username: String,
pub about: String,
pub pronouns: Pronouns,
}
#[derive(Debug, Decode, Encode)]
pub struct RoomInfo {
pub id: String,
pub title: String,
pub short_about: String,
pub long_about: String,
}
#[derive(Debug, Decode, Encode)]
pub struct RoomList {
pub room_ids: Vec<String>,
}
#[derive(Debug, Decode, Encode)]
pub struct Message {
pub sender: String,
pub contents: String,
}
pub struct Room {
pub info: RoomInfo,
}
pub struct App {
args: Args,
socket: UdpSocket,
owned_rooms: HashMap<String, Room>,
remote_rooms: HashMap<String, Room>,
}
impl App {
pub fn new(args: Args) -> Self {
let socket = UdpSocket::bind(args.bind_addr).unwrap();
let mut app = Self {
args,
owned_rooms: Default::default(),
remote_rooms: Default::default(),
socket,
};
app.startup();
app
}
pub fn startup(&mut self) {
if let Some(connect) = self.args.connect.as_ref() {
self.send_empty_packet(connect, PacketKind::Ping).unwrap();
}
let room = Room {
info: RoomInfo {
id: format!("{}_owned_room", self.args.username),
title: format!("{}'s Bombass Owned Room", self.args.username),
short_about: "An automatically-created room for testing.".into(),
long_about: "".into(),
}
};
self.owned_rooms.insert(room.info.id.clone(), room);
}
pub fn run(mut self) {
let mut buf = [0u8; 65507];
while let Ok((len, from)) = self.socket.recv_from(&mut buf) {
let mut buf = buf.as_slice();
println!("recv'd from {:?}: {:?}", from, &buf[..len]);
let kind = Var::<u16>::decode(&mut buf).unwrap().0;
let kind: PacketKind = match kind.try_into() {
Ok(kind) => kind,
Err(int) => {
eprintln!("unrecognized packet kind {}", int);
continue;
}
};
self.on_packet(from, kind, buf);
}
}
pub fn on_packet(&mut self, from: SocketAddr, kind: PacketKind, mut reader: &[u8]) {
println!("handling {:?}", kind);
match kind {
PacketKind::Ping => self.send_empty_packet(from, PacketKind::Pong).unwrap(),
PacketKind::Pong => self
.send_empty_packet(from, PacketKind::RequestRoomList)
.unwrap(),
PacketKind::RequestRoomList => self
.send_packet(from, PacketKind::RoomList, |writer| {
let room_list = self.build_room_list();
room_list.encode(writer)
})
.unwrap(),
PacketKind::RoomList => {
let room_list: RoomList = Decode::decode(&mut reader).unwrap();
for room_id in room_list.room_ids.iter() {
self.send_packet(from, PacketKind::RequestRoomInfo, |writer| {
room_id.encode(writer)
})
.unwrap();
}
}
PacketKind::RequestRoomInfo => {
let room_id = String::decode(&mut reader).unwrap();
if let Some(room) = self.owned_rooms.get(&room_id) {
self.send_packet(from, PacketKind::RoomInfo, |writer| {
room.info.encode(writer)
})
.unwrap();
} else {
eprintln!("Unrecognized room info request for {}", room_id);
}
}
PacketKind::RoomInfo => {
let info = RoomInfo::decode(&mut reader).unwrap();
eprintln!("Received room info: {:#?}", info);
self.remote_rooms.insert(info.id.clone(), Room { info });
}
kind => eprintln!("unimplemented packet handler for {:?}", kind),
}
}
pub fn build_room_list(&self) -> RoomList {
let room_ids: Vec<_> = self
.owned_rooms
.iter()
.map(|(id, _room)| id.to_owned())
.collect();
RoomList { room_ids }
}
pub fn send_packet(
&self,
addr: impl ToSocketAddrs,
kind: PacketKind,
encode: impl FnOnce(&mut Vec<u8>) -> std::io::Result<()>,
) -> std::io::Result<()> {
let mut buf = Vec::new();
Var(kind as u16).encode(&mut buf)?;
encode(&mut buf)?;
self.socket.send_to(&buf, addr)?;
Ok(())
}
pub fn send_empty_packet(
&self,
addr: impl ToSocketAddrs,
kind: PacketKind,
) -> std::io::Result<()> {
self.send_packet(addr, kind, |_| Ok(()))
}
}
fn main() {
let data = TestData {
var_int: Var(42),
string: "Hello world!".to_string(),
};
let mut buf = Vec::new();
data.encode(&mut buf).unwrap();
println!("encoded: {:?}", buf);
let mut reader = buf.as_slice();
let decoded = TestData::decode(&mut reader).unwrap();
println!("decoded: {:#?}", decoded);
let args = Args::parse();
let app = App::new(args);
app.run();
}