simple-irc-server 0.1.5

Simple IRC server
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
// utils.rs - commands
//
// simple-irc-server - simple IRC server
// Copyright (C) 2022  Mateusz Szpakowski
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

use std::error::Error;
use std::io;
use std::pin::Pin;
use std::convert::TryFrom;
use futures::{Stream, SinkExt};
use futures::task::{Poll, Context};
use tokio::io::{ReadBuf};
use tokio::io::{AsyncRead, AsyncWrite};
use bytes::{BufMut, BytesMut};
use tokio::net::TcpStream;
#[cfg(feature = "tls_rustls")]
use tokio_rustls::server::TlsStream;
#[cfg(feature = "tls_openssl")]
use tokio_openssl::SslStream;
use tokio_util::codec::{Framed, LinesCodec, LinesCodecError, Decoder, Encoder};
use validator::ValidationError;
use argon2::{self, Argon2};
use argon2::password_hash;
use argon2::password_hash::{SaltString, PasswordHash, PasswordHasher, PasswordVerifier};
use tokio;
use lazy_static::lazy_static;

use crate::command::CommandId::*;
use crate::command::CommandError;
use crate::command::CommandError::*;

#[derive(Debug)]
pub(crate) enum DualTcpStream {
    PlainStream(TcpStream),
    #[cfg(feature = "tls_rustls")]
    SecureStream(TlsStream<TcpStream>),
    #[cfg(feature = "tls_openssl")]
    SecureStream(SslStream<TcpStream>),
}

impl DualTcpStream {
    pub(crate) fn is_secure(&self) -> bool {
        !matches!(*self, DualTcpStream::PlainStream(_))
    }
}

impl AsyncRead for DualTcpStream {
    fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>)
            -> Poll<io::Result<()>> {
        match self.get_mut() {
            DualTcpStream::PlainStream(ref mut t) => Pin::new(t).poll_read(cx, buf),
            #[cfg(any(feature = "tls_openssl", feature = "tls_rustls"))]
            DualTcpStream::SecureStream(ref mut t) => Pin::new(t).poll_read(cx, buf),
        }
    }
}

impl AsyncWrite for DualTcpStream {
    fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8])
            -> Poll<io::Result<usize>> {
        match self.get_mut() {
            DualTcpStream::PlainStream(ref mut t) => Pin::new(t).poll_write(cx, buf),
            #[cfg(any(feature = "tls_openssl", feature = "tls_rustls"))]
            DualTcpStream::SecureStream(ref mut t) => Pin::new(t).poll_write(cx, buf),
        }
    }
    
    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            DualTcpStream::PlainStream(ref mut t) => Pin::new(t).poll_flush(cx),
            #[cfg(any(feature = "tls_openssl", feature = "tls_rustls"))]
            DualTcpStream::SecureStream(ref mut t) => Pin::new(t).poll_flush(cx),
        }
    }
    
    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            DualTcpStream::PlainStream(ref mut t) => Pin::new(t).poll_shutdown(cx),
            #[cfg(any(feature = "tls_openssl", feature = "tls_rustls"))]
            DualTcpStream::SecureStream(ref mut t) => Pin::new(t).poll_shutdown(cx),
        }
    }
}

// BufferedStream - to avoid deadlocks if no immediately data sent
#[derive(Debug)]
pub(crate) struct BufferedLineStream {
    stream: Framed<DualTcpStream, IRCLinesCodec>,
    buffer: Vec<String>,
}

impl BufferedLineStream {
    pub(crate) fn new(stream: Framed<DualTcpStream, IRCLinesCodec>) -> Self {
        BufferedLineStream{ stream, buffer: vec![] }
    }
    
    pub(crate) async fn feed(&mut self, msg: String) -> Result<(), LinesCodecError> {
        self.buffer.push(msg);
        Ok(())
    }
    
    pub(crate) async fn flush(&mut self) -> Result<(), LinesCodecError> {
        for msg in self.buffer.drain(..) {
            self.stream.feed(msg).await?;
        }
        self.stream.flush().await?;
        Ok(())
    }
    
