use std::collections::VecDeque;
use std::fmt;
use std::io::{self, Write};
use std::net::{self, SocketAddr, TcpStream, ToSocketAddrs};
use std::ops::DerefMut;
use std::path::PathBuf;
use std::str::{from_utf8, FromStr};
use std::time::Duration;
use crate::cmd::{cmd, pipe, Cmd};
use crate::parser::Parser;
use crate::pipeline::Pipeline;
use crate::types::{
from_owned_redis_value, from_redis_value, ErrorKind, FromRedisValue, RedisError, RedisResult,
ToRedisArgs, Value,
};
#[cfg(unix)]
use crate::types::HashMap;
#[cfg(unix)]
use std::os::unix::net::UnixStream;
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
use native_tls::{TlsConnector, TlsStream};
#[cfg(feature = "tls-rustls")]
use rustls::{RootCertStore, StreamOwned};
#[cfg(feature = "tls-rustls")]
use std::sync::Arc;
#[cfg(all(
feature = "tls-rustls",
not(feature = "tls-native-tls"),
not(feature = "tls-rustls-webpki-roots")
))]
use rustls_native_certs::load_native_certs;
#[cfg(feature = "tls-rustls")]
use crate::tls::TlsConnParams;
#[cfg(not(feature = "tls-rustls"))]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct TlsConnParams;
static DEFAULT_PORT: u16 = 6379;
#[inline(always)]
fn connect_tcp(addr: (&str, u16)) -> io::Result<TcpStream> {
let socket = TcpStream::connect(addr)?;
#[cfg(feature = "tcp_nodelay")]
socket.set_nodelay(true)?;
#[cfg(feature = "keep-alive")]
{
const KEEP_ALIVE: socket2::TcpKeepalive = socket2::TcpKeepalive::new();
let socket2: socket2::Socket = socket.into();
socket2.set_tcp_keepalive(&KEEP_ALIVE)?;
Ok(socket2.into())
}
#[cfg(not(feature = "keep-alive"))]
{
Ok(socket)
}
}
#[inline(always)]
fn connect_tcp_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
let socket = TcpStream::connect_timeout(addr, timeout)?;
#[cfg(feature = "tcp_nodelay")]
socket.set_nodelay(true)?;
#[cfg(feature = "keep-alive")]
{
const KEEP_ALIVE: socket2::TcpKeepalive = socket2::TcpKeepalive::new();
let socket2: socket2::Socket = socket.into();
socket2.set_tcp_keepalive(&KEEP_ALIVE)?;
Ok(socket2.into())
}
#[cfg(not(feature = "keep-alive"))]
{
Ok(socket)
}
}
pub fn parse_redis_url(input: &str) -> Option<url::Url> {
match url::Url::parse(input) {
Ok(result) => match result.scheme() {
"redis" | "rediss" | "redis+unix" | "unix" => Some(result),
_ => None,
},
Err(_) => None,
}
}
#[derive(Clone, Copy)]
pub enum TlsMode {
Secure,
Insecure,
}
#[derive(Clone, Debug)]
pub enum ConnectionAddr {
Tcp(String, u16),
TcpTls {
host: String,
port: u16,
insecure: bool,
tls_params: Option<TlsConnParams>,
},
Unix(PathBuf),
}
impl PartialEq for ConnectionAddr {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(ConnectionAddr::Tcp(host1, port1), ConnectionAddr::Tcp(host2, port2)) => {
host1 == host2 && port1 == port2
}
(
ConnectionAddr::TcpTls {
host: host1,
port: port1,
insecure: insecure1,
tls_params: _,
},
ConnectionAddr::TcpTls {
host: host2,
port: port2,
insecure: insecure2,
tls_params: _,
},
) => port1 == port2 && host1 == host2 && insecure1 == insecure2,
(ConnectionAddr::Unix(path1), ConnectionAddr::Unix(path2)) => path1 == path2,
_ => false,
}
}
}
impl Eq for ConnectionAddr {}
impl ConnectionAddr {
pub fn is_supported(&self) -> bool {
match *self {
ConnectionAddr::Tcp(_, _) => true,
ConnectionAddr::TcpTls { .. } => {
cfg!(any(feature = "tls-native-tls", feature = "tls-rustls"))
}
ConnectionAddr::Unix(_) => cfg!(unix),
}
}
}
impl fmt::Display for ConnectionAddr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ConnectionAddr::Tcp(ref host, port) => write!(f, "{host}:{port}"),
ConnectionAddr::TcpTls { ref host, port, .. } => write!(f, "{host}:{port}"),
ConnectionAddr::Unix(ref path) => write!(f, "{}", path.display()),
}
}
}
#[derive(Clone, Debug)]
pub struct ConnectionInfo {
pub addr: ConnectionAddr,
pub redis: RedisConnectionInfo,
}
#[derive(Clone, Debug, Default)]
pub struct RedisConnectionInfo {
pub db: i64,
pub username: Option<String>,
pub password: Option<String>,
}
impl FromStr for ConnectionInfo {
type Err = RedisError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.into_connection_info()
}
}
pub trait IntoConnectionInfo {
fn into_connection_info(self) -> RedisResult<ConnectionInfo>;
}
impl IntoConnectionInfo for ConnectionInfo {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
Ok(self)
}
}
impl<'a> IntoConnectionInfo for &'a str {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
match parse_redis_url(self) {
Some(u) => u.into_connection_info(),
None => fail!((ErrorKind::InvalidClientConfig, "Redis URL did not parse")),
}
}
}
impl<T> IntoConnectionInfo for (T, u16)
where
T: Into<String>,
{
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
Ok(ConnectionInfo {
addr: ConnectionAddr::Tcp(self.0.into(), self.1),
redis: RedisConnectionInfo::default(),
})
}
}
impl IntoConnectionInfo for String {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
match parse_redis_url(&self) {
Some(u) => u.into_connection_info(),
None => fail!((ErrorKind::InvalidClientConfig, "Redis URL did not parse")),
}
}
}
fn url_to_tcp_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
let host = match url.host() {
Some(host) => {
match host {
url::Host::Domain(path) => path.to_string(),
url::Host::Ipv4(v4) => v4.to_string(),
url::Host::Ipv6(v6) => v6.to_string(),
}
}
None => fail!((ErrorKind::InvalidClientConfig, "Missing hostname")),
};
let port = url.port().unwrap_or(DEFAULT_PORT);
let addr = if url.scheme() == "rediss" {
#[cfg(any(feature = "tls-native-tls", feature = "tls-rustls"))]
{
match url.fragment() {
Some("insecure") => ConnectionAddr::TcpTls {
host,
port,
insecure: true,
tls_params: None,
},
Some(_) => fail!((
ErrorKind::InvalidClientConfig,
"only #insecure is supported as URL fragment"
)),
_ => ConnectionAddr::TcpTls {
host,
port,
insecure: false,
tls_params: None,
},
}
}
#[cfg(not(any(feature = "tls-native-tls", feature = "tls-rustls")))]
fail!((
ErrorKind::InvalidClientConfig,
"can't connect with TLS, the feature is not enabled"
));
} else {
ConnectionAddr::Tcp(host, port)
};
Ok(ConnectionInfo {
addr,
redis: RedisConnectionInfo {
db: match url.path().trim_matches('/') {
"" => 0,
path => path.parse::<i64>().map_err(|_| -> RedisError {
(ErrorKind::InvalidClientConfig, "Invalid database number").into()
})?,
},
username: if url.username().is_empty() {
None
} else {
match percent_encoding::percent_decode(url.username().as_bytes()).decode_utf8() {
Ok(decoded) => Some(decoded.into_owned()),
Err(_) => fail!((
ErrorKind::InvalidClientConfig,
"Username is not valid UTF-8 string"
)),
}
},
password: match url.password() {
Some(pw) => match percent_encoding::percent_decode(pw.as_bytes()).decode_utf8() {
Ok(decoded) => Some(decoded.into_owned()),
Err(_) => fail!((
ErrorKind::InvalidClientConfig,
"Password is not valid UTF-8 string"
)),
},
None => None,
},
},
})
}
#[cfg(unix)]
fn url_to_unix_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
let query: HashMap<_, _> = url.query_pairs().collect();
Ok(ConnectionInfo {
addr: ConnectionAddr::Unix(url.to_file_path().map_err(|_| -> RedisError {
(ErrorKind::InvalidClientConfig, "Missing path").into()
})?),
redis: RedisConnectionInfo {
db: match query.get("db") {
Some(db) => db.parse::<i64>().map_err(|_| -> RedisError {
(ErrorKind::InvalidClientConfig, "Invalid database number").into()
})?,
None => 0,
},
username: query.get("user").map(|username| username.to_string()),
password: query.get("pass").map(|password| password.to_string()),
},
})
}
#[cfg(not(unix))]
fn url_to_unix_connection_info(_: url::Url) -> RedisResult<ConnectionInfo> {
fail!((
ErrorKind::InvalidClientConfig,
"Unix sockets are not available on this platform."
));
}
impl IntoConnectionInfo for url::Url {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
match self.scheme() {
"redis" | "rediss" => url_to_tcp_connection_info(self),
"unix" | "redis+unix" => url_to_unix_connection_info(self),
_ => fail!((
ErrorKind::InvalidClientConfig,
"URL provided is not a redis URL"
)),
}
}
}
struct TcpConnection {
reader: TcpStream,
open: bool,
}
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
struct TcpNativeTlsConnection {
reader: TlsStream<TcpStream>,
open: bool,
}
#[cfg(feature = "tls-rustls")]
struct TcpRustlsConnection {
reader: StreamOwned<rustls::ClientConnection, TcpStream>,
open: bool,
}
#[cfg(unix)]
struct UnixConnection {
sock: UnixStream,
open: bool,
}
enum ActualConnection {
Tcp(TcpConnection),
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
TcpNativeTls(Box<TcpNativeTlsConnection>),
#[cfg(feature = "tls-rustls")]
TcpRustls(Box<TcpRustlsConnection>),
#[cfg(unix)]
Unix(UnixConnection),
}
#[cfg(feature = "tls-rustls-insecure")]
struct NoCertificateVerification {
supported: rustls::crypto::WebPkiSupportedAlgorithms,
}
#[cfg(feature = "tls-rustls-insecure")]
impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
fn verify_server_cert(
&self,
_end_entity: &rustls_pki_types::CertificateDer<'_>,
_intermediates: &[rustls_pki_types::CertificateDer<'_>],
_server_name: &rustls_pki_types::ServerName<'_>,
_ocsp_response: &[u8],
_now: rustls_pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.supported.supported_schemes()
}
}
#[cfg(feature = "tls-rustls-insecure")]
impl fmt::Debug for NoCertificateVerification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NoCertificateVerification").finish()
}
}
pub struct Connection {
con: ActualConnection,
parser: Parser,
db: i64,
pubsub: bool,
}
pub struct PubSub<'a> {
con: &'a mut Connection,
waiting_messages: VecDeque<Msg>,
}
#[derive(Debug)]
pub struct Msg {
payload: Value,
channel: Value,
pattern: Option<Value>,
}
impl ActualConnection {
pub fn new(addr: &ConnectionAddr, timeout: Option<Duration>) -> RedisResult<ActualConnection> {
Ok(match *addr {
ConnectionAddr::Tcp(ref host, ref port) => {
let addr = (host.as_str(), *port);
let tcp = match timeout {
None => connect_tcp(addr)?,
Some(timeout) => {
let mut tcp = None;
let mut last_error = None;
for addr in addr.to_socket_addrs()? {
match connect_tcp_timeout(&addr, timeout) {
Ok(l) => {
tcp = Some(l);
break;
}
Err(e) => {
last_error = Some(e);
}
};
}
match (tcp, last_error) {
(Some(tcp), _) => tcp,
(None, Some(e)) => {
fail!(e);
}
(None, None) => {
fail!((
ErrorKind::InvalidClientConfig,
"could not resolve to any addresses"
));
}
}
}
};
ActualConnection::Tcp(TcpConnection {
reader: tcp,
open: true,
})
}
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
ConnectionAddr::TcpTls {
ref host,
port,
insecure,
..
} => {
let tls_connector = if insecure {
TlsConnector::builder()
.danger_accept_invalid_certs(true)
.danger_accept_invalid_hostnames(true)
.use_sni(false)
.build()?
} else {
TlsConnector::new()?
};
let addr = (host.as_str(), port);
let tls = match timeout {
None => {
let tcp = connect_tcp(addr)?;
match tls_connector.connect(host, tcp) {
Ok(res) => res,
Err(e) => {
fail!((ErrorKind::IoError, "SSL Handshake error", e.to_string()));
}
}
}
Some(timeout) => {
let mut tcp = None;
let mut last_error = None;
for addr in (host.as_str(), port).to_socket_addrs()? {
match connect_tcp_timeout(&addr, timeout) {
Ok(l) => {
tcp = Some(l);
break;
}
Err(e) => {
last_error = Some(e);
}
};
}
match (tcp, last_error) {
(Some(tcp), _) => tls_connector.connect(host, tcp).unwrap(),
(None, Some(e)) => {
fail!(e);
}
(None, None) => {
fail!((
ErrorKind::InvalidClientConfig,
"could not resolve to any addresses"
));
}
}
}
};
ActualConnection::TcpNativeTls(Box::new(TcpNativeTlsConnection {
reader: tls,
open: true,
}))
}
#[cfg(feature = "tls-rustls")]
ConnectionAddr::TcpTls {
ref host,
port,
insecure,
ref tls_params,
} => {
let host: &str = host;
let config = create_rustls_config(insecure, tls_params.clone())?;
let conn = rustls::ClientConnection::new(
Arc::new(config),
rustls_pki_types::ServerName::try_from(host)?.to_owned(),
)?;
let reader = match timeout {
None => {
let tcp = connect_tcp((host, port))?;
StreamOwned::new(conn, tcp)
}
Some(timeout) => {
let mut tcp = None;
let mut last_error = None;
for addr in (host, port).to_socket_addrs()? {
match connect_tcp_timeout(&addr, timeout) {
Ok(l) => {
tcp = Some(l);
break;
}
Err(e) => {
last_error = Some(e);
}
};
}
match (tcp, last_error) {
(Some(tcp), _) => StreamOwned::new(conn, tcp),
(None, Some(e)) => {
fail!(e);
}
(None, None) => {
fail!((
ErrorKind::InvalidClientConfig,
"could not resolve to any addresses"
));
}
}
}
};
ActualConnection::TcpRustls(Box::new(TcpRustlsConnection { reader, open: true }))
}
#[cfg(not(any(feature = "tls-native-tls", feature = "tls-rustls")))]
ConnectionAddr::TcpTls { .. } => {
fail!((
ErrorKind::InvalidClientConfig,
"Cannot connect to TCP with TLS without the tls feature"
));
}
#[cfg(unix)]
ConnectionAddr::Unix(ref path) => ActualConnection::Unix(UnixConnection {
sock: UnixStream::connect(path)?,
open: true,
}),
#[cfg(not(unix))]
ConnectionAddr::Unix(ref _path) => {
fail!((
ErrorKind::InvalidClientConfig,
"Cannot connect to unix sockets \
on this platform"
));
}
})
}
pub fn send_bytes(&mut self, bytes: &[u8]) -> RedisResult<Value> {
match *self {
ActualConnection::Tcp(ref mut connection) => {
let res = connection.reader.write_all(bytes).map_err(RedisError::from);
match res {
Err(e) => {
if e.is_unrecoverable_error() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
ActualConnection::TcpNativeTls(ref mut connection) => {
let res = connection.reader.write_all(bytes).map_err(RedisError::from);
match res {
Err(e) => {
if e.is_unrecoverable_error() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
#[cfg(feature = "tls-rustls")]
ActualConnection::TcpRustls(ref mut connection) => {
let res = connection.reader.write_all(bytes).map_err(RedisError::from);
match res {
Err(e) => {
if e.is_unrecoverable_error() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let result = connection.sock.write_all(bytes).map_err(RedisError::from);
match result {
Err(e) => {
if e.is_unrecoverable_error() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
}
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader, .. }) => {
reader.set_write_timeout(dur)?;
}
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
ActualConnection::TcpNativeTls(ref boxed_tls_connection) => {
let reader = &(boxed_tls_connection.reader);
reader.get_ref().set_write_timeout(dur)?;
}
#[cfg(feature = "tls-rustls")]
ActualConnection::TcpRustls(ref boxed_tls_connection) => {
let reader = &(boxed_tls_connection.reader);
reader.get_ref().set_write_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock, .. }) => {
sock.set_write_timeout(dur)?;
}
}
Ok(())
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader, .. }) => {
reader.set_read_timeout(dur)?;
}
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
ActualConnection::TcpNativeTls(ref boxed_tls_connection) => {
let reader = &(boxed_tls_connection.reader);
reader.get_ref().set_read_timeout(dur)?;
}
#[cfg(feature = "tls-rustls")]
ActualConnection::TcpRustls(ref boxed_tls_connection) => {
let reader = &(boxed_tls_connection.reader);
reader.get_ref().set_read_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock, .. }) => {
sock.set_read_timeout(dur)?;
}
}
Ok(())
}
pub fn is_open(&self) -> bool {
match *self {
ActualConnection::Tcp(TcpConnection { open, .. }) => open,
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
ActualConnection::TcpNativeTls(ref boxed_tls_connection) => boxed_tls_connection.open,
#[cfg(feature = "tls-rustls")]
ActualConnection::TcpRustls(ref boxed_tls_connection) => boxed_tls_connection.open,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { open, .. }) => open,
}
}
}
#[cfg(feature = "tls-rustls")]
pub(crate) fn create_rustls_config(
insecure: bool,
tls_params: Option<TlsConnParams>,
) -> RedisResult<rustls::ClientConfig> {
use crate::tls::ClientTlsParams;
#[allow(unused_mut)]
let mut root_store = RootCertStore::empty();
#[cfg(feature = "tls-rustls-webpki-roots")]
root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
#[cfg(all(
feature = "tls-rustls",
not(feature = "tls-native-tls"),
not(feature = "tls-rustls-webpki-roots")
))]
for cert in load_native_certs()? {
root_store.add(cert)?;
}
let config = rustls::ClientConfig::builder();
let config = if let Some(tls_params) = tls_params {
let config_builder =
config.with_root_certificates(tls_params.root_cert_store.unwrap_or(root_store));
if let Some(ClientTlsParams {
client_cert_chain: client_cert,
client_key,
}) = tls_params.client_tls_params
{
config_builder
.with_client_auth_cert(client_cert, client_key)
.map_err(|err| {
RedisError::from((
ErrorKind::InvalidClientConfig,
"Unable to build client with TLS parameters provided.",
err.to_string(),
))
})?
} else {
config_builder.with_no_client_auth()
}
} else {
config
.with_root_certificates(root_store)
.with_no_client_auth()
};
match (insecure, cfg!(feature = "tls-rustls-insecure")) {
#[cfg(feature = "tls-rustls-insecure")]
(true, true) => {
let mut config = config;
config.enable_sni = false;
config
.dangerous()
.set_certificate_verifier(Arc::new(NoCertificateVerification {
supported: rustls::crypto::ring::default_provider()
.signature_verification_algorithms,
}));
Ok(config)
}
(true, false) => {
fail!((
ErrorKind::InvalidClientConfig,
"Cannot create insecure client without tls-rustls-insecure feature"
));
}
_ => Ok(config),
}
}
fn connect_auth(con: &mut Connection, connection_info: &RedisConnectionInfo) -> RedisResult<()> {
let mut command = cmd("AUTH");
if let Some(username) = &connection_info.username {
command.arg(username);
}
let password = connection_info.password.as_ref().unwrap();
let err = match command.arg(password).query::<Value>(con) {
Ok(Value::Okay) => return Ok(()),
Ok(_) => {
fail!((
ErrorKind::ResponseError,
"Redis server refused to authenticate, returns Ok() != Value::Okay"
));
}
Err(e) => e,
};
let err_msg = err.detail().ok_or((
ErrorKind::AuthenticationFailed,
"Password authentication failed",
))?;
if !err_msg.contains("wrong number of arguments for 'auth' command") {
fail!((
ErrorKind::AuthenticationFailed,
"Password authentication failed",
));
}
let mut command = cmd("AUTH");
match command.arg(password).query::<Value>(con) {
Ok(Value::Okay) => Ok(()),
_ => fail!((
ErrorKind::AuthenticationFailed,
"Password authentication failed",
)),
}
}
pub fn connect(
connection_info: &ConnectionInfo,
timeout: Option<Duration>,
) -> RedisResult<Connection> {
let con = ActualConnection::new(&connection_info.addr, timeout)?;
setup_connection(con, &connection_info.redis)
}
#[cfg(not(feature = "disable-client-setinfo"))]
pub(crate) fn client_set_info_pipeline() -> Pipeline {
let mut pipeline = crate::pipe();
pipeline
.cmd("CLIENT")
.arg("SETINFO")
.arg("LIB-NAME")
.arg("redis-rs")
.ignore();
pipeline
.cmd("CLIENT")
.arg("SETINFO")
.arg("LIB-VER")
.arg(env!("CARGO_PKG_VERSION"))
.ignore();
pipeline
}
fn setup_connection(
con: ActualConnection,
connection_info: &RedisConnectionInfo,
) -> RedisResult<Connection> {
let mut rv = Connection {
con,
parser: Parser::new(),
db: connection_info.db,
pubsub: false,
};
if connection_info.password.is_some() {
connect_auth(&mut rv, connection_info)?;
}
if connection_info.db != 0 {
match cmd("SELECT")
.arg(connection_info.db)
.query::<Value>(&mut rv)
{
Ok(Value::Okay) => {}
_ => fail!((
ErrorKind::ResponseError,
"Redis server refused to switch database"
)),
}
}
#[cfg(not(feature = "disable-client-setinfo"))]
let _: RedisResult<()> = client_set_info_pipeline().query(&mut rv);
Ok(rv)
}
pub trait ConnectionLike {
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value>;
#[doc(hidden)]
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>>;
fn req_command(&mut self, cmd: &Cmd) -> RedisResult<Value> {
let pcmd = cmd.get_packed_command();
self.req_packed_command(&pcmd)
}
fn get_db(&self) -> i64;
#[doc(hidden)]
fn supports_pipelining(&self) -> bool {
true
}
fn check_connection(&mut self) -> bool;
fn is_open(&self) -> bool;
}
impl Connection {
pub fn send_packed_command(&mut self, cmd: &[u8]) -> RedisResult<()> {
self.con.send_bytes(cmd)?;
Ok(())
}
pub fn recv_response(&mut self) -> RedisResult<Value> {
self.read_response()
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_write_timeout(dur)
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_read_timeout(dur)
}
pub fn as_pubsub(&mut self) -> PubSub<'_> {
PubSub::new(self)
}
fn exit_pubsub(&mut self) -> RedisResult<()> {
let res = self.clear_active_subscriptions();
if res.is_ok() {
self.pubsub = false;
} else {
self.pubsub = true;
}
res
}
fn clear_active_subscriptions(&mut self) -> RedisResult<()> {
{
let unsubscribe = cmd("UNSUBSCRIBE").get_packed_command();
let punsubscribe = cmd("PUNSUBSCRIBE").get_packed_command();
let con = &mut self.con;
con.send_bytes(&unsubscribe)?;
con.send_bytes(&punsubscribe)?;
}
let mut received_unsub = false;
let mut received_punsub = false;
loop {
let res: (Vec<u8>, (), isize) = from_owned_redis_value(self.recv_response()?)?;
match res.0.first() {
Some(&b'u') => received_unsub = true,
Some(&b'p') => received_punsub = true,
_ => (),
}
if received_unsub && received_punsub && res.2 == 0 {
break;
}
}
Ok(())
}
fn read_response(&mut self) -> RedisResult<Value> {
let result = match self.con {
ActualConnection::Tcp(TcpConnection { ref mut reader, .. }) => {
self.parser.parse_value(reader)
}
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
ActualConnection::TcpNativeTls(ref mut boxed_tls_connection) => {
let reader = &mut boxed_tls_connection.reader;
self.parser.parse_value(reader)
}
#[cfg(feature = "tls-rustls")]
ActualConnection::TcpRustls(ref mut boxed_tls_connection) => {
let reader = &mut boxed_tls_connection.reader;
self.parser.parse_value(reader)
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref mut sock, .. }) => {
self.parser.parse_value(sock)
}
};
if let Err(e) = &result {
let shutdown = match e.as_io_error() {
Some(e) => e.kind() == io::ErrorKind::UnexpectedEof,
None => false,
};
if shutdown {
match self.con {
ActualConnection::Tcp(ref mut connection) => {
let _ = connection.reader.shutdown(net::Shutdown::Both);
connection.open = false;
}
#[cfg(all(feature = "tls-native-tls", not(feature = "tls-rustls")))]
ActualConnection::TcpNativeTls(ref mut connection) => {
let _ = connection.reader.shutdown();
connection.open = false;
}
#[cfg(feature = "tls-rustls")]
ActualConnection::TcpRustls(ref mut connection) => {
let _ = connection.reader.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let _ = connection.sock.shutdown(net::Shutdown::Both);
connection.open = false;
}
}
}
}
result
}
}
impl ConnectionLike for Connection {
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value> {
if self.pubsub {
self.exit_pubsub()?;
}
self.con.send_bytes(cmd)?;
self.read_response()
}
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>> {
if self.pubsub {
self.exit_pubsub()?;
}
self.con.send_bytes(cmd)?;
let mut rv = vec![];
let mut first_err = None;
for idx in 0..(offset + count) {
let response = self.read_response();
match response {
Ok(item) => {
if idx >= offset {
rv.push(item);
}
}
Err(err) => {
if first_err.is_none() {
first_err = Some(err);
}
}
}
}
first_err.map_or(Ok(rv), Err)
}
fn get_db(&self) -> i64 {
self.db
}
fn is_open(&self) -> bool {
self.con.is_open()
}
fn check_connection(&mut self) -> bool {
cmd("PING").query::<String>(self).is_ok()
}
}
impl<C, T> ConnectionLike for T
where
C: ConnectionLike,
T: DerefMut<Target = C>,
{
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value> {
self.deref_mut().req_packed_command(cmd)
}
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>> {
self.deref_mut().req_packed_commands(cmd, offset, count)
}
fn req_command(&mut self, cmd: &Cmd) -> RedisResult<Value> {
self.deref_mut().req_command(cmd)
}
fn get_db(&self) -> i64 {
self.deref().get_db()
}
fn supports_pipelining(&self) -> bool {
self.deref().supports_pipelining()
}
fn check_connection(&mut self) -> bool {
self.deref_mut().check_connection()
}
fn is_open(&self) -> bool {
self.deref().is_open()
}
}
impl<'a> PubSub<'a> {
fn new(con: &'a mut Connection) -> Self {
Self {
con,
waiting_messages: VecDeque::new(),
}
}
fn cache_messages_until_received_response(&mut self, cmd: &Cmd) -> RedisResult<()> {
let mut response = self.con.req_packed_command(&cmd.get_packed_command())?;
loop {
if let Some(msg) = Msg::from_value(&response) {
self.waiting_messages.push_back(msg);
} else {
return Ok(());
}
response = self.con.recv_response()?;
}
}
pub fn subscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
self.cache_messages_until_received_response(cmd("SUBSCRIBE").arg(channel))
}
pub fn psubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
self.cache_messages_until_received_response(cmd("PSUBSCRIBE").arg(pchannel))
}
pub fn unsubscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
self.cache_messages_until_received_response(cmd("UNSUBSCRIBE").arg(channel))
}
pub fn punsubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
self.cache_messages_until_received_response(cmd("PUNSUBSCRIBE").arg(pchannel))
}
pub fn get_message(&mut self) -> RedisResult<Msg> {
if let Some(msg) = self.waiting_messages.pop_front() {
return Ok(msg);
}
loop {
if let Some(msg) = Msg::from_value(&self.con.recv_response()?) {
return Ok(msg);
} else {
continue;
}
}
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_read_timeout(dur)
}
}
impl<'a> Drop for PubSub<'a> {
fn drop(&mut self) {
let _ = self.con.exit_pubsub();
}
}
impl Msg {
pub fn from_value(value: &Value) -> Option<Self> {
let raw_msg: Vec<Value> = from_redis_value(value).ok()?;
let mut iter = raw_msg.into_iter();
let msg_type: String = from_owned_redis_value(iter.next()?).ok()?;
let mut pattern = None;
let payload;
let channel;
if msg_type == "message" {
channel = iter.next()?;
payload = iter.next()?;
} else if msg_type == "pmessage" {
pattern = Some(iter.next()?);
channel = iter.next()?;
payload = iter.next()?;
} else {
return None;
}
Some(Msg {
payload,
channel,
pattern,
})
}
pub fn get_channel<T: FromRedisValue>(&self) -> RedisResult<T> {
from_redis_value(&self.channel)
}
pub fn get_channel_name(&self) -> &str {
match self.channel {
Value::Data(ref bytes) => from_utf8(bytes).unwrap_or("?"),
_ => "?",
}
}
pub fn get_payload<T: FromRedisValue>(&self) -> RedisResult<T> {
from_redis_value(&self.payload)
}
pub fn get_payload_bytes(&self) -> &[u8] {
match self.payload {
Value::Data(ref bytes) => bytes,
_ => b"",
}
}
#[allow(clippy::wrong_self_convention)]
pub fn from_pattern(&self) -> bool {
self.pattern.is_some()
}
pub fn get_pattern<T: FromRedisValue>(&self) -> RedisResult<T> {
match self.pattern {
None => from_redis_value(&Value::Nil),
Some(ref x) => from_redis_value(x),
}
}
}
pub fn transaction<
C: ConnectionLike,
K: ToRedisArgs,
T,
F: FnMut(&mut C, &mut Pipeline) -> RedisResult<Option<T>>,
>(
con: &mut C,
keys: &[K],
func: F,
) -> RedisResult<T> {
let mut func = func;
loop {
cmd("WATCH").arg(keys).query::<()>(con)?;
let mut p = pipe();
let response: Option<T> = func(con, p.atomic())?;
match response {
None => {
continue;
}
Some(response) => {
cmd("UNWATCH").query::<()>(con)?;
return Ok(response);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_redis_url() {
let cases = vec![
("redis://127.0.0.1", true),
("redis://[::1]", true),
("redis+unix:///run/redis.sock", true),
("unix:///run/redis.sock", true),
("http://127.0.0.1", false),
("tcp://127.0.0.1", false),
];
for (url, expected) in cases.into_iter() {
let res = parse_redis_url(url);
assert_eq!(
res.is_some(),
expected,
"Parsed result of `{url}` is not expected",
);
}
}
#[test]
fn test_url_to_tcp_connection_info() {
let cases = vec![
(
url::Url::parse("redis://127.0.0.1").unwrap(),
ConnectionInfo {
addr: ConnectionAddr::Tcp("127.0.0.1".to_string(), 6379),
redis: Default::default(),
},
),
(
url::Url::parse("redis://[::1]").unwrap(),
ConnectionInfo {
addr: ConnectionAddr::Tcp("::1".to_string(), 6379),
redis: Default::default(),
},
),
(
url::Url::parse("redis://%25johndoe%25:%23%40%3C%3E%24@example.com/2").unwrap(),
ConnectionInfo {
addr: ConnectionAddr::Tcp("example.com".to_string(), 6379),
redis: RedisConnectionInfo {
db: 2,
username: Some("%johndoe%".to_string()),
password: Some("#@<>$".to_string()),
},
},
),
];
for (url, expected) in cases.into_iter() {
let res = url_to_tcp_connection_info(url.clone()).unwrap();
assert_eq!(res.addr, expected.addr, "addr of {url} is not expected");
assert_eq!(
res.redis.db, expected.redis.db,
"db of {url} is not expected",
);
assert_eq!(
res.redis.username, expected.redis.username,
"username of {url} is not expected",
);
assert_eq!(
res.redis.password, expected.redis.password,
"password of {url} is not expected",
);
}
}
#[test]
fn test_url_to_tcp_connection_info_failed() {
let cases = vec![
(url::Url::parse("redis://").unwrap(), "Missing hostname"),
(
url::Url::parse("redis://127.0.0.1/db").unwrap(),
"Invalid database number",
),
(
url::Url::parse("redis://C3%B0@127.0.0.1").unwrap(),
"Username is not valid UTF-8 string",
),
(
url::Url::parse("redis://:C3%B0@127.0.0.1").unwrap(),
"Password is not valid UTF-8 string",
),
];
for (url, expected) in cases.into_iter() {
let res = url_to_tcp_connection_info(url).unwrap_err();
assert_eq!(
res.kind(),
crate::ErrorKind::InvalidClientConfig,
"{}",
&res,
);
#[allow(deprecated)]
let desc = std::error::Error::description(&res);
assert_eq!(desc, expected, "{}", &res);
assert_eq!(res.detail(), None, "{}", &res);
}
}
#[test]
#[cfg(unix)]
fn test_url_to_unix_connection_info() {
let cases = vec![
(
url::Url::parse("unix:///var/run/redis.sock").unwrap(),
ConnectionInfo {
addr: ConnectionAddr::Unix("/var/run/redis.sock".into()),
redis: RedisConnectionInfo {
db: 0,
username: None,
password: None,
},
},
),
(
url::Url::parse("redis+unix:///var/run/redis.sock?db=1").unwrap(),
ConnectionInfo {
addr: ConnectionAddr::Unix("/var/run/redis.sock".into()),
redis: RedisConnectionInfo {
db: 1,
username: None,
password: None,
},
},
),
(
url::Url::parse(
"unix:///example.sock?user=%25johndoe%25&pass=%23%40%3C%3E%24&db=2",
)
.unwrap(),
ConnectionInfo {
addr: ConnectionAddr::Unix("/example.sock".into()),
redis: RedisConnectionInfo {
db: 2,
username: Some("%johndoe%".to_string()),
password: Some("#@<>$".to_string()),
},
},
),
(
url::Url::parse(
"redis+unix:///example.sock?pass=%26%3F%3D+%2A%2B&db=2&user=%25johndoe%25",
)
.unwrap(),
ConnectionInfo {
addr: ConnectionAddr::Unix("/example.sock".into()),
redis: RedisConnectionInfo {
db: 2,
username: Some("%johndoe%".to_string()),
password: Some("&?= *+".to_string()),
},
},
),
];
for (url, expected) in cases.into_iter() {
assert_eq!(
ConnectionAddr::Unix(url.to_file_path().unwrap()),
expected.addr,
"addr of {url} is not expected",
);
let res = url_to_unix_connection_info(url.clone()).unwrap();
assert_eq!(res.addr, expected.addr, "addr of {url} is not expected");
assert_eq!(
res.redis.db, expected.redis.db,
"db of {url} is not expected",
);
assert_eq!(
res.redis.username, expected.redis.username,
"username of {url} is not expected",
);
assert_eq!(
res.redis.password, expected.redis.password,
"password of {url} is not expected",
);
}
}
}