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
#[cfg(test)]
pub mod test;

use std::io;

use bitflags::bitflags;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use failure::Fail;
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive, ToPrimitive};

use crate::{
    impl_from_error, try_read_optional, try_write_optional, utils, utils::CharacterSet, PduParsing,
};

const RECONNECT_COOKIE_LEN: usize = 28;
const TIMEZONE_INFO_NAME_LEN: usize = 64;
const COMPRESSION_TYPE_MASK: u32 = 0x0000_1E00;

const CODE_PAGE_SIZE: usize = 4;
const FLAGS_SIZE: usize = 4;
const DOMAIN_LENGTH_SIZE: usize = 2;
const USER_NAME_LENGTH_SIZE: usize = 2;
const PASSWORD_LENGTH_SIZE: usize = 2;
const ALTERNATE_SHELL_LENGTH_SIZE: usize = 2;
const WORK_DIR_LENGTH_SIZE: usize = 2;

const CLIENT_ADDRESS_FAMILY_SIZE: usize = 2;
const CLIENT_ADDRESS_LENGTH_SIZE: usize = 2;
const CLIENT_DIR_LENGTH_SIZE: usize = 2;
const SESSION_ID_SIZE: usize = 4;
const PERFORMANCE_FLAGS_SIZE: usize = 4;
const RECONNECT_COOKIE_LENGTH_SIZE: usize = 2;
const BIAS_SIZE: usize = 4;
const SYSTEM_TIME_SIZE: usize = 16;

#[derive(Debug, Clone, PartialEq)]
pub struct ClientInfo {
    pub credentials: Credentials,
    pub code_page: u32,
    pub flags: ClientInfoFlags,
    pub compression_type: CompressionType,
    pub alternate_shell: String,
    pub work_dir: String,
    pub extra_info: ExtendedClientInfo,
}

impl PduParsing for ClientInfo {
    type Error = ClientInfoError;

    fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
        let code_page = stream.read_u32::<LittleEndian>()?;
        let flags_with_compression_type = stream.read_u32::<LittleEndian>()?;

        let flags =
            ClientInfoFlags::from_bits(flags_with_compression_type & !COMPRESSION_TYPE_MASK)
                .ok_or(ClientInfoError::InvalidClientInfoFlags)?;
        let compression_type = CompressionType::from_u8(
            ((flags_with_compression_type & COMPRESSION_TYPE_MASK) >> 9) as u8,
        )
        .ok_or(ClientInfoError::InvalidClientInfoFlags)?;
        let character_set = if flags.contains(ClientInfoFlags::UNICODE) {
            CharacterSet::Unicode
        } else {
            CharacterSet::Ansi
        };

        // Sizes exclude the length of the mandatory null terminator
        let domain_size = stream.read_u16::<LittleEndian>()? as usize;
        let user_name_size = stream.read_u16::<LittleEndian>()? as usize;
        let password_size = stream.read_u16::<LittleEndian>()? as usize;
        let alternate_shell_size = stream.read_u16::<LittleEndian>()? as usize;
        let work_dir_size = stream.read_u16::<LittleEndian>()? as usize;

        let domain = utils::read_string(&mut stream, domain_size, character_set, true)?;
        let username = utils::read_string(&mut stream, user_name_size, character_set, true)?;
        let password = utils::read_string(&mut stream, password_size, character_set, true)?;

        let domain = if domain.is_empty() {
            None
        } else {
            Some(domain)
        };
        let credentials = Credentials {
            username,
            password,
            domain,
        };

        let alternate_shell =
            utils::read_string(&mut stream, alternate_shell_size, character_set, true)?;
        let work_dir = utils::read_string(&mut stream, work_dir_size, character_set, true)?;

        let extra_info = ExtendedClientInfo::from_buffer(&mut stream, character_set)?;

