1use std::{
2 io::{self, Read},
3 str,
4};
5
6use crate::errors::{ParsingError, RedisError, Repr, ServerError, ServerErrorKind};
7use crate::types::{PushKind, RedisResult, Value, VerbatimFormat};
8
9use combine::{
10 ParseError, Parser as _, any,
11 error::StreamError,
12 opaque,
13 parser::{
14 byte::{crlf, take_until_bytes},
15 combinator::{AnySendSyncPartialState, any_send_sync_partial_state},
16 range::{recognize, take},
17 },
18 stream::{
19 PointerOffset, RangeStream, StreamErrorFor,
20 decoder::{self, Decoder},
21 },
22 unexpected_any,
23};
24
25const MAX_RECURSE_DEPTH: usize = 100;
26
27fn err_parser(line: &str) -> ServerError {
28 let mut pieces = line.splitn(2, ' ');
29 let kind = match pieces.next().unwrap() {
30 "ERR" => ServerErrorKind::ResponseError,
31 "EXECABORT" => ServerErrorKind::ExecAbort,
32 "LOADING" => ServerErrorKind::BusyLoading,
33 "NOSCRIPT" => ServerErrorKind::NoScript,
34 "MOVED" => ServerErrorKind::Moved,
35 "ASK" => ServerErrorKind::Ask,
36 "TRYAGAIN" => ServerErrorKind::TryAgain,
37 "CLUSTERDOWN" => ServerErrorKind::ClusterDown,
38 "CROSSSLOT" => ServerErrorKind::CrossSlot,
39 "MASTERDOWN" => ServerErrorKind::MasterDown,
40 "READONLY" => ServerErrorKind::ReadOnly,
41 "NOTBUSY" => ServerErrorKind::NotBusy,
42 "NOSUB" => ServerErrorKind::NoSub,
43 "NOPERM" => ServerErrorKind::NoPerm,
44 code => {
45 return ServerError(Repr::Extension {
46 code: code.into(),
47 detail: pieces.next().map(|str| str.into()),
48 });
49 }
50 };
51 let detail = pieces.next().map(|str| str.into());
52 ServerError(Repr::Known { kind, detail })
53}
54
55pub fn get_push_kind(kind: String) -> PushKind {
56 match kind.as_str() {
57 "invalidate" => PushKind::Invalidate,
58 "message" => PushKind::Message,
59 "pmessage" => PushKind::PMessage,
60 "smessage" => PushKind::SMessage,
61 "unsubscribe" => PushKind::Unsubscribe,
62 "punsubscribe" => PushKind::PUnsubscribe,
63 "sunsubscribe" => PushKind::SUnsubscribe,
64 "subscribe" => PushKind::Subscribe,
65 "psubscribe" => PushKind::PSubscribe,
66 "ssubscribe" => PushKind::SSubscribe,
67 _ => PushKind::Other(kind),
68 }
69}
70
71fn value<'a, I>(
72 count: Option<usize>,
73) -> impl combine::Parser<I, Output = Value, PartialState = AnySendSyncPartialState>
74where
75 I: RangeStream<Token = u8, Range = &'a [u8]>,
76 I::Error: combine::ParseError<u8, &'a [u8], I::Position>,
77{
78 let count = count.unwrap_or(1);
79
80 opaque!(any_send_sync_partial_state(
81 any()
82 .then_partial(move |&mut b| {
83 if count > MAX_RECURSE_DEPTH {
84 combine::unexpected_any("Maximum recursion depth exceeded").left()
85 } else {
86 combine::value(b).right()
87 }
88 })
89 .then_partial(move |&mut b| {
90 let line = || {
91 recognize(take_until_bytes(&b"\r\n"[..]).with(take(2).map(|_| ()))).and_then(
92 |line: &[u8]| {
93 str::from_utf8(&line[..line.len() - 2])
94 .map_err(StreamErrorFor::<I>::other)
95 },
96 )
97 };
98
99 let simple_string = || {
100 line().map(|line| {
101 if line == "OK" {
102 Value::Okay
103 } else {
104 Value::SimpleString(line.into())
105 }
106 })
107 };
108
109 let int = || {
110 line().and_then(|line| {
111 line.trim().parse::<i64>().map_err(|_| {
112 StreamErrorFor::<I>::message_static_message(
113 "Expected integer, got garbage",
114 )
115 })
116 })
117 };
118
119 let bulk_string = || {
120 int().then_partial(move |size| {
121 if *size < 0 {
122 combine::produce(|| Value::Nil).left()
123 } else {
124 take(*size as usize)
125 .map(|bs: &[u8]| Value::BulkString(bs.to_vec()))
126 .skip(crlf())
127 .right()
128 }
129 })
130 };
131 let blob = || {
132 int().then_partial(move |size| {
133 take(*size as usize)
134 .map(|bs: &[u8]| String::from_utf8_lossy(bs).to_string())
135 .skip(crlf())
136 })
137 };
138
139 let array = || {
140 int().then_partial(move |&mut length| {
141 if length < 0 {
142 combine::produce(|| Value::Nil).left()
143 } else {
144 let length = length as usize;
145 combine::count_min_max(length, length, value(Some(count + 1)))
146 .map(Value::Array)
147 .right()
148 }
149 })
150 };
151
152 let error = || line().map(err_parser);
153 let map = || {
154 int().then_partial(move |&mut kv_length| {
155 match (kv_length as usize).checked_mul(2) {
156 Some(length) => {
157 combine::count_min_max(length, length, value(Some(count + 1)))
158 .map(move |result: Vec<Value>| {
159 let mut it = result.into_iter();
160 let mut x = vec![];
161 for _ in 0..kv_length {
162 if let (Some(k), Some(v)) = (it.next(), it.next()) {
163 x.push((k, v));
164 }
165 }
166 Value::Map(x)
167 })
168 .left()
169 }
170 None => {
171 unexpected_any("Attribute key-value length is too large").right()
172 }
173 }
174 })
175 };
176 let attribute = || {
177 int().then_partial(move |&mut kv_length| {
178 match (kv_length as usize).checked_mul(2) {
179 Some(length) => {
180 let length = length + 1;
182 combine::count_min_max(length, length, value(Some(count + 1)))
183 .map(move |result: Vec<Value>| {
184 let mut it = result.into_iter();
185 let mut attributes = vec![];
186 for _ in 0..kv_length {
187 if let (Some(k), Some(v)) = (it.next(), it.next()) {
188 attributes.push((k, v));
189 }
190 }
191 Value::Attribute {
192 data: Box::new(it.next().unwrap()),
193 attributes,
194 }
195 })
196 .left()
197 }
198 None => {
199 unexpected_any("Attribute key-value length is too large").right()
200 }
201 }
202 })
203 };
204 let set = || {
205 int().then_partial(move |&mut length| {
206 if length < 0 {
207 combine::produce(|| Value::Nil).left()
208 } else {
209 let length = length as usize;
210 combine::count_min_max(length, length, value(Some(count + 1)))
211 .map(Value::Set)
212 .right()
213 }
214 })
215 };
216 let push = || {
217 int().then_partial(move |&mut length| {
218 if length <= 0 {
219 combine::produce(|| Value::Push {
220 kind: PushKind::Other("".to_string()),
221 data: vec![],
222 })
223 .left()
224 } else {
225 let length = length as usize;
226 combine::count_min_max(length, length, value(Some(count + 1)))
227 .and_then(|result: Vec<Value>| {
228 let mut it = result.into_iter();
229 let first = it.next().unwrap_or(Value::Nil);
230 if let Value::BulkString(kind) = first {
231 let push_kind = String::from_utf8(kind)
232 .map_err(StreamErrorFor::<I>::other)?;
233 Ok(Value::Push {
234 kind: get_push_kind(push_kind),
235 data: it.collect(),
236 })
237 } else if let Value::SimpleString(kind) = first {
238 Ok(Value::Push {
239 kind: get_push_kind(kind),
240 data: it.collect(),
241 })
242 } else {
243 Err(StreamErrorFor::<I>::message_static_message(
244 "parse error when decoding push",
245 ))
246 }
247 })
248 .right()
249 }
250 })
251 };
252 let null = || line().map(|_| Value::Nil);
253 let double = || {
254 line().and_then(|line| {
255 line.trim()
256 .parse::<f64>()
257 .map_err(StreamErrorFor::<I>::other)
258 })
259 };
260 let boolean = || {
261 line().and_then(|line: &str| match line {
262 "t" => Ok(true),
263 "f" => Ok(false),
264 _ => Err(StreamErrorFor::<I>::message_static_message(
265 "Expected boolean, got garbage",
266 )),
267 })
268 };
269 let blob_error = || blob().map(|line| err_parser(&line));
270 let verbatim = || {
271 blob().and_then(|line| {
272 if let Some((format, text)) = line.split_once(':') {
273 let format = match format {
274 "txt" => VerbatimFormat::Text,
275 "mkd" => VerbatimFormat::Markdown,
276 x => VerbatimFormat::Unknown(x.to_string()),
277 };
278 Ok(Value::VerbatimString {
279 format,
280 text: text.to_string(),
281 })
282 } else {
283 Err(StreamErrorFor::<I>::message_static_message(
284 "parse error when decoding verbatim string",
285 ))
286 }
287 })
288 };
289 let big_number = || {
290 line().and_then(|line| {
291 #[cfg(not(feature = "num-bigint"))]
292 return Ok::<_, StreamErrorFor<I>>(Value::BigNumber(
293 line.as_bytes().to_vec(),
294 ));
295 #[cfg(feature = "num-bigint")]
296 num_bigint::BigInt::parse_bytes(line.as_bytes(), 10)
297 .ok_or_else(|| {
298 StreamErrorFor::<I>::message_static_message(
299 "Expected bigint, got garbage",
300 )
301 })
302 .map(Value::BigNumber)
303 })
304 };
305 combine::dispatch!(b;
306 b'+' => simple_string(),
307 b':' => int().map(Value::Int),
308 b'$' => bulk_string(),
309 b'*' => array(),
310 b'%' => map(),
311 b'|' => attribute(),
312 b'~' => set(),
313 b'-' => error().map(Value::ServerError),
314 b'_' => null(),
315 b',' => double().map(Value::Double),
316 b'#' => boolean().map(Value::Boolean),
317 b'!' => blob_error().map(Value::ServerError),
318 b'=' => verbatim(),
319 b'(' => big_number(),
320 b'>' => push(),
321 b => combine::unexpected_any(combine::error::Token(b))
322 )
323 })
324 ))
325}
326
327macro_rules! to_redis_err {
329 ($err: expr, $decoder: expr) => {
330 match $err {
331 decoder::Error::Io { error, .. } => error.into(),
332 decoder::Error::Parse(err) => {
333 if err.is_unexpected_end_of_input() {
334 RedisError::from(io::Error::from(io::ErrorKind::UnexpectedEof))
335 } else {
336 let err = err
337 .map_range(|range| format!("{range:?}"))
338 .map_position(|pos| pos.translate_position($decoder.buffer()))
339 .to_string();
340 RedisError::from(ParsingError::from(err))
341 }
342 }
343 }
344 };
345}
346
347#[cfg(feature = "aio")]
348mod aio_support {
349 use super::*;
350
351 use bytes::{Buf, BytesMut};
352 use tokio::io::AsyncRead;
353 use tokio_util::codec::{Decoder, Encoder};
354
355 #[derive(Default)]
360 pub struct ValueCodec {
361 state: AnySendSyncPartialState,
362 }
363
364 impl ValueCodec {
365 fn decode_stream(&mut self, bytes: &mut BytesMut, eof: bool) -> RedisResult<Option<Value>> {
366 let (opt, removed_len) = {
367 let buffer = &bytes[..];
368 let mut stream =
369 combine::easy::Stream(combine::stream::MaybePartialStream(buffer, !eof));
370 match combine::stream::decode_tokio(value(None), &mut stream, &mut self.state) {
371 Ok(x) => x,
372 Err(err) => {
373 let err = err
374 .map_position(|pos| pos.translate_position(buffer))
375 .map_range(|range| format!("{range:?}"))
376 .to_string();
377 return Err(RedisError::from(ParsingError::from(err)));
378 }
379 }
380 };
381
382 bytes.advance(removed_len);
383 match opt {
384 Some(result) => Ok(Some(result)),
385 None => Ok(None),
386 }
387 }
388 }
389
390 impl Encoder<Vec<u8>> for ValueCodec {
391 type Error = RedisError;
392 fn encode(&mut self, item: Vec<u8>, dst: &mut BytesMut) -> Result<(), Self::Error> {
393 dst.extend_from_slice(item.as_ref());
394 Ok(())
395 }
396 }
397
398 impl Decoder for ValueCodec {
399 type Item = Value;
400 type Error = RedisError;
401
402 fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
403 self.decode_stream(src, false)
404 }
405
406 fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
407 self.decode_stream(buf, true)
408 }
409 }
410
411 pub async fn parse_redis_value_async<R>(
413 decoder: &mut combine::stream::Decoder<AnySendSyncPartialState, PointerOffset<[u8]>>,
414 read: &mut R,
415 ) -> RedisResult<Value>
416 where
417 R: AsyncRead + std::marker::Unpin,
418 {
419 let result = combine::decode_tokio!(*decoder, *read, value(None), |input, _| {
420 combine::stream::easy::Stream::from(input)
421 });
422 match result {
423 Err(err) => Err(to_redis_err!(err, decoder)),
424 Ok(result) => Ok(result),
425 }
426 }
427}
428
429#[cfg(feature = "aio")]
430#[cfg_attr(docsrs, doc(cfg(feature = "aio")))]
431pub use self::aio_support::*;
432
433pub struct Parser {
435 decoder: Decoder<AnySendSyncPartialState, PointerOffset<[u8]>>,
436}
437
438impl Default for Parser {
439 fn default() -> Self {
440 Self::new()
441 }
442}
443
444impl Parser {
449 pub fn new() -> Self {
454 Self {
455 decoder: Decoder::new(),
456 }
457 }
458
459 pub fn parse_value<T: Read>(&mut self, mut reader: T) -> RedisResult<Value> {
463 let mut decoder = &mut self.decoder;
464 let result = combine::decode!(decoder, reader, value(None), |input, _| {
465 combine::stream::easy::Stream::from(input)
466 });
467 match result {
468 Err(err) => Err(to_redis_err!(err, decoder)),
469 Ok(result) => Ok(result),
470 }
471 }
472}
473
474pub fn parse_redis_value(bytes: &[u8]) -> RedisResult<Value> {
479 let mut parser = Parser::new();
480 parser.parse_value(bytes)
481}
482
483#[cfg(test)]
484mod tests {
485 use super::*;
486 use crate::errors::ErrorKind;
487 use assert_matches::assert_matches;
488
489 #[cfg(feature = "aio")]
490 #[test]
491 fn decode_eof_returns_none_at_eof() {
492 use tokio_util::codec::Decoder;
493 let mut codec = ValueCodec::default();
494
495 let mut bytes = bytes::BytesMut::from(&b"+GET 123\r\n"[..]);
496 assert_eq!(
497 codec.decode_eof(&mut bytes),
498 Ok(Some(parse_redis_value(b"+GET 123\r\n").unwrap()))
499 );
500 assert_eq!(codec.decode_eof(&mut bytes), Ok(None));
501 assert_eq!(codec.decode_eof(&mut bytes), Ok(None));
502 }
503
504 #[cfg(feature = "aio")]
505 #[test]
506 fn decode_eof_returns_error_inside_array_and_can_parse_more_inputs() {
507 use tokio_util::codec::Decoder;
508 let mut codec = ValueCodec::default();
509
510 let mut bytes =
511 bytes::BytesMut::from(b"*3\r\n+OK\r\n-LOADING server is loading\r\n+OK\r\n".as_slice());
512 let result = codec.decode_eof(&mut bytes).unwrap().unwrap();
513
514 assert_eq!(
515 result,
516 Value::Array(vec![
517 Value::Okay,
518 Value::ServerError(ServerError(Repr::Known {
519 kind: ServerErrorKind::BusyLoading,
520 detail: Some(arcstr::literal!("server is loading"))
521 })),
522 Value::Okay
523 ])
524 );
525
526 let mut bytes = bytes::BytesMut::from(b"+OK\r\n".as_slice());
527 let result = codec.decode_eof(&mut bytes).unwrap().unwrap();
528
529 assert_eq!(result, Value::Okay);
530 }
531
532 #[test]
533 fn parse_nested_error_and_handle_more_inputs() {
534 let bytes = b"*3\r\n+OK\r\n-LOADING server is loading\r\n+OK\r\n";
538 let result = parse_redis_value(bytes);
539
540 assert_eq!(
541 result.unwrap(),
542 Value::Array(vec![
543 Value::Okay,
544 Value::ServerError(ServerError(Repr::Known {
545 kind: ServerErrorKind::BusyLoading,
546 detail: Some(arcstr::literal!("server is loading"))
547 })),
548 Value::Okay
549 ])
550 );
551
552 let result = parse_redis_value(b"+OK\r\n").unwrap();
553
554 assert_eq!(result, Value::Okay);
555 }
556
557 #[test]
558 fn decode_resp3_double() {
559 let val = parse_redis_value(b",1.23\r\n").unwrap();
560 assert_eq!(val, Value::Double(1.23));
561 let val = parse_redis_value(b",nan\r\n").unwrap();
562 if let Value::Double(val) = val {
563 assert!(val.is_sign_positive());
564 assert!(val.is_nan());
565 } else {
566 panic!("expected double");
567 }
568 let val = parse_redis_value(b",-nan\r\n").unwrap();
570 if let Value::Double(val) = val {
571 assert!(val.is_sign_negative());
572 assert!(val.is_nan());
573 } else {
574 panic!("expected double");
575 }
576 let val = parse_redis_value(b",2.67923e+8\r\n").unwrap();
578 assert_eq!(val, Value::Double(267923000.0));
579 let val = parse_redis_value(b",2.67923E+8\r\n").unwrap();
580 assert_eq!(val, Value::Double(267923000.0));
581 let val = parse_redis_value(b",-2.67923E+8\r\n").unwrap();
582 assert_eq!(val, Value::Double(-267923000.0));
583 let val = parse_redis_value(b",2.1E-2\r\n").unwrap();
584 assert_eq!(val, Value::Double(0.021));
585
586 let val = parse_redis_value(b",-inf\r\n").unwrap();
587 assert_eq!(val, Value::Double(-f64::INFINITY));
588 let val = parse_redis_value(b",inf\r\n").unwrap();
589 assert_eq!(val, Value::Double(f64::INFINITY));
590 }
591
592 #[test]
593 fn decode_resp3_map() {
594 let val = parse_redis_value(b"%2\r\n+first\r\n:1\r\n+second\r\n:2\r\n").unwrap();
595 let mut v = val.as_map_iter().unwrap();
596 assert_eq!(
597 (&Value::SimpleString("first".to_string()), &Value::Int(1)),
598 v.next().unwrap()
599 );
600 assert_eq!(
601 (&Value::SimpleString("second".to_string()), &Value::Int(2)),
602 v.next().unwrap()
603 );
604 }
605
606 #[test]
607 fn decode_resp3_boolean() {
608 let val = parse_redis_value(b"#t\r\n").unwrap();
609 assert_eq!(val, Value::Boolean(true));
610 let val = parse_redis_value(b"#f\r\n").unwrap();
611 assert_eq!(val, Value::Boolean(false));
612 let val = parse_redis_value(b"#x\r\n");
613 assert_matches!(val, Err(_));
614 let val = parse_redis_value(b"#\r\n");
615 assert_matches!(val, Err(_));
616 }
617
618 #[test]
619 fn decode_resp3_blob_error() {
620 let val = parse_redis_value(b"!21\r\nSYNTAX invalid syntax\r\n");
621 assert_eq!(
622 val.unwrap(),
623 Value::ServerError(ServerError(Repr::Extension {
624 code: arcstr::literal!("SYNTAX"),
625 detail: Some(arcstr::literal!("invalid syntax"))
626 }))
627 );
628 }
629
630 #[test]
631 fn decode_resp3_big_number() {
632 let val = parse_redis_value(b"(3492890328409238509324850943850943825024385\r\n").unwrap();
633 #[cfg(feature = "num-bigint")]
634 let expected = Value::BigNumber(
635 num_bigint::BigInt::parse_bytes(b"3492890328409238509324850943850943825024385", 10)
636 .unwrap(),
637 );
638 #[cfg(not(feature = "num-bigint"))]
639 let expected = Value::BigNumber(b"3492890328409238509324850943850943825024385".to_vec());
640 assert_eq!(val, expected);
641 }
642
643 #[test]
644 fn decode_resp3_set() {
645 let val = parse_redis_value(b"~5\r\n+orange\r\n+apple\r\n#t\r\n:100\r\n:999\r\n").unwrap();
646 let v = val.as_sequence().unwrap();
647 assert!(v.len() >= 5);
648 assert_eq!(Value::SimpleString("orange".to_string()), v[0]);
649 assert_eq!(Value::SimpleString("apple".to_string()), v[1]);
650 assert_eq!(Value::Boolean(true), v[2]);
651 assert_eq!(Value::Int(100), v[3]);
652 assert_eq!(Value::Int(999), v[4]);
653 }
654
655 #[test]
656 fn decode_resp3_push() {
657 let val = parse_redis_value(b">3\r\n+message\r\n+somechannel\r\n+this is the message\r\n")
658 .unwrap();
659 if let Value::Push { ref kind, ref data } = val {
660 assert_eq!(&PushKind::Message, kind);
661 assert_eq!(Value::SimpleString("somechannel".to_string()), data[0]);
662 assert_eq!(
663 Value::SimpleString("this is the message".to_string()),
664 data[1]
665 );
666 } else {
667 panic!("Expected Value::Push")
668 }
669 }
670
671 #[test]
672 fn test_max_recursion_depth_set_and_array() {
673 for test_byte in ["*", "~"] {
674 let initial = format!("{test_byte}1\r\n").as_bytes().to_vec();
675 let end = format!("{test_byte}0\r\n").as_bytes().to_vec();
676
677 let mut ba = initial.repeat(MAX_RECURSE_DEPTH - 1).to_vec();
678 ba.extend(end.clone());
679 match parse_redis_value(&ba) {
680 Ok(Value::Array(a)) => assert_eq!(a.len(), 1),
681 Ok(Value::Set(s)) => assert_eq!(s.len(), 1),
682 _ => panic!("Expected valid array or set"),
683 }
684
685 let mut ba = initial.repeat(MAX_RECURSE_DEPTH).to_vec();
686 ba.extend(end);
687 match parse_redis_value(&ba) {
688 Ok(_) => panic!("Expected ParseError"),
689 Err(e) => assert_matches!(e.kind(), ErrorKind::Parse),
690 }
691 }
692 }
693
694 #[test]
695 fn test_max_recursion_depth_map() {
696 let initial = b"%1\r\n+a\r\n";
697 let end = b"%0\r\n";
698
699 let mut ba = initial.repeat(MAX_RECURSE_DEPTH - 1).to_vec();
700 ba.extend(*end);
701 match parse_redis_value(&ba) {
702 Ok(Value::Map(m)) => assert_eq!(m.len(), 1),
703 Ok(Value::Set(s)) => assert_eq!(s.len(), 1),
704 _ => panic!("Expected valid array or set"),
705 }
706
707 let mut ba = initial.repeat(MAX_RECURSE_DEPTH).to_vec();
708 ba.extend(end);
709 match parse_redis_value(&ba) {
710 Ok(_) => panic!("Expected ParseError"),
711 Err(e) => assert_matches!(e.kind(), ErrorKind::Parse),
712 }
713 }
714}