-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathmod.rs
2479 lines (2142 loc) · 83.2 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) 2016 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 futures_util::FutureExt;
pub use mysql_common::named_params;
use mysql_common::{
constants::{DEFAULT_MAX_ALLOWED_PACKET, UTF8MB4_GENERAL_CI, UTF8_GENERAL_CI},
crypto,
io::ParseBuf,
packets::{
binlog_request::BinlogRequest, AuthPlugin, AuthSwitchRequest, CommonOkPacket, ErrPacket,
HandshakePacket, HandshakeResponse, OkPacket, OkPacketDeserializer, OldAuthSwitchRequest,
OldEofPacket, ResultSetTerminator, SslRequest,
},
proto::MySerialize,
row::Row,
};
use std::{
borrow::Cow,
fmt,
future::Future,
mem::{self, replace},
pin::Pin,
str::FromStr,
sync::Arc,
time::{Duration, Instant},
};
use crate::{
buffer_pool::PooledBuf,
conn::{pool::Pool, stmt_cache::StmtCache},
consts::{CapabilityFlags, Command, StatusFlags},
error::*,
io::Stream,
metrics::ConnMetrics,
opts::Opts,
queryable::{
query_result::{QueryResult, ResultSetMeta},
transaction::TxStatus,
BinaryProtocol, Queryable, TextProtocol,
},
BinlogStream, ChangeUserOpts, InfileData, OptsBuilder,
};
use self::routines::Routine;
pub mod binlog_stream;
pub mod pool;
pub mod routines;
pub mod stmt_cache;
const DEFAULT_WAIT_TIMEOUT: usize = 28800;
/// Helper that asynchronously disconnects the givent connection on the default tokio executor.
fn disconnect(mut conn: Conn) {
conn.metrics().disconnects.incr();
let disconnected = conn.inner.disconnected;
// Mark conn as disconnected.
conn.inner.disconnected = true;
if !disconnected {
// We shouldn't call tokio::spawn if unwinding
if std::thread::panicking() {
return;
}
// Server will report broken connection if spawn fails.
// this might fail if, say, the runtime is shutting down, but we've done what we could
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
if let Ok(conn) = conn.cleanup_for_pool().await {
let _ = conn.disconnect().await;
}
});
}
}
}
/// Pending result set.
#[derive(Debug, Clone)]
pub(crate) enum PendingResult {
/// There is a pending result set.
Pending(ResultSetMeta),
/// Result set metadata was taken but not yet consumed.
Taken(Arc<ResultSetMeta>),
}
/// Mysql connection
struct ConnInner {
stream: Option<Stream>,
id: u32,
is_mariadb: bool,
version: (u16, u16, u16),
socket: Option<String>,
capabilities: CapabilityFlags,
status: StatusFlags,
last_ok_packet: Option<OkPacket<'static>>,
last_err_packet: Option<mysql_common::packets::ServerError<'static>>,
pool: Option<Pool>,
pending_result: std::result::Result<Option<PendingResult>, ServerError>,
tx_status: TxStatus,
reset_upon_returning_to_a_pool: bool,
opts: Opts,
ttl_deadline: Option<Instant>,
last_io: Instant,
wait_timeout: Duration,
stmt_cache: StmtCache,
nonce: Vec<u8>,
auth_plugin: AuthPlugin<'static>,
auth_switched: bool,
server_key: Option<Vec<u8>>,
/// Connection is already disconnected.
pub(crate) disconnected: bool,
/// One-time connection-level infile handler.
infile_handler:
Option<Pin<Box<dyn Future<Output = crate::Result<InfileData>> + Send + Sync + 'static>>>,
conn_metrics: Arc<ConnMetrics>,
}
impl fmt::Debug for ConnInner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Conn")
.field("connection id", &self.id)
.field("server version", &self.version)
.field("pool", &self.pool)
.field("pending_result", &self.pending_result)
.field("tx_status", &self.tx_status)
.field("stream", &self.stream)
.field("options", &self.opts)
.field("server_key", &self.server_key)
.field("auth_plugin", &self.auth_plugin)
.finish()
}
}
impl ConnInner {
/// Constructs an empty connection.
fn empty(opts: Opts) -> ConnInner {
let ttl_deadline = opts.pool_opts().new_connection_ttl_deadline();
let conn_metrics: Arc<ConnMetrics> = Default::default();
ConnInner {
capabilities: opts.get_capabilities(),
status: StatusFlags::empty(),
last_ok_packet: None,
last_err_packet: None,
stream: None,
is_mariadb: false,
version: (0, 0, 0),
id: 0,
pending_result: Ok(None),
pool: None,
tx_status: TxStatus::None,
last_io: Instant::now(),
wait_timeout: Duration::from_secs(0),
stmt_cache: StmtCache::new(opts.stmt_cache_size(), conn_metrics.clone()),
socket: opts.socket().map(Into::into),
opts,
ttl_deadline,
nonce: Vec::default(),
auth_plugin: AuthPlugin::MysqlNativePassword,
auth_switched: false,
disconnected: false,
server_key: None,
infile_handler: None,
reset_upon_returning_to_a_pool: false,
conn_metrics,
}
}
/// Returns mutable reference to a connection stream.
///
/// Returns `DriverError::ConnectionClosed` if there is no stream.
fn stream_mut(&mut self) -> Result<&mut Stream> {
self.stream
.as_mut()
.ok_or_else(|| DriverError::ConnectionClosed.into())
}
fn set_pool(&mut self, pool: Option<Pool>) {
let conn_metrics = if let Some(ref pool) = pool {
Arc::clone(&pool.inner.metrics.conn)
} else {
Default::default()
};
self.conn_metrics = Arc::clone(&conn_metrics);
self.stmt_cache.conn_metrics = conn_metrics;
self.pool = pool;
}
}
/// MySql server connection.
#[derive(Debug)]
pub struct Conn {
inner: Box<ConnInner>,
}
impl Conn {
/// Returns connection identifier.
pub fn id(&self) -> u32 {
self.inner.id
}
/// Returns the ID generated by a query (usually `INSERT`) on a table with a column having the
/// `AUTO_INCREMENT` attribute. Returns `None` if there was no previous query on the connection
/// or if the query did not update an AUTO_INCREMENT value.
pub fn last_insert_id(&self) -> Option<u64> {
self.inner
.last_ok_packet
.as_ref()
.and_then(|ok| ok.last_insert_id())
}
/// Returns the number of rows affected by the last `INSERT`, `UPDATE`, `REPLACE` or `DELETE`
/// query.
pub fn affected_rows(&self) -> u64 {
self.inner
.last_ok_packet
.as_ref()
.map(|ok| ok.affected_rows())
.unwrap_or_default()
}
/// Text information, as reported by the server in the last OK packet, or an empty string.
pub fn info(&self) -> Cow<'_, str> {
self.inner
.last_ok_packet
.as_ref()
.and_then(|ok| ok.info_str())
.unwrap_or_else(|| "".into())
}
/// Number of warnings, as reported by the server in the last OK packet, or `0`.
pub fn get_warnings(&self) -> u16 {
self.inner
.last_ok_packet
.as_ref()
.map(|ok| ok.warnings())
.unwrap_or_default()
}
/// Returns a reference to the last OK packet.
pub fn last_ok_packet(&self) -> Option<&OkPacket<'static>> {
self.inner.last_ok_packet.as_ref()
}
/// Turns on/off automatic connection reset (see [`crate::PoolOpts::with_reset_connection`]).
///
/// Only makes sense for pooled connections.
pub fn reset_connection(&mut self, reset_connection: bool) {
self.inner.reset_upon_returning_to_a_pool = reset_connection;
}
pub(crate) fn stream_mut(&mut self) -> Result<&mut Stream> {
self.inner.stream_mut()
}
pub(crate) fn capabilities(&self) -> CapabilityFlags {
self.inner.capabilities
}
/// Will update last IO time for this connection.
pub(crate) fn touch(&mut self) {
self.inner.last_io = Instant::now();
}
/// Will set packet sequence id to `0`.
pub(crate) fn reset_seq_id(&mut self) {
if let Some(stream) = self.inner.stream.as_mut() {
stream.reset_seq_id();
}
}
/// Will syncronize sequence ids between compressed and uncompressed codecs.
pub(crate) fn sync_seq_id(&mut self) {
if let Some(stream) = self.inner.stream.as_mut() {
stream.sync_seq_id();
}
}
/// Handles OK packet.
pub(crate) fn handle_ok(&mut self, ok_packet: OkPacket<'static>) {
self.inner.status = ok_packet.status_flags();
self.inner.last_err_packet = None;
self.inner.last_ok_packet = Some(ok_packet);
}
/// Handles ERR packet.
pub(crate) fn handle_err(&mut self, err_packet: ErrPacket<'_>) -> Result<()> {
match err_packet {
ErrPacket::Error(err) => {
self.inner.status = StatusFlags::empty();
self.inner.last_ok_packet = None;
self.inner.last_err_packet = Some(err.clone().into_owned());
Err(Error::from(err))
}
ErrPacket::Progress(_) => Ok(()),
}
}
/// Returns the current transaction status.
pub(crate) fn get_tx_status(&self) -> TxStatus {
self.inner.tx_status
}
/// Sets the given transaction status for this connection.
pub(crate) fn set_tx_status(&mut self, tx_status: TxStatus) {
self.inner.tx_status = tx_status;
}
/// Returns pending result metadata, if any.
///
/// If `Some(_)`, then result is not yet consumed.
pub(crate) fn use_pending_result(
&mut self,
) -> std::result::Result<Option<&PendingResult>, ServerError> {
if let Err(ref e) = self.inner.pending_result {
let e = e.clone();
self.inner.pending_result = Ok(None);
return Err(e);
} else {
Ok(self.inner.pending_result.as_ref().unwrap().as_ref())
}
}
pub(crate) fn get_pending_result(
&self,
) -> std::result::Result<Option<&PendingResult>, &ServerError> {
self.inner.pending_result.as_ref().map(|x| x.as_ref())
}
pub(crate) fn has_pending_result(&self) -> bool {
matches!(self.inner.pending_result, Err(_))
|| matches!(self.inner.pending_result, Ok(Some(_)))
}
/// Sets the given pening result metadata for this connection. Returns the previous value.
pub(crate) fn set_pending_result(
&mut self,
meta: Option<ResultSetMeta>,
) -> std::result::Result<Option<PendingResult>, ServerError> {
replace(
&mut self.inner.pending_result,
Ok(meta.map(PendingResult::Pending)),
)
}
pub(crate) fn set_pending_result_error(
&mut self,
error: ServerError,
) -> std::result::Result<Option<PendingResult>, ServerError> {
replace(&mut self.inner.pending_result, Err(error))
}
/// Gives the currently pending result to a caller for consumption.
pub(crate) fn take_pending_result(
&mut self,
) -> std::result::Result<Option<Arc<ResultSetMeta>>, ServerError> {
let mut output = None;
self.inner.pending_result = match replace(&mut self.inner.pending_result, Ok(None))? {
Some(PendingResult::Pending(x)) => {
let meta = Arc::new(x);
output = Some(meta.clone());
Ok(Some(PendingResult::Taken(meta)))
}
x => Ok(x),
};
Ok(output)
}
/// Returns current status flags.
pub(crate) fn status(&self) -> StatusFlags {
self.inner.status
}
pub(crate) async fn routine<'a, F, T>(&mut self, mut f: F) -> crate::Result<T>
where
F: Routine<T> + 'a,
{
self.inner.disconnected = true;
let result = f.call(&mut *self).await;
match result {
result @ Ok(_) | result @ Err(crate::Error::Server(_)) => {
// either OK or non-fatal error
self.inner.disconnected = false;
result
}
Err(err) => {
if self.inner.stream.is_some() {
self.take_stream().close().await?;
}
Err(err)
}
}
}
/// Returns server version.
pub fn server_version(&self) -> (u16, u16, u16) {
self.inner.version
}
/// Returns connection options.
pub fn opts(&self) -> &Opts {
&self.inner.opts
}
/// Setup _local_ `LOCAL INFILE` handler (see ["LOCAL INFILE Handlers"][2] section
/// of the crate-level docs).
///
/// It'll overwrite existing _local_ handler, if any.
///
/// [2]: ../mysql_async/#local-infile-handlers
pub fn set_infile_handler<T>(&mut self, handler: T)
where
T: Future<Output = crate::Result<InfileData>>,
T: Send + Sync + 'static,
{
self.inner.infile_handler = Some(Box::pin(handler));
}
fn take_stream(&mut self) -> Stream {
self.inner.stream.take().unwrap()
}
/// Disconnects this connection from server.
pub async fn disconnect(mut self) -> Result<()> {
if !self.inner.disconnected {
self.inner.disconnected = true;
self.write_command_data(Command::COM_QUIT, &[]).await?;
let stream = self.take_stream();
stream.close().await?;
}
Ok(())
}
/// Closes the connection.
async fn close_conn(mut self) -> Result<()> {
self = self.cleanup_for_pool().await?;
self.disconnect().await
}
/// Returns true if io stream is encrypted.
fn is_secure(&self) -> bool {
#[cfg(any(feature = "native-tls-tls", feature = "rustls-tls"))]
{
self.inner
.stream
.as_ref()
.map(|x| x.is_secure())
.unwrap_or_default()
}
#[cfg(not(any(feature = "native-tls-tls", feature = "rustls-tls")))]
false
}
/// Returns true if io stream is socket.
fn is_socket(&self) -> bool {
#[cfg(unix)]
{
self.inner
.stream
.as_ref()
.map(|x| x.is_socket())
.unwrap_or_default()
}
#[cfg(not(unix))]
false
}
/// Hacky way to move connection through &mut. `self` becomes unusable.
fn take(&mut self) -> Conn {
mem::replace(self, Conn::empty(Default::default()))
}
fn empty(opts: Opts) -> Self {
Self {
inner: Box::new(ConnInner::empty(opts)),
}
}
/// Set `io::Stream` options as defined in the `Opts` of the connection.
///
/// Requires that self.inner.stream is Some
fn setup_stream(&mut self) -> Result<()> {
debug_assert!(self.inner.stream.is_some());
if let Some(stream) = self.inner.stream.as_mut() {
stream.set_tcp_nodelay(self.inner.opts.tcp_nodelay())?;
}
Ok(())
}
async fn handle_handshake(&mut self) -> Result<()> {
let packet = self.read_packet().await?;
let handshake = ParseBuf(&*packet).parse::<HandshakePacket>(())?;
// Handshake scramble is always 21 bytes length (20 + zero terminator)
self.inner.nonce = {
let mut nonce = Vec::from(handshake.scramble_1_ref());
nonce.extend_from_slice(handshake.scramble_2_ref().unwrap_or(&[][..]));
// Trim zero terminator. Fill with zeroes if nonce
// is somehow smaller than 20 bytes (this matches the server behavior).
nonce.resize(20, 0);
nonce
};
self.inner.capabilities = handshake.capabilities() & self.inner.opts.get_capabilities();
self.inner.version = handshake
.maria_db_server_version_parsed()
.map(|version| {
self.inner.is_mariadb = true;
version
})
.or_else(|| handshake.server_version_parsed())
.unwrap_or((0, 0, 0));
self.inner.id = handshake.connection_id();
self.inner.status = handshake.status_flags();
// Allow only CachingSha2Password and MysqlNativePassword here
// because sha256_password is deprecated and other plugins won't
// appear here.
self.inner.auth_plugin = match handshake.auth_plugin() {
Some(AuthPlugin::CachingSha2Password) => AuthPlugin::CachingSha2Password,
_ => AuthPlugin::MysqlNativePassword,
};
Ok(())
}
async fn switch_to_ssl_if_needed(&mut self) -> Result<()> {
if self
.inner
.opts
.get_capabilities()
.contains(CapabilityFlags::CLIENT_SSL)
{
if !self
.inner
.capabilities
.contains(CapabilityFlags::CLIENT_SSL)
{
return Err(DriverError::NoClientSslFlagFromServer.into());
}
let collation = if self.inner.version >= (5, 5, 3) {
UTF8MB4_GENERAL_CI
} else {
UTF8_GENERAL_CI
};
let ssl_request = SslRequest::new(
self.inner.capabilities,
DEFAULT_MAX_ALLOWED_PACKET as u32,
collation as u8,
);
self.write_struct(&ssl_request).await?;
let conn = self;
let ssl_opts = conn.opts().ssl_opts().cloned().expect("unreachable");
let domain = conn.opts().ip_or_hostname().into();
conn.stream_mut()?.make_secure(domain, ssl_opts).await?;
Ok(())
} else {
Ok(())
}
}
async fn do_handshake_response(&mut self) -> Result<()> {
let auth_data = self
.inner
.auth_plugin
.gen_data(self.inner.opts.pass(), &*self.inner.nonce);
let handshake_response = HandshakeResponse::new(
auth_data.as_deref(),
self.inner.version,
self.inner.opts.user().map(|x| x.as_bytes()),
self.inner.opts.db_name().map(|x| x.as_bytes()),
Some(self.inner.auth_plugin.borrow()),
self.capabilities(),
Default::default(), // TODO: Add support
);
// Serialize here to satisfy borrow checker.
let mut buf = crate::BUFFER_POOL.get();
handshake_response.serialize(buf.as_mut());
self.write_packet(buf).await?;
Ok(())
}
async fn perform_auth_switch(
&mut self,
auth_switch_request: AuthSwitchRequest<'_>,
) -> Result<()> {
if !self.inner.auth_switched {
self.inner.auth_switched = true;
self.inner.nonce = auth_switch_request.plugin_data().to_vec();
if matches!(
auth_switch_request.auth_plugin(),
AuthPlugin::MysqlOldPassword
) {
if self.inner.opts.secure_auth() {
return Err(DriverError::MysqlOldPasswordDisabled.into());
}
}
self.inner.auth_plugin = auth_switch_request.auth_plugin().clone().into_owned();
let plugin_data = match &self.inner.auth_plugin {
x @ AuthPlugin::CachingSha2Password => {
x.gen_data(self.inner.opts.pass(), &self.inner.nonce)
}
x @ AuthPlugin::MysqlNativePassword => {
x.gen_data(self.inner.opts.pass(), &self.inner.nonce)
}
x @ AuthPlugin::MysqlOldPassword => {
if self.inner.opts.secure_auth() {
return Err(DriverError::MysqlOldPasswordDisabled.into());
} else {
x.gen_data(self.inner.opts.pass(), &self.inner.nonce)
}
}
x @ AuthPlugin::MysqlClearPassword => {
if self.inner.opts.enable_cleartext_plugin() {
x.gen_data(self.inner.opts.pass(), &self.inner.nonce)
} else {
return Err(DriverError::CleartextPluginDisabled.into());
}
}
x @ AuthPlugin::Other(_) => x.gen_data(self.inner.opts.pass(), &self.inner.nonce),
};
if let Some(plugin_data) = plugin_data {
self.write_struct(&plugin_data.into_owned()).await?;
} else {
self.write_packet(crate::BUFFER_POOL.get()).await?;
}
self.continue_auth().await?;
Ok(())
} else {
unreachable!("auth_switched flag should be checked by caller")
}
}
fn continue_auth(&mut self) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
// NOTE: we need to box this since it may recurse
// see https://github.com/rust-lang/rust/issues/46415#issuecomment-528099782
Box::pin(async move {
match self.inner.auth_plugin {
AuthPlugin::MysqlNativePassword | AuthPlugin::MysqlOldPassword => {
self.continue_mysql_native_password_auth().await?;
Ok(())
}
AuthPlugin::CachingSha2Password => {
self.continue_caching_sha2_password_auth().await?;
Ok(())
}
AuthPlugin::MysqlClearPassword => {
if self.inner.opts.enable_cleartext_plugin() {
self.continue_mysql_native_password_auth().await?;
Ok(())
} else {
Err(DriverError::CleartextPluginDisabled.into())
}
}
AuthPlugin::Other(ref name) => Err(DriverError::UnknownAuthPlugin {
name: String::from_utf8_lossy(name.as_ref()).to_string(),
}
.into()),
}
})
}
fn switch_to_compression(&mut self) -> Result<()> {
if self
.capabilities()
.contains(CapabilityFlags::CLIENT_COMPRESS)
{
if let Some(compression) = self.inner.opts.compression() {
if let Some(stream) = self.inner.stream.as_mut() {
stream.compress(compression);
}
}
}
Ok(())
}
async fn continue_caching_sha2_password_auth(&mut self) -> Result<()> {
let packet = self.read_packet().await?;
match packet.get(0) {
Some(0x00) => {
// ok packet for empty password
Ok(())
}
Some(0x01) => match packet.get(1) {
Some(0x03) => {
// auth ok
self.drop_packet().await
}
Some(0x04) => {
let pass = self.inner.opts.pass().unwrap_or_default();
let mut pass = crate::BUFFER_POOL.get_with(pass.as_bytes());
pass.as_mut().push(0);
if self.is_secure() || self.is_socket() {
self.write_packet(pass).await?;
} else {
if self.inner.server_key.is_none() {
self.write_bytes(&[0x02][..]).await?;
let packet = self.read_packet().await?;
self.inner.server_key = Some(packet[1..].to_vec());
}
for (i, byte) in pass.as_mut().iter_mut().enumerate() {
*byte ^= self.inner.nonce[i % self.inner.nonce.len()];
}
let encrypted_pass = crypto::encrypt(
&*pass,
self.inner.server_key.as_deref().expect("unreachable"),
);
self.write_bytes(&*encrypted_pass).await?;
};
self.drop_packet().await?;
Ok(())
}
_ => Err(DriverError::UnexpectedPacket {
payload: packet.to_vec(),
}
.into()),
},
Some(0xfe) if !self.inner.auth_switched => {
let auth_switch_request = ParseBuf(&*packet).parse::<AuthSwitchRequest>(())?;
self.perform_auth_switch(auth_switch_request).await?;
Ok(())
}
_ => Err(DriverError::UnexpectedPacket {
payload: packet.to_vec(),
}
.into()),
}
}
async fn continue_mysql_native_password_auth(&mut self) -> Result<()> {
let packet = self.read_packet().await?;
match packet.get(0) {
Some(0x00) => Ok(()),
Some(0xfe) if !self.inner.auth_switched => {
let auth_switch = if packet.len() > 1 {
ParseBuf(&*packet).parse(())?
} else {
let _ = ParseBuf(&*packet).parse::<OldAuthSwitchRequest>(())?;
// map OldAuthSwitch to AuthSwitch with mysql_old_password plugin
AuthSwitchRequest::new(
"mysql_old_password".as_bytes(),
self.inner.nonce.clone(),
)
};
self.perform_auth_switch(auth_switch).await
}
_ => Err(DriverError::UnexpectedPacket {
payload: packet.to_vec(),
}
.into()),
}
}
/// Returns `true` for ProgressReport packet.
fn handle_packet(&mut self, packet: &PooledBuf) -> Result<bool> {
let ok_packet = if self.has_pending_result() {
if self
.capabilities()
.contains(CapabilityFlags::CLIENT_DEPRECATE_EOF)
{
ParseBuf(&*packet)
.parse::<OkPacketDeserializer<ResultSetTerminator>>(self.capabilities())
.map(|x| x.into_inner())
} else {
ParseBuf(&*packet)
.parse::<OkPacketDeserializer<OldEofPacket>>(self.capabilities())
.map(|x| x.into_inner())
}
} else {
ParseBuf(&*packet)
.parse::<OkPacketDeserializer<CommonOkPacket>>(self.capabilities())
.map(|x| x.into_inner())
};
if let Ok(ok_packet) = ok_packet {
self.handle_ok(ok_packet.into_owned());
} else {
let err_packet = ParseBuf(&*packet).parse::<ErrPacket>(self.capabilities());
if let Ok(err_packet) = err_packet {
self.handle_err(err_packet)?;
return Ok(true);
}
}
Ok(false)
}
pub(crate) async fn read_packet(&mut self) -> Result<PooledBuf> {
loop {
let packet = crate::io::ReadPacket::new(&mut *self)
.await
.map_err(|io_err| {
self.inner.stream.take();
self.inner.disconnected = true;
Error::from(io_err)
})?;
if self.handle_packet(&packet)? {
// ignore progress report
continue;
} else {
return Ok(packet);
}
}
}
/// Returns future that reads packets from a server.
pub(crate) async fn read_packets(&mut self, n: usize) -> Result<Vec<PooledBuf>> {
let mut packets = Vec::with_capacity(n);
for _ in 0..n {
packets.push(self.read_packet().await?);
}
Ok(packets)
}
pub(crate) async fn write_packet(&mut self, data: PooledBuf) -> Result<()> {
crate::io::WritePacket::new(&mut *self, data)
.await
.map_err(|io_err| {
self.inner.stream.take();
self.inner.disconnected = true;
From::from(io_err)
})
}
/// Writes bytes to a server.
pub(crate) async fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
let buf = crate::BUFFER_POOL.get_with(bytes);
self.write_packet(buf).await
}
/// Sends a serializable structure to a server.
pub(crate) async fn write_struct<T: MySerialize>(&mut self, x: &T) -> Result<()> {
let mut buf = crate::BUFFER_POOL.get();
x.serialize(buf.as_mut());
self.write_packet(buf).await
}
/// Sends a command to a server.
pub(crate) async fn write_command<T: MySerialize>(&mut self, cmd: &T) -> Result<()> {
self.clean_dirty().await?;
self.reset_seq_id();
self.write_struct(cmd).await
}
/// Returns future that sends full command body to a server.
pub(crate) async fn write_command_raw(&mut self, body: PooledBuf) -> Result<()> {
debug_assert!(!body.is_empty());
self.clean_dirty().await?;
self.reset_seq_id();
self.write_packet(body).await
}
/// Returns future that writes command to a server.
pub(crate) async fn write_command_data<T>(&mut self, cmd: Command, cmd_data: T) -> Result<()>
where
T: AsRef<[u8]>,
{
let cmd_data = cmd_data.as_ref();
let mut buf = crate::BUFFER_POOL.get();
let body = buf.as_mut();
body.push(cmd as u8);
body.extend_from_slice(cmd_data);
self.write_command_raw(buf).await
}
async fn drop_packet(&mut self) -> Result<()> {
self.read_packet().await?;
Ok(())
}
async fn run_init_commands(&mut self) -> Result<()> {
let mut init = self.inner.opts.init().to_vec();
while let Some(query) = init.pop() {
self.query_drop(query).await?;
}
Ok(())
}
async fn run_setup_commands(&mut self) -> Result<()> {
let mut setup = self.inner.opts.setup().to_vec();
while let Some(query) = setup.pop() {
self.query_drop(query).await?;
}
Ok(())
}
/// Returns a future that resolves to [`Conn`].
pub fn new<T: Into<Opts>>(opts: T) -> crate::BoxFuture<'static, Conn> {
let opts = opts.into();
async move {
let mut conn = Conn::empty(opts.clone());
let stream = if let Some(_path) = opts.socket() {
#[cfg(unix)]
{
Stream::connect_socket(_path.to_owned()).await?
}
#[cfg(target_os = "windows")]
return Err(crate::DriverError::NamedPipesDisabled.into());
} else {
let keepalive = opts
.tcp_keepalive()
.map(|x| std::time::Duration::from_millis(x.into()));
Stream::connect_tcp(opts.hostport_or_url(), keepalive).await?
};
conn.inner.stream = Some(stream);
conn.setup_stream()?;
conn.handle_handshake().await?;
conn.switch_to_ssl_if_needed().await?;
conn.do_handshake_response().await?;
conn.continue_auth().await?;
conn.switch_to_compression()?;
conn.read_settings().await?;
conn.reconnect_via_socket_if_needed().await?;
conn.run_init_commands().await?;
conn.run_setup_commands().await?;
conn.metrics().connects.incr();
Ok(conn)
}
.boxed()
}
/// Returns a future that resolves to [`Conn`].
pub async fn from_url<T: AsRef<str>>(url: T) -> Result<Conn> {
Conn::new(Opts::from_str(url.as_ref())?).await
}
/// Will try to reconnect via socket using socket address in `self.inner.socket`.
///
/// Won't try to reconnect if socket connection is already enforced in [`Opts`].
async fn reconnect_via_socket_if_needed(&mut self) -> Result<()> {
if let Some(socket) = self.inner.socket.as_ref() {
let opts = self.inner.opts.clone();
if opts.socket().is_none() {
let opts = OptsBuilder::from_opts(opts).socket(Some(&**socket));
if let Ok(conn) = Conn::new(opts).await {
let old_conn = std::mem::replace(self, conn);
// tidy up the old connection
old_conn.close_conn().await?;
}
}
}
Ok(())
}
/// Configures the connection based on server settings. In particular:
///
/// * It reads and stores socket address inside the connection unless if socket address is
/// already in [`Opts`] or if `prefer_socket` is `false`.
///
/// * It reads and stores `max_allowed_packet` in the connection unless it's already in [`Opts`]
///
/// * It reads and stores `wait_timeout` in the connection unless it's already in [`Opts`]
///
async fn read_settings(&mut self) -> Result<()> {
enum Action {
Load(Cfg),
Apply(CfgData),
}
enum CfgData {
MaxAllowedPacket(usize),
WaitTimeout(usize),
}
impl CfgData {