|
| 1 | +// Original implementation from tiberius: https://github.com/prisma/tiberius/blob/main/src/client/tls.rs |
| 2 | + |
| 3 | +use crate::mssql::protocol::packet::{PacketHeader, PacketType}; |
| 4 | + |
| 5 | +use super::stream::write_packets; |
| 6 | + |
| 7 | +use crate::io::Decode; |
| 8 | +use bytes::Bytes; |
| 9 | +use sqlx_rt::{AsyncRead, AsyncWrite, ReadBuf}; |
| 10 | +use std::cmp; |
| 11 | +use std::io; |
| 12 | +use std::pin::Pin; |
| 13 | +use std::task::{self, ready, Poll}; |
| 14 | + |
| 15 | +/// This wrapper handles TDS (Tabular Data Stream) packet encapsulation during the TLS handshake phase |
| 16 | +/// of a connection to a Microsoft SQL Server. |
| 17 | +/// |
| 18 | +/// In the PRELOGIN phase of the TDS protocol, all communication must be wrapped in TDS packets, |
| 19 | +/// even during TLS negotiation. This presents a challenge when using standard TLS libraries, |
| 20 | +/// which expect to work with raw TCP streams. |
| 21 | +/// |
| 22 | +/// This wrapper solves the problem by: |
| 23 | +/// 1. During handshake: |
| 24 | +/// - For writes: It buffers outgoing data and wraps it in TDS packets before sending. |
| 25 | +/// Each packet starts with an 8-byte header containing type (0x12 for PRELOGIN), |
| 26 | +/// status flags, length, and other metadata. |
| 27 | +/// - For reads: It strips the TDS packet headers from incoming data before passing |
| 28 | +/// it to the TLS library. |
| 29 | +/// 2. After handshake: |
| 30 | +/// - It becomes transparent, directly passing through all reads and writes to the |
| 31 | +/// underlying stream without modification. |
| 32 | +/// |
| 33 | +/// This allows us to use standard TLS libraries while still conforming to the TDS protocol |
| 34 | +/// requirements for the PRELOGIN phase. |
| 35 | +
|
| 36 | +const HEADER_BYTES: usize = 8; |
| 37 | + |
| 38 | +pub(crate) struct TlsPreloginWrapper<S> { |
| 39 | + stream: S, |
| 40 | + pending_handshake: bool, |
| 41 | + |
| 42 | + header_buf: [u8; HEADER_BYTES], |
| 43 | + header_pos: usize, |
| 44 | + read_remaining: usize, |
| 45 | + |
| 46 | + wr_buf: Vec<u8>, |
| 47 | + header_written: bool, |
| 48 | +} |
| 49 | + |
| 50 | +impl<S> TlsPreloginWrapper<S> { |
| 51 | + pub fn new(stream: S) -> Self { |
| 52 | + TlsPreloginWrapper { |
| 53 | + stream, |
| 54 | + pending_handshake: false, |
| 55 | + |
| 56 | + header_buf: [0u8; HEADER_BYTES], |
| 57 | + header_pos: 0, |
| 58 | + read_remaining: 0, |
| 59 | + wr_buf: Vec::new(), |
| 60 | + header_written: false, |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + pub fn start_handshake(&mut self) { |
| 65 | + self.pending_handshake = true; |
| 66 | + } |
| 67 | + |
| 68 | + pub fn handshake_complete(&mut self) { |
| 69 | + self.pending_handshake = false; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncRead for TlsPreloginWrapper<S> { |
| 74 | + fn poll_read( |
| 75 | + mut self: Pin<&mut Self>, |
| 76 | + cx: &mut task::Context<'_>, |
| 77 | + buf: &mut ReadBuf<'_>, |
| 78 | + ) -> Poll<io::Result<()>> { |
| 79 | + if !self.pending_handshake { |
| 80 | + return Pin::new(&mut self.stream).poll_read(cx, buf); |
| 81 | + } |
| 82 | + |
| 83 | + let inner = self.get_mut(); |
| 84 | + |
| 85 | + if !inner.header_buf[inner.header_pos..].is_empty() { |
| 86 | + while !inner.header_buf[inner.header_pos..].is_empty() { |
| 87 | + let mut header_buf = ReadBuf::new(&mut inner.header_buf[inner.header_pos..]); |
| 88 | + ready!(Pin::new(&mut inner.stream).poll_read(cx, &mut header_buf))?; |
| 89 | + |
| 90 | + let read = header_buf.filled().len(); |
| 91 | + if read == 0 { |
| 92 | + return Poll::Ready(Ok(())); |
| 93 | + } |
| 94 | + |
| 95 | + inner.header_pos += read; |
| 96 | + } |
| 97 | + |
| 98 | + let header: PacketHeader = Decode::decode(Bytes::copy_from_slice(&inner.header_buf)) |
| 99 | + .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; |
| 100 | + |
| 101 | + inner.read_remaining = usize::from(header.length) - HEADER_BYTES; |
| 102 | + |
| 103 | + log::trace!( |
| 104 | + "Discarding header ({:?}), reading packet of {} bytes", |
| 105 | + header, |
| 106 | + inner.read_remaining, |
| 107 | + ); |
| 108 | + } |
| 109 | + |
| 110 | + let max_read = std::cmp::min(inner.read_remaining, buf.remaining()); |
| 111 | + let mut limited_buf = buf.take(max_read); |
| 112 | + |
| 113 | + ready!(Pin::new(&mut inner.stream).poll_read(cx, &mut limited_buf))?; |
| 114 | + |
| 115 | + let read = limited_buf.filled().len(); |
| 116 | + buf.advance(read); |
| 117 | + inner.read_remaining -= read; |
| 118 | + |
| 119 | + if inner.read_remaining == 0 { |
| 120 | + inner.header_pos = 0; |
| 121 | + } |
| 122 | + |
| 123 | + Poll::Ready(Ok(())) |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl<S: AsyncRead + AsyncWrite + Unpin + Send> AsyncWrite for TlsPreloginWrapper<S> { |
| 128 | + fn poll_write( |
| 129 | + mut self: Pin<&mut Self>, |
| 130 | + cx: &mut task::Context<'_>, |
| 131 | + buf: &[u8], |
| 132 | + ) -> Poll<io::Result<usize>> { |
| 133 | + // Normal operation does not need any extra treatment, we handle |
| 134 | + // packets in the codec. |
| 135 | + if !self.pending_handshake { |
| 136 | + return Pin::new(&mut self.stream).poll_write(cx, buf); |
| 137 | + } |
| 138 | + |
| 139 | + // Buffering data. |
| 140 | + self.wr_buf.extend_from_slice(buf); |
| 141 | + |
| 142 | + Poll::Ready(Ok(buf.len())) |
| 143 | + } |
| 144 | + |
| 145 | + fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { |
| 146 | + let inner = self.get_mut(); |
| 147 | + |
| 148 | + // If on handshake mode, wraps the data to a TDS packet before sending. |
| 149 | + if inner.pending_handshake { |
| 150 | + if !inner.header_written { |
| 151 | + let buf = std::mem::take(&mut inner.wr_buf); |
| 152 | + write_packets( |
| 153 | + &mut inner.wr_buf, |
| 154 | + 4096, |
| 155 | + PacketType::PreLogin, |
| 156 | + buf.as_slice(), |
| 157 | + ); |
| 158 | + inner.header_written = true; |
| 159 | + } |
| 160 | + |
| 161 | + while !inner.wr_buf.is_empty() { |
| 162 | + let written = ready!(Pin::new(&mut inner.stream).poll_write(cx, &inner.wr_buf))?; |
| 163 | + |
| 164 | + inner.wr_buf.drain(..written); |
| 165 | + } |
| 166 | + |
| 167 | + inner.header_written = false; |
| 168 | + } |
| 169 | + |
| 170 | + Pin::new(&mut inner.stream).poll_flush(cx) |
| 171 | + } |
| 172 | + |
| 173 | + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { |
| 174 | + Pin::new(&mut self.stream).poll_shutdown(cx) |
| 175 | + } |
| 176 | +} |
0 commit comments