| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733 |
- /* This file is part of DarkFi (https://dark.fi)
- *
- * Copyright (C) 2020-2026 Dyne.org foundation
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- */
- use std::{
- collections::{HashMap, HashSet, VecDeque},
- sync::{
- atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
- Arc,
- },
- };
- use darkfi::{
- event_graph::{proto::EventPut, Event, NULL_ID},
- system::Subscription,
- Error, Result,
- };
- use darkfi_serial::{deserialize_async_partial, serialize_async};
- use futures::FutureExt;
- use sled_overlay::sled;
- use smol::{
- io::{self, AsyncBufRead, AsyncBufReadExt, AsyncWriteExt, BufReader},
- lock::{OnceCell, RwLock},
- net::SocketAddr,
- prelude::{AsyncRead, AsyncWrite},
- };
- use tracing::{debug, error, warn};
- use super::{
- server::{IrcServer, RlnMessageReservation, MAX_MSG_LEN},
- NickServ, SERVER_NAME,
- };
- use crate::Privmsg;
- const PENALTY_LIMIT: usize = 5;
- const MAX_IRC_LINE_LEN: usize = 1024;
- const MAX_PENDING_PRIVMSGS: usize = 128;
- /// Read one IRC line without allowing unbounded buffer growth.
- async fn read_bounded_line<R>(reader: &mut R, line: &mut String) -> Result<usize>
- where
- R: AsyncBufRead + Unpin,
- {
- line.clear();
- let mut bytes = Vec::new();
- loop {
- let (consumed, complete) = {
- let available = reader.fill_buf().await?;
- if available.is_empty() {
- if bytes.is_empty() {
- return Ok(0)
- }
- *line = String::from_utf8(bytes)?;
- return Ok(line.len())
- }
- let newline = available.iter().position(|b| *b == b'\n');
- let take = newline.map_or(available.len(), |idx| idx + 1);
- if bytes.len().saturating_add(take) > MAX_IRC_LINE_LEN {
- return Err(Error::ParseFailed("IRC line too long"))
- }
- bytes.extend_from_slice(&available[..take]);
- (take, newline.is_some())
- };
- reader.consume(consumed);
- if complete {
- *line = String::from_utf8(bytes)?;
- return Ok(line.len())
- }
- }
- }
- fn enqueue_pending_privmsg(args_queue: &mut VecDeque<Privmsg>, privmsg: Privmsg) -> bool {
- if args_queue.len() >= MAX_PENDING_PRIVMSGS {
- return false
- }
- args_queue.push_back(privmsg);
- true
- }
- /// Reply types, we can either send server replies, or client replies.
- pub enum ReplyType {
- /// Server reply, we have to use numerics
- Server((u16, String)),
- /// Client reply, message from someone to some{one,where}
- Client((String, String)),
- /// Pong reply, we just use server origin
- Pong(String),
- /// CAP reply
- Cap(String),
- /// NOTICE reply (from, to, what)
- Notice((String, String, String)),
- }
- /// Stateful IRC client handler, used for each client connection
- pub struct Client {
- /// Pointer to parent `IrcServer`
- pub server: Arc<IrcServer>,
- /// Subscription for incoming events
- pub incoming: Subscription<Event>,
- /// Subscription for incoming static events
- pub incoming_st: Subscription<Event>,
- /// Client socket addr
- pub addr: SocketAddr,
- /// ID of the last sent event
- pub last_sent: RwLock<blake3::Hash>,
- /// Active (joined) channels for this client
- pub channels: RwLock<HashSet<String>>,
- /// Penalty counter, when limit is reached, disconnect client
- pub penalty: AtomicUsize,
- /// Registration marker
- pub registered: AtomicBool,
- /// Registration pause marker
- pub reg_paused: AtomicBool,
- /// CAP END marker
- pub is_cap_end: AtomicBool,
- /// Password setup marker
- pub is_pass_set: AtomicBool,
- /// Client username
- pub username: Arc<RwLock<String>>,
- /// Client nickname
- pub nickname: Arc<RwLock<String>>,
- /// Client realname
- pub realname: RwLock<String>,
- /// Client caps
- pub caps: RwLock<HashMap<String, bool>>,
- /// Set of seen messages for the user
- /// TODO: It grows indefinitely, needs to be pruned.
- pub seen: OnceCell<sled::Tree>,
- /// NickServ instance
- pub nickserv: Arc<NickServ>,
- }
- impl Client {
- /// Instantiate a new Client.
- pub async fn new(
- server: Arc<IrcServer>,
- incoming: Subscription<Event>,
- incoming_st: Subscription<Event>,
- addr: SocketAddr,
- ) -> Result<Self> {
- let caps =
- HashMap::from([("no-history".to_string(), false), ("no-autojoin".to_string(), false)]);
- let username = Arc::new(RwLock::new(String::from("*")));
- let nickname = Arc::new(RwLock::new(String::from("*")));
- Ok(Self {
- server: server.clone(),
- incoming,
- incoming_st,
- addr,
- last_sent: RwLock::new(NULL_ID),
- channels: RwLock::new(HashSet::new()),
- penalty: AtomicUsize::new(0),
- registered: AtomicBool::new(false),
- reg_paused: AtomicBool::new(false),
- is_cap_end: AtomicBool::new(false),
- is_pass_set: AtomicBool::new(false),
- username: username.clone(),
- nickname: nickname.clone(),
- realname: RwLock::new(String::from("*")),
- caps: RwLock::new(caps),
- seen: OnceCell::new(),
- nickserv: Arc::new(
- NickServ::new(username.clone(), nickname.clone(), server.clone()).await?,
- ),
- })
- }
- /// This function handles a single IRC client. We listen to messages from the
- /// IRC client and relay them to the network, and we also get notified of
- /// incoming messages and relay them to the IRC client. The notifications come
- /// from events being inserted into the Event Graph.
- pub async fn multiplex_connection<S>(&self, stream: S) -> Result<()>
- where
- S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
- {
- let (reader, mut writer) = io::split(stream);
- let mut reader = BufReader::new(reader);
- // Our buffer for the client line
- let mut line = String::new();
- let mut args_queue: VecDeque<_> = VecDeque::new();
- loop {
- futures::select! {
- // Process message from the IRC client
- r = read_bounded_line(&mut reader, &mut line).fuse() => {
- // If client closed unexpectedly, we disconnect.
- if let Ok(0) = r {
- error!("[IRC CLIENT] Read failed for {}: Client disconnected", self.addr);
- self.incoming.unsubscribe().await;
- self.incoming_st.unsubscribe().await;
- return Err(Error::ChannelStopped)
- }
- // If something failed during reading, we disconnect.
- if let Err(e) = r {
- error!("[IRC CLIENT] Read failed for {}: {e}", self.addr);
- self.incoming.unsubscribe().await;
- self.incoming_st.unsubscribe().await;
- return Err(Error::ChannelStopped)
- }
- // If the penalty limit is reached, disconnect the client.
- if self.penalty.load(SeqCst) == PENALTY_LIMIT {
- self.incoming.unsubscribe().await;
- self.incoming_st.unsubscribe().await;
- return Err(Error::ChannelStopped)
- }
- // We'll be strict here and disconnect the client
- // in case line processing failed in any way.
- match self.process_client_line(&line, &mut writer, &mut args_queue).await {
- // If we got an event back, we should broadcast it.
- // This means we add it to our DAG, and the DAG will
- // handle the rest of the propagation.
- Ok(Some(events)) => {
- for event in events {
- // Update the last sent event.
- let event_id = event.header.id();
- *self.last_sent.write().await = event_id;
- let current_genesis = self.server.darkirc.event_graph.current_genesis.read().await;
- let dag_name = current_genesis.header.timestamp.to_string();
- drop(current_genesis);
- // Build the RLN signal blob before touching the local
- // DAG when RLN is enabled. With RLN disabled, outbound
- // events deliberately carry no proof blob.
- let blob = if self.server.darkirc.event_graph.rln_enabled() {
- let (rln_identity, mid) = match self
- .server
- .reserve_rln_message_id(event.header.timestamp)
- .await?
- {
- RlnMessageReservation::Reserved {
- identity,
- message_id,
- } => (identity, message_id),
- RlnMessageReservation::MissingIdentity => {
- warn!(
- "[IRC CLIENT] No RLN identity registered; \
- refusing to send. Use \
- `/msg NickServ REGISTER ...` to register."
- );
- continue
- }
- RlnMessageReservation::BudgetExhausted => {
- warn!(
- "[IRC CLIENT] RLN message budget \
- exhausted for this epoch; dropping \
- message to avoid slash"
- );
- continue
- }
- };
- match rln_identity
- .create_signal(
- &event,
- mid,
- &self.server.darkirc.event_graph,
- )
- .await
- {
- Ok(blob) => serialize_async(&blob).await,
- Err(e) => {
- error!(
- "[IRC CLIENT] Failed creating RLN \
- signal proof: {e}"
- );
- return Err(e)
- }
- }
- } else {
- Vec::new()
- };
- // Commit our outbound signal through
- // the safe public API. It inserts the
- // header, verifies and stores the RLN
- // blob, then commits the event body.
- if let Err(e) = self
- .server
- .darkirc
- .event_graph
- .insert_signal_with_blob(&event, &blob, &dag_name)
- .await
- {
- error!(
- "[IRC CLIENT] Failed inserting verified \
- signal event: {e}"
- );
- continue
- }
- // We sent this, so it should be considered seen.
- if let Err(e) = self.mark_seen(&event_id).await {
- error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({event_id}) failed: {e}");
- return Err(e)
- }
- if let Err(e) =
- self.server.darkirc.p2p.broadcast(&EventPut(event, blob)).await
- {
- error!("[IRC CLIENT] Event broadcast was not admitted: {e}");
- }
- }
- }
- // If we got nothing, we just pass.
- Ok(None) => {}
- // If we got an error, we disconnect the client.
- Err(e) => {
- self.incoming.unsubscribe().await;
- self.incoming_st.unsubscribe().await;
- return Err(e)
- }
- }
- // Clear the line buffer
- line = String::new();
- }
- // Process message from the network. These should only be PRIVMSG.
- //
- // N.b. handling "historical messages", i.e. outstanding messages
- // which have occured when darkirc is offline are handled in
- // <file:./command.rs::async fn get_history(&self, channels: &HashSet<String>) -> Result<Vec<ReplyType>> {>
- // for which the logic for delivery should be kept in sync
- r = self.incoming.receive().fuse() => {
- // We will skip this if it's our own message.
- let event_id = r.header.id();
- if *self.last_sent.read().await == event_id {
- continue
- }
- // If this event was seen, skip it
- match self.is_seen(&event_id).await {
- Ok(true) => continue,
- Ok(false) => {},
- Err(e) => {
- error!("[IRC CLIENT] (multiplex_connection) self.is_seen({event_id}) failed: {e}");
- return Err(e)
- }
- }
- // Try to deserialize the `Event`'s content into a `Privmsg`
- let mut privmsg = match deserialize_async_partial(r.content()).await {
- Ok((v, _)) => v,
- Err(e) => {
- error!(target: "irc::client", "[IRC CLIENT] Failed deserializing event: {e}");
- continue
- }
- };
- // If successful, potentially decrypt it:
- self.server.try_decrypt(&mut privmsg, self.nickname.read().await.as_ref()).await;
- // We should skip any attempts to contact services from the network.
- if ["nickserv", "chanserv"].contains(&privmsg.nick.to_lowercase().as_str()) {
- continue
- }
- // If the privmsg is not intented for any of the given
- // channels or contacts, ignore it
- // otherwise add it as a reply and mark it as seen
- // in the seen_events tree.
- let channels = self.channels.read().await;
- let contacts = self.server.contacts.read().await;
- if !channels.contains(&privmsg.channel) &&
- !contacts.contains_key(&privmsg.channel)
- {
- continue
- }
- // Add the nickname to the list of nicks on the channel, if it's a channel.
- let mut chans_lock = self.server.channels.write().await;
- if let Some(chan) = chans_lock.get_mut(&privmsg.channel) {
- chan.nicks.insert(privmsg.nick.clone());
- }
- drop(chans_lock);
- // Handle message lines individually
- for line in privmsg.msg.lines() {
- // Skip empty lines
- if line.is_empty() {
- continue
- }
- // Format the message
- let msg = format!("PRIVMSG {} :{line}", privmsg.channel);
- // Send it to the client
- let reply = ReplyType::Client((privmsg.nick.clone(), msg));
- if let Err(e) = self.reply(&mut writer, &reply).await {
- error!("[IRC CLIENT] Failed writing PRIVMSG to client: {e}");
- continue
- }
- }
- // Mark the message as seen for this USER
- if let Err(e) = self.mark_seen(&event_id).await {
- error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({}) failed: {}", event_id, e);
- return Err(e)
- }
- }
- // Process message from the network. These should only be RLN identities.
- r = self.incoming_st.receive().fuse() => {
- // We will skip this if it's our own message.
- let event_id = r.header.id();
- if *self.last_sent.read().await == event_id {
- continue
- }
- // If this event was seen, skip it
- match self.is_seen(&event_id).await {
- Ok(true) => continue,
- Ok(false) => {},
- Err(e) => {
- error!("[IRC CLIENT] (multiplex_connection) self.is_seen({}) failed: {}", event_id, e);
- return Err(e)
- }
- }
- // Static-event arrival path. EventGraph notifies
- // `static_pub` only after `commit_verified_static_event`
- // has durably stored the event/blob and applied the RLN
- // state change. So all we need to do is bookkeeping for
- // this client's seen-set.
- // Mark the message as seen for this USER
- if let Err(e) = self.mark_seen(&event_id).await {
- error!("[IRC CLIENT] (multiplex_connection) self.mark_seen({event_id}) failed: {e}");
- return Err(e)
- }
- }
- }
- }
- }
- /// Send a reply to the IRC client. Matches on the reply type.
- async fn reply<W>(&self, writer: &mut W, reply: &ReplyType) -> Result<()>
- where
- W: AsyncWrite + Unpin,
- {
- let r = match reply {
- ReplyType::Server((rpl, msg)) => format!(":{SERVER_NAME} {rpl:03} {msg}"),
- ReplyType::Client((nick, msg)) => format!(":{nick}!~anon@darkirc {msg}"),
- ReplyType::Pong(origin) => format!(":{SERVER_NAME} PONG :{origin}"),
- ReplyType::Cap(msg) => format!(":{SERVER_NAME} {msg}"),
- ReplyType::Notice((src, dst, msg)) => {
- format!(":{src}!~anon@darkirc NOTICE {dst} :{msg}")
- }
- };
- debug!("[{}] <-- {r}", self.addr);
- writer.write(r.as_bytes()).await?;
- writer.write(b"\r\n").await?;
- writer.flush().await?;
- Ok(())
- }
- /// Handle the incoming line given sent by the IRC client
- async fn process_client_line<W>(
- &self,
- line: &str,
- writer: &mut W,
- args_queue: &mut VecDeque<Privmsg>,
- ) -> Result<Option<Vec<Event>>>
- where
- W: AsyncWrite + Unpin,
- {
- if line.trim().is_empty() {
- // Silently ignore empty commands
- return Ok(None)
- }
- let mut line = line.to_string();
- // Remove CRLF
- if line.ends_with("\r\n") {
- line.pop();
- line.pop();
- } else if line.ends_with("\n") {
- line.pop();
- } else {
- return Err(Error::ParseFailed("Line doesn't end with CR/LF"))
- }
- // Prefix the message part of PRIVMSG with ':' if is not already.
- // Or realname part of USER command.
- if let Some(index) = match line.split_whitespace().next() {
- Some("PRIVMSG") => Some(2),
- Some("USER") => Some(4),
- _ => None,
- } {
- let mut words: Vec<String> =
- line.splitn(index + 1, char::is_whitespace).map(|s| s.to_string()).collect();
- if words.len() > index && !words[index].starts_with(':') {
- words[index] = format!(":{}", words[index]);
- }
- line = words.join(" ");
- }
- // Parse the line
- let mut tokens = line.split_ascii_whitespace();
- // Commands can begin with :garbage, but we will reject clients
- // doing that for now to keep the protocol simple and focused.
- let cmd = tokens.next().ok_or(Error::ParseFailed("Invalid command line"))?;
- let args = line.replacen(cmd, "", 1);
- let cmd = cmd.to_uppercase();
- debug!("[{}] --> {cmd}{args}", self.addr);
- // Handle the command. These implementations are in `command.rs`.
- let replies: Vec<ReplyType> = match cmd.as_str() {
- "ADMIN" => self.handle_cmd_admin(&args).await?,
- "CAP" => self.handle_cmd_cap(&args).await?,
- "INFO" => self.handle_cmd_info(&args).await?,
- "JOIN" => self.handle_cmd_join(&args, true).await?,
- "LIST" => self.handle_cmd_list(&args).await?,
- "MODE" => self.handle_cmd_mode(&args).await?,
- "MOTD" => self.handle_cmd_motd(&args).await?,
- "NAMES" => self.handle_cmd_names(&args).await?,
- "NICK" => self.handle_cmd_nick(&args).await?,
- "PART" => self.handle_cmd_part(&args).await?,
- "PASS" => self.handle_cmd_pass(&args).await?,
- "PING" => self.handle_cmd_ping(&args).await?,
- "PRIVMSG" => self.handle_cmd_privmsg(&args).await?,
- "REHASH" => self.handle_cmd_rehash(&args).await?,
- "TOPIC" => self.handle_cmd_topic(&args).await?,
- "USER" => self.handle_cmd_user(&args).await?,
- "VERSION" => self.handle_cmd_version(&args).await?,
- "QUIT" => return Err(Error::ChannelStopped),
- _ => {
- warn!("[IRC CLIENT] Unimplemented \"{cmd}\" command");
- vec![]
- }
- };
- // Depending on the reply type, we send according messages.
- for reply in replies.iter() {
- self.reply(writer, reply).await?;
- }
- // If the command was a PRIVMSG the client sent, we need to encrypt it and
- // create an Event to broadcast and return it from this function. So let's try.
- // We also do not allow sending unencrypted DMs. In that case, we send a notice
- // to the client to inform them that the feature is not enabled.
- // NOTE: This is not the most performant way to do this, probably not even
- // TODO: the best place to do it. Patches welcome. It's also a bit fragile
- // since we assume that `handle_cmd_privmsg()` won't return any replies.
- if cmd.as_str() == "PRIVMSG" && replies.is_empty() {
- // If the DAG is not synced yet, queue client lines
- // Once synced, send queued lines and continue as normal
- if !self.server.darkirc.event_graph.is_synced() {
- debug!("DAG is still syncing, queuing and skipping...");
- let Some(privmsg) = self.args_to_privmsg(args).await else {
- self.penalty.fetch_add(1, SeqCst);
- return Ok(None)
- };
- if !enqueue_pending_privmsg(args_queue, privmsg) {
- self.penalty.fetch_add(1, SeqCst);
- let nick = self.nickname.read().await.to_string();
- let reply = ReplyType::Notice((
- SERVER_NAME.to_string(),
- nick,
- "PRIVMSG queue is full; wait for sync before sending more".to_string(),
- ));
- self.reply(writer, &reply).await?;
- }
- return Ok(None)
- }
- // Check if we have queued PRIVMSGs, if we do send all of them first.
- let mut pending_events = vec![];
- if !args_queue.is_empty() {
- for _ in 0..args_queue.len() {
- let privmsg = args_queue.pop_front().unwrap();
- pending_events.push(self.privmsg_to_event(privmsg).await?);
- }
- return Ok(Some(pending_events))
- }
- // If queue is empty, create an event and return it
- let Some(privmsg) = self.args_to_privmsg(args).await else {
- self.penalty.fetch_add(1, SeqCst);
- return Ok(None)
- };
- let event = self.privmsg_to_event(privmsg).await?;
- return Ok(Some(vec![event]))
- }
- Ok(None)
- }
- // Internal helper function that creates a PRIVMSG from IRC client arguments
- async fn args_to_privmsg(&self, args: String) -> Option<Privmsg> {
- let nick = self.nickname.read().await.to_string();
- let channel = args.split_ascii_whitespace().next()?.to_string();
- let msg_offset = args.find(':')? + 1;
- let (_, msg) = args.split_at(msg_offset);
- // Truncate messages longer than MAX_MSG_LEN
- let msg = if msg.len() > MAX_MSG_LEN { msg.split_at(MAX_MSG_LEN).0 } else { msg };
- Some(Privmsg { version: 0, msg_type: 0, channel, nick, msg: msg.to_string() })
- }
- // Internal helper function that creates an Event from PRIVMSG arguments
- async fn privmsg_to_event(&self, mut privmsg: Privmsg) -> Result<Event> {
- // Encrypt the Privmsg if an encryption method is available.
- self.server.try_encrypt(&mut privmsg).await;
- // Build a DAG event and return it.
- Event::new(serialize_async(&privmsg).await, &self.server.darkirc.event_graph).await
- }
- /// Atomically mark a message as seen for this client.
- pub async fn mark_seen(&self, event_id: &blake3::Hash) -> Result<()> {
- let db = self
- .seen
- .get_or_init(|| async {
- let u = self.username.read().await.to_string();
- self.server.darkirc.sled.open_tree(format!("darkirc_user_{u}")).unwrap()
- })
- .await;
- debug!("Marking event {event_id} as seen");
- let mut batch = sled::Batch::default();
- batch.insert(event_id.as_bytes(), &[]);
- Ok(db.apply_batch(batch)?)
- }
- /// Check if a message was already marked seen for this client.
- pub async fn is_seen(&self, event_id: &blake3::Hash) -> Result<bool> {
- let db = self
- .seen
- .get_or_init(|| async {
- let u = self.username.read().await.to_string();
- self.server.darkirc.sled.open_tree(format!("darkirc_user_{u}")).unwrap()
- })
- .await;
- Ok(db.contains_key(event_id.as_bytes())?)
- }
- }
- #[cfg(test)]
- mod tests {
- use std::collections::VecDeque;
- use smol::io::{BufReader, Cursor};
- use super::{
- enqueue_pending_privmsg, read_bounded_line, MAX_IRC_LINE_LEN, MAX_PENDING_PRIVMSGS,
- };
- use crate::Privmsg;
- #[test]
- fn read_bounded_line_accepts_line_within_limit() {
- smol::block_on(async {
- let input = format!("{}\n", "a".repeat(MAX_IRC_LINE_LEN - 1));
- let mut reader = BufReader::new(Cursor::new(input.into_bytes()));
- let mut line = String::new();
- let read = read_bounded_line(&mut reader, &mut line).await.unwrap();
- assert_eq!(read, MAX_IRC_LINE_LEN);
- assert!(line.ends_with('\n'));
- });
- }
- #[test]
- fn read_bounded_line_rejects_oversized_line() {
- smol::block_on(async {
- let input = format!("{}\n", "a".repeat(MAX_IRC_LINE_LEN));
- let mut reader = BufReader::new(Cursor::new(input.into_bytes()));
- let mut line = String::new();
- assert!(read_bounded_line(&mut reader, &mut line).await.is_err());
- });
- }
- #[test]
- fn pending_privmsg_queue_has_fixed_capacity() {
- let mut queue = VecDeque::new();
- for _ in 0..MAX_PENDING_PRIVMSGS {
- assert!(enqueue_pending_privmsg(&mut queue, privmsg()));
- }
- assert!(!enqueue_pending_privmsg(&mut queue, privmsg()));
- assert_eq!(queue.len(), MAX_PENDING_PRIVMSGS);
- }
- fn privmsg() -> Privmsg {
- Privmsg {
- version: 0,
- msg_type: 0,
- channel: "#chan".to_string(),
- nick: "nick".to_string(),
- msg: "msg".to_string(),
- }
- }
- }
|