-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathmod.rs
3415 lines (2980 loc) · 108 KB
/
mod.rs
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
// Copyright (c) 2017 Anatoly Ikorsky
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use bytes::BufMut;
use lexical::parse;
use regex::bytes::Regex;
use smallvec::SmallVec;
use std::{
borrow::Cow, cmp::max, collections::HashMap, convert::TryFrom, fmt, io, marker::PhantomData,
};
use crate::{
constants::{
CapabilityFlags, ColumnFlags, ColumnType, Command, CursorType, SessionStateType,
StatusFlags, StmtExecuteParamFlags, StmtExecuteParamsFlags, MAX_PAYLOAD_LEN,
UTF8MB4_GENERAL_CI, UTF8_GENERAL_CI,
},
io::{BufMutExt, ParseBuf},
misc::{
lenenc_str_len,
raw::{
bytes::{
BareBytes, ConstBytes, ConstBytesValue, EofBytes, LenEnc, NullBytes, U32Bytes,
U8Bytes,
},
int::{ConstU32, ConstU8, LeU16, LeU24, LeU32, LeU32LowerHalf, LeU32UpperHalf, LeU64},
seq::Seq,
Const, Either, RawBytes, RawConst, RawInt, Skip,
},
unexpected_buf_eof,
},
proto::{MyDeserialize, MySerialize},
value::{ClientSide, SerializationSide, Value},
};
use self::session_state_change::SessionStateChange;
lazy_static::lazy_static! {
static ref MARIADB_VERSION_RE: Regex =
Regex::new(r"^5.5.5-(\d{1,2})\.(\d{1,2})\.(\d{1,3})-MariaDB").unwrap();
static ref VERSION_RE: Regex = Regex::new(r"^(\d{1,2})\.(\d{1,2})\.(\d{1,3})(.*)").unwrap();
}
macro_rules! define_header {
($name:ident, $err:ident($msg:literal), $val:literal) => {
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error($msg)]
pub struct $err;
pub type $name = ConstU8<$err, $val>;
};
($name:ident, $cmd:ident, $err:ident) => {
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error("Invalid header for {}", stringify!($cmd))]
pub struct $err;
pub type $name = ConstU8<$err, { Command::$cmd as u8 }>;
};
}
macro_rules! define_const {
($kind:ident, $name:ident, $err:ident($msg:literal), $val:literal) => {
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error($msg)]
pub struct $err;
pub type $name = $kind<$err, $val>;
};
}
macro_rules! define_const_bytes {
($vname:ident, $name:ident, $err:ident($msg:literal), $val:expr, $len:literal) => {
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error($msg)]
pub struct $err;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub struct $vname;
impl ConstBytesValue<$len> for $vname {
const VALUE: [u8; $len] = $val;
type Error = $err;
}
pub type $name = ConstBytes<$vname, $len>;
};
}
pub mod binlog_request;
pub mod session_state_change;
define_const_bytes!(
Catalog,
ColumnDefinitionCatalog,
InvalidCatalog("Invalid catalog value in the column definition"),
*b"\x03def",
4
);
define_const!(
ConstU8,
FixedLengthFieldsLen,
InvalidFixedLengthFieldsLen("Invalid fixed length field length in the column definition"),
0x0c
);
/// Represents MySql Column (column packet).
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Column {
catalog: ColumnDefinitionCatalog,
schema: SmallVec<[u8; 16]>,
table: SmallVec<[u8; 16]>,
org_table: SmallVec<[u8; 16]>,
name: SmallVec<[u8; 16]>,
org_name: SmallVec<[u8; 16]>,
fixed_length_fields_len: FixedLengthFieldsLen,
column_length: RawInt<LeU32>,
character_set: RawInt<LeU16>,
column_type: Const<ColumnType, u8>,
flags: Const<ColumnFlags, LeU16>,
decimals: RawInt<u8>,
__filler: Skip<2>,
// COM_FIELD_LIST is deprecated, so we won't support it
}
impl<'de> MyDeserialize<'de> for Column {
const SIZE: Option<usize> = None;
type Ctx = ();
fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
let catalog = buf.parse(())?;
let schema = buf.parse_unchecked(())?;
let table = buf.parse_unchecked(())?;
let org_table = buf.parse_unchecked(())?;
let name = buf.parse_unchecked(())?;
let org_name = buf.parse_unchecked(())?;
let mut buf: ParseBuf = buf.parse(13)?;
Ok(Column {
catalog,
schema,
table,
org_table,
name,
org_name,
fixed_length_fields_len: buf.parse_unchecked(())?,
character_set: buf.parse_unchecked(())?,
column_length: buf.parse_unchecked(())?,
column_type: buf.parse_unchecked(())?,
flags: buf.parse_unchecked(())?,
decimals: buf.parse_unchecked(())?,
__filler: buf.parse_unchecked(())?,
})
}
}
impl MySerialize for Column {
fn serialize(&self, buf: &mut Vec<u8>) {
self.catalog.serialize(&mut *buf);
self.schema.serialize(&mut *buf);
self.table.serialize(&mut *buf);
self.org_table.serialize(&mut *buf);
self.name.serialize(&mut *buf);
self.org_name.serialize(&mut *buf);
self.fixed_length_fields_len.serialize(&mut *buf);
self.column_length.serialize(&mut *buf);
self.character_set.serialize(&mut *buf);
self.column_type.serialize(&mut *buf);
self.flags.serialize(&mut *buf);
self.decimals.serialize(&mut *buf);
self.__filler.serialize(&mut *buf);
}
}
impl Column {
pub fn new(column_type: ColumnType) -> Self {
Self {
catalog: Default::default(),
schema: Default::default(),
table: Default::default(),
org_table: Default::default(),
name: Default::default(),
org_name: Default::default(),
fixed_length_fields_len: Default::default(),
column_length: Default::default(),
character_set: Default::default(),
flags: Default::default(),
column_type: Const::new(column_type),
decimals: Default::default(),
__filler: Skip,
}
}
pub fn with_schema(mut self, schema: &[u8]) -> Self {
self.schema = schema.into();
self
}
pub fn with_table(mut self, table: &[u8]) -> Self {
self.table = table.into();
self
}
pub fn with_org_table(mut self, org_table: &[u8]) -> Self {
self.org_table = org_table.into();
self
}
pub fn with_name(mut self, name: &[u8]) -> Self {
self.name = name.into();
self
}
pub fn with_org_name(mut self, org_name: &[u8]) -> Self {
self.org_name = org_name.into();
self
}
pub fn with_flags(mut self, flags: ColumnFlags) -> Self {
self.flags = Const::new(flags);
self
}
pub fn with_column_length(mut self, column_length: u32) -> Self {
self.column_length = RawInt::new(column_length);
self
}
pub fn with_character_set(mut self, character_set: u16) -> Self {
self.character_set = RawInt::new(character_set);
self
}
pub fn with_decimals(mut self, decimals: u8) -> Self {
self.decimals = RawInt::new(decimals);
self
}
/// Returns value of the column_length field of a column packet.
///
/// Can be used for text-output formatting.
pub fn column_length(&self) -> u32 {
*self.column_length
}
/// Returns value of the column_type field of a column packet.
pub fn column_type(&self) -> ColumnType {
*self.column_type
}
/// Returns value of the character_set field of a column packet.
pub fn character_set(&self) -> u16 {
*self.character_set
}
/// Returns value of the flags field of a column packet.
pub fn flags(&self) -> ColumnFlags {
*self.flags
}
/// Returns value of the decimals field of a column packet.
///
/// Max shown decimal digits. Can be used for text-output formatting
///
/// * `0x00` for integers and static strings
/// * `0x1f` for dynamic strings, double, float
/// * `0x00..=0x51` for decimals
pub fn decimals(&self) -> u8 {
*self.decimals
}
/// Returns value of the schema field of a column packet as a byte slice.
pub fn schema_ref(&self) -> &[u8] {
&*self.schema
}
/// Returns value of the schema field of a column packet as a string (lossy converted).
pub fn schema_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.schema_ref())
}
/// Returns value of the table field of a column packet as a byte slice.
pub fn table_ref(&self) -> &[u8] {
&*self.table
}
/// Returns value of the table field of a column packet as a string (lossy converted).
pub fn table_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.table_ref())
}
/// Returns value of the org_table field of a column packet as a byte slice.
///
/// "org_table" is for original table name.
pub fn org_table_ref(&self) -> &[u8] {
&*self.org_table
}
/// Returns value of the org_table field of a column packet as a string (lossy converted).
pub fn org_table_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.org_table_ref())
}
/// Returns value of the name field of a column packet as a byte slice.
pub fn name_ref(&self) -> &[u8] {
&*self.name
}
/// Returns value of the name field of a column packet as a string (lossy converted).
pub fn name_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.name_ref())
}
/// Returns value of the org_name field of a column packet as a byte slice.
///
/// "org_name" is for original column name.
pub fn org_name_ref(&self) -> &[u8] {
&*self.org_name
}
/// Returns value of the org_name field of a column packet as a string (lossy converted).
pub fn org_name_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.org_name_ref())
}
}
/// Represents change in session state (part of MySql's Ok packet).
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SessionStateInfo<'a> {
data_type: Const<SessionStateType, u8>,
data: RawBytes<'a, LenEnc>,
}
impl<'a> SessionStateInfo<'a> {
pub fn into_owned(self) -> SessionStateInfo<'static> {
let SessionStateInfo { data_type, data } = self;
SessionStateInfo {
data_type,
data: data.into_owned(),
}
}
pub fn data_type(&self) -> SessionStateType {
*self.data_type
}
/// Returns raw session state info data.
pub fn data_ref(&self) -> &[u8] {
self.data.as_bytes()
}
/// Tries to decode session state info data.
pub fn decode(&self) -> io::Result<SessionStateChange<'_>> {
ParseBuf(self.data.as_bytes()).parse_unchecked(*self.data_type)
}
}
impl<'de> MyDeserialize<'de> for SessionStateInfo<'de> {
const SIZE: Option<usize> = None;
type Ctx = ();
fn deserialize(_ctx: Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
Ok(SessionStateInfo {
data_type: buf.parse(())?,
data: buf.parse(())?,
})
}
}
impl MySerialize for SessionStateInfo<'_> {
fn serialize(&self, buf: &mut Vec<u8>) {
self.data_type.serialize(&mut *buf);
self.data.serialize(buf);
}
}
/// Represents MySql's Ok packet.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct OkPacketBody<'a> {
affected_rows: RawInt<LenEnc>,
last_insert_id: RawInt<LenEnc>,
status_flags: Const<StatusFlags, LeU16>,
warnings: RawInt<LeU16>,
info: RawBytes<'a, LenEnc>,
session_state_info: RawBytes<'a, LenEnc>,
}
/// OK packet kind (see _OK packet identifier_ section of [WL#7766][1]).
///
/// [1]: https://dev.mysql.com/worklog/task/?id=7766
pub trait OkPacketKind {
const HEADER: u8;
fn parse_body<'de>(
capabilities: CapabilityFlags,
buf: &mut ParseBuf<'de>,
) -> io::Result<OkPacketBody<'de>>;
}
/// Ok pakcet that terminates a result set (text or binary).
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct ResultSetTerminator;
impl OkPacketKind for ResultSetTerminator {
const HEADER: u8 = 0xFE;
fn parse_body<'de>(
_: CapabilityFlags,
buf: &mut ParseBuf<'de>,
) -> io::Result<OkPacketBody<'de>> {
// We assume that CLIENT_PROTOCOL_41 was set
let mut buf: ParseBuf = buf.parse(4)?;
let warnings = buf.parse_unchecked(())?;
let status_flags = buf.parse_unchecked(())?;
Ok(OkPacketBody {
affected_rows: RawInt::new(0),
last_insert_id: RawInt::new(0),
status_flags,
warnings,
info: RawBytes::new(&[][..]),
session_state_info: RawBytes::new(&[][..]),
})
}
}
/// This packet terminates a binlog network stream.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct NetworkStreamTerminator;
impl OkPacketKind for NetworkStreamTerminator {
const HEADER: u8 = 0xFE;
fn parse_body<'de>(
flags: CapabilityFlags,
buf: &mut ParseBuf<'de>,
) -> io::Result<OkPacketBody<'de>> {
ResultSetTerminator::parse_body(flags, buf)
}
}
/// Ok packet that is not a result set terminator.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct CommonOkPacket;
impl OkPacketKind for CommonOkPacket {
const HEADER: u8 = 0x00;
fn parse_body<'de>(
capabilities: CapabilityFlags,
buf: &mut ParseBuf<'de>,
) -> io::Result<OkPacketBody<'de>> {
let affected_rows = buf.parse(())?;
let last_insert_id = buf.parse(())?;
// We assume that CLIENT_PROTOCOL_41 was set
let mut sbuf: ParseBuf = buf.parse(4)?;
let status_flags: Const<StatusFlags, LeU16> = sbuf.parse_unchecked(())?;
let warnings = sbuf.parse_unchecked(())?;
let (info, session_state_info) =
if capabilities.contains(CapabilityFlags::CLIENT_SESSION_TRACK) && !buf.is_empty() {
let info = buf.parse(())?;
let session_state_info =
if status_flags.contains(StatusFlags::SERVER_SESSION_STATE_CHANGED) {
buf.parse(())?
} else {
RawBytes::default()
};
(info, session_state_info)
} else if !buf.is_empty() && buf.0[0] > 0 {
// The `info` field is a `string<EOF>` according to the MySQL Internals
// Manual, but actually it's a `string<lenenc>`.
// SEE: sql/protocol_classics.cc `net_send_ok`
let info = buf.parse(())?;
(info, RawBytes::default())
} else {
(RawBytes::default(), RawBytes::default())
};
Ok(OkPacketBody {
affected_rows,
last_insert_id,
status_flags,
warnings,
info,
session_state_info,
})
}
}
impl<'a> TryFrom<OkPacketBody<'a>> for OkPacket<'a> {
type Error = io::Error;
fn try_from(body: OkPacketBody<'a>) -> io::Result<Self> {
Ok(OkPacket {
affected_rows: *body.affected_rows,
last_insert_id: if *body.last_insert_id == 0 {
None
} else {
Some(*body.last_insert_id)
},
status_flags: *body.status_flags,
warnings: *body.warnings,
info: if !body.info.is_empty() {
Some(body.info)
} else {
None
},
session_state_info: if !body.session_state_info.is_empty() {
Some(body.session_state_info)
} else {
None
},
})
}
}
/// Represents MySql's Ok packet.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct OkPacket<'a> {
affected_rows: u64,
last_insert_id: Option<u64>,
status_flags: StatusFlags,
warnings: u16,
info: Option<RawBytes<'a, LenEnc>>,
session_state_info: Option<RawBytes<'a, LenEnc>>,
}
impl<'a> OkPacket<'a> {
pub fn into_owned(self) -> OkPacket<'static> {
OkPacket {
affected_rows: self.affected_rows,
last_insert_id: self.last_insert_id,
status_flags: self.status_flags,
warnings: self.warnings,
info: self.info.map(|x| x.into_owned()),
session_state_info: self.session_state_info.map(|x| x.into_owned()),
}
}
/// Value of the affected_rows field of an Ok packet.
pub fn affected_rows(&self) -> u64 {
self.affected_rows
}
/// Value of the last_insert_id field of an Ok packet.
pub fn last_insert_id(&self) -> Option<u64> {
self.last_insert_id
}
/// Value of the status_flags field of an Ok packet.
pub fn status_flags(&self) -> StatusFlags {
self.status_flags
}
/// Value of the warnings field of an Ok packet.
pub fn warnings(&self) -> u16 {
self.warnings
}
/// Value of the info field of an Ok packet as a byte slice.
pub fn info_ref(&self) -> Option<&[u8]> {
self.info.as_ref().map(|x| x.as_bytes())
}
/// Value of the info field of an Ok packet as a string (lossy converted).
pub fn info_str(&self) -> Option<Cow<str>> {
self.info.as_ref().map(|x| x.as_str())
}
/// Returns raw reference to a session state info.
pub fn session_state_info_ref(&self) -> Option<&[u8]> {
self.session_state_info.as_ref().map(|x| x.as_bytes())
}
/// Tries to parse session state info, if any.
pub fn session_state_info(&self) -> io::Result<Vec<SessionStateInfo<'_>>> {
self.session_state_info_ref()
.map(|data| {
let mut data = ParseBuf(data);
let mut entries = Vec::new();
while !data.is_empty() {
entries.push(data.parse(())?);
}
Ok(entries)
})
.transpose()
.map(|x| x.unwrap_or_default())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OkPacketDeserializer<'de, T>(OkPacket<'de>, PhantomData<T>);
impl<'de, T> OkPacketDeserializer<'de, T> {
pub fn into_inner(self) -> OkPacket<'de> {
self.0
}
}
impl<'de, T> From<OkPacketDeserializer<'de, T>> for OkPacket<'de> {
fn from(x: OkPacketDeserializer<'de, T>) -> Self {
x.0
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[error("Invalid OK packet header")]
pub struct InvalidOkPacketHeader;
impl<'de, T: OkPacketKind> MyDeserialize<'de> for OkPacketDeserializer<'de, T> {
const SIZE: Option<usize> = None;
type Ctx = CapabilityFlags;
fn deserialize(capabilities: Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
if *buf.parse::<RawInt<u8>>(())? == T::HEADER {
let body = T::parse_body(capabilities, buf)?;
let ok = OkPacket::try_from(body)?;
Ok(Self(ok, PhantomData))
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
InvalidOkPacketHeader,
))
}
}
}
/// Progress report information (may be in an error packet of MariaDB server).
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ProgressReport<'a> {
stage: RawInt<u8>,
max_stage: RawInt<u8>,
progress: RawInt<LeU24>,
stage_info: RawBytes<'a, LenEnc>,
}
impl<'a> ProgressReport<'a> {
pub fn new(
stage: u8,
max_stage: u8,
progress: u32,
stage_info: impl Into<Cow<'a, [u8]>>,
) -> ProgressReport<'a> {
ProgressReport {
stage: RawInt::new(stage),
max_stage: RawInt::new(max_stage),
progress: RawInt::new(progress),
stage_info: RawBytes::new(stage_info),
}
}
/// 1 to max_stage
pub fn stage(&self) -> u8 {
*self.stage
}
pub fn max_stage(&self) -> u8 {
*self.max_stage
}
/// Progress as '% * 1000'
pub fn progress(&self) -> u32 {
*self.progress
}
/// Status or state name as a byte slice.
pub fn stage_info_ref(&self) -> &[u8] {
&self.stage_info.as_bytes()
}
/// Status or state name as a string (lossy converted).
pub fn stage_info_str(&self) -> Cow<'_, str> {
self.stage_info.as_str()
}
pub fn into_owned(self) -> ProgressReport<'static> {
ProgressReport {
stage: self.stage,
max_stage: self.max_stage,
progress: self.progress,
stage_info: self.stage_info.into_owned(),
}
}
}
impl<'de> MyDeserialize<'de> for ProgressReport<'de> {
const SIZE: Option<usize> = None;
type Ctx = ();
fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
let mut sbuf: ParseBuf = buf.parse(6)?;
sbuf.skip(1); // Ignore number of strings.
Ok(ProgressReport {
stage: sbuf.parse_unchecked(())?,
max_stage: sbuf.parse_unchecked(())?,
progress: sbuf.parse_unchecked(())?,
stage_info: buf.parse(())?,
})
}
}
impl MySerialize for ProgressReport<'_> {
fn serialize(&self, buf: &mut Vec<u8>) {
buf.put_u8(1);
self.stage.serialize(&mut *buf);
self.max_stage.serialize(&mut *buf);
self.progress.serialize(&mut *buf);
self.stage_info.serialize(buf);
}
}
impl<'a> fmt::Display for ProgressReport<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Stage: {} of {} '{}' {:.2}% of stage done",
self.stage(),
self.max_stage(),
self.progress(),
self.stage_info_str()
)
}
}
define_header!(
ErrPacketHeader,
InvalidErrPacketHeader("Invalid error packet header"),
0xFF
);
/// MySql error packet.
///
/// May hold an error or a progress report.
#[derive(Debug, Clone, PartialEq)]
pub enum ErrPacket<'a> {
Error(ServerError<'a>),
Progress(ProgressReport<'a>),
}
impl<'a> ErrPacket<'a> {
/// Returns false if this error packet contains progress report.
pub fn is_error(&self) -> bool {
matches!(self, ErrPacket::Error { .. })
}
/// Returns true if this error packet contains progress report.
pub fn is_progress_report(&self) -> bool {
!self.is_error()
}
/// Will panic if ErrPacket does not contains progress report
pub fn progress_report(&self) -> &ProgressReport<'_> {
match *self {
ErrPacket::Progress(ref progress_report) => progress_report,
_ => panic!("This ErrPacket does not contains progress report"),
}
}
/// Will panic if ErrPacket does not contains a `ServerError`.
pub fn server_error(&self) -> &ServerError<'_> {
match self {
ErrPacket::Error(error) => error,
ErrPacket::Progress(_) => panic!("This ErrPacket does not contain a ServerError"),
}
}
}
impl<'de> MyDeserialize<'de> for ErrPacket<'de> {
const SIZE: Option<usize> = None;
type Ctx = CapabilityFlags;
fn deserialize(capabilities: Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
let mut sbuf: ParseBuf = buf.parse(3)?;
sbuf.parse_unchecked::<ErrPacketHeader>(())?;
let code: RawInt<LeU16> = sbuf.parse_unchecked(())?;
// We assume that CLIENT_PROTOCOL_41 was set
if *code == 0xFFFF && capabilities.contains(CapabilityFlags::CLIENT_PROGRESS_OBSOLETE) {
buf.parse(()).map(ErrPacket::Progress)
} else {
buf.parse(*code).map(ErrPacket::Error)
}
}
}
impl MySerialize for ErrPacket<'_> {
fn serialize(&self, buf: &mut Vec<u8>) {
ErrPacketHeader::new().serialize(&mut *buf);
match self {
ErrPacket::Error(server_error) => {
server_error.code.serialize(&mut *buf);
server_error.serialize(buf);
}
ErrPacket::Progress(progress_report) => {
RawInt::<LeU16>::new(0xFFFF).serialize(&mut *buf);
progress_report.serialize(buf);
}
}
}
}
impl<'a> fmt::Display for ErrPacket<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ErrPacket::Error(server_error) => write!(f, "{}", server_error),
ErrPacket::Progress(progress_report) => write!(f, "{}", progress_report),
}
}
}
/// MySql error packet.
///
/// May hold an error or a progress report.
#[derive(Debug, Clone, PartialEq)]
pub struct ServerError<'a> {
code: RawInt<LeU16>,
state: [u8; 5],
message: RawBytes<'a, EofBytes>,
}
impl<'a> ServerError<'a> {
pub fn new(code: u16, state: [u8; 5], msg: impl Into<Cow<'a, [u8]>>) -> Self {
Self {
code: RawInt::new(code),
state,
message: RawBytes::new(msg),
}
}
/// Returns an error code.
pub fn error_code(&self) -> u16 {
*self.code
}
/// Returns an sql state.
pub fn sql_state_ref(&self) -> [u8; 5] {
self.state
}
/// Returns an sql state as a string (lossy converted).
pub fn sql_state_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(&self.state[..])
}
/// Returns an error message.
pub fn message_ref(&self) -> &[u8] {
self.message.as_bytes()
}
/// Returns an error message as a string (lossy converted).
pub fn message_str(&self) -> Cow<'_, str> {
self.message.as_str()
}
pub fn into_owned(self) -> ServerError<'static> {
ServerError {
code: self.code,
state: self.state,
message: self.message.into_owned(),
}
}
}
impl<'de> MyDeserialize<'de> for ServerError<'de> {
const SIZE: Option<usize> = None;
/// An error packet error code.
type Ctx = u16;
fn deserialize(code: Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
match buf.0[0] {
b'#' => {
buf.skip(1);
Ok(ServerError {
code: RawInt::new(code),
state: buf.parse(())?,
message: buf.parse(())?,
})
}
_ => Ok(ServerError {
code: RawInt::new(code),
state: *b"HY000",
message: buf.parse(())?,
}),
}
}
}
impl MySerialize for ServerError<'_> {
fn serialize(&self, buf: &mut Vec<u8>) {
buf.put_u8(b'#');
buf.put_slice(&self.state[..]);
self.message.serialize(buf);
}
}
impl fmt::Display for ServerError<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"ERROR {} ({}): {}",
self.error_code(),
self.sql_state_str(),
self.message_str()
)
}
}
define_header!(
LocalInfileHeader,
InvalidLocalInfileHeader("Invalid LOCAL_INFILE header"),
0xFB
);
/// Represents MySql's local infile packet.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct LocalInfilePacket<'a> {
__header: LocalInfileHeader,
file_name: RawBytes<'a, EofBytes>,
}
impl<'a> LocalInfilePacket<'a> {
pub fn new(file_name: impl Into<Cow<'a, [u8]>>) -> Self {
Self {
__header: LocalInfileHeader::new(),
file_name: RawBytes::new(file_name),
}
}
/// Value of the file_name field of a local infile packet as a byte slice.
pub fn file_name_ref(&self) -> &[u8] {
self.file_name.as_bytes()
}
/// Value of the file_name field of a local infile packet as a string (lossy converted).
pub fn file_name_str(&self) -> Cow<'_, str> {
self.file_name.as_str()
}
pub fn into_owned(self) -> LocalInfilePacket<'static> {
LocalInfilePacket {
__header: self.__header,
file_name: self.file_name.into_owned(),
}
}
}
impl<'de> MyDeserialize<'de> for LocalInfilePacket<'de> {
const SIZE: Option<usize> = None;
type Ctx = ();
fn deserialize((): Self::Ctx, buf: &mut ParseBuf<'de>) -> io::Result<Self> {
Ok(LocalInfilePacket {
__header: buf.parse(())?,
file_name: buf.parse(())?,
})
}
}
impl MySerialize for LocalInfilePacket<'_> {
fn serialize(&self, buf: &mut Vec<u8>) {
self.__header.serialize(buf);
self.file_name.serialize(buf);
}
}
const MYSQL_OLD_PASSWORD_PLUGIN_NAME: &[u8] = b"mysql_old_password";
const MYSQL_NATIVE_PASSWORD_PLUGIN_NAME: &[u8] = b"mysql_native_password";
const CACHING_SHA2_PASSWORD_PLUGIN_NAME: &[u8] = b"caching_sha2_password";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthPluginData {
/// Auth data for the `mysql_old_password` plugin.
Old([u8; 8]),
/// Auth data for the `mysql_native_password` plugin.
Native([u8; 20]),
/// Auth data for `sha2_password` and `caching_sha2_password` plugins.
Sha2([u8; 32]),
}
impl std::ops::Deref for AuthPluginData {
type Target = [u8];
fn deref(&self) -> &Self::Target {
match self {
Self::Sha2(x) => &x[..],
Self::Native(x) => &x[..],
Self::Old(x) => &x[..],
}
}
}
impl MySerialize for AuthPluginData {
fn serialize(&self, buf: &mut Vec<u8>) {
match self {