use super::conn::{Conn, LinkError};
use super::opts::Opts;
use kevy_resp::Reply;
use std::io::Write;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PushSink {
Print,
Discard,
Return,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Connect {
Report,
Quiet,
}
pub(crate) struct Session {
pub(crate) opts: Opts,
pub(crate) conn: Option<Conn>,
pub(crate) link_error: Option<LinkError>,
pub(crate) dbnum: i32,
pub(crate) in_multi: bool,
pub(crate) pre_multi_dbnum: i32,
pub(crate) pubsub_mode: bool,
pub(crate) monitor_mode: bool,
pub(crate) shutdown: bool,
pub(crate) current_resp3: bool,
pub(crate) push: PushSink,
pub(crate) interactive: bool,
pub(crate) docs: Option<std::rc::Rc<super::docs::model::Docs>>,
pub(crate) ldb: super::ldb::Ldb,
pub(crate) rds: super::rds::meta::Prefs,
}
static HINTS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
pub(crate) fn set_hints(on: bool) {
HINTS.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub(crate) fn hints_on() -> bool {
HINTS.load(std::sync::atomic::Ordering::Relaxed)
}
pub(crate) fn eprint_bytes(parts: &[&[u8]]) {
let _ = std::io::stderr().write_all(&parts.concat()); }
impl Session {
pub(crate) fn new(opts: Opts) -> Session {
Session {
opts,
conn: None,
link_error: None,
dbnum: 0,
in_multi: false,
pre_multi_dbnum: 0,
pubsub_mode: false,
monitor_mode: false,
shutdown: false,
current_resp3: false,
push: PushSink::Discard,
interactive: false,
docs: None,
ldb: super::ldb::Ldb::default(),
rds: super::rds::meta::Prefs::default(),
}
}
pub(crate) fn connect(&mut self, how: Connect) -> bool {
if self.conn.take().is_some() {
self.dbnum = 0;
self.in_multi = false;
self.pubsub_mode = false;
}
let opened = match (&self.opts.socket, &self.opts.secure) {
(Some(path), _) => Conn::unix(path),
(None, Some(t)) => {
Conn::secure(&self.opts.host, self.opts.port, self.opts.connect_timeout, t)
}
(None, None) => Conn::tcp(&self.opts.host, self.opts.port, self.opts.connect_timeout),
};
let conn = match opened {
Ok(c) => c,
Err(errstr) => {
if how != Connect::Quiet {
self.print_connect_failure(&errstr);
}
return false;
}
};
self.conn = Some(conn);
self.link_error = None;
self.current_resp3 = false;
self.push = PushSink::Discard;
if !(self.auth() && self.select() && self.switch_proto() && self.set_name()) {
return false;
}
self.arm_push();
true
}
fn arm_push(&mut self) {
if self.opts.push_output {
self.push = PushSink::Print;
}
}
fn print_connect_failure(&self, errstr: &str) {
let target = match &self.opts.socket {
Some(path) => path.clone(),
None => [self.opts.host.as_slice(), format!(":{}", self.opts.port).as_bytes()].concat(),
};
eprint_bytes(&[
b"Could not connect to Redis at ",
&target,
b": ",
errstr.as_bytes(),
b"\n",
]);
}
fn handshake(&mut self, argv: &[&[u8]]) -> Option<Reply> {
let conn = self.conn.as_mut()?;
let argv: Vec<Vec<u8>> = argv.iter().map(|a| a.to_vec()).collect();
match conn.send(&argv).and_then(|()| conn.read_reply()) {
Ok((reply, _)) => Some(reply),
Err(e) => {
eprint_bytes(&[b"\nI/O error\n"]);
self.link_error = Some(e);
None
}
}
}
fn auth(&mut self) -> bool {
let Some(pass) = self.opts.auth.clone() else { return true };
let reply = match self.opts.user.clone() {
None => self.handshake(&[b"AUTH", &pass]),
Some(user) => self.handshake(&[b"AUTH", &user, &pass]),
};
expect_ok(reply, |msg| eprint_bytes(&[b"AUTH failed: ", msg, b"\n"]))
}
pub(crate) fn select(&mut self) -> bool {
if self.opts.input_dbnum == self.dbnum {
return true;
}
let db = self.opts.input_dbnum.to_string();
let reply = self.handshake(&[b"SELECT", db.as_bytes()]);
let ok = expect_ok(reply, |msg| {
eprint_bytes(&[b"SELECT ", db.as_bytes(), b" failed: ", msg, b"\n"])
});
if ok {
self.dbnum = self.opts.input_dbnum;
}
ok
}
fn switch_proto(&mut self) -> bool {
if self.opts.resp3 == 0 || self.opts.resp2 {
return true;
}
let Some(reply) = self.handshake(&[b"HELLO", b"3"]) else { return false };
let mut ok = true;
if let Reply::Error(msg) | Reply::BlobError(msg) = &reply {
eprint_bytes(&[b"HELLO 3 failed: ", super::format::c_str(msg), b"\n"]);
ok = self.opts.resp3 != 1;
}
self.current_resp3 = true;
ok
}
fn set_name(&mut self) -> bool {
let Some(name) = self.opts.client_name.clone() else { return true };
let reply = self.handshake(&[b"CLIENT", b"SETNAME", &name]);
expect_ok(reply, |msg| eprint_bytes(&[b"CLIENT SETNAME failed: ", msg, b"\n"]))
}
pub(crate) fn print_context_error(&self) {
if let (Some(_), Some(e)) = (&self.conn, &self.link_error) {
eprint_bytes(&[b"Error: ", e.text().as_bytes(), b"\n"]);
}
}
}
fn expect_ok(reply: Option<Reply>, report: impl FnOnce(&[u8])) -> bool {
match reply {
None => false,
Some(Reply::Error(msg) | Reply::BlobError(msg)) => {
report(super::format::c_str(&msg));
false
}
Some(_) => true,
}
}