    pub(crate) fn get_ref(&self) -> &DualTcpStream {
        self.stream.get_ref()
    }
}

impl Stream for BufferedLineStream {
    type Item = Result<String, LinesCodecError>;
    
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.get_mut().stream).poll_next(cx)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

// special LinesCodec for IRC - encode with "\r\n".
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub(crate) struct IRCLinesCodec(LinesCodec);

impl IRCLinesCodec {
    pub(crate) fn new_with_max_length(max_length: usize) -> IRCLinesCodec {
        IRCLinesCodec(LinesCodec::new_with_max_length(max_length))
    }
}

impl Encoder<String> for IRCLinesCodec {
    type Error = LinesCodecError;

    fn encode(&mut self, line: String, buf: &mut BytesMut) -> Result<(), Self::Error> {
        buf.reserve(line.len() + 1);
        buf.put(line.as_bytes());
        // put "\r\n"
        buf.put_u8(b'\r');
        buf.put_u8(b'\n');
        Ok(())
    }
}

impl Decoder for IRCLinesCodec {
    type Item = String;
    type Error = LinesCodecError;
    
    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<String>, Self::Error> {
        self.0.decode(buf)
    }
}

pub(crate) fn validate_source(s: &str) -> bool {
    if s.contains(':') {  // if have ':' then is not source
        false
    } else {
        // must be in format nick[!username[@host]]
        let excl = s.find('!');
        let atchar = s.find('@');
        if let Some(excl_pos) = excl {
            if let Some(atchar_pos) = atchar {
                return excl_pos < atchar_pos;
            }
        }
        true
    }
}

pub(crate) fn validate_username(username: &str) -> Result<(), ValidationError> {
    if !username.is_empty() && (username.as_bytes()[0] == b'#' ||
            username.as_bytes()[0] == b'&') {
        Err(ValidationError::new("Username must not have channel prefix."))
    } else if !username.contains('.') && !username.contains(':') && !username.contains(',') {
        Ok(())
    } else {
        Err(ValidationError::new("Username must not contains '.', ',' or ':'."))
    }
}

pub(crate) fn validate_channel(channel: &str) -> Result<(), ValidationError> {
    if !channel.is_empty() && !channel.contains(':') && !channel.contains(',') &&
        (channel.as_bytes()[0] == b'#' || channel.as_bytes()[0] == b'&') {
        Ok(())
    } else {
        Err(ValidationError::new("Channel name must have '#' or '&' at start and \
                must not contains ',' or ':'."))
    }
}

pub(crate) fn validate_server<E: Error>(s: &str, e: E) -> Result<(), E> {
    if s.contains('.') { Ok(()) }
    else { Err(e) }
}

pub(crate) fn validate_server_mask<E: Error>(s: &str, e: E) -> Result<(), E>  {
    if s.contains('.') | s.contains('*') { Ok(()) }
    else { Err(e) }
}

pub(crate) fn validate_prefixed_channel<E: Error>(channel: &str, e: E) -> Result<(), E> {
    if !channel.is_empty() && !channel.contains(':') && !channel.contains(',') {
        let mut is_channel = false;
        let mut last_amp = false;
        for (i,c) in channel.bytes().enumerate() {
            match c {
                b'~'|b'@'|b'%'|b'+' => (),
                b'&' => (),
                b'#' => {
                    is_channel = i+1 < channel.len();
                    break; }
                _ => {
                    // if last special character is & - then local channel
                    is_channel = last_amp;
                    break; }
            }
            last_amp = c == b'&';
        }
        if is_channel { Ok(())
        } else { Err(e) }
    } else { Err(e) }
}

pub(crate) fn validate_usermodes<'a>(modes: &Vec<(&'a str, Vec<&'a str>)>)
                -> Result<(), CommandError> {
    let mut param_idx = 1;
    modes.iter().try_for_each(|(ms, margs)| {
        if !ms.is_empty() {
            if ms.find(|c|
                c!='+' && c!='-' && c!='i' && c!='o' &&
                    c!='O' && c!='r' && c!='w').is_some() {
                Err(UnknownUModeFlag(param_idx))
            } else if !margs.is_empty() {
                Err(WrongParameter(MODEId, param_idx))
            } else {
                param_idx += 1;
                Ok(())
            }
        } else { // if empty
            Err(WrongParameter(MODEId, param_idx))
        }
    })
}

