|
| 1 | +use crate::error::Error; |
| 2 | +use encoding_rs::WINDOWS_1252; |
| 3 | +use sqlx_rt::{timeout, UdpSocket}; |
| 4 | +use std::time::Duration; |
| 5 | + |
| 6 | +const SSRP_PORT: u16 = 1434; |
| 7 | +const CLNT_UCAST_INST: u8 = 0x04; |
| 8 | +const SVR_RESP: u8 = 0x05; |
| 9 | +const SSRP_TIMEOUT: Duration = Duration::from_secs(1); |
| 10 | + |
| 11 | +struct InstanceInfo<'a> { |
| 12 | + server_name: Option<&'a str>, |
| 13 | + instance_name: Option<&'a str>, |
| 14 | + is_clustered: Option<bool>, |
| 15 | + version: Option<&'a str>, |
| 16 | + tcp_port: Option<u16>, |
| 17 | +} |
| 18 | + |
| 19 | +pub(crate) async fn resolve_instance_port(server: &str, instance: &str) -> Result<u16, Error> { |
| 20 | + log::debug!( |
| 21 | + "resolving SQL Server instance port for '{}' on server '{}'", |
| 22 | + instance, |
| 23 | + server |
| 24 | + ); |
| 25 | + |
| 26 | + let mut request = Vec::with_capacity(1 + instance.len() + 1); |
| 27 | + request.push(CLNT_UCAST_INST); |
| 28 | + request.extend_from_slice(instance.as_bytes()); |
| 29 | + request.push(0); |
| 30 | + |
| 31 | + let socket = UdpSocket::bind("0.0.0.0:0") |
| 32 | + .await |
| 33 | + .map_err(|e| err_protocol!("failed to bind UDP socket for SSRP: {}", e))?; |
| 34 | + |
| 35 | + log::debug!( |
| 36 | + "sending SSRP CLNT_UCAST_INST request to {}:{} for instance '{}'", |
| 37 | + server, |
| 38 | + SSRP_PORT, |
| 39 | + instance |
| 40 | + ); |
| 41 | + |
| 42 | + socket |
| 43 | + .send_to(&request, (server, SSRP_PORT)) |
| 44 | + .await |
| 45 | + .map_err(|e| { |
| 46 | + err_protocol!( |
| 47 | + "failed to send SSRP request to {}:{}: {}", |
| 48 | + server, |
| 49 | + SSRP_PORT, |
| 50 | + e |
| 51 | + ) |
| 52 | + })?; |
| 53 | + |
| 54 | + let mut buffer = [0u8; 1024]; |
| 55 | + let bytes_read = timeout(SSRP_TIMEOUT, socket.recv(&mut buffer)) |
| 56 | + .await |
| 57 | + .map_err(|_| { |
| 58 | + err_protocol!( |
| 59 | + "SSRP request to {} for instance {} timed out after {:?}", |
| 60 | + server, |
| 61 | + instance, |
| 62 | + SSRP_TIMEOUT |
| 63 | + ) |
| 64 | + })? |
| 65 | + .map_err(|e| { |
| 66 | + err_protocol!( |
| 67 | + "failed to receive SSRP response from {} for instance {}: {}", |
| 68 | + server, |
| 69 | + instance, |
| 70 | + e |
| 71 | + ) |
| 72 | + })?; |
| 73 | + |
| 74 | + log::debug!( |
| 75 | + "received SSRP response from {} ({} bytes)", |
| 76 | + server, |
| 77 | + bytes_read |
| 78 | + ); |
| 79 | + |
| 80 | + if bytes_read < 3 { |
| 81 | + return Err(err_protocol!( |
| 82 | + "SSRP response too short: {} bytes", |
| 83 | + bytes_read |
| 84 | + )); |
| 85 | + } |
| 86 | + |
| 87 | + if buffer[0] != SVR_RESP { |
| 88 | + return Err(err_protocol!( |
| 89 | + "invalid SSRP response type: expected 0x05, got 0x{:02x}", |
| 90 | + buffer[0] |
| 91 | + )); |
| 92 | + } |
| 93 | + |
| 94 | + let response_size = u16::from_le_bytes([buffer[1], buffer[2]]) as usize; |
| 95 | + if response_size + 3 > bytes_read { |
| 96 | + return Err(err_protocol!( |
| 97 | + "SSRP response size mismatch: expected {} bytes, got {}", |
| 98 | + response_size + 3, |
| 99 | + bytes_read |
| 100 | + )); |
| 101 | + } |
| 102 | + |
| 103 | + let response_bytes = &buffer[3..(3 + response_size)]; |
| 104 | + let (response_str, _encoding_used, had_errors) = WINDOWS_1252.decode(response_bytes); |
| 105 | + |
| 106 | + if had_errors { |
| 107 | + log::debug!("SSRP response had MBCS decoding errors, continuing anyway"); |
| 108 | + } |
| 109 | + |
| 110 | + log::debug!("SSRP response data: {}", response_str); |
| 111 | + |
| 112 | + find_instance_tcp_port(&response_str, instance) |
| 113 | +} |
| 114 | + |
| 115 | +fn find_instance_tcp_port(data: &str, instance_name: &str) -> Result<u16, Error> { |
| 116 | + for instance_data in data.split(";;") { |
| 117 | + if instance_data.is_empty() { |
| 118 | + continue; |
| 119 | + } |
| 120 | + |
| 121 | + let info = parse_instance_info(instance_data); |
| 122 | + |
| 123 | + if let Some(name) = info.instance_name { |
| 124 | + log::debug!("found instance '{}' in SSRP response", name); |
| 125 | + |
| 126 | + if name.eq_ignore_ascii_case(instance_name) { |
| 127 | + log::debug!( |
| 128 | + "instance '{}' matches requested instance '{}'", |
| 129 | + name, |
| 130 | + instance_name |
| 131 | + ); |
| 132 | + |
| 133 | + if let Some(port) = info.tcp_port { |
| 134 | + log::debug!("resolved instance '{}' to port {}", instance_name, port); |
| 135 | + return Ok(port); |
| 136 | + } else { |
| 137 | + return Err(err_protocol!( |
| 138 | + "instance '{}' found but no TCP port available", |
| 139 | + instance_name |
| 140 | + )); |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + Err(err_protocol!( |
| 147 | + "instance '{}' not found in SSRP response", |
| 148 | + instance_name |
| 149 | + )) |
| 150 | +} |
| 151 | + |
| 152 | +fn parse_instance_info<'a>(data: &'a str) -> InstanceInfo<'a> { |
| 153 | + let mut info = InstanceInfo { |
| 154 | + server_name: None, |
| 155 | + instance_name: None, |
| 156 | + is_clustered: None, |
| 157 | + version: None, |
| 158 | + tcp_port: None, |
| 159 | + }; |
| 160 | + |
| 161 | + let mut tokens = data.split(';'); |
| 162 | + while let Some(key) = tokens.next() { |
| 163 | + let value = tokens.next(); |
| 164 | + |
| 165 | + match key { |
| 166 | + "ServerName" => info.server_name = value, |
| 167 | + "InstanceName" => info.instance_name = value, |
| 168 | + "IsClustered" => { |
| 169 | + info.is_clustered = value.and_then(|v| match v { |
| 170 | + "Yes" => Some(true), |
| 171 | + "No" => Some(false), |
| 172 | + _ => None, |
| 173 | + }); |
| 174 | + } |
| 175 | + "Version" => info.version = value, |
| 176 | + "tcp" => { |
| 177 | + info.tcp_port = value.and_then(|v| v.parse::<u16>().ok()); |
| 178 | + } |
| 179 | + _ => { |
| 180 | + if !key.is_empty() { |
| 181 | + log::debug!("ignoring unknown SSRP key: '{}'", key); |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + info |
| 188 | +} |
| 189 | + |
| 190 | +#[cfg(test)] |
| 191 | +mod tests { |
| 192 | + use super::*; |
| 193 | + |
| 194 | + #[test] |
| 195 | + fn test_find_instance_tcp_port_single_instance() { |
| 196 | + let data = "ServerName;MYSERVER;InstanceName;SQLEXPRESS;IsClustered;No;Version;15.0.2000.5;tcp;1433;;"; |
| 197 | + let port = find_instance_tcp_port(data, "SQLEXPRESS").unwrap(); |
| 198 | + assert_eq!(port, 1433); |
| 199 | + } |
| 200 | + |
| 201 | + #[test] |
| 202 | + fn test_find_instance_tcp_port_multiple_instances() { |
| 203 | + let data = "ServerName;SRV1;InstanceName;INST1;IsClustered;No;Version;15.0.2000.5;tcp;1433;;ServerName;SRV1;InstanceName;INST2;IsClustered;No;Version;16.0.1000.6;tcp;1434;np;\\\\SRV1\\pipe\\MSSQL$INST2\\sql\\query;;"; |
| 204 | + let port = find_instance_tcp_port(data, "INST2").unwrap(); |
| 205 | + assert_eq!(port, 1434); |
| 206 | + } |
| 207 | + |
| 208 | + #[test] |
| 209 | + fn test_find_instance_tcp_port_case_insensitive() { |
| 210 | + let data = "ServerName;MYSERVER;InstanceName;SQLExpress;IsClustered;No;Version;15.0.2000.5;tcp;1433;;"; |
| 211 | + let port = find_instance_tcp_port(data, "sqlexpress").unwrap(); |
| 212 | + assert_eq!(port, 1433); |
| 213 | + } |
| 214 | + |
| 215 | + #[test] |
| 216 | + fn test_find_instance_tcp_port_instance_not_found() { |
| 217 | + let data = "ServerName;MYSERVER;InstanceName;SQLEXPRESS;IsClustered;No;Version;15.0.2000.5;tcp;1433;;"; |
| 218 | + let result = find_instance_tcp_port(data, "NOTFOUND"); |
| 219 | + assert!(result.is_err()); |
| 220 | + } |
| 221 | + |
| 222 | + #[test] |
| 223 | + fn test_find_instance_tcp_port_no_tcp_port() { |
| 224 | + let data = |
| 225 | + "ServerName;MYSERVER;InstanceName;SQLEXPRESS;IsClustered;No;Version;15.0.2000.5;;"; |
| 226 | + let result = find_instance_tcp_port(data, "SQLEXPRESS"); |
| 227 | + assert!(result.is_err()); |
| 228 | + } |
| 229 | +} |
0 commit comments