        Ok(Self {
            credentials,
            code_page,
            flags,
            compression_type,
            alternate_shell,
            work_dir,
            extra_info,
        })
    }

    fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
        let character_set = if self.flags.contains(ClientInfoFlags::UNICODE) {
            CharacterSet::Unicode
        } else {
            CharacterSet::Ansi
        };

        stream.write_u32::<LittleEndian>(self.code_page)?;

        let flags_with_compression_type =
            self.flags.bits() | (self.compression_type.to_u32().unwrap() << 9);
        stream.write_u32::<LittleEndian>(flags_with_compression_type)?;

        let domain = self.credentials.domain.clone().unwrap_or_default();
        stream.write_u16::<LittleEndian>(string_len(domain.as_str(), character_set))?;
        stream.write_u16::<LittleEndian>(string_len(
            self.credentials.username.as_str(),
            character_set,
        ))?;
        stream.write_u16::<LittleEndian>(string_len(
            self.credentials.password.as_str(),
            character_set,
        ))?;
        stream
            .write_u16::<LittleEndian>(string_len(self.alternate_shell.as_str(), character_set))?;
        stream.write_u16::<LittleEndian>(string_len(self.work_dir.as_str(), character_set))?;

        utils::write_string_with_null_terminator(&mut stream, domain.as_str(), character_set)?;
        utils::write_string_with_null_terminator(
            &mut stream,
            self.credentials.username.as_str(),
            character_set,
        )?;
        utils::write_string_with_null_terminator(
            &mut stream,
            self.credentials.password.as_str(),
            character_set,
        )?;
        utils::write_string_with_null_terminator(
            &mut stream,
            self.alternate_shell.as_str(),
            character_set,
        )?;
        utils::write_string_with_null_terminator(
            &mut stream,
            self.work_dir.as_str(),
            character_set,
        )?;

        self.extra_info.to_buffer(&mut stream, character_set)?;

        Ok(())
    }

    fn buffer_length(&self) -> usize {
        let character_set = if self.flags.contains(ClientInfoFlags::UNICODE) {
            CharacterSet::Unicode
        } else {
            CharacterSet::Ansi
        };
        let domain = self.credentials.domain.clone().unwrap_or_default();

        CODE_PAGE_SIZE
            + FLAGS_SIZE
            + DOMAIN_LENGTH_SIZE
            + USER_NAME_LENGTH_SIZE
            + PASSWORD_LENGTH_SIZE
            + ALTERNATE_SHELL_LENGTH_SIZE
            + WORK_DIR_LENGTH_SIZE
            + (string_len(domain.as_str(), character_set)
                + string_len(self.credentials.username.as_str(), character_set)
                + string_len(self.credentials.password.as_str(), character_set)
                + string_len(self.alternate_shell.as_str(), character_set)
                + string_len(self.work_dir.as_str(), character_set)) as usize
            + character_set.to_usize().unwrap() * 5 // null terminator
            + self.extra_info.buffer_length(character_set)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Credentials {
    pub username: String,
    pub password: String,
    pub domain: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ExtendedClientInfo {
    pub address_family: AddressFamily,
    pub address: String,
    pub dir: String,
    pub optional_data: ExtendedClientOptionalInfo,
}

impl ExtendedClientInfo {
    fn from_buffer(
        mut stream: impl io::Read,
        character_set: CharacterSet,
    ) -> Result<Self, ClientInfoError> {
        let address_family = AddressFamily::from_u16(stream.read_u16::<LittleEndian>()?)
            .ok_or(ClientInfoError::InvalidAddressFamily)?;

        // This size includes the length of the mandatory null terminator.
        let address_size = stream.read_u16::<LittleEndian>()? as usize;
        let address = utils::read_string(&mut stream, address_size, character_set, false)?;

        // This size includes the length of the mandatory null terminator.
        let dir_size = stream.read_u16::<LittleEndian>()? as usize;
        let dir = utils::read_string(&mut stream, dir_size, character_set, false)?;

        let optional_data = ExtendedClientOptionalInfo::from_buffer(&mut stream)?;

        Ok(Self {
            address_family,
            address,
            dir,
            optional_data,
        })
    }

    fn to_buffer(
        &self,
        mut stream: impl io::Write,
        character_set: CharacterSet,
    ) -> Result<(), ClientInfoError> {
        stream.write_u16::<LittleEndian>(self.address_family.to_u16().unwrap())?;

        // + size of null terminator, which will write in the write_string function
        stream.write_u16::<LittleEndian>(
            string_len(self.address.as_str(), character_set) + character_set.to_u16().unwrap(),
        )?;
        utils::write_string_with_null_terminator(
            &mut stream,
            self.address.as_str(),
            character_set,
        )?;

        stream.write_u16::<LittleEndian>(
            string_len(self.dir.as_str(), character_set) + character_set.to_u16().unwrap(),
        )?;
        utils::write_string_with_null_terminator(&mut stream, self.dir.as_str(), character_set)?;

        self.optional_data.to_buffer(&mut stream)?;

        Ok(())
    }

    fn buffer_length(&self, character_set: CharacterSet) -> usize {
        CLIENT_ADDRESS_FAMILY_SIZE
            + CLIENT_ADDRESS_LENGTH_SIZE
            + string_len(self.address.as_str(), character_set) as usize
            + character_set.to_usize().unwrap() // null terminator
        + CLIENT_DIR_LENGTH_SIZE
        + string_len(self.dir.as_str(), character_set) as usize
            + character_set.to_usize().unwrap() // null terminator
        + self.optional_data.buffer_length()
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct ExtendedClientOptionalInfo {
    pub timezone: Option<TimezoneInfo>,
    pub session_id: Option<u32>,
    pub performance_flags: Option<PerformanceFlags>,
    pub reconnect_cookie: Option<[u8; RECONNECT_COOKIE_LEN]>,
    // other fields are read by RdpVersion::Ten+
}

impl PduParsing for ExtendedClientOptionalInfo {
    type Error = ClientInfoError;

    fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
        let mut optional_data = Self::default();

        optional_data.timezone = match TimezoneInfo::from_buffer(&mut stream) {
            Ok(v) => Some(v),
            Err(ClientInfoError::IOError(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => {
                return Ok(optional_data)
            }
            Err(e) => return Err(e),
        };
        optional_data.session_id = Some(try_read_optional!(
            stream.read_u32::<LittleEndian>(),
            optional_data
        ));
        optional_data.performance_flags = Some(
            PerformanceFlags::from_bits(try_read_optional!(
                stream.read_u32::<LittleEndian>(),
                optional_data
            ))
            .ok_or(ClientInfoError::InvalidPerformanceFlags)?,
        );

        let reconnect_cookie_size =
            try_read_optional!(stream.read_u16::<LittleEndian>(), optional_data);
        if reconnect_cookie_size != RECONNECT_COOKIE_LEN as u16 && reconnect_cookie_size != 0 {
            return Err(ClientInfoError::InvalidReconnectCookie);
        }
        if reconnect_cookie_size == 0 {
            return Ok(optional_data);
        }

        let mut reconnect_cookie = [0; RECONNECT_COOKIE_LEN];
        try_read_optional!(stream.read_exact(&mut reconnect_cookie), optional_data);
        optional_data.reconnect_cookie = Some(reconnect_cookie);

        try_read_optional!(stream.read_u16::<LittleEndian>(), optional_data); // reserved1
        try_read_optional!(stream.read_u16::<LittleEndian>(), optional_data); // reserved2

        Ok(optional_data)
    }

    fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
        try_write_optional!(self.timezone, |value: &TimezoneInfo| value
            .to_buffer(&mut stream));
        try_write_optional!(self.session_id, |value: &u32| stream
            .write_u32::<LittleEndian>(*value));
        try_write_optional!(self.performance_flags, |value: &PerformanceFlags| {
            stream.write_u32::<LittleEndian>(value.bits())
        });
        if let Some(reconnection_cookie) = self.reconnect_cookie {
            stream.write_u16::<LittleEndian>(reconnection_cookie.len() as u16)?;
            stream.write_all(reconnection_cookie.as_ref())?;
        }

        Ok(())
    }

    fn buffer_length(&self) -> usize {
        let mut size = 0;

        if let Some(ref timezone) = self.timezone {
            size += timezone.buffer_length();
        }
        if self.session_id.is_some() {
            size += SESSION_ID_SIZE;
        }
        if self.performance_flags.is_some() {
            size += PERFORMANCE_FLAGS_SIZE;
        }
        if self.reconnect_cookie.is_some() {
            size += RECONNECT_COOKIE_LENGTH_SIZE + RECONNECT_COOKIE_LEN;
        }

        size
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct TimezoneInfo {
    pub bias: u32,
    pub standard_name: String,
    pub standard_date: Option<SystemTime>,
    pub standard_bias: u32,
    pub daylight_name: String,
    pub daylight_date: Option<SystemTime>,
    pub daylight_bias: u32,
}

impl PduParsing for TimezoneInfo {
    type Error = ClientInfoError;

    fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
        let bias = stream.read_u32::<LittleEndian>()?;

        let standard_name = utils::read_string(
            &mut stream,
            TIMEZONE_INFO_NAME_LEN,
            CharacterSet::Unicode,
            false,
        )?;
        let standard_date = Option::<SystemTime>::from_buffer(&mut stream)?;
        let standard_bias = stream.read_u32::<LittleEndian>()?;

        let daylight_name = utils::read_string(
            &mut stream,
            TIMEZONE_INFO_NAME_LEN,
            CharacterSet::Unicode,
            false,
        )?;
        let daylight_date = Option::<SystemTime>::from_buffer(&mut stream)?;
        let daylight_bias = stream.read_u32::<LittleEndian>()?;

        Ok(Self {
            bias,
            standard_name,
            standard_date,
            standard_bias,
            daylight_name,
            daylight_date,
            daylight_bias,
        })
    }

    fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
        stream.write_u32::<LittleEndian>(self.bias)?;

        let mut standard_name = utils::string_to_utf16(self.standard_name.as_str());
        standard_name.resize(TIMEZONE_INFO_NAME_LEN, 0);
        stream.write_all(standard_name.as_ref())?;

        self.standard_date.to_buffer(&mut stream)?;
        stream.write_u32::<LittleEndian>(self.standard_bias)?;

        let mut daylight_name = utils::string_to_utf16(self.daylight_name.as_str());
        daylight_name.resize(TIMEZONE_INFO_NAME_LEN, 0);
        stream.write_all(daylight_name.as_ref())?;

        self.daylight_date.to_buffer(&mut stream)?;
        stream.write_u32::<LittleEndian>(self.daylight_bias)?;

        Ok(())
    }

    fn buffer_length(&self) -> usize {
        BIAS_SIZE
            + TIMEZONE_INFO_NAME_LEN
            + self.standard_date.buffer_length()
            + BIAS_SIZE
            + TIMEZONE_INFO_NAME_LEN
            + self.daylight_date.buffer_length()
            + BIAS_SIZE
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct SystemTime {
    pub month: Month,
    pub day_of_week: DayOfWeek,
    pub day: DayOfWeekOccurrence,
    pub hour: u16,
    pub minute: u16,
    pub second: u16,
    pub milliseconds: u16,
}

impl PduParsing for Option<SystemTime> {
    type Error = ClientInfoError;

    fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
        let _year = stream.read_u16::<LittleEndian>()?; // This field MUST be set to zero.
        let month = stream.read_u16::<LittleEndian>()?;
        let day_of_week = stream.read_u16::<LittleEndian>()?;
        let day = stream.read_u16::<LittleEndian>()?;
        let hour = stream.read_u16::<LittleEndian>()?;
        let minute = stream.read_u16::<LittleEndian>()?;
        let second = stream.read_u16::<LittleEndian>()?;
        let milliseconds = stream.read_u16::<LittleEndian>()?;

        match (
            Month::from_u16(month),
            DayOfWeek::from_u16(day_of_week),
            DayOfWeekOccurrence::from_u16(day),
        ) {
            (Some(month), Some(day_of_week), Some(day)) => Ok(Some(SystemTime {
                month,
                day_of_week,
                day,
                hour,
                minute,
                second,
                milliseconds,
            })),
            _ => Ok(None),
        }
    }

    fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
        stream.write_u16::<LittleEndian>(0)?; // year
        match *self {
            Some(SystemTime {
                month,
                day_of_week,
                day,
                hour,
                minute,
                second,
                milliseconds,
            }) => {
                stream.write_u16::<LittleEndian>(month.to_u16().unwrap())?;
                stream.write_u16::<LittleEndian>(day_of_week.to_u16().unwrap())?;
                stream.write_u16::<LittleEndian>(day.to_u16().unwrap())?;
                stream.write_u16::<LittleEndian>(hour)?;
                stream.write_u16::<LittleEndian>(minute)?;
                stream.write_u16::<LittleEndian>(second)?;
                stream.write_u16::<LittleEndian>(milliseconds)?;
            }
            None => {
                stream.write_u16::<LittleEndian>(0)?;
                stream.write_u16::<LittleEndian>(0)?;
                stream.write_u16::<LittleEndian>(0)?;
                stream.write_u16::<LittleEndian>(0)?;
                stream.write_u16::<LittleEndian>(0)?;
                stream.write_u16::<LittleEndian>(0)?;
                stream.write_u16::<LittleEndian>(0)?;
            }
        }

        Ok(())
    }

    fn buffer_length(&self) -> usize {
        SYSTEM_TIME_SIZE
    }
}

#[repr(u16)]
#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum Month {
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12,
}

#[repr(u16)]
#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum DayOfWeek {
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
}

#[repr(u16)]
#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum DayOfWeekOccurrence {
    First = 1,
    Second = 2,
    Third = 3,
    Fourth = 4,
    Last = 5,
}

bitflags! {
    pub struct PerformanceFlags: u32 {
        const DISABLE_WALLPAPER = 0x0000_0001;
        const DISABLE_FULLWINDOWDRAG = 0x0000_0002;
        const DISABLE_MENUANIMATIONS = 0x0000_0004;
        const DISABLE_THEMING = 0x0000_0008;
        const RESERVED1 = 0x0000_0010;
        const DISABLE_CURSOR_SHADOW = 0x0000_0020;
        const DISABLE_CURSORSETTINGS = 0x0000_0040;
        const ENABLE_FONT_SMOOTHING = 0x0000_0080;
        const ENABLE_DESKTOP_COMPOSITION = 0x0000_0100;
        const RESERVED2 = 0x8000_0000;
    }
}

#[repr(u16)]
#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum AddressFamily {
    INet = 0x0002,
    INet6 = 0x0017,
}

