1use std::fmt;
6use std::io::{self, Read, Write};
7use std::net::{TcpStream, ToSocketAddrs};
8use std::path::{Path, PathBuf};
9use std::time::Duration;
10
11#[cfg(feature = "tls")]
12use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
13#[cfg(feature = "tls")]
14use rustls::pki_types::ServerName;
15#[cfg(feature = "tls")]
16use rustls::pki_types::{CertificateDer, UnixTime};
17#[cfg(feature = "tls")]
18use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
19#[cfg(feature = "tls")]
20use rustls::{DigitallySignedStruct, Error as TlsError, SignatureScheme};
21#[cfg(feature = "tls")]
22use std::sync::Arc;
23
24pub type Result<T> = std::result::Result<T, Error>;
25
26#[derive(Debug)]
27pub enum Error {
28 Io(io::Error),
29 Protocol(String),
30 Server {
31 code: u16,
32 state: String,
33 message: String,
34 },
35 Type(String),
36 Url(String),
37 Unsupported(String),
38 Timeout,
39}
40impl fmt::Display for Error {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 match self {
43 Error::Io(e) => e.fmt(f),
44 Error::Protocol(s) | Error::Type(s) | Error::Url(s) | Error::Unsupported(s) => {
45 f.write_str(s)
46 }
47 Error::Server {
48 code,
49 state,
50 message,
51 } => write!(f, "mysql error {code} ({state}): {message}"),
52 Error::Timeout => f.write_str("operation timed out"),
53 }
54 }
55}
56impl std::error::Error for Error {}
57impl From<io::Error> for Error {
58 fn from(e: io::Error) -> Self {
59 if e.kind() == io::ErrorKind::TimedOut {
60 Self::Timeout
61 } else {
62 Self::Io(e)
63 }
64 }
65}
66
67const CLIENT_LONG_PASSWORD: u32 = 1;
68const CLIENT_LONG_FLAG: u32 = 1 << 2;
69const CLIENT_CONNECT_WITH_DB: u32 = 1 << 3;
70const CLIENT_PROTOCOL_41: u32 = 1 << 9;
71const CLIENT_TRANSACTIONS: u32 = 1 << 13;
72const CLIENT_SSL: u32 = 1 << 11;
73const CLIENT_SECURE_CONNECTION: u32 = 1 << 15;
74const CLIENT_MULTI_STATEMENTS: u32 = 1 << 16;
75const CLIENT_MULTI_RESULTS: u32 = 1 << 17;
76const CLIENT_PLUGIN_AUTH: u32 = 1 << 19;
77const CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA: u32 = 1 << 21;
78const CLIENT_DEPRECATE_EOF: u32 = 1 << 24;
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum TlsMode {
82 Disabled,
83 Preferred,
84 Required,
85 VerifyIdentity,
86}
87#[derive(Debug, Clone)]
88pub struct ConnectOptions {
89 pub user: String,
90 pub password: String,
91 pub host: String,
92 pub port: u16,
93 pub database: Option<String>,
94 pub connect_timeout: Option<Duration>,
95 pub read_timeout: Option<Duration>,
96 pub write_timeout: Option<Duration>,
97 pub tls: TlsMode,
98 pub tls_server_name: Option<String>,
99 pub ca_certificates: Vec<Vec<u8>>,
100 pub charset: u8,
101 pub max_packet_size: u32,
102 pub attributes: Vec<(String, String)>,
103}
104impl Default for ConnectOptions {
105 fn default() -> Self {
106 Self {
107 user: String::new(),
108 password: String::new(),
109 host: "127.0.0.1".into(),
110 port: 3306,
111 database: None,
112 connect_timeout: Some(Duration::from_secs(10)),
113 read_timeout: None,
114 write_timeout: None,
115 tls: TlsMode::Disabled,
116 tls_server_name: None,
117 ca_certificates: Vec::new(),
118 charset: 255,
119 max_packet_size: 16 * 1024 * 1024,
120 attributes: Vec::new(),
121 }
122 }
123}
124impl ConnectOptions {
125 pub fn from_url(url: &str) -> Result<Self> {
126 let rest = url
127 .strip_prefix("mysql://")
128 .ok_or_else(|| Error::Url("URL must start with mysql://".into()))?;
129 let (authority, database) = match rest.split_once('/') {
130 Some((a, d)) => (a, Some(percent_decode(d)?)),
131 None => (rest, None),
132 };
133 let (userinfo, hostport) = authority
134 .rsplit_once('@')
135 .ok_or_else(|| Error::Url("URL requires user and password".into()))?;
136 let (user, password) = userinfo
137 .split_once(':')
138 .ok_or_else(|| Error::Url("URL requires user:password".into()))?;
139 let (host, port) = if let Some((h, p)) = hostport.rsplit_once(':') {
140 (
141 h.to_string(),
142 p.parse().map_err(|_| Error::Url("invalid port".into()))?,
143 )
144 } else {
145 (hostport.to_string(), 3306)
146 };
147 if host.is_empty() {
148 return Err(Error::Url("host is empty".into()));
149 }
150 Ok(Self {
151 user: percent_decode(user)?,
152 password: percent_decode(password)?,
153 host,
154 port,
155 database,
156 ..Self::default()
157 })
158 }
159}
160fn percent_decode(s: &str) -> Result<String> {
161 let b = s.as_bytes();
162 let mut out = Vec::with_capacity(b.len());
163 let mut i = 0;
164 while i < b.len() {
165 if b[i] == b'%' {
166 if i + 2 >= b.len() {
167 return Err(Error::Url("bad percent escape".into()));
168 }
169 let h = |x: u8| (x as char).to_digit(16).map(|n| n as u8);
170 out.push(
171 h(b[i + 1])
172 .zip(h(b[i + 2]))
173 .map(|(a, c)| a * 16 + c)
174 .ok_or_else(|| Error::Url("bad percent escape".into()))?,
175 );
176 i += 3;
177 } else {
178 out.push(b[i]);
179 i += 1;
180 }
181 }
182 String::from_utf8(out).map_err(|_| Error::Url("URL is not UTF-8".into()))
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum ValueType {
187 Null,
188 Int,
189 UInt,
190 Float,
191 Bytes,
192 Text,
193 Date,
194 Time,
195 DateTime,
196 Decimal,
197 Json,
198}
199#[derive(Debug, Clone, PartialEq)]
200pub enum Value {
201 Null,
202 Int(i64),
203 UInt(u64),
204 Float(f64),
205 Bool(bool),
206 Bytes(Vec<u8>),
207 Text(String),
208 Date(String),
209 Time(String),
210 DateTime(String),
211 Decimal(String),
212 Json(String),
213}
214pub trait ToSql {
215 fn to_value(&self) -> Value;
216}
217pub trait FromSql: Sized {
218 fn from_value(v: &Value) -> Result<Self>;
219}
220macro_rules! ints { ($($t:ty),*) => { $(impl ToSql for $t { fn to_value(&self)->Value { Value::Int(*self as i64) } } impl FromSql for $t { fn from_value(v:&Value)->Result<Self> { match v { Value::Int(x)=>Ok(*x as $t), Value::UInt(x)=>Ok(*x as $t), _=>Err(Error::Type("expected integer".into())) } } })* }; }
221ints!(i8, i16, i32, i64, isize, u8, u16, u32);
222impl ToSql for u64 {
223 fn to_value(&self) -> Value {
224 Value::UInt(*self)
225 }
226}
227impl FromSql for u64 {
228 fn from_value(v: &Value) -> Result<Self> {
229 match v {
230 Value::Int(x) => Ok(*x as u64),
231 Value::UInt(x) => Ok(*x),
232 _ => Err(Error::Type("expected integer".into())),
233 }
234 }
235}
236impl ToSql for bool {
237 fn to_value(&self) -> Value {
238 Value::Bool(*self)
239 }
240}
241impl FromSql for bool {
242 fn from_value(v: &Value) -> Result<Self> {
243 match v {
244 Value::Bool(x) => Ok(*x),
245 Value::Int(x) => Ok(*x != 0),
246 Value::UInt(x) => Ok(*x != 0),
247 _ => Err(Error::Type("expected boolean".into())),
248 }
249 }
250}
251impl ToSql for f32 {
252 fn to_value(&self) -> Value {
253 Value::Float(*self as f64)
254 }
255}
256impl ToSql for f64 {
257 fn to_value(&self) -> Value {
258 Value::Float(*self)
259 }
260}
261impl FromSql for f32 {
262 fn from_value(v: &Value) -> Result<Self> {
263 f64::from_value(v).map(|x| x as f32)
264 }
265}
266impl FromSql for f64 {
267 fn from_value(v: &Value) -> Result<Self> {
268 match v {
269 Value::Float(x) => Ok(*x),
270 Value::Int(x) => Ok(*x as f64),
271 Value::UInt(x) => Ok(*x as f64),
272 _ => Err(Error::Type("expected number".into())),
273 }
274 }
275}
276impl ToSql for String {
277 fn to_value(&self) -> Value {
278 Value::Text(self.clone())
279 }
280}
281impl ToSql for &str {
282 fn to_value(&self) -> Value {
283 Value::Text((*self).into())
284 }
285}
286impl ToSql for Vec<u8> {
287 fn to_value(&self) -> Value {
288 Value::Bytes(self.clone())
289 }
290}
291impl ToSql for &[u8] {
292 fn to_value(&self) -> Value {
293 Value::Bytes(self.to_vec())
294 }
295}
296impl FromSql for String {
297 fn from_value(v: &Value) -> Result<Self> {
298 match v {
299 Value::Text(x)
300 | Value::Date(x)
301 | Value::Time(x)
302 | Value::DateTime(x)
303 | Value::Decimal(x)
304 | Value::Json(x) => Ok(x.clone()),
305 Value::Bytes(x) => {
306 String::from_utf8(x.clone()).map_err(|_| Error::Type("invalid UTF-8".into()))
307 }
308 _ => Err(Error::Type("expected string".into())),
309 }
310 }
311}
312impl FromSql for Vec<u8> {
313 fn from_value(v: &Value) -> Result<Self> {
314 match v {
315 Value::Bytes(x) => Ok(x.clone()),
316 Value::Text(x) => Ok(x.as_bytes().to_vec()),
317 _ => Err(Error::Type("expected bytes".into())),
318 }
319 }
320}
321impl<T: ToSql> ToSql for Option<T> {
322 fn to_value(&self) -> Value {
323 self.as_ref().map_or(Value::Null, ToSql::to_value)
324 }
325}
326impl<T: FromSql> FromSql for Option<T> {
327 fn from_value(v: &Value) -> Result<Self> {
328 if matches!(v, Value::Null) {
329 Ok(None)
330 } else {
331 T::from_value(v).map(Some)
332 }
333 }
334}
335
336#[derive(Debug, Clone)]
337pub struct Column {
338 pub name: String,
339 pub table: String,
340 pub type_code: u8,
341 pub flags: u16,
342}
343#[derive(Debug, Clone)]
344pub struct Row {
345 pub columns: Vec<Column>,
346 pub values: Vec<Value>,
347}
348impl Row {
349 pub fn get<T: FromSql>(&self, index: usize) -> Result<T> {
350 self.values
351 .get(index)
352 .ok_or_else(|| Error::Type("column index out of range".into()))
353 .and_then(T::from_value)
354 }
355 pub fn get_by_name<T: FromSql>(&self, name: &str) -> Result<T> {
356 let i = self
357 .columns
358 .iter()
359 .position(|c| c.name.eq_ignore_ascii_case(name))
360 .ok_or_else(|| Error::Type(format!("unknown column {name}")))?;
361 self.get(i)
362 }
363}
364#[derive(Debug, Clone, Default)]
365pub struct QueryResult {
366 pub rows: Vec<Row>,
367 pub affected_rows: u64,
368 pub last_insert_id: u64,
369 pub warnings: u16,
370 pub status: u16,
371 pub more_results: bool,
372}
373
374fn le_u16(b: &[u8]) -> u16 {
375 u16::from_le_bytes([b[0], b[1]])
376}
377fn le_u32(b: &[u8]) -> u32 {
378 u32::from_le_bytes([b[0], b[1], b[2], b[3]])
379}
380fn le_u64(b: &[u8]) -> u64 {
381 u64::from_le_bytes(b[..8].try_into().unwrap())
382}
383fn lenenc(v: u64, out: &mut Vec<u8>) {
384 if v < 251 {
385 out.push(v as u8)
386 } else if v <= 0xffff {
387 out.push(0xfc);
388 out.extend_from_slice(&(v as u16).to_le_bytes())
389 } else if v <= 0xffff_ffff {
390 out.push(0xfd);
391 out.extend_from_slice(&(v as u32).to_le_bytes())
392 } else {
393 out.push(0xfe);
394 out.extend_from_slice(&v.to_le_bytes())
395 }
396}
397fn read_lenenc(b: &[u8], p: &mut usize) -> Result<Option<u64>> {
398 let x = *b
399 .get(*p)
400 .ok_or_else(|| Error::Protocol("short length encoded integer".into()))?;
401 *p += 1;
402 match x {
403 0xfb => Ok(None),
404 0xfc => {
405 let v = le_u16(
406 b.get(*p..*p + 2)
407 .ok_or_else(|| Error::Protocol("short lenenc".into()))?,
408 );
409 *p += 2;
410 Ok(Some(v as u64))
411 }
412 0xfd => {
413 let q = b
414 .get(*p..*p + 3)
415 .ok_or_else(|| Error::Protocol("short lenenc".into()))?;
416 *p += 3;
417 Ok(Some(
418 (q[0] as u64) | ((q[1] as u64) << 8) | ((q[2] as u64) << 16),
419 ))
420 }
421 0xfe => {
422 let v = le_u64(
423 b.get(*p..*p + 8)
424 .ok_or_else(|| Error::Protocol("short lenenc".into()))?,
425 );
426 *p += 8;
427 Ok(Some(v))
428 }
429 _ => Ok(Some(x as u64)),
430 }
431}
432fn len_bytes(b: &[u8], out: &mut Vec<u8>) {
433 lenenc(b.len() as u64, out);
434 out.extend_from_slice(b);
435}
436
437#[derive(Debug)]
438struct Conn {
439 stream: Transport,
440 seq: u8,
441 caps: u32,
442 status: u16,
443}
444#[derive(Debug)]
445enum Transport {
446 Plain(TcpStream),
447 #[cfg(feature = "tls")]
448 Tls(Box<StreamOwned<ClientConnection, TcpStream>>),
449}
450impl Read for Transport {
451 fn read(&mut self, b: &mut [u8]) -> io::Result<usize> {
452 match self {
453 Self::Plain(s) => s.read(b),
454 #[cfg(feature = "tls")]
455 Self::Tls(s) => s.read(b),
456 }
457 }
458}
459impl Write for Transport {
460 fn write(&mut self, b: &[u8]) -> io::Result<usize> {
461 match self {
462 Self::Plain(s) => s.write(b),
463 #[cfg(feature = "tls")]
464 Self::Tls(s) => s.write(b),
465 }
466 }
467 fn flush(&mut self) -> io::Result<()> {
468 match self {
469 Self::Plain(s) => s.flush(),
470 #[cfg(feature = "tls")]
471 Self::Tls(s) => s.flush(),
472 }
473 }
474}
475impl Conn {
476 fn read_packet(&mut self) -> Result<Vec<u8>> {
477 let mut out = Vec::new();
478 loop {
479 let mut h = [0; 4];
480 self.stream.read_exact(&mut h)?;
481 let n = (h[0] as usize) | ((h[1] as usize) << 8) | ((h[2] as usize) << 16);
482 if h[3] != self.seq {
483 return Err(Error::Protocol(format!(
484 "packet sequence {}, expected {}",
485 h[3], self.seq
486 )));
487 }
488 self.seq = self.seq.wrapping_add(1);
489 let mut p = vec![0; n];
490 self.stream.read_exact(&mut p)?;
491 out.extend_from_slice(&p);
492 if n < 0x00ff_ffff {
493 break;
494 }
495 }
496 Ok(out)
497 }
498 fn write_packet(&mut self, data: &[u8]) -> Result<()> {
499 let mut pos = 0;
500 loop {
501 let n = (data.len() - pos).min(0x00ff_ffff);
502 let h = [n as u8, (n >> 8) as u8, (n >> 16) as u8, self.seq];
503 self.stream.write_all(&h)?;
504 self.stream.write_all(&data[pos..pos + n])?;
505 self.seq = self.seq.wrapping_add(1);
506 pos += n;
507 if n < 0x00ff_ffff {
508 break;
509 }
510 }
511 self.stream.flush()?;
512 Ok(())
513 }
514 fn command(&mut self, cmd: u8, payload: &[u8]) -> Result<Vec<u8>> {
515 self.seq = 0;
516 let mut b = Vec::with_capacity(payload.len() + 1);
517 b.push(cmd);
518 b.extend_from_slice(payload);
519 self.write_packet(&b)?;
520 self.read_packet()
521 }
522}
523
524#[derive(Debug)]
525pub struct Client {
526 conn: Conn,
527 pub server_version: String,
528}
529impl Client {
530 pub fn connect(url: &str) -> Result<Self> {
531 Self::connect_with_options(ConnectOptions::from_url(url)?)
532 }
533 pub fn connect_with_options(opts: ConnectOptions) -> Result<Self> {
534 #[cfg(not(feature = "tls"))]
535 if opts.tls != TlsMode::Disabled {
536 return Err(Error::Unsupported("TLS requires the tls feature".into()));
537 }
538 let addr = (opts.host.as_str(), opts.port)
539 .to_socket_addrs()?
540 .next()
541 .ok_or_else(|| Error::Url("host did not resolve".into()))?;
542 let s = TcpStream::connect_timeout(
543 &addr,
544 opts.connect_timeout.unwrap_or(Duration::from_secs(10)),
545 )?;
546 s.set_read_timeout(opts.read_timeout)?;
547 s.set_write_timeout(opts.write_timeout)?;
548 let mut c = Conn {
549 stream: Transport::Plain(s),
550 seq: 0,
551 caps: 0,
552 status: 0,
553 };
554 let hello = c.read_packet()?;
555 let (version, caps, scramble, plugin) = parse_handshake(&hello)?;
556 let want = CLIENT_LONG_PASSWORD
557 | CLIENT_LONG_FLAG
558 | CLIENT_CONNECT_WITH_DB
559 | CLIENT_PROTOCOL_41
560 | CLIENT_TRANSACTIONS
561 | CLIENT_SSL
562 | CLIENT_SECURE_CONNECTION
563 | CLIENT_PLUGIN_AUTH
564 | CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA
565 | CLIENT_MULTI_RESULTS
566 | CLIENT_MULTI_STATEMENTS
567 | CLIENT_DEPRECATE_EOF;
568 #[allow(unused_mut)]
569 let mut caps = caps & want;
570 #[cfg(feature = "tls")]
571 if opts.tls != TlsMode::Disabled {
572 if caps & (1 << 11) == 0 {
573 if opts.tls == TlsMode::Required || opts.tls == TlsMode::VerifyIdentity {
574 return Err(Error::Unsupported("server does not support TLS".into()));
575 }
576 } else {
577 caps |= 1 << 11;
578 let mut ssl = Vec::new();
579 ssl.extend_from_slice(&caps.to_le_bytes());
580 ssl.extend_from_slice(&opts.max_packet_size.to_le_bytes());
581 ssl.push(opts.charset);
582 ssl.extend_from_slice(&[0; 23]);
583 c.seq = 1;
584 c.write_packet(&ssl)?;
585 let plain = match c.stream {
586 Transport::Plain(s) => s,
587 _ => return Err(Error::Protocol("invalid TLS transport state".into())),
588 };
589 let name = opts
590 .tls_server_name
591 .clone()
592 .unwrap_or_else(|| opts.host.clone());
593 let server_name = ServerName::try_from(name)
594 .map_err(|_| Error::Url("invalid TLS server name".into()))?;
595 let config = tls_config(&opts)?;
596 let mut tls = ClientConnection::new(config, server_name)
597 .map_err(|e| Error::Protocol(format!("TLS setup failed: {e}")))?;
598 let mut plain = plain;
599 tls.complete_io(&mut plain)?;
600 c.stream = Transport::Tls(Box::new(StreamOwned::new(tls, plain)));
601 }
602 }
603 let auth = match plugin.as_str() {
604 "mysql_native_password" => native_auth(&opts.password, &scramble),
605 "caching_sha2_password" => sha2_auth(&opts.password, &scramble),
606 p => return Err(Error::Unsupported(format!("authentication plugin {p}"))),
607 };
608 let mut b = Vec::new();
609 b.extend_from_slice(&caps.to_le_bytes());
610 b.extend_from_slice(&opts.max_packet_size.to_le_bytes());
611 b.push(opts.charset);
612 b.extend_from_slice(&[0; 23]);
613 b.extend_from_slice(opts.user.as_bytes());
614 b.push(0);
615 len_bytes(&auth, &mut b);
616 if caps & CLIENT_CONNECT_WITH_DB != 0
617 && let Some(db) = &opts.database
618 {
619 b.extend_from_slice(db.as_bytes());
620 b.push(0)
621 }
622 if caps & CLIENT_PLUGIN_AUTH != 0 {
623 b.extend_from_slice(plugin.as_bytes());
624 b.push(0)
625 };
626 c.caps = caps;
627 c.seq = if matches!(&c.stream, Transport::Plain(_)) {
628 1
629 } else {
630 2
631 };
632 c.write_packet(&b)?;
633 loop {
634 let response = c.read_packet()?;
635 match response.first() {
636 Some(0xff) => return Err(parse_err(&response)),
637 Some(0x00) => break,
638 Some(0x01) if response.get(1) == Some(&0x03) => continue,
639 Some(0x01) if response.get(1) == Some(&0x04) => {
640 #[cfg(feature = "tls")]
641 if opts.tls != TlsMode::Disabled {
642 let mut password = opts.password.as_bytes().to_vec();
643 password.push(0);
644 c.write_packet(&password)?;
645 continue;
646 }
647 return Err(Error::Unsupported(
648 "caching_sha2_password full authentication requires TLS".into(),
649 ));
650 }
651 _ => return Err(Error::Protocol("unexpected authentication response".into())),
652 }
653 }
654 Ok(Self {
655 conn: c,
656 server_version: version,
657 })
658 }
659 pub fn query(&mut self, sql: &str) -> Result<QueryResult> {
660 let p = self.conn.command(0x03, sql.as_bytes())?;
661 self.read_result(p, false)
662 }
663 pub fn execute(&mut self, sql: &str) -> Result<QueryResult> {
664 self.query(sql)
665 }
666 pub fn ping(&mut self) -> Result<()> {
667 let p = self.conn.command(0x0e, &[])?;
668 if p.first() == Some(&0xff) {
669 Err(parse_err(&p))
670 } else {
671 Ok(())
672 }
673 }
674 pub fn prepare(&mut self, sql: &str) -> Result<Statement> {
675 let p = self.conn.command(0x16, sql.as_bytes())?;
676 if p.first() == Some(&0xff) {
677 return Err(parse_err(&p));
678 }
679 if p.first() != Some(&0) {
680 return Err(Error::Protocol("invalid prepare response".into()));
681 }
682 let id = le_u32(&p[1..5]);
683 let params = le_u16(&p[5..7]) as usize;
684 Ok(Statement {
685 id,
686 param_count: params,
687 })
688 }
689 fn read_result(&mut self, first: Vec<u8>, binary: bool) -> Result<QueryResult> {
690 if first.first() == Some(&0xff) {
691 return Err(parse_err(&first));
692 }
693 if first.first() == Some(&0x00) {
694 let mut p = 1;
695 let affected = read_lenenc(&first, &mut p)?.unwrap_or(0);
696 let last = read_lenenc(&first, &mut p)?.unwrap_or(0);
697 let status = if p + 2 <= first.len() {
698 le_u16(&first[p..p + 2])
699 } else {
700 0
701 };
702 self.conn.status = status;
703 return Ok(QueryResult {
704 affected_rows: affected,
705 last_insert_id: last,
706 status,
707 ..Default::default()
708 });
709 }
710 let mut p = 0;
711 let n = read_lenenc(&first, &mut p)?
712 .ok_or_else(|| Error::Protocol("NULL column count".into()))? as usize;
713 let mut cols = Vec::with_capacity(n);
714 for _ in 0..n {
715 let x = self.conn.read_packet()?;
716 cols.push(parse_column(&x)?);
717 }
718 let mut rows = Vec::new();
719 let mut pending = Some(self.conn.read_packet()?);
720 loop {
721 let x = match pending.take() {
722 Some(x) => x,
723 None => self.conn.read_packet()?,
724 };
725 if (x.first() == Some(&0xfe) && x.len() < 9)
726 || (x.first() == Some(&0x00) && x.len() >= 7)
727 {
728 if x.len() >= 5 {
729 self.conn.status = le_u16(&x[3..5]);
730 }
731 break;
732 }
733 if x.first() == Some(&0xff) {
734 return Err(parse_err(&x));
735 }
736 rows.push(if binary {
737 parse_binary_row(&x, &cols)?
738 } else {
739 parse_text_row(&x, &cols)?
740 });
741 }
742 Ok(QueryResult {
743 rows,
744 status: self.conn.status,
745 ..Default::default()
746 })
747 }
748}
749
750#[derive(Debug)]
751pub struct Statement {
752 id: u32,
753 param_count: usize,
754}
755impl Statement {
756 pub fn parameter_count(&self) -> usize {
757 self.param_count
758 }
759 pub fn query(&self, c: &mut Client, params: &[&dyn ToSql]) -> Result<QueryResult> {
760 self.exec(c, params)
761 }
762 pub fn execute(&self, c: &mut Client, params: &[&dyn ToSql]) -> Result<QueryResult> {
763 self.exec(c, params)
764 }
765 fn exec(&self, c: &mut Client, params: &[&dyn ToSql]) -> Result<QueryResult> {
766 if params.len() != self.param_count {
767 return Err(Error::Protocol(format!(
768 "expected {} parameters, got {}",
769 self.param_count,
770 params.len()
771 )));
772 }
773 let vals = params.iter().map(|x| x.to_value()).collect::<Vec<_>>();
774 let mut b = Vec::new();
775 b.extend_from_slice(&self.id.to_le_bytes());
776 b.push(0);
777 b.extend_from_slice(&1u32.to_le_bytes());
778 b.extend_from_slice(&[0; 4]);
779 let mut nulls = vec![0u8; vals.len().div_ceil(8)];
780 for (i, v) in vals.iter().enumerate() {
781 if matches!(v, Value::Null) {
782 nulls[i / 8] |= 1 << (i % 8)
783 }
784 }
785 b.extend_from_slice(&nulls);
786 b.push(1);
787 for v in &vals {
788 b.extend_from_slice(&type_of(v).to_le_bytes());
789 }
790 for v in &vals {
791 encode_binary(v, &mut b)
792 }
793 let p = c.conn.command(0x17, &b)?;
794 c.read_result(p, true)
795 }
796 pub fn close(self, c: &mut Client) -> Result<()> {
797 let mut b = Vec::new();
798 b.extend_from_slice(&self.id.to_le_bytes());
799 c.conn.command(0x19, &b).map(|_| ())
800 }
801}
802fn type_of(v: &Value) -> u16 {
803 match v {
804 Value::Null => 0x06,
805 Value::Int(_) => 0x03,
806 Value::UInt(_) => 0x08,
807 Value::Float(_) => 0x05,
808 Value::Bool(_) => 0x01,
809 Value::Bytes(_) | Value::Text(_) | Value::Json(_) | Value::Decimal(_) => 0xfd,
810 _ => 0x0f,
811 }
812}
813fn encode_binary(v: &Value, b: &mut Vec<u8>) {
814 match v {
815 Value::Null => {}
816 Value::Int(x) => b.extend_from_slice(&x.to_le_bytes()),
817 Value::UInt(x) => b.extend_from_slice(&x.to_le_bytes()),
818 Value::Float(x) => b.extend_from_slice(&x.to_le_bytes()),
819 Value::Bool(x) => b.push(*x as u8),
820 Value::Bytes(x) => len_bytes(x, b),
821 Value::Text(x) | Value::Json(x) | Value::Decimal(x) => len_bytes(x.as_bytes(), b),
822 Value::Date(x) | Value::Time(x) | Value::DateTime(x) => len_bytes(x.as_bytes(), b),
823 }
824}
825
826pub struct Transaction<'a> {
827 client: &'a mut Client,
828 done: bool,
829}
830impl Client {
831 pub fn transaction(&mut self) -> Result<Transaction<'_>> {
832 self.query("START TRANSACTION")?;
833 Ok(Transaction {
834 client: self,
835 done: false,
836 })
837 }
838 pub fn begin(&mut self) -> Result<()> {
839 self.query("START TRANSACTION").map(|_| ())
840 }
841 pub fn commit(&mut self) -> Result<()> {
842 self.query("COMMIT").map(|_| ())
843 }
844 pub fn rollback(&mut self) -> Result<()> {
845 self.query("ROLLBACK").map(|_| ())
846 }
847 pub fn savepoint(&mut self, name: &str) -> Result<()> {
848 validate_ident(name)?;
849 self.query(&format!("SAVEPOINT `{name}`")).map(|_| ())
850 }
851 pub fn rollback_to(&mut self, name: &str) -> Result<()> {
852 validate_ident(name)?;
853 self.query(&format!("ROLLBACK TO SAVEPOINT `{name}`"))
854 .map(|_| ())
855 }
856}
857impl<'a> Transaction<'a> {
858 pub fn query(&mut self, s: &str) -> Result<QueryResult> {
859 self.client.query(s)
860 }
861 pub fn commit(mut self) -> Result<()> {
862 self.client.commit()?;
863 self.done = true;
864 Ok(())
865 }
866 pub fn rollback(mut self) -> Result<()> {
867 self.client.rollback()?;
868 self.done = true;
869 Ok(())
870 }
871}
872impl Drop for Transaction<'_> {
873 fn drop(&mut self) {
874 if !self.done {
875 let _ = self.client.rollback();
876 }
877 }
878}
879fn validate_ident(s: &str) -> Result<()> {
880 if s.is_empty() || s.bytes().any(|b| !(b.is_ascii_alphanumeric() || b == b'_')) {
881 Err(Error::Protocol("invalid identifier".into()))
882 } else {
883 Ok(())
884 }
885}
886
887pub struct Pool {
888 opts: ConnectOptions,
889 max: usize,
890 idle: Vec<Client>,
891}
892impl Pool {
893 pub fn new(opts: ConnectOptions, max: usize) -> Self {
894 Self {
895 opts,
896 max: max.max(1),
897 idle: Vec::new(),
898 }
899 }
900 pub fn get(&mut self) -> Result<PooledConnection<'_>> {
901 if let Some(c) = self.idle.pop() {
902 return Ok(PooledConnection {
903 pool: self,
904 client: Some(c),
905 });
906 }
907 if self.idle.len() < self.max {
908 let opts = self.opts.clone();
909 Ok(PooledConnection {
910 pool: self,
911 client: Some(Client::connect_with_options(opts)?),
912 })
913 } else {
914 Err(Error::Timeout)
915 }
916 }
917}
918pub struct PooledConnection<'a> {
919 pool: &'a mut Pool,
920 client: Option<Client>,
921}
922impl std::ops::Deref for PooledConnection<'_> {
923 type Target = Client;
924 fn deref(&self) -> &Client {
925 self.client.as_ref().unwrap()
926 }
927}
928impl std::ops::DerefMut for PooledConnection<'_> {
929 fn deref_mut(&mut self) -> &mut Client {
930 self.client.as_mut().unwrap()
931 }
932}
933impl Drop for PooledConnection<'_> {
934 fn drop(&mut self) {
935 if let Some(c) = self.client.take()
936 && self.pool.idle.len() < self.pool.max
937 {
938 self.pool.idle.push(c)
939 }
940 }
941}
942
943fn parse_handshake(b: &[u8]) -> Result<(String, u32, Vec<u8>, String)> {
944 if b.len() < 34 {
945 return Err(Error::Protocol("short handshake".into()));
946 }
947 let mut p = 0;
948 if b[p] != 10 {
949 return Err(Error::Unsupported(
950 "only MySQL protocol 10 is supported".into(),
951 ));
952 }
953 p += 1;
954 let end = b[p..]
955 .iter()
956 .position(|x| *x == 0)
957 .ok_or_else(|| Error::Protocol("bad handshake version".into()))?
958 + p;
959 let ver = String::from_utf8_lossy(&b[p..end]).into();
960 p = end + 1;
961 p += 4;
962 let scramble1 = b[p..p + 8].to_vec();
963 p += 9;
964 let low = le_u16(&b[p..p + 2]) as u32;
965 p += 2;
966 if p >= b.len() {
967 return Ok((ver, low, scramble1, "mysql_native_password".into()));
968 }
969 p += 1 + 2;
970 let high = le_u16(&b[p..p + 2]) as u32;
971 p += 2;
972 let caps = low | (high << 16);
973 p += 1 + 10;
974 let n = b.get(p - 11).copied().unwrap_or(0) as usize;
975 let mut scramble = scramble1;
976 if p < b.len() {
977 let take = n.saturating_sub(1).min(13).min(b.len() - p);
978 scramble.extend_from_slice(&b[p..p + take]);
979 p += take;
980 }
981 let plugin = b[p..]
982 .split(|x| *x == 0)
983 .next()
984 .map(|x| String::from_utf8_lossy(x).into_owned())
985 .unwrap_or_else(|| "mysql_native_password".into());
986 Ok((ver, caps, scramble, plugin))
987}
988fn sha1(data: &[u8]) -> [u8; 20] {
989 let mut h = [
990 0x67452301u32,
991 0xefcdab89,
992 0x98badcfe,
993 0x10325476,
994 0xc3d2e1f0,
995 ];
996 let mut msg = data.to_vec();
997 let bit = (msg.len() as u64) * 8;
998 msg.push(0x80);
999 while msg.len() % 64 != 56 {
1000 msg.push(0)
1001 }
1002 msg.extend_from_slice(&bit.to_be_bytes());
1003 for chunk in msg.chunks(64) {
1004 let mut w = [0u32; 80];
1005 for i in 0..16 {
1006 w[i] = u32::from_be_bytes(chunk[i * 4..i * 4 + 4].try_into().unwrap())
1007 }
1008 for i in 16..80 {
1009 w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1)
1010 }
1011 let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
1012 for (i, &x) in w.iter().enumerate() {
1013 let (f, k) = match i {
1014 0..=19 => ((b & c) | (!b & d), 0x5a827999),
1015 20..=39 => (b ^ c ^ d, 0x6ed9eba1),
1016 40..=59 => ((b & c) | (b & d) | (c & d), 0x8f1bbcdc),
1017 _ => (b ^ c ^ d, 0xca62c1d6),
1018 };
1019 let t = a
1020 .rotate_left(5)
1021 .wrapping_add(f)
1022 .wrapping_add(e)
1023 .wrapping_add(k)
1024 .wrapping_add(x);
1025 e = d;
1026 d = c;
1027 c = b.rotate_left(30);
1028 b = a;
1029 a = t
1030 }
1031 h = [
1032 h[0].wrapping_add(a),
1033 h[1].wrapping_add(b),
1034 h[2].wrapping_add(c),
1035 h[3].wrapping_add(d),
1036 h[4].wrapping_add(e),
1037 ]
1038 }
1039 let mut out = [0; 20];
1040 for (i, x) in h.iter().enumerate() {
1041 out[i * 4..i * 4 + 4].copy_from_slice(&x.to_be_bytes())
1042 }
1043 out
1044}
1045fn native_auth(p: &str, s: &[u8]) -> Vec<u8> {
1046 if p.is_empty() {
1047 return vec![];
1048 }
1049 let a = sha1(p.as_bytes());
1050 let b = sha1(&a);
1051 let mut x = Vec::new();
1052 x.extend_from_slice(s);
1053 x.extend_from_slice(&b);
1054 let c = sha1(&x);
1055 a.iter().zip(c).map(|(x, y)| x ^ y).collect()
1056}
1057fn sha256(data: &[u8]) -> [u8; 32] {
1058 const K: [u32; 64] = [
1059 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
1060 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
1061 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
1062 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
1063 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
1064 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
1065 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
1066 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1067 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
1068 0xc67178f2,
1069 ];
1070 let mut h: [u32; 8] = [
1071 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
1072 0x5be0cd19,
1073 ];
1074 let mut m = data.to_vec();
1075 let bits = (m.len() as u64) * 8;
1076 m.push(0x80);
1077 while m.len() % 64 != 56 {
1078 m.push(0);
1079 }
1080 m.extend_from_slice(&bits.to_be_bytes());
1081 for c in m.chunks(64) {
1082 let mut w = [0u32; 64];
1083 for i in 0..16 {
1084 w[i] = u32::from_be_bytes(c[i * 4..i * 4 + 4].try_into().unwrap());
1085 }
1086 for i in 16..64 {
1087 let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
1088 let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
1089 w[i] = w[i - 16]
1090 .wrapping_add(s0)
1091 .wrapping_add(w[i - 7])
1092 .wrapping_add(s1);
1093 }
1094 let (mut a, mut b, mut cc, mut d, mut e, mut f, mut g, mut q) =
1095 (h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
1096 for i in 0..64 {
1097 let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
1098 let ch = (e & f) ^ (!e & q);
1099 let t1 = q
1100 .wrapping_add(s1)
1101 .wrapping_add(ch)
1102 .wrapping_add(K[i])
1103 .wrapping_add(w[i]);
1104 let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
1105 let maj = (a & b) ^ (a & cc) ^ (b & cc);
1106 let t2 = s0.wrapping_add(maj);
1107 q = g;
1108 g = f;
1109 f = e;
1110 e = d.wrapping_add(t1);
1111 d = cc;
1112 cc = b;
1113 b = a;
1114 a = t1.wrapping_add(t2);
1115 }
1116 h = [
1117 h[0].wrapping_add(a),
1118 h[1].wrapping_add(b),
1119 h[2].wrapping_add(cc),
1120 h[3].wrapping_add(d),
1121 h[4].wrapping_add(e),
1122 h[5].wrapping_add(f),
1123 h[6].wrapping_add(g),
1124 h[7].wrapping_add(q),
1125 ];
1126 }
1127 let mut out = [0; 32];
1128 for (i, x) in h.iter().enumerate() {
1129 out[i * 4..i * 4 + 4].copy_from_slice(&x.to_be_bytes());
1130 }
1131 out
1132}
1133fn sha2_auth(p: &str, s: &[u8]) -> Vec<u8> {
1134 if p.is_empty() {
1135 return vec![];
1136 }
1137 let stage1 = sha256(p.as_bytes());
1138 let stage2 = sha256(&stage1);
1139 let mut x = Vec::with_capacity(stage2.len() + s.len());
1140 x.extend_from_slice(&stage2);
1141 x.extend_from_slice(s);
1142 let scramble = sha256(&x);
1143 stage1.iter().zip(scramble).map(|(a, b)| a ^ b).collect()
1144}
1145
1146#[cfg(feature = "tls")]
1147fn tls_config(opts: &ConnectOptions) -> Result<Arc<ClientConfig>> {
1148 let mut roots = RootCertStore::empty();
1149 for pem in &opts.ca_certificates {
1150 let mut r = std::io::Cursor::new(pem);
1151 for cert in rustls_pemfile::certs(&mut r) {
1152 let cert = cert.map_err(|e| Error::Protocol(format!("invalid CA certificate: {e}")))?;
1153 roots
1154 .add(cert)
1155 .map_err(|e| Error::Protocol(format!("invalid CA certificate: {e}")))?;
1156 }
1157 }
1158 if opts.tls == TlsMode::VerifyIdentity && roots.is_empty() {
1159 return Err(Error::Unsupported(
1160 "VerifyIdentity requires at least one CA certificate".into(),
1161 ));
1162 }
1163 if opts.tls == TlsMode::VerifyIdentity {
1164 return Ok(Arc::new(
1165 ClientConfig::builder()
1166 .with_root_certificates(roots)
1167 .with_no_client_auth(),
1168 ));
1169 }
1170 let config = ClientConfig::builder()
1171 .dangerous()
1172 .with_custom_certificate_verifier(Arc::new(NoVerifier))
1173 .with_no_client_auth();
1174 Ok(Arc::new(config))
1175}
1176
1177#[cfg(feature = "tls")]
1178#[derive(Debug)]
1179struct NoVerifier;
1180#[cfg(feature = "tls")]
1181impl ServerCertVerifier for NoVerifier {
1182 fn verify_server_cert(
1183 &self,
1184 _: &CertificateDer<'_>,
1185 _: &[CertificateDer<'_>],
1186 _: &ServerName<'_>,
1187 _: &[u8],
1188 _: UnixTime,
1189 ) -> std::result::Result<ServerCertVerified, TlsError> {
1190 Ok(ServerCertVerified::assertion())
1191 }
1192 fn verify_tls12_signature(
1193 &self,
1194 _: &[u8],
1195 _: &CertificateDer<'_>,
1196 _: &DigitallySignedStruct,
1197 ) -> std::result::Result<HandshakeSignatureValid, TlsError> {
1198 Ok(HandshakeSignatureValid::assertion())
1199 }
1200 fn verify_tls13_signature(
1201 &self,
1202 _: &[u8],
1203 _: &CertificateDer<'_>,
1204 _: &DigitallySignedStruct,
1205 ) -> std::result::Result<HandshakeSignatureValid, TlsError> {
1206 Ok(HandshakeSignatureValid::assertion())
1207 }
1208 fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1209 vec![
1210 SignatureScheme::RSA_PSS_SHA256,
1211 SignatureScheme::ECDSA_NISTP256_SHA256,
1212 SignatureScheme::ED25519,
1213 ]
1214 }
1215}
1216fn parse_err(b: &[u8]) -> Error {
1217 let code = if b.len() >= 3 { le_u16(&b[1..3]) } else { 0 };
1218 let state = if b.len() > 4 && b[3] == b'#' {
1219 String::from_utf8_lossy(&b[4..9.min(b.len())]).into()
1220 } else {
1221 "HY000".into()
1222 };
1223 let message = String::from_utf8_lossy(if b.len() > 3 { &b[3..] } else { &[] }).into();
1224 Error::Server {
1225 code,
1226 state,
1227 message,
1228 }
1229}
1230fn parse_column(b: &[u8]) -> Result<Column> {
1231 let mut p = 0;
1232 let mut fields = Vec::new();
1233 for _ in 0..6 {
1234 let n = read_lenenc(b, &mut p)?.unwrap_or(0) as usize;
1235 let end = p
1236 .checked_add(n)
1237 .ok_or_else(|| Error::Protocol("column overflow".into()))?;
1238 fields.push(
1239 String::from_utf8_lossy(
1240 b.get(p..end)
1241 .ok_or_else(|| Error::Protocol("short column".into()))?,
1242 )
1243 .into_owned(),
1244 );
1245 p = end;
1246 }
1247 let fixed = read_lenenc(b, &mut p)?
1248 .ok_or_else(|| Error::Protocol("missing column definition".into()))?
1249 as usize;
1250 if fixed < 12 || p + fixed > b.len() {
1251 return Err(Error::Protocol("short column definition".into()));
1252 }
1253 let charset = p + 2;
1254 let _ = charset;
1255 let type_code = b[p + 6];
1256 let flags = le_u16(&b[p + 7..p + 9]);
1257 Ok(Column {
1258 name: fields[4].clone(),
1259 table: fields[2].clone(),
1260 type_code,
1261 flags,
1262 })
1263}
1264fn parse_text_row(b: &[u8], c: &[Column]) -> Result<Row> {
1265 let mut p = 0;
1266 let mut v = Vec::with_capacity(c.len());
1267 for col in c {
1268 match read_lenenc(b, &mut p)? {
1269 None => v.push(Value::Null),
1270 Some(n) => {
1271 let n = n as usize;
1272 let x = b
1273 .get(p..p + n)
1274 .ok_or_else(|| Error::Protocol("short row".into()))?;
1275 p += n;
1276 v.push(decode_text(col.type_code, x));
1277 }
1278 }
1279 }
1280 Ok(Row {
1281 columns: c.to_vec(),
1282 values: v,
1283 })
1284}
1285fn parse_binary_row(b: &[u8], c: &[Column]) -> Result<Row> {
1286 if b.first() != Some(&0) {
1287 return Err(Error::Protocol("invalid binary row".into()));
1288 }
1289 let null_len = (c.len() + 7 + 2) / 8;
1290 let nulls = b
1291 .get(1..1 + null_len)
1292 .ok_or_else(|| Error::Protocol("short binary row".into()))?;
1293 let mut p = 1 + null_len;
1294 let mut v = Vec::new();
1295 for (i, col) in c.iter().enumerate() {
1296 if nulls[i / 8] & (1 << (i % 8)) != 0 {
1297 v.push(Value::Null);
1298 continue;
1299 }
1300 let n = match col.type_code {
1301 1 => 1,
1302 2..=4 => 4,
1303 8 => 8,
1304 5 => 8,
1305 _ => read_lenenc(b, &mut p)?.unwrap_or(0) as usize,
1306 };
1307 let x = b
1308 .get(p..p + n)
1309 .ok_or_else(|| Error::Protocol("short binary value".into()))?;
1310 p += n;
1311 v.push(decode(col.type_code, x))
1312 }
1313 Ok(Row {
1314 columns: c.to_vec(),
1315 values: v,
1316 })
1317}
1318fn decode(t: u8, b: &[u8]) -> Value {
1319 match t {
1320 1 => Value::Bool(b.first() == Some(&1)),
1321 2..=4 => Value::Int(if b.len() >= 4 {
1322 le_u32(b) as i32 as i64
1323 } else {
1324 0
1325 }),
1326 8 => Value::UInt(if b.len() >= 8 { le_u64(b) } else { 0 }),
1327 5 => Value::Float(if b.len() >= 8 {
1328 f64::from_le_bytes(b[..8].try_into().unwrap())
1329 } else {
1330 0.
1331 }),
1332 245 => Value::Json(String::from_utf8_lossy(b).into()),
1333 _ => String::from_utf8(b.to_vec()).map_or_else(|_| Value::Bytes(b.to_vec()), Value::Text),
1334 }
1335}
1336fn decode_text(t: u8, b: &[u8]) -> Value {
1337 let text = String::from_utf8_lossy(b).into_owned();
1338 match t {
1339 1 => Value::Bool(text != "0"),
1340 2..=4 => text.parse().map(Value::Int).unwrap_or(Value::Text(text)),
1341 8 => text.parse().map(Value::UInt).unwrap_or(Value::Text(text)),
1342 5 => text.parse().map(Value::Float).unwrap_or(Value::Text(text)),
1343 245 => Value::Json(text),
1344 _ => String::from_utf8(b.to_vec()).map_or_else(|_| Value::Bytes(b.to_vec()), Value::Text),
1345 }
1346}
1347
1348pub struct LocalInfile {
1349 path: PathBuf,
1350}
1351impl LocalInfile {
1352 pub fn new(path: impl AsRef<Path>) -> Result<Self> {
1353 let p = path.as_ref().canonicalize().map_err(Error::Io)?;
1354 if !p.is_file() {
1355 return Err(Error::Protocol("local infile path is not a file".into()));
1356 }
1357 Ok(Self { path: p })
1358 }
1359 pub fn path(&self) -> &Path {
1360 &self.path
1361 }
1362}
1363
1364#[cfg(feature = "tls")]
1365pub mod tls {
1366 pub use rustls;
1367 pub fn available() -> bool {
1368 true
1369 }
1370}
1371#[cfg(feature = "tokio")]
1372pub mod tokio_support {
1373 pub use tokio;
1374}
1375
1376#[cfg(test)]
1377mod tests {
1378 use super::*;
1379 #[test]
1380 fn url_and_lenenc() {
1381 let o = ConnectOptions::from_url("mysql://u:p%40ss@localhost:3307/db").unwrap();
1382 assert_eq!(o.password, "p@ss");
1383 let mut b = Vec::new();
1384 lenenc(300, &mut b);
1385 let mut p = 0;
1386 assert_eq!(read_lenenc(&b, &mut p).unwrap(), Some(300));
1387 }
1388 #[test]
1389 fn auth_is_deterministic() {
1390 assert_eq!(native_auth("p", b"scramble").len(), 20);
1391 }
1392}