pub(crate) fn validate_channelmodes<'a>(target: &'a str, modes: &Vec<(&'a str, Vec<&'a str>)>)
                -> Result<(), CommandError> {
    let mut param_idx = 1;
    modes.iter().try_for_each(|(ms, margs)| {
        if !ms.is_empty() {
            let mut mode_set = false;
            let mut arg_param_idx = param_idx+1;
            
            let mut margs_it = margs.iter();
            
            ms.chars().try_for_each(|c| {
                match c {
                    '+' => { mode_set = true; }
                    '-' => { mode_set = false; }
                    'b'|'e'|'I' => {
                        margs_it.next(); // consume argument
                        arg_param_idx += 1;
                    }
                    'o'|'v'|'h'|'q'|'a' => {
                        if let Some(arg) = margs_it.next() {
                            validate_username(arg).map_err(|e|
                                InvalidModeParam{ target: target.to_string(),
                                        modechar: c, param: arg.to_string(),
                                        description: e.to_string() })?;
                            arg_param_idx += 1;
                        } else {
                            return Err(InvalidModeParam{ target: target.to_string(),
                                            modechar: c, param: "".to_string(),
                                            description: "No argument".to_string() });
                        }
                    }
                    'l' => {
                        if mode_set {
                            if let Some(arg) = margs_it.next() {
                                if let Err(e) = arg.parse::<usize>() {
                                    // if argument is not number, then error
                                    return Err(InvalidModeParam{ target: target.to_string(),
                                            modechar: c, param: arg.to_string(),
                                            description: e.to_string() });
                                }
                                arg_param_idx += 1;
                            } else {
                                return Err(InvalidModeParam{ target: target.to_string(),
                                            modechar: c, param: "".to_string(),
                                            description: "No argument".to_string() });
                            }
                        } else if let Some(arg) = margs_it.next() {
                            return Err(InvalidModeParam{ target: target.to_string(),
                                        modechar: c, param: arg.to_string(),
                                        description: "Unexpected argument".to_string() });
                        }
                    }
                    'k' => {
                        if mode_set {
                            if margs_it.next().is_some() {
                                arg_param_idx += 1;
                            } else { // no argument
                                return Err(InvalidModeParam{ target: target.to_string(),
                                            modechar: c, param: "".to_string(),
                                            description: "No argument".to_string() });
                            }
                        } else if let Some(arg) = margs_it.next() {
                            return Err(InvalidModeParam{ target: target.to_string(),
                                        modechar: c, param: arg.to_string(),
                                        description: "Unexpected argument".to_string() });
                        }
                    }
                    'i'|'m'|'t'|'n'|'s' => { },
                    c => { return Err(UnknownMode(param_idx, c, target.to_string())); }
                }
                Ok(())
            })?;
            
            param_idx += margs.len() + 1;
            
            Ok(())
        } else { // if empty
            Err(WrongParameter(MODEId, param_idx))
        }
    })
}

fn starts_single_wilcards<'a>(pattern: &'a str, text: &'a str) -> bool {
    if pattern.len() <= text.len() {
        pattern.bytes().enumerate().all(|(i,c)| {
            c == b'?' || c == text.as_bytes()[i]
        })
    } else { false }
}