bitflags! {
    pub struct ClientInfoFlags: u32 {
        const MOUSE = 0x0000_0001;
        const DISABLE_CTRL_ALT_DEL = 0x0000_0002;
        const AUTOLOGON = 0x0000_0008;
        const UNICODE = 0x0000_0010;
        const MAXIMIZE_SHELL = 0x0000_0020;
        const LOGON_NOTIFY = 0x0000_0040;
        const COMPRESSION = 0x0000_0080;
        const ENABLE_WINDOWS_KEY = 0x0000_0100;
        const REMOTE_CONSOLE_AUDIO = 0x0000_2000;
        const FORCE_ENCRYPTED_CS_PDU = 0x0000_4000;
        const RAIL = 0x0000_8000;
        const LOGON_ERRORS = 0x0001_0000;
        const MOUSE_HAS_WHEEL = 0x0002_0000;
        const PASSWORD_IS_SC_PIN = 0x0004_0000;
        const NO_AUDIO_PLAYBACK = 0x0008_0000;
        const USING_SAVED_CREDS = 0x0010_0000;
        const AUDIO_CAPTURE = 0x0020_0000;
        const VIDEO_DISABLE = 0x0040_0000;
        const RESERVED1 = 0x0080_0000;
        const RESERVED2 = 0x0100_0000;
        const HIDEF_RAIL_SUPPORTED = 0x0200_0000;
    }
}

#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum CompressionType {
    K8 = 0,
    K64 = 1,
    Rdp6 = 2,
    Rdp61 = 3,
}

#[derive(Debug, Fail)]
pub enum ClientInfoError {
    #[fail(display = "IO error: {}", _0)]
    IOError(#[fail(cause)] io::Error),
    #[fail(display = "UTF-8 error: {}", _0)]
    Utf8Error(#[fail(cause)] std::string::FromUtf8Error),
    #[fail(display = "Invalid address family field")]
    InvalidAddressFamily,
    #[fail(display = "Invalid flags field")]
    InvalidClientInfoFlags,
    #[fail(display = "Invalid performance flags field")]
    InvalidPerformanceFlags,
    #[fail(display = "Invalid reconnect cookie field")]
    InvalidReconnectCookie,
}

impl_from_error!(io::Error, ClientInfoError, ClientInfoError::IOError);
impl_from_error!(
    std::string::FromUtf8Error,
    ClientInfoError,
    ClientInfoError::Utf8Error
);

fn string_len(value: &str, character_set: CharacterSet) -> u16 {
    value.len() as u16 * character_set.to_u16().unwrap()
}