jsonserver.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. use crate::{net, Error, Result};
  2. use crate::rpc::options::ProgramOptions;
  3. use crate::rpc::adapter::RpcAdapter;
  4. use async_executor::Executor;
  5. use async_native_tls::TlsAcceptor;
  6. use async_std::sync::Mutex;
  7. use http_types::{Request, Response, StatusCode};
  8. use log::*;
  9. use smol::Async;
  10. use std::net::TcpListener;
  11. use std::sync::Arc;
  12. /// Listens for incoming connections and serves them.
  13. pub async fn listen(
  14. executor: Arc<Executor<'_>>,
  15. rpc: Arc<RpcInterface>,
  16. listener: Async<TcpListener>,
  17. tls: Option<TlsAcceptor>,
  18. ) -> Result<()> {
  19. // Format the full host address.
  20. let host = match &tls {
  21. None => format!("http://{}", listener.get_ref().local_addr()?),
  22. Some(_) => format!("https://{}", listener.get_ref().local_addr()?),
  23. };
  24. println!("Listening on {}", host);
  25. loop {
  26. // Accept the next connection.
  27. debug!(target: "rpc", "waiting for stream accept [START]");
  28. let (stream, _) = listener.accept().await?;
  29. debug!(target: "rpc", "stream accepted [END]");
  30. // Spawn a background task serving this connection.
  31. let task = match &tls {
  32. None => {
  33. let stream = async_dup::Arc::new(stream);
  34. let rpc = rpc.clone();
  35. executor.spawn(async move {
  36. if let Err(err) = async_h1::accept(stream, move |req| {
  37. let rpc = rpc.clone();
  38. rpc.serve(req)
  39. })
  40. .await
  41. {
  42. println!("Connection error: {:#?}", err);
  43. }
  44. })
  45. }
  46. Some(tls) => {
  47. // In case of HTTPS, establish a secure TLS connection first.
  48. match tls.accept(stream).await {
  49. Ok(stream) => {
  50. let _stream = async_dup::Arc::new(async_dup::Mutex::new(stream));
  51. executor.spawn(async move {
  52. /*if let Err(err) = async_h1::accept(stream, serve).await {
  53. println!("Connection error: {:#?}", err);
  54. }*/
  55. unimplemented!();
  56. })
  57. }
  58. Err(err) => {
  59. println!("Failed to establish secure TLS connection: {:#?}", err);
  60. continue;
  61. }
  62. }
  63. }
  64. };
  65. // Detach the task to let it run in the background.
  66. task.detach();
  67. }
  68. }
  69. pub async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions, _adapter: Arc<RpcAdapter>) -> Result<()> {
  70. let p2p = net::P2p::new(options.network_settings);
  71. let rpc = RpcInterface::new(p2p.clone());
  72. let http = listen(
  73. executor.clone(),
  74. rpc.clone(),
  75. Async::<TcpListener>::bind(([127, 0, 0, 1], options.rpc_port))?,
  76. None,
  77. );
  78. let http_task = executor.spawn(http);
  79. *rpc.started.lock().await = true;
  80. p2p.clone().start(executor.clone()).await?;
  81. p2p.run(executor).await?;
  82. rpc.wait_for_quit().await?;
  83. http_task.cancel().await;
  84. Ok(())
  85. }
  86. // json RPC server goes here
  87. pub struct RpcInterface {
  88. p2p: Arc<net::P2p>,
  89. pub started: Mutex<bool>,
  90. stop_send: async_channel::Sender<()>,
  91. stop_recv: async_channel::Receiver<()>,
  92. }
  93. impl RpcInterface {
  94. pub fn new(p2p: Arc<net::P2p>) -> Arc<Self> {
  95. let (stop_send, stop_recv) = async_channel::unbounded::<()>();
  96. Arc::new(Self {
  97. p2p,
  98. started: Mutex::new(false),
  99. stop_send,
  100. stop_recv,
  101. })
  102. }
  103. pub async fn serve(self: Arc<Self>, mut req: Request) -> http_types::Result<Response> {
  104. info!("RPC serving {}", req.url());
  105. let request = req.body_string().await?;
  106. let io = self.handle_input().await?;
  107. let response = io
  108. .handle_request_sync(&request)
  109. .ok_or(Error::BadOperationType)?;
  110. let mut res = Response::new(StatusCode::Ok);
  111. res.insert_header("Content-Type", "text/plain");
  112. res.set_body(response);
  113. Ok(res)
  114. }
  115. pub async fn handle_input(&self) -> Result<jsonrpc_core::IoHandler> {
  116. debug!(target: "rpc", "JsonRpcInterface::handle_input() [START]");
  117. let mut io = jsonrpc_core::IoHandler::new();
  118. io.add_sync_method("say_hello", |_| {
  119. Ok(jsonrpc_core::Value::String("Hello World!".into()))
  120. });
  121. io.add_method("get_info", move |_| async move {
  122. RpcAdapter::get_info().await;
  123. Ok(jsonrpc_core::Value::Null)
  124. });
  125. io.add_method("stop", move |_| async move {
  126. RpcAdapter::stop().await;
  127. Ok(jsonrpc_core::Value::Null)
  128. });
  129. io.add_method("key_gen", move |_| async move {
  130. RpcAdapter::key_gen().await;
  131. Ok(jsonrpc_core::Value::Null)
  132. });
  133. debug!(target: "rpc", "JsonRpcInterface::handle_input() [END]");
  134. Ok(io)
  135. }
  136. pub async fn wait_for_quit(self: Arc<Self>) -> Result<()> {
  137. Ok(self.stop_recv.recv().await?)
  138. }
  139. }