-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathmod.rs
More file actions
2228 lines (2031 loc) · 75.3 KB
/
Copy pathmod.rs
File metadata and controls
2228 lines (2031 loc) · 75.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A simple, thread-safe, and async-friendly IRC client library.
//!
//! This API provides the ability to connect to an IRC server via the
//! [`Client`] type. The [`Client`] trait that
//! [`Client`] implements provides methods for communicating with the
//! server.
//!
//! # Examples
//!
//! Using these APIs, we can connect to a server and send a one-off message (in this case,
//! identifying with the server).
//!
//! ```no_run
//! # extern crate irc;
//! use irc::client::prelude::Client;
//!
//! # #[tokio::main]
//! # async fn main() -> irc::error::Result<()> {
//! let client = Client::new("config.toml").await?;
//! client.identify()?;
//! # Ok(())
//! # }
//! ```
//!
//! We can then use functions from [`Client`] to receive messages from the
//! server in a blocking fashion and perform any desired actions in response. The following code
//! performs a simple call-and-response when the bot's name is mentioned in a channel.
//!
//! ```no_run
//! use irc::client::prelude::*;
//! use futures::*;
//!
//! # #[tokio::main]
//! # async fn main() -> irc::error::Result<()> {
//! let mut client = Client::new("config.toml").await?;
//! let mut stream = client.stream()?;
//! client.identify()?;
//!
//! while let Some(message) = stream.next().await.transpose()? {
//! if let Command::PRIVMSG(channel, message) = message.command {
//! if message.contains(client.current_nickname()) {
//! client.send_privmsg(&channel, "beep boop").unwrap();
//! }
//! }
//! }
//! # Ok(())
//! # }
//! ```
#[cfg(feature = "ctcp")]
use chrono::prelude::*;
use futures_util::{
future::{FusedFuture, Future},
ready,
stream::{FusedStream, Stream},
};
use futures_util::{
sink::Sink as _,
stream::{SplitSink, SplitStream, StreamExt as _},
};
use parking_lot::RwLock;
use std::{
collections::HashMap,
fmt,
path::Path,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use crate::{
client::{
conn::Connection,
data::{Config, User},
},
error,
proto::{
mode::ModeType,
CapSubCommand::{END, LS, REQ},
Capability, ChannelMode, Command,
Command::{
ChannelMODE, AUTHENTICATE, CAP, INVITE, JOIN, KICK, KILL, NICK, NICKSERV, NOTICE, OPER,
PART, PASS, PONG, PRIVMSG, QUIT, SAMODE, SANICK, TOPIC, USER,
},
Message, Mode, NegotiationVersion, Response,
},
};
pub mod conn;
pub mod data;
mod mock;
pub mod prelude;
pub mod transport;
macro_rules! pub_state_base {
() => {
/// Changes the modes for the specified target.
pub fn send_mode<S, T>(&self, target: S, modes: &[Mode<T>]) -> error::Result<()>
where
S: fmt::Display,
T: ModeType,
{
self.send(T::mode(&target.to_string(), modes))
}
/// Joins the specified channel or chanlist.
pub fn send_join<S>(&self, chanlist: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send(JOIN(chanlist.to_string(), None, None))
}
/// Joins the specified channel or chanlist using the specified key or keylist.
pub fn send_join_with_keys<S1, S2>(&self, chanlist: S1, keylist: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
self.send(JOIN(chanlist.to_string(), Some(keylist.to_string()), None))
}
/// Sends a notice to the specified target.
pub fn send_notice<S1, S2>(&self, target: S1, message: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
let message = message.to_string();
for line in message.split("\r\n") {
self.send(NOTICE(target.to_string(), line.to_string()))?
}
Ok(())
}
};
}
macro_rules! pub_sender_base {
() => {
/// Sends a request for a list of server capabilities for a specific IRCv3 version.
pub fn send_cap_ls(&self, version: NegotiationVersion) -> error::Result<()> {
self.send(Command::CAP(
None,
LS,
match version {
NegotiationVersion::V301 => None,
NegotiationVersion::V302 => Some("302".to_owned()),
},
None,
))
}
/// Sends an IRCv3 capabilities request for the specified extensions.
pub fn send_cap_req(&self, extensions: &[Capability]) -> error::Result<()> {
let append = |mut s: String, c| {
s.push_str(c);
s.push(' ');
s
};
let mut exts = extensions
.iter()
.map(|c| c.as_ref())
.fold(String::new(), append);
let len = exts.len() - 1;
exts.truncate(len);
self.send(CAP(None, REQ, None, Some(exts)))
}
/// Sends a SASL AUTHENTICATE message with the specified data.
pub fn send_sasl<S: fmt::Display>(&self, data: S) -> error::Result<()> {
self.send(AUTHENTICATE(data.to_string()))
}
/// Sends a SASL AUTHENTICATE request to use the PLAIN mechanism.
pub fn send_sasl_plain(&self) -> error::Result<()> {
self.send_sasl("PLAIN")
}
/// Sends a SASL AUTHENTICATE request to use the EXTERNAL mechanism.
pub fn send_sasl_external(&self) -> error::Result<()> {
self.send_sasl("EXTERNAL")
}
/// Sends a SASL AUTHENTICATE request to abort authentication.
pub fn send_sasl_abort(&self) -> error::Result<()> {
self.send_sasl("*")
}
/// Sends a PONG with the specified message.
pub fn send_pong<S>(&self, msg: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send(PONG(msg.to_string(), None))
}
/// Parts the specified channel or chanlist.
pub fn send_part<S>(&self, chanlist: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send(PART(chanlist.to_string(), None))
}
/// Attempts to oper up using the specified username and password.
pub fn send_oper<S1, S2>(&self, username: S1, password: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
self.send(OPER(username.to_string(), password.to_string()))
}
/// Sends a message to the specified target. If the message contains IRC newlines (`\r\n`), it
/// will automatically be split and sent as multiple separate `PRIVMSG`s to the specified
/// target. If you absolutely must avoid this behavior, you can do
/// `client.send(PRIVMSG(target, message))` directly.
pub fn send_privmsg<S1, S2>(&self, target: S1, message: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
let message = message.to_string();
for line in message.split("\r\n") {
self.send(PRIVMSG(target.to_string(), line.to_string()))?
}
Ok(())
}
/// Sets the topic of a channel or requests the current one.
/// If `topic` is an empty string, it won't be included in the message.
pub fn send_topic<S1, S2>(&self, channel: S1, topic: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
let topic = topic.to_string();
self.send(TOPIC(
channel.to_string(),
if topic.is_empty() { None } else { Some(topic) },
))
}
/// Kills the target with the provided message.
pub fn send_kill<S1, S2>(&self, target: S1, message: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
self.send(KILL(target.to_string(), message.to_string()))
}
/// Kicks the listed nicknames from the listed channels with a comment.
/// If `message` is an empty string, it won't be included in the message.
pub fn send_kick<S1, S2, S3>(
&self,
chanlist: S1,
nicklist: S2,
message: S3,
) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
S3: fmt::Display,
{
let message = message.to_string();
self.send(KICK(
chanlist.to_string(),
nicklist.to_string(),
if message.is_empty() {
None
} else {
Some(message)
},
))
}
/// Changes the mode of the target by force.
/// If `modeparams` is an empty string, it won't be included in the message.
pub fn send_samode<S1, S2, S3>(
&self,
target: S1,
mode: S2,
modeparams: S3,
) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
S3: fmt::Display,
{
let modeparams = modeparams.to_string();
self.send(SAMODE(
target.to_string(),
mode.to_string(),
if modeparams.is_empty() {
None
} else {
Some(modeparams)
},
))
}
/// Forces a user to change from the old nickname to the new nickname.
pub fn send_sanick<S1, S2>(&self, old_nick: S1, new_nick: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
self.send(SANICK(old_nick.to_string(), new_nick.to_string()))
}
/// Invites a user to the specified channel.
pub fn send_invite<S1, S2>(&self, nick: S1, chan: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
self.send(INVITE(nick.to_string(), chan.to_string()))
}
/// Quits the server entirely with a message.
/// This defaults to `Powered by Rust.` if none is specified.
pub fn send_quit<S>(&self, msg: S) -> error::Result<()>
where
S: fmt::Display,
{
let msg = msg.to_string();
self.send(QUIT(Some(if msg.is_empty() {
"Powered by Rust.".to_string()
} else {
msg
})))
}
/// Sends a CTCP-escaped message to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_ctcp<S1, S2>(&self, target: S1, msg: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
let msg = msg.to_string();
for line in msg.split("\r\n") {
self.send(PRIVMSG(
target.to_string(),
format!("\u{001}{}\u{001}", line),
))?
}
Ok(())
}
/// Sends an action command to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_action<S1, S2>(&self, target: S1, msg: S2) -> error::Result<()>
where
S1: fmt::Display,
S2: fmt::Display,
{
self.send_ctcp(target, &format!("ACTION {}", msg.to_string())[..])
}
/// Sends a finger request to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_finger<S: fmt::Display>(&self, target: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send_ctcp(target, "FINGER")
}
/// Sends a version request to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_version<S>(&self, target: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send_ctcp(target, "VERSION")
}
/// Sends a source request to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_source<S>(&self, target: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send_ctcp(target, "SOURCE")
}
/// Sends a user info request to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_user_info<S>(&self, target: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send_ctcp(target, "USERINFO")
}
/// Sends a finger request to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_ctcp_ping<S>(&self, target: S) -> error::Result<()>
where
S: fmt::Display,
{
let time = Local::now();
self.send_ctcp(target, &format!("PING {}", time.timestamp())[..])
}
/// Sends a time request to the specified target.
/// This requires the CTCP feature to be enabled.
#[cfg(feature = "ctcp")]
pub fn send_time<S>(&self, target: S) -> error::Result<()>
where
S: fmt::Display,
{
self.send_ctcp(target, "TIME")
}
};
}
/// A stream of `Messages` received from an IRC server via an `Client`.
///
/// Interaction with this stream relies on the `futures` API, but is only expected for less
/// traditional use cases. To learn more, you can view the documentation for the
/// [`futures`](https://docs.rs/futures/) crate, or the tutorials for
/// [`tokio`](https://tokio.rs/docs/getting-started/futures/).
#[derive(Debug)]
pub struct ClientStream {
state: Arc<ClientState>,
stream: SplitStream<Connection>,
// In case the client stream also handles outgoing messages.
outgoing: Option<Outgoing>,
}
impl ClientStream {
/// collect stream and collect all messages available.
pub async fn collect(mut self) -> error::Result<Vec<Message>> {
let mut output = Vec::new();
while let Some(message) = self.next().await {
match message {
Ok(message) => output.push(message),
Err(e) => return Err(e),
}
}
Ok(output)
}
}
impl FusedStream for ClientStream {
fn is_terminated(&self) -> bool {
false
}
}
impl Stream for ClientStream {
type Item = Result<Message, error::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if let Some(outgoing) = self.as_mut().outgoing.as_mut() {
match Pin::new(outgoing).poll(cx) {
Poll::Ready(Ok(())) => {
// assure that we wake up again to check the incoming stream.
cx.waker().wake_by_ref();
return Poll::Ready(None);
}
Poll::Ready(Err(e)) => {
cx.waker().wake_by_ref();
return Poll::Ready(Some(Err(e)));
}
Poll::Pending => (),
}
}
match ready!(Pin::new(&mut self.as_mut().stream).poll_next(cx)) {
Some(Ok(msg)) => {
self.state.handle_message(&msg)?;
Poll::Ready(Some(Ok(msg)))
}
other => Poll::Ready(other),
}
}
}
/// Thread-safe internal state for an IRC server connection.
#[derive(Debug)]
struct ClientState {
sender: Sender,
/// The configuration used with this connection.
config: Config,
/// A thread-safe map of channels to the list of users in them.
chanlists: RwLock<HashMap<String, Vec<User>>>,
/// A thread-safe index to track the current alternative nickname being used.
alt_nick_index: RwLock<usize>,
/// Default ghost sequence to send if one is required but none is configured.
default_ghost_sequence: Vec<String>,
}
impl ClientState {
fn new(sender: Sender, config: Config) -> ClientState {
ClientState {
sender,
config,
chanlists: RwLock::new(HashMap::new()),
alt_nick_index: RwLock::new(0),
default_ghost_sequence: vec![String::from("GHOST")],
}
}
fn config(&self) -> &Config {
&self.config
}
fn send<M: Into<Message>>(&self, msg: M) -> error::Result<()> {
let msg = msg.into();
self.handle_sent_message(&msg)?;
self.sender.send(msg)
}
/// Gets the current nickname in use.
fn current_nickname(&self) -> &str {
let alt_nicks = self.config().alternate_nicknames();
let index = self.alt_nick_index.read();
match *index {
0 => self
.config()
.nickname()
.expect("current_nickname should not be callable if nickname is not defined."),
i => alt_nicks[i - 1].as_str(),
}
}
/// Handles sent messages internally for basic client functionality.
fn handle_sent_message(&self, msg: &Message) -> error::Result<()> {
log::trace!("[SENT] {}", msg.to_string());
if let PART(ref chan, _) = msg.command {
let _ = self.chanlists.write().remove(chan);
}
Ok(())
}
/// Handles received messages internally for basic client functionality.
fn handle_message(&self, msg: &Message) -> error::Result<()> {
log::trace!("[RECV] {}", msg.to_string());
match msg.command {
JOIN(ref chan, _, _) => self.handle_join(msg.source_nickname().unwrap_or(""), chan),
PART(ref chan, _) => self.handle_part(msg.source_nickname().unwrap_or(""), chan),
KICK(ref chan, ref user, _) => self.handle_part(user, chan),
QUIT(_) => self.handle_quit(msg.source_nickname().unwrap_or("")),
NICK(ref new_nick) => {
self.handle_nick_change(msg.source_nickname().unwrap_or(""), new_nick)
}
ChannelMODE(ref chan, ref modes) => self.handle_mode(chan, modes),
PRIVMSG(ref target, ref body) => {
if body.starts_with('\u{001}') {
let tokens: Vec<_> = {
let end = if body.ends_with('\u{001}') && body.len() > 1 {
body.len() - 1
} else {
body.len()
};
body[1..end].split(' ').collect()
};
if target.starts_with('#') {
self.handle_ctcp(target, &tokens)?
} else if let Some(user) = msg.source_nickname() {
self.handle_ctcp(user, &tokens)?
}
}
}
Command::Response(Response::RPL_NAMREPLY, ref args) => self.handle_namreply(args),
Command::Response(Response::RPL_ENDOFMOTD, _)
| Command::Response(Response::ERR_NOMOTD, _) => {
self.send_nick_password()?;
self.send_umodes()?;
let config_chans = self.config().channels();
for chan in config_chans {
match self.config().channel_key(chan) {
Some(key) => self.send_join_with_keys::<&str, &str>(chan, key)?,
None => self.send_join(chan)?,
}
}
let joined_chans = self.chanlists.read();
for chan in joined_chans
.keys()
.filter(|x| !config_chans.iter().any(|c| c == *x))
{
self.send_join(chan)?
}
}
Command::Response(Response::ERR_NICKNAMEINUSE, _)
| Command::Response(Response::ERR_ERRONEOUSNICKNAME, _) => {
let alt_nicks = self.config().alternate_nicknames();
let mut index = self.alt_nick_index.write();
if *index >= alt_nicks.len() {
return Err(error::Error::NoUsableNick);
} else {
self.send(NICK(alt_nicks[*index].to_owned()))?;
*index += 1;
}
}
_ => (),
}
Ok(())
}
fn send_nick_password(&self) -> error::Result<()> {
if self.config().nick_password().is_empty() {
Ok(())
} else {
let mut index = self.alt_nick_index.write();
if self.config().should_ghost() && *index != 0 {
let seq = match self.config().ghost_sequence() {
Some(seq) => seq,
None => &*self.default_ghost_sequence,
};
for s in seq {
self.send(NICKSERV(vec![
s.to_string(),
self.config().nickname()?.to_string(),
self.config().nick_password().to_string(),
]))?;
}
*index = 0;
self.send(NICK(self.config().nickname()?.to_owned()))?
}
self.send(NICKSERV(vec![
"IDENTIFY".to_string(),
self.config().nick_password().to_string(),
]))
}
}
fn send_umodes(&self) -> error::Result<()> {
if self.config().umodes().is_empty() {
Ok(())
} else {
self.send_mode(
self.current_nickname(),
&Mode::as_user_modes(
self.config()
.umodes()
.split(' ')
.collect::<Vec<_>>()
.as_ref(),
)
.map_err(|e| error::Error::InvalidMessage {
string: format!(
"MODE {} {}",
self.current_nickname(),
self.config().umodes()
),
cause: e,
})?,
)
}
}
#[cfg(not(feature = "channel-lists"))]
fn handle_join(&self, _: &str, _: &str) {}
#[cfg(feature = "channel-lists")]
fn handle_join(&self, src: &str, chan: &str) {
if let Some(vec) = self.chanlists.write().get_mut(&chan.to_owned()) {
if !src.is_empty() {
vec.push(User::new(src))
}
}
}
#[cfg(not(feature = "channel-lists"))]
fn handle_part(&self, _: &str, _: &str) {}
#[cfg(feature = "channel-lists")]
fn handle_part(&self, src: &str, chan: &str) {
if let Some(vec) = self.chanlists.write().get_mut(&chan.to_owned()) {
if !src.is_empty() {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == src) {
vec.swap_remove(n);
}
}
}
}
#[cfg(not(feature = "channel-lists"))]
fn handle_quit(&self, _: &str) {}
#[cfg(feature = "channel-lists")]
fn handle_quit(&self, src: &str) {
if src.is_empty() {
return;
}
for vec in self.chanlists.write().values_mut() {
if let Some(p) = vec.iter().position(|x| x.get_nickname() == src) {
vec.swap_remove(p);
}
}
}
#[cfg(not(feature = "channel-lists"))]
fn handle_nick_change(&self, _: &str, _: &str) {}
#[cfg(feature = "channel-lists")]
fn handle_nick_change(&self, old_nick: &str, new_nick: &str) {
if old_nick.is_empty() || new_nick.is_empty() {
return;
}
for (_, vec) in self.chanlists.write().iter_mut() {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == old_nick) {
let new_entry = User::new(new_nick);
vec[n] = new_entry;
}
}
}
#[cfg(not(feature = "channel-lists"))]
fn handle_mode(&self, _: &str, _: &[Mode<ChannelMode>]) {}
#[cfg(feature = "channel-lists")]
fn handle_mode(&self, chan: &str, modes: &[Mode<ChannelMode>]) {
for mode in modes {
match *mode {
Mode::Plus(_, Some(ref user)) | Mode::Minus(_, Some(ref user)) => {
if let Some(vec) = self.chanlists.write().get_mut(chan) {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == user) {
vec[n].update_access_level(mode)
}
}
}
_ => (),
}
}
}
#[cfg(not(feature = "channel-lists"))]
fn handle_namreply(&self, _: &[String]) {}
#[cfg(feature = "channel-lists")]
fn handle_namreply(&self, args: &[String]) {
if args.len() == 4 {
let chan = &args[2];
for user in args[3].split(' ') {
self.chanlists
.write()
.entry(chan.clone())
.or_insert_with(Vec::new)
.push(User::new(user))
}
}
}
#[cfg(feature = "ctcp")]
fn handle_ctcp(&self, resp: &str, tokens: &[&str]) -> error::Result<()> {
if tokens.is_empty() {
return Ok(());
}
if tokens[0].eq_ignore_ascii_case("FINGER") {
self.send_ctcp_internal(
resp,
&format!(
"FINGER :{} ({})",
self.config().real_name(),
self.config().username()
),
)
} else if tokens[0].eq_ignore_ascii_case("VERSION") {
self.send_ctcp_internal(resp, &format!("VERSION {}", self.config().version()))
} else if tokens[0].eq_ignore_ascii_case("SOURCE") {
self.send_ctcp_internal(resp, &format!("SOURCE {}", self.config().source()))
} else if tokens[0].eq_ignore_ascii_case("PING") && tokens.len() > 1 {
self.send_ctcp_internal(resp, &format!("PING {}", tokens[1]))
} else if tokens[0].eq_ignore_ascii_case("TIME") {
self.send_ctcp_internal(resp, &format!("TIME :{}", Local::now().to_rfc2822()))
} else if tokens[0].eq_ignore_ascii_case("USERINFO") {
self.send_ctcp_internal(resp, &format!("USERINFO :{}", self.config().user_info()))
} else {
Ok(())
}
}
#[cfg(feature = "ctcp")]
fn send_ctcp_internal(&self, target: &str, msg: &str) -> error::Result<()> {
self.send_notice(target, format!("\u{001}{}\u{001}", msg))
}
#[cfg(not(feature = "ctcp"))]
fn handle_ctcp(&self, _: &str, _: &[&str]) -> error::Result<()> {
Ok(())
}
pub_state_base!();
}
/// Thread-safe sender that can be used with the client.
#[derive(Debug, Clone)]
pub struct Sender {
tx_outgoing: UnboundedSender<Message>,
}
impl Sender {
/// Send a single message to the unbounded queue.
pub fn send<M: Into<Message>>(&self, msg: M) -> error::Result<()> {
Ok(self.tx_outgoing.send(msg.into())?)
}
pub_state_base!();
pub_sender_base!();
}
/// Future to handle outgoing messages with IRC flood protection.
///
/// Implements a penalty-based throttle modeled after IRCd (RFC 2813 §5.8). Each outgoing
/// message incurs a penalty based on both its byte length and command type, matching the
/// server's own flood detection formula. When accumulated penalty exceeds a configurable
/// threshold (default 10s), messages are delayed until the penalty drains below it.
/// Penalty drains in real-time at 1ms per 1ms elapsed.
///
/// Total penalty per message: `(1 + message_bytes / 100) * 1000 + command_penalty_ms`
#[derive(Debug)]
pub struct Outgoing {
sink: SplitSink<Connection, Message>,
stream: UnboundedReceiver<Message>,
buffered: Option<Message>,
/// Accumulated penalty in milliseconds.
penalty: u64,
/// Threshold above which messages are delayed. 0 = disabled.
penalty_threshold: u64,
/// Last time penalty was drained.
last_penalty_check: tokio::time::Instant,
/// Active delay future for throttling.
delay: Option<Pin<Box<tokio::time::Sleep>>>,
}
impl Outgoing {
/// Returns the penalty cost in milliseconds for a given IRC command.
///
/// Values mirror the IRCd penalty model (RFC 2813 §5.8). The server-side
/// implementation charges `(1 + message_bytes / 100)` seconds as a base
/// cost per message, plus a command-specific penalty. We replicate this
/// client-side to stay under the server's flood threshold.
///
/// The total penalty for a message is: `base_penalty(len) + command_penalty`
fn command_penalty(command: &Command) -> u64 {
match command {
// Connection control — never throttled client-side. The server
// does charge 1-2s for PONG, but delaying pong replies risks
// ping timeout disconnects, so we exempt these.
Command::PONG(..) | Command::QUIT(..) | Command::PASS(..) => 0,
// CAP negotiation — must not be throttled during registration
Command::CAP(..) | Command::AUTHENTICATE(..) => 0,
// NICK changes incur 3s on IRCd
Command::NICK(..) => 3000,
// PART is expensive on IRCd (4s)
Command::PART(..) => 4000,
// WHO, NAMES, LIST without args are catastrophic on IRCd (10s).
// With args they're 2s. We can't distinguish no-arg vs arg here
// since the Option is always present in the enum, so we check
// whether the argument is None/empty.
Command::WHO(ref mask, _) => match mask {
None => 10_000,
Some(m) if m.is_empty() => 10_000,
_ => 2000,
},
Command::LIST(ref mask, _) | Command::NAMES(ref mask, _) => match mask {
None => 10_000,
Some(m) if m.is_empty() => 10_000,
_ => 2000,
},
// Other expensive server queries
Command::WHOIS(..) | Command::WHOWAS(..) => 3000,
Command::LINKS(..) | Command::STATS(..) => 3000,
Command::LUSERS(..) | Command::TRACE(..) => 2000,
Command::USERS(..) | Command::MOTD(..) | Command::INFO(..) => 5000,
// PRIVMSG/NOTICE: IRCd charges 1s per target. We approximate
// with a flat 2s since most client sends target a single entity.
Command::PRIVMSG(..) | Command::NOTICE(..) => 2000,
// JOIN, KICK, INVITE, MODE, TOPIC, AWAY, and all others: 2s
_ => 2000,
}
}
/// Returns the base penalty in milliseconds derived from message length.
///
/// Mirrors the IRCd formula: `(1 + message_bytes / 100)` seconds.
/// This ensures long messages incur proportionally higher penalties,
/// matching the server's own flood calculation.
fn length_penalty(message: &Message) -> u64 {
let len = message.to_string().len() as u64;
(1 + len / 100) * 1000
}
/// Drains accumulated penalty based on elapsed real time.
fn drain_penalty(&mut self) {
let now = tokio::time::Instant::now();
let elapsed = now.duration_since(self.last_penalty_check).as_millis() as u64;
self.penalty = self.penalty.saturating_sub(elapsed);
self.last_penalty_check = now;
}
fn try_start_send(
&mut self,
cx: &mut Context<'_>,
message: Message,
) -> Poll<Result<(), error::Error>> {
debug_assert!(self.buffered.is_none());
match Pin::new(&mut self.sink).poll_ready(cx)? {
Poll::Ready(()) => Poll::Ready(Pin::new(&mut self.sink).start_send(message)),
Poll::Pending => {
self.buffered = Some(message);
Poll::Pending
}
}
}
}
impl FusedFuture for Outgoing {
fn is_terminated(&self) -> bool {
// NB: outgoing stream never terminates.
// TODO: should it terminate if rx_outgoing is terminated?
false
}
}
impl Future for Outgoing {
type Output = error::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
// If we're waiting on a throttle delay, poll it first.
if let Some(ref mut delay) = this.delay {
ready!(delay.as_mut().poll(cx));
this.delay = None;
this.drain_penalty();
}
// Send the message that was buffered during the delay, then flush
// it to TCP immediately. Without this flush, messages accumulate
// in the codec buffer across multiple delay cycles and burst all
// at once when the stream finally goes idle — causing Excess Flood.
if let Some(message) = this.buffered.take() {
ready!(this.try_start_send(cx, message))?;
ready!(Pin::new(&mut this.sink).poll_flush(cx))?;
}
loop {
match this.stream.poll_recv(cx) {
Poll::Ready(Some(message)) => {
// Apply penalty-based throttle if enabled.
if this.penalty_threshold > 0 {
let cmd_cost = Self::command_penalty(&message.command);
if cmd_cost > 0 {
let len_cost = Self::length_penalty(&message);
let cost = len_cost + cmd_cost;
this.drain_penalty();
this.penalty += cost;
if this.penalty > this.penalty_threshold {
let excess = this.penalty - this.penalty_threshold;
log::debug!(
"Flood penalty {}ms exceeds threshold {}ms, delaying {}ms.",
this.penalty,
this.penalty_threshold,
excess,
);
this.delay = Some(Box::pin(tokio::time::sleep(
std::time::Duration::from_millis(excess),
)));
// Buffer the message and return Pending so the delay runs.
this.buffered = Some(message);
// Register waker with the delay future.
if let Some(ref mut delay) = this.delay {
let _ = delay.as_mut().poll(cx);
}