pub(crate) fn match_wildcard<'a>(pattern: &'a str, text: &'a str) -> bool {
    let mut pat = pattern;
    let mut t = text;
    let mut asterisk = false;
    while !pat.is_empty() {
        let (newpat, m, cur_ast) = if let Some(i) = pat.find('*') {
            (&pat[i+1..], &pat[..i], true)
        } else {
            (&pat[pat.len()..pat.len()], pat, false)
        };
        
        if !m.is_empty() {
            if !asterisk {
                // if first match
                if !starts_single_wilcards(m, t) { return false; }
                t = &t[m.len()..];
            } else if cur_ast || newpat.len() != 0 {
                // after asterisk. only if some rest in pattern and
                // if last current character is asterisk
                let mut i = 0;
                // find first single wildcards occurrence.
                while i <= t.len()-m.len() && !starts_single_wilcards(m, &t[i..]) {
                    i += 1; }
                if i <= t.len()-m.len() { // if found
                    t = &t[i+m.len()..];
                } else { return false; }
            } else {
                // if last pattern is not asterisk
                if !starts_single_wilcards(m, &t[t.len()-m.len()..]) {
                    return false; }
                t = &t[t.len()..t.len()];
            }
        }
        
        asterisk = true;
        pat = newpat;
    }
    // if last character in pattern is '*' or text has been fully consumed
    (!pattern.is_empty() && pattern.as_bytes()[pattern.len()-1] == b'*') || t.is_empty()
}

// normalize source mask - for example '*' to '*!*@*'
pub(crate) fn normalize_sourcemask(mask: &str) -> String {
    let mut out = String::new();
    if let Some(p) = mask.find('!') {
        out += mask; // normalized
        if mask[p+1..].find('@').is_none() {
            out += "@*";
        }
    } else {
        if let Some(p2) = mask.find('@') {
           out += &mask[..p2]; 
           out += "!*";
           out += &mask[p2..];
        } else {
            out += mask; // normalized
            out += "!*@*";
        }
    }
    out
}

//  argon2

static ARGON2_M_COST: u32 = 2048;
static ARGON2_T_COST: u32 = 2;
static ARGON2_P_COST: u32 = 1;
static ARGON2_OUT_LEN: usize = 64;

lazy_static! {
    static ref ARGON2_SALT: SaltString = SaltString::b64_encode(
            option_env!("PASSWORD_SALT").unwrap_or(
                    "br8f4efc3F4heecdsdS").as_bytes()).unwrap();
    static ref ARGON2: Argon2<'static> = Argon2::new(argon2::Algorithm::Argon2id,
            argon2::Version::V0x13,
            argon2::Params::new(ARGON2_M_COST, ARGON2_T_COST, ARGON2_P_COST,
                Some(ARGON2_OUT_LEN)).unwrap());
}

pub(crate) fn argon2_hash_password(password: &str) -> String {
    ARGON2.hash_password(password.as_bytes(), ARGON2_SALT.as_str())
                .unwrap().hash.unwrap().to_string()
}

pub(crate) fn argon2_verify_password<'a>(password: &'a str, hash_str: &'a str)
            -> password_hash::errors::Result<()> {
    let password_hash = PasswordHash{
        algorithm: argon2::Algorithm::Argon2id.ident(),
        version: Some(argon2::Version::V0x13.into()),
        params: password_hash::ParamsString::try_from(ARGON2.params()).unwrap(),
        salt: Some(ARGON2_SALT.as_salt()),
        hash: Some(password_hash::Output::b64_decode(hash_str)?),
    };
    ARGON2.verify_password(password.as_bytes(), &password_hash)
}

pub(crate) async fn argon2_verify_password_async(password: String, hash_str: String)
            -> password_hash::errors::Result<()> {
    tokio::task::spawn_blocking(move || {
        argon2_verify_password(&password, &hash_str)
    }).await.unwrap()
}

