Skip to main content

turnloop_mysql/
lib.rs

1#![deny(unsafe_op_in_unsafe_fn)]
2//!
3//! # Getting started on turnloop
4//! Enable the `turnloop` feature for the `asynchronous` module. The embedding
5//! host owns `LocalExecutor` and calls `turn`; adapters await its streams and
6//! deadline futures. See the crate README and turnloop-io for ownership, streaming
7//! and cancellation examples. Default features retain the sans-I/O API.
8
9#![forbid(unsafe_code)]
10//! Pull-driven MySQL protocol. The host owns transport, entropy, time and JS conversion.
11#[cfg(all(target_os = "wasi", target_env = "p3"))]
12use turnloop_wasi_random as _;
13
14use bytes::BytesMut;
15use mysql_common::{
16    auth::plugins::{
17        caching_sha2_password::scramble_sha256, mysql_native_password::scramble_native,
18    },
19    constants::CapabilityFlags as Caps,
20    io::ParseBuf,
21    packets::{
22        AuthPlugin, AuthSwitchRequest, CommonOkPacket, HandshakePacket, HandshakeResponse,
23        OkPacket, OkPacketDeserializer, OldEofPacket, SslRequest, StmtPacket,
24    },
25    proto::{MyDeserialize, MySerialize},
26};
27pub use mysql_common::{
28    constants::{ColumnFlags, ColumnType, StatusFlags},
29    value::Value,
30};
31use std::fmt;
32mod codec;
33mod wire;
34mod zlib;
35use codec::PacketCodec;
36pub mod pool;
37pub mod types;
38pub use wire::{Column, ColumnTypeInfo, RawValue, Row, ServerError, error_code};
39
40#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
41mod host_time;
42#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
43pub use host_time::Instant;
44#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
45pub use std::time::Instant;
46
47pub type Token = u64;
48pub type Result<T> = std::result::Result<T, Error>;
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Error {
51    Protocol(&'static str),
52    State(&'static str),
53    Limit,
54    Timeout,
55    Transport,
56    Cancelled,
57    LocalInfileDisabled,
58}
59impl fmt::Display for Error {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            Self::Protocol(s) | Self::State(s) => f.write_str(s),
63            Self::Limit => f.write_str("protocol buffer limit exceeded"),
64            Self::Timeout => f.write_str("connect ETIMEDOUT"),
65            Self::Transport => f.write_str("Connection lost: The server closed the connection."),
66            Self::Cancelled => f.write_str("Connection closed"),
67            Self::LocalInfileDisabled => f.write_str("LOAD DATA LOCAL INFILE is disabled"),
68        }
69    }
70}
71impl std::error::Error for Error {}
72impl From<std::io::Error> for Error {
73    fn from(_: std::io::Error) -> Self {
74        Self::Protocol("invalid MySQL packet")
75    }
76}
77#[derive(Clone)]
78pub struct Config {
79    pub user: String,
80    pub password: Vec<u8>,
81    pub database: Option<String>,
82    pub tls: bool,
83    pub compression: bool,
84    pub multiple_statements: bool,
85    pub local_infile: bool,
86    pub max_buffer: usize,
87    pub max_columns: usize,
88    pub connect_deadline: Option<Instant>,
89}
90impl Default for Config {
91    fn default() -> Self {
92        Self {
93            user: "root".into(),
94            password: Vec::new(),
95            database: None,
96            tls: false,
97            compression: false,
98            multiple_statements: false,
99            local_infile: false,
100            max_buffer: 64 * 1024 * 1024,
101            max_columns: 4096,
102            connect_deadline: None,
103        }
104    }
105}
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum Outcome {
108    Success,
109    ServerError,
110    Aborted(Error),
111}
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct Statement {
114    pub id: u32,
115    pub parameters: u16,
116    pub columns: u16,
117    pub warnings: u16,
118}
119#[derive(Debug)]
120pub enum Event<'a> {
121    Progress,
122    UpgradeTls,
123    Connected {
124        connection_id: u32,
125    },
126    /// Supply 20 fresh random bytes to rsa_seed; no entropy is read by the core.
127    RsaSeedNeeded,
128    AuthFastSuccess,
129    AuthFull,
130    ColumnCount {
131        token: Token,
132        count: usize,
133    },
134    Column {
135        token: Token,
136        column: Column<'a>,
137        parameter: bool,
138    },
139    Row {
140        token: Token,
141        row: Row<'a>,
142    },
143    /// A genuine OK packet: a command or one statement of a multi-statement
144    /// query finished without a result set. `affected_rows`, `last_insert_id`
145    /// and `info` are meaningful.
146    Ok {
147        token: Token,
148        packet: OkPacket<'a>,
149    },
150    /// The EOF packet ending one result set's rows. It carries no row counts,
151    /// only the warning count and status flags (`SERVER_MORE_RESULTS_EXISTS`
152    /// announces another result).
153    Eof {
154        token: Token,
155        warnings: u16,
156        status: StatusFlags,
157    },
158    Prepared {
159        token: Token,
160        statement: Statement,
161    },
162    Error {
163        token: Option<Token>,
164        error: ServerError<'a>,
165    },
166    LocalInfile {
167        token: Token,
168        file_name: &'a [u8],
169    },
170    Completed {
171        token: Token,
172        outcome: Outcome,
173    },
174    Closed {
175        reason: Error,
176    },
177}
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179enum State {
180    Handshake,
181    Tls,
182    Auth,
183    Key,
184    Seed,
185    Ready,
186    Header,
187    Columns(usize),
188    ColumnsEnd,
189    Rows,
190    Prepare,
191    Parameters(usize),
192    ParametersEnd,
193    PrepareColumns(usize),
194    PrepareEnd,
195    Infile,
196    NoResponse,
197    Closing,
198    Closed,
199}
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201enum CommandKind {
202    Query,
203    Prepare,
204    Execute,
205    Reset,
206    ChangeUser,
207    /// COM_STMT_CLOSE for this statement ID; forgotten once its bytes are sent.
208    CloseStatement(u32),
209    Other,
210}
211struct Pending {
212    token: Token,
213    deadline: Option<Instant>,
214    kind: CommandKind,
215}
216pub struct Connection {
217    packet_ready: bool,
218    config: Config,
219    state: State,
220    codec: PacketCodec,
221    input: BytesMut,
222    packet: Vec<u8>,
223    scratch: Vec<u8>,
224    output: BytesMut,
225    output_at: usize,
226    caps: Caps,
227    tls: bool,
228    plugin: AuthPlugin<'static>,
229    nonce: [u8; 20],
230    connection_id: u32,
231    server_version: (u16, u16, u16),
232    pending: Option<Pending>,
233    completion: Option<Outcome>,
234    columns: Vec<ColumnTypeInfo>,
235    binary: bool,
236    statement: Option<Statement>,
237    statements: Vec<Statement>,
238    status: StatusFlags,
239    reason: Error,
240}
241impl Connection {
242    pub fn new(config: Config) -> Result<Self> {
243        if config.max_buffer < 1024
244            || config.max_buffer > u32::MAX as usize
245            || config.max_columns == 0
246        {
247            return Err(Error::Limit);
248        }
249        if config.user.contains('\0')
250            || config.database.as_ref().is_some_and(|s| s.contains('\0'))
251            || config.password.contains(&0)
252        {
253            return Err(Error::State("NUL in credentials"));
254        }
255        let mut codec = PacketCodec::default();
256        codec.max_allowed_packet = config.max_buffer;
257        Ok(Self {
258            packet_ready: false,
259            config,
260            state: State::Handshake,
261            codec,
262            input: BytesMut::with_capacity(8192),
263            packet: Vec::with_capacity(8192),
264            scratch: Vec::with_capacity(8192),
265            output: BytesMut::with_capacity(8192),
266            output_at: 0,
267            caps: Caps::empty(),
268            tls: false,
269            plugin: AuthPlugin::CachingSha2Password,
270            nonce: [0; 20],
271            connection_id: 0,
272            server_version: (8, 0, 0),
273            pending: None,
274            completion: None,
275            columns: Vec::with_capacity(16),
276            binary: false,
277            statement: None,
278            statements: Vec::new(),
279            status: StatusFlags::empty(),
280            reason: Error::Transport,
281        })
282    }
283    pub fn output(&self) -> &[u8] {
284        &self.output[self.output_at..]
285    }
286    /// Acknowledge `n` written bytes of `output()`.
287    ///
288    /// Returns `true` when an event is now deliverable without further input,
289    /// in which case the host must call `next_event()` right away. This matters
290    /// for COM_STMT_CLOSE and COM_QUIT: the server never answers them, so their
291    /// `Completed` / `Closed` is produced by this acknowledgement itself and no
292    /// read completion or timer would otherwise wake a completion-driven host.
293    pub fn consume_output(&mut self, n: usize) -> Result<bool> {
294        if n > self.output().len() {
295            return Err(Error::State("invalid output acknowledgement"));
296        }
297        self.output_at += n;
298        if self.output_at == self.output.len() {
299            self.output.clear();
300            self.output_at = 0;
301            if self.state == State::NoResponse {
302                // The server holds the statement until these bytes reach it, so
303                // it is dropped from the bookkeeping only now; a failed flush
304                // aborts instead and leaves it listed.
305                if let Some(Pending {
306                    kind: CommandKind::CloseStatement(id),
307                    ..
308                }) = self.pending
309                {
310                    self.statements.retain(|s| s.id != id);
311                }
312                self.complete(Outcome::Success);
313            }
314        }
315        Ok(self.completion.is_some() || (self.state == State::Closing && self.output.is_empty()))
316    }
317    pub fn receive(&mut self, b: &[u8]) -> Result<()> {
318        if matches!(
319            self.state,
320            State::Tls | State::Seed | State::Closing | State::Closed
321        ) {
322            return Err(Error::State("cannot receive plaintext now"));
323        }
324        if b.len()
325            > self.config.max_buffer.saturating_sub(
326                self.input.len()
327                    + if self.packet_ready {
328                        0
329                    } else {
330                        self.packet.len()
331                    },
332            )
333        {
334            self.abort(Error::Limit);
335            return Err(Error::Limit);
336        }
337        self.input.extend_from_slice(b);
338        Ok(())
339    }
340    fn send(&mut self) -> Result<()> {
341        if self.scratch.len() > self.config.max_buffer
342            || self.output.len().saturating_add(self.scratch.len() + 32) > self.config.max_buffer
343        {
344            return Err(Error::Limit);
345        }
346        self.codec
347            .encode(&mut &self.scratch[..], &mut self.output)
348            .map_err(|_| Error::Protocol("packet encoding failed"))?;
349        self.scratch.clear();
350        Ok(())
351    }
352    fn scramble(&mut self) -> Result<()> {
353        match self.plugin {
354            AuthPlugin::CachingSha2Password => {
355                if let Some(b) = scramble_sha256(&self.nonce, &self.config.password) {
356                    self.scratch.extend_from_slice(&b);
357                }
358            }
359            AuthPlugin::MysqlNativePassword => {
360                if let Some(b) = scramble_native(&self.nonce, &self.config.password) {
361                    self.scratch.extend_from_slice(&b);
362                }
363            }
364            _ => return Err(Error::Protocol("unsupported authentication plugin")),
365        }
366        Ok(())
367    }
368    fn handshake_response(&mut self) -> Result<()> {
369        self.scratch.clear();
370        self.scramble()?;
371        // Connection-time allocation only; the upstream packet borrows the auth bytes.
372        let response = HandshakeResponse::new(
373            Some(&self.scratch[..]),
374            self.server_version,
375            Some(self.config.user.as_bytes()),
376            self.config.database.as_deref().map(str::as_bytes),
377            Some(self.plugin.borrow()),
378            self.caps,
379            None,
380            self.config.max_buffer as u32,
381        );
382        let mut bytes = Vec::new();
383        response.serialize(&mut bytes);
384        self.scratch.clear();
385        self.scratch.extend_from_slice(&bytes);
386        self.send()?;
387        self.state = State::Auth;
388        Ok(())
389    }
390    pub fn tls_established(&mut self) -> Result<()> {
391        if self.state != State::Tls || !self.output().is_empty() {
392            return Err(Error::State("TLS transition not ready"));
393        }
394        self.tls = true;
395        self.handshake_response()
396    }
397    /// RSA OAEP SHA1 consumes this one-use, host-generated cryptographic seed.
398    pub fn rsa_seed(&mut self, seed: [u8; 20]) -> Result<()> {
399        use mysql_common::crypto::rsa::{Pkcs1OaepPadding, PublicKey, Rng};
400        struct Seed(Option<[u8; 20]>);
401        impl Rng for Seed {
402            type Error = Error;
403            fn fill(&mut self, b: &mut [u8]) -> Result<()> {
404                if b.len() != 20 {
405                    return Err(Error::Protocol("unexpected OAEP entropy request"));
406                }
407                b.copy_from_slice(&self.0.take().ok_or(Error::State("seed consumed"))?);
408                Ok(())
409            }
410        }
411        if self.state != State::Seed {
412            return Err(Error::State("RSA entropy not requested"));
413        }
414        let key = PublicKey::from_pem(&self.packet[1..])
415            .map_err(|_| Error::Protocol("invalid server RSA public key"))?;
416        if !(128..=1024).contains(&key.num_octets()) {
417            return Err(Error::Protocol("invalid RSA modulus size"));
418        }
419        self.scratch.clear();
420        self.scratch.extend_from_slice(&self.config.password);
421        self.scratch.push(0);
422        for (i, b) in self.scratch.iter_mut().enumerate() {
423            *b ^= self.nonce[i % 20];
424        }
425        // Guard upstream OAEP's length arithmetic before calling it.
426        if self.scratch.len() > key.num_octets() - 42 {
427            return Err(Error::Protocol("password too long for RSA key"));
428        }
429        let encrypted = key
430            .encrypt_block(&self.scratch, Pkcs1OaepPadding::new(Seed(Some(seed))))
431            .map_err(|_| Error::Protocol("RSA encryption failed"))?;
432        self.scratch.clear();
433        self.scratch.extend_from_slice(&encrypted);
434        self.send()?;
435        self.packet.clear();
436        self.state = State::Auth;
437        Ok(())
438    }
439    /// Whether a command submitted now would be admitted. This is the exact rule
440    /// every command method applies: the session is authenticated and idle, the
441    /// previous command's `Completed` has been delivered and all output has been
442    /// acknowledged. A host queue can gate submission on it instead of copying
443    /// the preconditions. Unlike `is_ready`, it also requires flushed output.
444    pub fn can_accept(&self) -> bool {
445        self.state == State::Ready && self.pending.is_none() && self.output().is_empty()
446    }
447    fn accept(&self) -> Result<()> {
448        if !self.can_accept() {
449            Err(Error::State("connection busy or closed"))
450        } else {
451            Ok(())
452        }
453    }
454    fn command(
455        &mut self,
456        token: Token,
457        kind: CommandKind,
458        state: State,
459        deadline: Option<Instant>,
460    ) -> Result<()> {
461        self.codec.reset_seq_id();
462        self.send()?;
463        self.pending = Some(Pending {
464            token,
465            deadline,
466            kind,
467        });
468        self.state = state;
469        Ok(())
470    }
471    pub fn query(&mut self, token: Token, sql: &str, deadline: Option<Instant>) -> Result<()> {
472        self.accept()?;
473        if sql.len().saturating_add(33) > self.config.max_buffer {
474            return Err(Error::Limit);
475        }
476
477        self.scratch.clear();
478        self.scratch.push(3);
479        self.scratch.extend_from_slice(sql.as_bytes());
480        self.binary = false;
481        self.command(token, CommandKind::Query, State::Header, deadline)
482    }
483    pub fn prepare(&mut self, token: Token, sql: &str, deadline: Option<Instant>) -> Result<()> {
484        self.accept()?;
485        if sql.len().saturating_add(33) > self.config.max_buffer {
486            return Err(Error::Limit);
487        }
488
489        self.scratch.clear();
490        self.scratch.push(0x16);
491        self.scratch.extend_from_slice(sql.as_bytes());
492        self.command(token, CommandKind::Prepare, State::Prepare, deadline)
493    }
494    pub fn execute(
495        &mut self,
496        token: Token,
497        id: u32,
498        params: &[Value],
499        deadline: Option<Instant>,
500    ) -> Result<()> {
501        self.accept()?;
502        let stmt = self
503            .statements
504            .iter()
505            .find(|s| s.id == id)
506            .ok_or(Error::State("unknown prepared statement"))?;
507        if params.len() != stmt.parameters as usize {
508            return Err(Error::State("Incorrect arguments to mysqld_stmt_execute"));
509        }
510        let size = params
511            .iter()
512            .fold(16u64.saturating_add(params.len() as u64 * 3), |n, p| {
513                n.saturating_add(p.bin_len())
514            });
515        if size > self.config.max_buffer.saturating_sub(32) as u64 {
516            return Err(Error::Limit);
517        }
518        self.scratch.clear();
519        self.scratch.push(0x17);
520        self.scratch.extend_from_slice(&id.to_le_bytes());
521        self.scratch.push(0);
522        self.scratch.extend_from_slice(&1u32.to_le_bytes());
523        if !params.is_empty() {
524            let start = self.scratch.len();
525            self.scratch.resize(start + params.len().div_ceil(8), 0);
526            for (i, p) in params.iter().enumerate() {
527                if matches!(p, Value::NULL) {
528                    self.scratch[start + i / 8] |= 1 << (i % 8);
529                }
530            }
531            self.scratch.push(1);
532            for p in params {
533                let (t, flags) = match p {
534                    Value::NULL => (6, 0),
535                    Value::Bytes(_) => (253, 0),
536                    Value::Int(_) => (8, 0),
537                    Value::UInt(_) => (8, 128),
538                    Value::Float(_) => (4, 0),
539                    Value::Double(_) => (5, 0),
540                    Value::Date(..) => (12, 0),
541                    Value::Time(..) => (11, 0),
542                };
543                self.scratch.extend_from_slice(&[t, flags]);
544            }
545            for p in params {
546                p.serialize(&mut self.scratch);
547            }
548        }
549        self.binary = true;
550        self.command(token, CommandKind::Execute, State::Header, deadline)
551    }
552    fn simple(
553        &mut self,
554        token: Token,
555        code: u8,
556        id: Option<u32>,
557        kind: CommandKind,
558        state: State,
559    ) -> Result<()> {
560        self.accept()?;
561        self.scratch.clear();
562        self.scratch.push(code);
563        if let Some(id) = id {
564            if !self.statements.iter().any(|s| s.id == id) {
565                return Err(Error::State("unknown prepared statement"));
566            }
567            self.scratch.extend_from_slice(&id.to_le_bytes());
568        }
569        self.command(token, kind, state, None)
570    }
571    pub fn ping(&mut self, token: Token) -> Result<()> {
572        self.simple(token, 0x0e, None, CommandKind::Other, State::Header)
573    }
574    pub fn reset_connection(&mut self, token: Token) -> Result<()> {
575        self.simple(token, 0x1f, None, CommandKind::Reset, State::Header)
576    }
577    pub fn reset_statement(&mut self, token: Token, id: u32) -> Result<()> {
578        self.simple(token, 0x1a, Some(id), CommandKind::Other, State::Header)
579    }
580    pub fn close_statement(&mut self, token: Token, id: u32) -> Result<()> {
581        self.simple(
582            token,
583            0x19,
584            Some(id),
585            CommandKind::CloseStatement(id),
586            State::NoResponse,
587        )
588    }
589    /// Prepared statements the server still holds for this session. A statement
590    /// being closed stays listed until its COM_STMT_CLOSE bytes are acknowledged.
591    pub fn statements(&self) -> &[Statement] {
592        &self.statements
593    }
594    pub fn change_user(
595        &mut self,
596        token: Token,
597        user: String,
598        password: Vec<u8>,
599        database: Option<String>,
600    ) -> Result<()> {
601        use mysql_common::packets::{ComChangeUser, ComChangeUserMoreData};
602        self.accept()?;
603        if user.contains('\0') || database.as_ref().is_some_and(|s| s.contains('\0')) {
604            return Err(Error::State("NUL in credentials"));
605        }
606        self.config.user = user;
607        self.config.password = password;
608        self.config.database = database;
609        self.scratch.clear();
610        self.scramble()?;
611        let more = ComChangeUserMoreData::new(45).with_auth_plugin(Some(self.plugin.borrow()));
612        let command = ComChangeUser::new()
613            .with_user(Some(self.config.user.as_bytes()))
614            .with_database(self.config.database.as_deref().map(str::as_bytes))
615            .with_auth_plugin_data(Some(&self.scratch[..]))
616            .with_more_data(Some(more));
617        let mut bytes = Vec::new();
618        command.serialize(&mut bytes);
619        self.scratch.clear();
620        self.scratch.extend_from_slice(&bytes);
621        self.command(token, CommandKind::ChangeUser, State::Auth, None)
622    }
623    pub fn local_infile_data(&mut self, data: &[u8]) -> Result<()> {
624        if self.state != State::Infile || data.is_empty() {
625            return Err(Error::State("LOCAL INFILE not active or empty data"));
626        }
627        self.scratch.clear();
628        self.scratch.extend_from_slice(data);
629        self.send()
630    }
631    pub fn local_infile_finish(&mut self) -> Result<()> {
632        if self.state != State::Infile {
633            return Err(Error::State("LOCAL INFILE not active"));
634        }
635        self.scratch.clear();
636        self.send()?;
637        self.state = State::Header;
638        Ok(())
639    }
640    pub fn is_ready(&self) -> bool {
641        self.state == State::Ready && self.pending.is_none()
642    }
643    pub fn status(&self) -> StatusFlags {
644        self.status
645    }
646    pub fn next_timeout(&self) -> Option<Instant> {
647        if matches!(self.state, State::Closing | State::Closed) {
648            None
649        } else if let Some(p) = &self.pending {
650            p.deadline
651        } else if !self.is_ready() {
652            self.config.connect_deadline
653        } else {
654            None
655        }
656    }
657    pub fn handle_timeout(&mut self, now: Instant) {
658        if self.next_timeout().is_some_and(|t| t <= now) {
659            self.abort(Error::Timeout);
660        }
661    }
662    pub fn abort(&mut self, reason: Error) {
663        if matches!(self.state, State::Closed | State::Closing) {
664            return;
665        }
666        self.reason = reason;
667        self.state = State::Closing;
668        self.output.clear();
669        self.output_at = 0;
670        if self.pending.is_some() {
671            self.completion = Some(Outcome::Aborted(reason));
672        }
673    }
674    pub fn quit(&mut self) -> Result<()> {
675        self.accept()?;
676        self.scratch.clear();
677        self.scratch.push(1);
678        self.codec.reset_seq_id();
679        self.send()?;
680        self.state = State::Closing;
681        self.reason = Error::Cancelled;
682        Ok(())
683    }
684    fn token(&self) -> Result<Token> {
685        self.pending
686            .as_ref()
687            .map(|p| p.token)
688            .ok_or(Error::Protocol("unsolicited result"))
689    }
690    fn complete(&mut self, outcome: Outcome) {
691        self.completion = Some(outcome);
692        self.state = State::Ready;
693    }
694    pub fn next_event(&mut self) -> Result<Option<Event<'_>>> {
695        if let Some(outcome) = self.completion.take() {
696            let p = self
697                .pending
698                .take()
699                .ok_or(Error::Protocol("completion without command"))?;
700            return Ok(Some(Event::Completed {
701                token: p.token,
702                outcome,
703            }));
704        }
705        if self.state == State::Closing {
706            if !self.output().is_empty() {
707                return Ok(None);
708            }
709            self.state = State::Closed;
710            return Ok(Some(Event::Closed {
711                reason: self.reason,
712            }));
713        }
714        if matches!(
715            self.state,
716            State::Closed | State::Tls | State::Seed | State::Infile | State::NoResponse
717        ) {
718            return Ok(None);
719        }
720        if self.packet_ready {
721            self.packet.clear();
722            self.packet_ready = false;
723        }
724        if !self
725            .codec
726            .decode(&mut self.input, &mut self.packet)
727            .map_err(|_| Error::Protocol("invalid packet framing or sequence"))?
728        {
729            return Ok(None);
730        }
731        self.packet_ready = true;
732        if self.packet.is_empty() {
733            return Err(Error::Protocol("empty server packet"));
734        }
735        if self.packet[0] == 0xff {
736            let token = self.pending.as_ref().map(|p| p.token);
737            if token.is_some() {
738                self.complete(Outcome::ServerError);
739            } else {
740                self.state = State::Closing;
741            }
742            return Ok(Some(Event::Error {
743                token,
744                error: ServerError::parse(&self.packet)?,
745            }));
746        }
747        match self.state {
748            State::Handshake => {
749                let h = HandshakePacket::deserialize((), &mut ParseBuf(&self.packet))?;
750                if h.protocol_version() != 10 {
751                    return Err(Error::Protocol("unsupported handshake version"));
752                }
753                self.connection_id = h.connection_id();
754                self.server_version = h.server_version_parsed().unwrap_or((8, 0, 0));
755                self.nonce = h
756                    .nonce()
757                    .try_into()
758                    .map_err(|_| Error::Protocol("invalid auth nonce"))?;
759                self.plugin = h
760                    .auth_plugin()
761                    .unwrap_or(AuthPlugin::MysqlNativePassword)
762                    .into_owned();
763                let required = Caps::CLIENT_PROTOCOL_41
764                    | Caps::CLIENT_SECURE_CONNECTION
765                    | Caps::CLIENT_PLUGIN_AUTH;
766                if !h.capabilities().contains(required) {
767                    return Err(Error::Protocol("server lacks required capabilities"));
768                }
769                let mut caps = required
770                    | Caps::CLIENT_LONG_PASSWORD
771                    | Caps::CLIENT_LONG_FLAG
772                    | Caps::CLIENT_TRANSACTIONS
773                    | Caps::CLIENT_MULTI_RESULTS
774                    | Caps::CLIENT_PS_MULTI_RESULTS
775                    | Caps::CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA;
776                if self.config.database.is_some() {
777                    caps |= Caps::CLIENT_CONNECT_WITH_DB;
778                }
779                if self.config.multiple_statements {
780                    caps |= Caps::CLIENT_MULTI_STATEMENTS;
781                }
782                if self.config.local_infile {
783                    caps |= Caps::CLIENT_LOCAL_FILES;
784                }
785                if self.config.compression {
786                    caps |= Caps::CLIENT_COMPRESS;
787                }
788                if self.config.tls {
789                    if !h.capabilities().contains(Caps::CLIENT_SSL) {
790                        return Err(Error::Protocol("Server does not support secure connection"));
791                    }
792                    caps |= Caps::CLIENT_SSL;
793                }
794                self.caps = caps & h.capabilities();
795                if self.config.tls {
796                    if !self.input.is_empty() {
797                        return Err(Error::Protocol("plaintext after TLS handshake offer"));
798                    }
799                    self.scratch.clear();
800                    SslRequest::new(self.caps, self.config.max_buffer as u32, 45)
801                        .serialize(&mut self.scratch);
802                    self.send()?;
803                    self.state = State::Tls;
804                    return Ok(Some(Event::UpgradeTls));
805                }
806                self.handshake_response()?;
807            }
808            State::Auth | State::Key => match self.packet[0] {
809                0 => {
810                    let ok = parse_ok(&self.packet, self.caps)?;
811                    self.status = ok.status_flags();
812                    if self
813                        .pending
814                        .as_ref()
815                        .is_some_and(|p| p.kind == CommandKind::ChangeUser)
816                    {
817                        self.statements.clear();
818                        self.complete(Outcome::Success);
819                    } else {
820                        if self.caps.contains(Caps::CLIENT_COMPRESS) {
821                            self.codec.compress(flate2::Compression::default());
822                        }
823                        self.state = State::Ready;
824                        return Ok(Some(Event::Connected {
825                            connection_id: self.connection_id,
826                        }));
827                    }
828                }
829                0xfe => {
830                    let switch = AuthSwitchRequest::deserialize((), &mut ParseBuf(&self.packet))?;
831                    self.plugin = switch.auth_plugin().into_owned();
832                    self.nonce = switch
833                        .plugin_data()
834                        .try_into()
835                        .map_err(|_| Error::Protocol("invalid auth-switch nonce"))?;
836                    self.scratch.clear();
837                    self.scramble()?;
838                    self.send()?;
839                    self.state = State::Auth;
840                }
841                1 if self.state == State::Key => {
842                    self.state = State::Seed;
843                    return Ok(Some(Event::RsaSeedNeeded));
844                }
845                1 if matches!(self.plugin, AuthPlugin::CachingSha2Password) => {
846                    match self.packet.as_slice() {
847                        [1, 3] => return Ok(Some(Event::AuthFastSuccess)),
848                        [1, 4] => {
849                            self.scratch.clear();
850                            if self.tls {
851                                self.scratch.extend_from_slice(&self.config.password);
852                                self.scratch.push(0);
853                            } else {
854                                self.scratch.push(2);
855                                self.state = State::Key;
856                            }
857                            self.send()?;
858                            return Ok(Some(Event::AuthFull));
859                        }
860                        _ => return Err(Error::Protocol("invalid caching_sha2 challenge")),
861                    }
862                }
863                _ => return Err(Error::Protocol("unexpected authentication packet")),
864            },
865            State::Header => {
866                let token = self.token()?;
867                match self.packet[0] {
868                    0 => {
869                        let ok = parse_ok(&self.packet, self.caps)?;
870                        self.status = ok.status_flags();
871                        if !self
872                            .status
873                            .contains(StatusFlags::SERVER_MORE_RESULTS_EXISTS)
874                        {
875                            if self
876                                .pending
877                                .as_ref()
878                                .is_some_and(|p| p.kind == CommandKind::Reset)
879                            {
880                                self.statements.clear();
881                            }
882                            self.complete(Outcome::Success);
883                        }
884                        return Ok(Some(Event::Ok {
885                            token,
886                            packet: parse_ok(&self.packet, self.caps)?,
887                        }));
888                    }
889                    0xfb => {
890                        if !self.config.local_infile {
891                            self.abort(Error::LocalInfileDisabled);
892                            return Err(Error::LocalInfileDisabled);
893                        }
894                        self.state = State::Infile;
895                        return Ok(Some(Event::LocalInfile {
896                            token,
897                            file_name: &self.packet[1..],
898                        }));
899                    }
900                    _ => {
901                        let mut c = wire::Cursor(&self.packet);
902                        let count = usize::try_from(c.lenenc()?).map_err(|_| Error::Limit)?;
903                        c.end()?;
904                        if count == 0 || count > self.config.max_columns {
905                            return Err(Error::Limit);
906                        }
907                        self.columns.clear();
908                        self.state = State::Columns(count);
909                        return Ok(Some(Event::ColumnCount { token, count }));
910                    }
911                }
912            }
913            State::Columns(left) | State::Parameters(left) | State::PrepareColumns(left) => {
914                let column = Column::parse(&self.packet)?;
915                let parameter = matches!(self.state, State::Parameters(_));
916                match self.state {
917                    State::Columns(_) => {
918                        self.columns.push(column.type_info);
919                        self.state = if left == 1 {
920                            State::ColumnsEnd
921                        } else {
922                            State::Columns(left - 1)
923                        };
924                    }
925                    State::Parameters(_) => {
926                        self.state = if left == 1 {
927                            State::ParametersEnd
928                        } else {
929                            State::Parameters(left - 1)
930                        }
931                    }
932                    _ => {
933                        self.state = if left == 1 {
934                            State::PrepareEnd
935                        } else {
936                            State::PrepareColumns(left - 1)
937                        }
938                    }
939                }
940                return Ok(Some(Event::Column {
941                    token: self.token()?,
942                    column,
943                    parameter,
944                }));
945            }
946            State::ColumnsEnd => {
947                self.status = parse_eof(&self.packet, self.caps)?.status_flags();
948                self.state = State::Rows;
949            }
950            State::Rows => {
951                if self.packet[0] == 0xfe && self.packet.len() < 9 {
952                    let eof = parse_eof(&self.packet, self.caps)?;
953                    let warnings = eof.warnings();
954                    self.status = eof.status_flags();
955                    if self
956                        .status
957                        .contains(StatusFlags::SERVER_MORE_RESULTS_EXISTS)
958                    {
959                        self.state = State::Header;
960                    } else {
961                        self.complete(Outcome::Success);
962                    }
963                    return Ok(Some(Event::Eof {
964                        token: self.token()?,
965                        warnings,
966                        status: self.status,
967                    }));
968                }
969                return Ok(Some(Event::Row {
970                    token: self.token()?,
971                    row: Row::parse(&self.packet, &self.columns, self.binary)?,
972                }));
973            }
974            State::Prepare => {
975                let s = StmtPacket::deserialize((), &mut ParseBuf(&self.packet))?;
976                let stmt = Statement {
977                    id: s.statement_id(),
978                    parameters: s.num_params(),
979                    columns: s.num_columns(),
980                    warnings: s.warning_count(),
981                };
982                if stmt.parameters as usize > self.config.max_columns
983                    || stmt.columns as usize > self.config.max_columns
984                {
985                    return Err(Error::Limit);
986                }
987                self.statement = Some(stmt);
988                if stmt.parameters > 0 {
989                    self.state = State::Parameters(stmt.parameters as usize);
990                } else if stmt.columns > 0 {
991                    self.state = State::PrepareColumns(stmt.columns as usize);
992                } else {
993                    return self.prepared();
994                }
995            }
996            State::ParametersEnd => {
997                parse_eof(&self.packet, self.caps)?;
998                let stmt = self.statement.unwrap();
999                if stmt.columns > 0 {
1000                    self.state = State::PrepareColumns(stmt.columns as usize);
1001                } else {
1002                    return self.prepared();
1003                }
1004            }
1005            State::PrepareEnd => {
1006                parse_eof(&self.packet, self.caps)?;
1007                return self.prepared();
1008            }
1009            _ => return Err(Error::Protocol("unexpected packet in current state")),
1010        }
1011        // A consumed control packet may produce output without an event. The host
1012        // must flush output and continue polling while buffered input remains.
1013        Ok(Some(Event::Progress))
1014    }
1015    fn prepared(&mut self) -> Result<Option<Event<'_>>> {
1016        let statement = self
1017            .statement
1018            .take()
1019            .ok_or(Error::Protocol("missing prepare state"))?;
1020        self.statements.push(statement);
1021        self.complete(Outcome::Success);
1022        Ok(Some(Event::Prepared {
1023            token: self.token()?,
1024            statement,
1025        }))
1026    }
1027}
1028fn parse_ok(b: &[u8], caps: Caps) -> Result<OkPacket<'_>> {
1029    Ok(OkPacketDeserializer::<CommonOkPacket>::deserialize(caps, &mut ParseBuf(b))?.into_inner())
1030}
1031fn parse_eof(b: &[u8], caps: Caps) -> Result<OkPacket<'_>> {
1032    if b.len() != 5 || b[0] != 0xfe {
1033        return Err(Error::Protocol("expected legacy EOF"));
1034    }
1035    Ok(OkPacketDeserializer::<OldEofPacket>::deserialize(caps, &mut ParseBuf(b))?.into_inner())
1036}
1037
1038#[cfg(feature = "turnloop")]
1039pub mod asynchronous;