common.rs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{io, time::Duration};
  19. use smol::io::{AsyncReadExt, AsyncWriteExt, BufReader, ReadHalf, WriteHalf};
  20. use super::jsonrpc::*;
  21. use crate::net::transport::PtStream;
  22. pub(super) const INIT_BUF_SIZE: usize = 4096; // 4K
  23. pub(super) const MAX_BUF_SIZE: usize = 1024 * 8192; // 8M
  24. pub(super) const READ_TIMEOUT: Duration = Duration::from_secs(30);
  25. /// Internal read function that reads from the active stream into a buffer.
  26. /// Reading stops upon reaching CRLF or LF, or when `MAX_BUF_SIZE` is reached.
  27. pub(super) async fn read_from_stream(
  28. reader: &mut BufReader<ReadHalf<Box<dyn PtStream>>>,
  29. buf: &mut Vec<u8>,
  30. ) -> io::Result<usize> {
  31. let mut total_read = 0;
  32. // Intermediate buffer we use to read byte-by-byte.
  33. let mut tmpbuf = [0_u8];
  34. while total_read < MAX_BUF_SIZE {
  35. buf.resize(total_read + INIT_BUF_SIZE, 0);
  36. match reader.read(&mut tmpbuf).await {
  37. Ok(0) if total_read == 0 => return Err(io::ErrorKind::ConnectionAborted.into()),
  38. Ok(0) => break, // Finished reading
  39. Ok(_) => {
  40. // When we reach '\n', pop a possible '\r' from the buffer and bail.
  41. if tmpbuf[0] == b'\n' {
  42. if buf[total_read - 1] == b'\r' {
  43. buf.pop();
  44. total_read -= 1;
  45. }
  46. break
  47. }
  48. // Copy the read byte to the destination buffer.
  49. buf[total_read] = tmpbuf[0];
  50. total_read += 1;
  51. }
  52. Err(e) => return Err(e),
  53. }
  54. }
  55. // Truncate buffer to actual data size
  56. buf.truncate(total_read);
  57. Ok(total_read)
  58. }
  59. /// Internal write function that writes a JSON-RPC object to the active stream.
  60. pub(super) async fn write_to_stream(
  61. writer: &mut WriteHalf<Box<dyn PtStream>>,
  62. object: &JsonResult,
  63. ) -> io::Result<()> {
  64. let object_str = match object {
  65. JsonResult::Notification(v) => v.stringify().unwrap(),
  66. JsonResult::Response(v) => v.stringify().unwrap(),
  67. JsonResult::Error(v) => v.stringify().unwrap(),
  68. JsonResult::Request(v) => v.stringify().unwrap(),
  69. _ => unreachable!(),
  70. };
  71. // As we're a line-based protocol, we append CRLF to the end of the JSON string.
  72. for i in [object_str.as_bytes(), &[b'\r', b'\n']] {
  73. writer.write_all(i).await?
  74. }
  75. writer.flush().await?;
  76. Ok(())
  77. }