pub(crate) fn validate_password_hash(hash_str: &str) -> Result<(), ValidationError> {
    match password_hash::Output::b64_decode(hash_str) {
        Ok(o) => {
            if o.len() == ARGON2_OUT_LEN { Ok(()) }
            else { Err(ValidationError::new("Wrong password hash length")) }
        }
        Err(_) => Err(ValidationError::new("Wrong base64 password hash"))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    
    #[test]
    fn test_irc_lines_codec() {
        let mut codec = IRCLinesCodec::new_with_max_length(2000);
        let mut buf = BytesMut::new();
        codec.encode("my line".to_string(), &mut buf).unwrap();
        assert_eq!("my line\r\n".as_bytes(), buf);
        let mut buf = BytesMut::from("my line 2\n");
        assert_eq!(codec.decode(&mut buf).map_err(|e| e.to_string()),
                Ok(Some("my line 2".to_string())));
        assert_eq!(buf, BytesMut::new());
        let mut buf = BytesMut::from("my line 2\r\n");
        assert_eq!(codec.decode(&mut buf).map_err(|e| e.to_string()),
                Ok(Some("my line 2".to_string())));
        assert_eq!(buf, BytesMut::new());
    }
    
    #[test]
    fn test_validate_source() {
        assert_eq!(true, validate_source("bob!bobby@host.com"));
        assert_eq!(true, validate_source("bobby@host.com"));
        assert_eq!(true, validate_source("bob!bobby"));
        assert_eq!(true, validate_source("host.com"));
        assert_eq!(false, validate_source("bob@bobby!host.com"));
    }
    
    #[test]
    fn test_validate_username() {
        assert_eq!(true, validate_username("ala").is_ok());
        assert_eq!(false, validate_username("#ala").is_ok());
        assert_eq!(false, validate_username("&ala").is_ok());
        assert_eq!(false, validate_username("a.la").is_ok());
        assert_eq!(false, validate_username("a,la").is_ok());
        assert_eq!(false, validate_username("aL:a").is_ok());
    }
    
    #[test]
    fn test_validate_channel() {
        assert_eq!(true, validate_channel("#ala").is_ok());
        assert_eq!(true, validate_channel("&ala").is_ok());
        assert_eq!(false, validate_channel("&al:a").is_ok());
        assert_eq!(false, validate_channel("&al,a").is_ok());
        assert_eq!(false, validate_channel("#al:a").is_ok());
        assert_eq!(false, validate_channel("#al,a").is_ok());
        assert_eq!(false, validate_channel("ala").is_ok());
    }
    
    #[test]
    fn test_validate_server() {
        assert_eq!(true, validate_server("somebody.org",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_server("somebodyorg",
                WrongParameter(PINGId, 0)).is_ok());
    }
    
    #[test]
    fn test_validate_server_mask() {
        assert_eq!(true, validate_server_mask("somebody.org",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_server_mask("*org",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_server_mask("somebodyorg",
                WrongParameter(PINGId, 0)).is_ok());
    }
    
    #[test]
    fn test_validate_prefixed_channel() {
        assert_eq!(true, validate_prefixed_channel("#ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("&ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_prefixed_channel("&al:a",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_prefixed_channel("&al,a",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_prefixed_channel("#al:a",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_prefixed_channel("#al,a",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_prefixed_channel("ala",
                WrongParameter(PINGId, 0)).is_ok());
        
        assert_eq!(true, validate_prefixed_channel("~#ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("+#ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("%#ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("&#ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("@#ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("~&ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("+&ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("%&ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("&&ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(true, validate_prefixed_channel("@&ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_prefixed_channel("*#ala",
                WrongParameter(PINGId, 0)).is_ok());
        assert_eq!(false, validate_prefixed_channel("*&ala",
                WrongParameter(PINGId, 0)).is_ok());
    }
    
    #[test]
    fn test_validate_usermodes() {
        assert_eq!(Ok(()), validate_usermodes(&vec![
            ("+io-rw", vec![]), ("-O", vec![])]).map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_usermodes(&vec![
            ("+io", vec![]), ("-rO", vec![]), ("-w", vec![])])
                .map_err(|e| e.to_string()));
        assert_eq!(Err("Wrong parameter 1 in command 'MODE'".to_string()),
            validate_usermodes(&vec![("+io-rw", vec!["xx"]),
                    ("-O", vec![])]).map_err(|e| e.to_string()));
        assert_eq!(Err("Unknown umode flag in parameter 2".to_string()),
            validate_usermodes(&vec![
                ("+io-rw", vec![]), ("-x", vec![])]).map_err(|e| e.to_string()));
    }
    
    #[test]
    fn test_validate_channelmodes() {
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("+nt", vec![]), ("-sm", vec![])]).map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("+nlt", vec!["22"]), ("-s+km", vec!["xxyy"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("+ibl-h", vec!["*dudu.com", "22", "derek"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("-nlt", vec![]), ("+s-km", vec![])]).map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("+ot", vec!["barry"]), ("-nh", vec!["guru"]), ("+vm", vec!["jerry"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("-to", vec!["barry"]), ("+hn", vec!["guru"]), ("-mv", vec!["jerry"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("-tb", vec!["barry"]), ("+iI", vec!["guru"]), ("-es", vec!["eagle"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("+tb", vec!["barry"]), ("-iI", vec!["guru"]), ("+es", vec!["eagle"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Ok(()), validate_channelmodes("#xchan", &vec![
            ("-to", vec!["barry"]), ("+an", vec!["guru"]), ("-mq", vec!["jerry"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Err("Unknown mode u in parameter 2 for #xchan".to_string()),
            validate_channelmodes("#xchan", &vec![("+nt", vec![]), ("-sum", vec![])])
                .map_err(|e| e.to_string()));
        assert_eq!(Err("Invalid mode parameter: #xchan l  No argument".to_string()),
            validate_channelmodes("#xchan", &vec![("+nlt", vec![]), ("-s+km", vec!["xxyy"])])
                .map_err(|e| e.to_string()));
        assert_eq!(Err("Invalid mode parameter: #xchan v jer:ry Validation error: Username \
                must not contains '.', ',' or ':'. [{}]".to_string()),
            validate_channelmodes("#xchan", &vec![
                ("+ot", vec!["barry"]), ("-nh", vec!["guru"]), ("+vm", vec!["jer:ry"])])
                    .map_err(|e| e.to_string()));
        assert_eq!(Err("Invalid mode parameter: #xchan h gu:ru Validation error: Username \
                must not contains '.', ',' or ':'. [{}]".to_string()),
            validate_channelmodes("#xchan", &vec![
                ("+ot", vec!["barry"]), ("-nh", vec!["gu:ru"]), ("+vm", vec!["jerry"])])
                    .map_err(|e| e.to_string()));
        assert_eq!(Err("Invalid mode parameter: #xchan o b,arry Validation error: Username \
                must not contains '.', ',' or ':'. [{}]".to_string()),
            validate_channelmodes("#xchan", &vec![
                ("+ot", vec!["b,arry"]), ("-nh", vec!["guru"]), ("+vm", vec!["jerry"])])
                    .map_err(|e| e.to_string()));
    }
    
    #[test]
    fn test_match_wildcard() {
        assert!(match_wildcard("somebody", "somebody"));
        assert!(!match_wildcard("somebody", "somebady"));
        assert!(match_wildcard("s?meb?dy", "samebady"));
        assert!(!match_wildcard("s?mec?dy", "samebady"));
        assert!(!match_wildcard("somebody", "somebod"));
        assert!(!match_wildcard("somebody", "somebodyis"));
        assert!(match_wildcard("so*body", "somebody"));
        assert!(match_wildcard("so**body", "somebody"));
        assert!(match_wildcard("so*body", "sobody"));
        assert!(match_wildcard("so*body*", "sobody"));
        assert!(match_wildcard("*so*body*", "sobody"));
        assert!(!match_wildcard("so*body", "sbody"));
        assert!(!match_wildcard("*so*body*", "sbody"));
        assert!(match_wildcard("so*body", "something body"));
        assert!(match_wildcard("so*bo*", "somebody"));
        assert!(match_wildcard("*", "Alice and Others"));
        assert!(!match_wildcard("", "Alice and Others"));
        assert!(match_wildcard("", ""));
        assert!(match_wildcard("*", ""));
        assert!(match_wildcard("***", ""));
        assert!(match_wildcard("* and Others", "Alice and Others"));
        assert!(!match_wildcard("* and Others", "Alice and others"));
        assert!(!match_wildcard("* and Others", "Aliceand Others"));
        assert!(match_wildcard("* and *", "Alice and Others"));
        assert!(match_wildcard("*** and **", "Alice and Others"));
        assert!(!match_wildcard("* and *", "Aliceand Others"));
        assert!(!match_wildcard("* and *", "Alice andOthers"));
        assert!(!match_wildcard("*** and ***", "Aliceand Others"));
        assert!(!match_wildcard("*** and ***", "Alice andOthers"));
        assert!(match_wildcard("*?and *", "Aliceand Others"));
        assert!(match_wildcard("* and?*", "Alice andOthers"));
        assert!(!match_wildcard("*?and *", "Aliceund Others"));
        assert!(!match_wildcard("* and?*", "Alice undOthers"));
        assert!(match_wildcard("lu*na*Xna*Y", "lulu and nanaXnaY"));
        assert!(match_wildcard("lu*Xlu*Wlu*Zlu*B",
                "lulululuYlululuXlululuWluluZluluAluluB"));
        assert!(match_wildcard("lu*?lu*?lu*?lu*?",
                "lulululuYlululuXlululuWluluZluluAluluB"));
        assert!(match_wildcard("*lu*Xlu*Wlu*Zlu*B*",
                "XXXlulululuYlululuXlululuWluluZluluAluluBlululu"));
        assert!(match_wildcard("la*la", "labulabela"));
        assert!(!match_wildcard("la*la", "labulabele"));
        assert!(match_wildcard("la*la*la", "labulalabela"));
        assert!(!match_wildcard("la*la*la", "labulalabele"));
        assert!(match_wildcard("la*l?", "labulabela"));
        assert!(!match_wildcard("la*?a", "labulabele"));
        assert!(!match_wildcard("la*l?", "labulabeka"));
        assert!(match_wildcard("greg*@somehere*", "greg-guru@somehere.net"));
        assert!(match_wildcard("greg*@somehere*", "greg@@@@somehere@@@"));
        assert!(!match_wildcard("greg*@somehere*", "greg.somehere@@@"));
    }
    
    #[test]
    fn test_normalize_sourcemask() {
        assert_eq!("ax*!*bob*@*.com", &normalize_sourcemask("ax*!*bob*@*.com"));
        assert_eq!("ax*!*@*.com", &normalize_sourcemask("ax*@*.com"));
        assert_eq!("ax*!bo*@*", &normalize_sourcemask("ax*!bo*"));
        assert_eq!("*ax!*@*.com", &normalize_sourcemask("*ax@*.com"));
        assert_eq!("u*xn!b*o@*", &normalize_sourcemask("u*xn!b*o"));
        assert_eq!("*!*@*", &normalize_sourcemask("*"));
        assert_eq!("bob.com!*@*", &normalize_sourcemask("bob.com"));
    }
    
    #[test]
    fn test_test_argon2_verify_password() {
        let phash = argon2_hash_password("lalalaXX");
        assert!(argon2_verify_password("lalalaXX", &phash).is_ok());
        assert!(argon2_verify_password("lalalaXY", &phash).is_err());
    }
    
    #[tokio::test]
    async fn test_argon2_verify_password_async() {
        let phash = argon2_hash_password("lalalaXX");
        assert!(argon2_verify_password_async("lalalaXX".to_string(),
                        phash.clone()).await.is_ok());
        assert!(argon2_verify_password_async("lalalaXY".to_string(),
                        phash).await.is_err());
    }
    
    #[test]
    fn test_validate_password_hash() {
        assert!(validate_password_hash("VgWezXctjWvsY6V7gzSQPnluUuAwq06m5IxwcIg3OfBIMM+zWCJ\
        ntk8HEZDgh4ctFei3bqt1r0O1VIyOV7dL+w").is_ok());
        assert_eq!(Err("Validation error: Wrong password hash length [{}]".to_string()),
            validate_password_hash("zXctjWvsY6V7gzSQPnluUuAwq06m5IxwcIg3OfBIMM+zWCJ\
                ntk8HEZDgh4ctFei3bqt1r0O1VIyOV7dL+w").map_err(|e| e.to_string()));
        assert_eq!(Err("Validation error: Wrong base64 password hash [{}]".to_string()),
            validate_password_hash("xxxxxxxxx").map_err(|e| e.to_string()));
    }
}