mod.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. use alloc::sync::{Arc, Weak};
  2. use core::sync::atomic::{AtomicBool, AtomicUsize};
  3. use system_error::SystemError::{self, *};
  4. use crate::libs::rwlock::RwLock;
  5. use crate::net::event_poll::EPollEventType;
  6. use crate::net::net_core::poll_ifaces;
  7. use crate::net::socket::*;
  8. use crate::sched::SchedMode;
  9. use inet::{InetSocket, UNSPECIFIED_LOCAL_ENDPOINT};
  10. use smoltcp;
  11. mod inner;
  12. use inner::*;
  13. mod option;
  14. pub use option::Options as TcpOption;
  15. type EP = EPollEventType;
  16. #[derive(Debug)]
  17. pub struct TcpSocket {
  18. inner: RwLock<Option<Inner>>,
  19. #[allow(dead_code)]
  20. shutdown: Shutdown, // TODO set shutdown status
  21. nonblock: AtomicBool,
  22. wait_queue: WaitQueue,
  23. self_ref: Weak<Self>,
  24. pollee: AtomicUsize,
  25. }
  26. impl TcpSocket {
  27. pub fn new(nonblock: bool) -> Arc<Self> {
  28. Arc::new_cyclic(|me| Self {
  29. inner: RwLock::new(Some(Inner::Init(Init::new()))),
  30. shutdown: Shutdown::new(),
  31. nonblock: AtomicBool::new(nonblock),
  32. wait_queue: WaitQueue::default(),
  33. self_ref: me.clone(),
  34. pollee: AtomicUsize::new((EP::EPOLLIN.bits() | EP::EPOLLOUT.bits()) as usize),
  35. })
  36. }
  37. pub fn new_established(inner: Established, nonblock: bool) -> Arc<Self> {
  38. Arc::new_cyclic(|me| Self {
  39. inner: RwLock::new(Some(Inner::Established(inner))),
  40. shutdown: Shutdown::new(),
  41. nonblock: AtomicBool::new(nonblock),
  42. wait_queue: WaitQueue::default(),
  43. self_ref: me.clone(),
  44. pollee: AtomicUsize::new((EP::EPOLLIN.bits() | EP::EPOLLOUT.bits()) as usize),
  45. })
  46. }
  47. pub fn is_nonblock(&self) -> bool {
  48. self.nonblock.load(core::sync::atomic::Ordering::Relaxed)
  49. }
  50. pub fn do_bind(&self, local_endpoint: smoltcp::wire::IpEndpoint) -> Result<(), SystemError> {
  51. let mut writer = self.inner.write();
  52. match writer.take().expect("Tcp Inner is None") {
  53. Inner::Init(inner) => {
  54. let bound = inner.bind(local_endpoint)?;
  55. if let Init::Bound((ref bound, _)) = bound {
  56. bound
  57. .iface()
  58. .common()
  59. .bind_socket(self.self_ref.upgrade().unwrap());
  60. }
  61. writer.replace(Inner::Init(bound));
  62. Ok(())
  63. }
  64. _ => Err(EINVAL),
  65. }
  66. }
  67. pub fn do_listen(&self, backlog: usize) -> Result<(), SystemError> {
  68. let mut writer = self.inner.write();
  69. let inner = writer.take().expect("Tcp Inner is None");
  70. let (listening, err) = match inner {
  71. Inner::Init(init) => {
  72. let listen_result = init.listen(backlog);
  73. match listen_result {
  74. Ok(listening) => (Inner::Listening(listening), None),
  75. Err((init, err)) => (Inner::Init(init), Some(err)),
  76. }
  77. }
  78. _ => (inner, Some(EINVAL)),
  79. };
  80. writer.replace(listening);
  81. drop(writer);
  82. if let Some(err) = err {
  83. return Err(err);
  84. }
  85. return Ok(());
  86. }
  87. pub fn try_accept(&self) -> Result<(Arc<TcpSocket>, smoltcp::wire::IpEndpoint), SystemError> {
  88. poll_ifaces();
  89. match self.inner.write().as_mut().expect("Tcp Inner is None") {
  90. Inner::Listening(listening) => listening.accept().map(|(stream, remote)| {
  91. (
  92. TcpSocket::new_established(stream, self.is_nonblock()),
  93. remote,
  94. )
  95. }),
  96. _ => Err(EINVAL),
  97. }
  98. }
  99. pub fn start_connect(
  100. &self,
  101. remote_endpoint: smoltcp::wire::IpEndpoint,
  102. ) -> Result<(), SystemError> {
  103. let mut writer = self.inner.write();
  104. let inner = writer.take().expect("Tcp Inner is None");
  105. let (init, err) = match inner {
  106. Inner::Init(init) => {
  107. let conn_result = init.connect(remote_endpoint);
  108. match conn_result {
  109. Ok(connecting) => (
  110. Inner::Connecting(connecting),
  111. if self.is_nonblock() {
  112. None
  113. } else {
  114. Some(EINPROGRESS)
  115. },
  116. ),
  117. Err((init, err)) => (Inner::Init(init), Some(err)),
  118. }
  119. }
  120. Inner::Connecting(connecting) if self.is_nonblock() => {
  121. (Inner::Connecting(connecting), Some(EALREADY))
  122. }
  123. Inner::Connecting(connecting) => (Inner::Connecting(connecting), None),
  124. Inner::Listening(inner) => (Inner::Listening(inner), Some(EISCONN)),
  125. Inner::Established(inner) => (Inner::Established(inner), Some(EISCONN)),
  126. };
  127. writer.replace(init);
  128. drop(writer);
  129. poll_ifaces();
  130. if let Some(err) = err {
  131. return Err(err);
  132. }
  133. return Ok(());
  134. }
  135. pub fn finish_connect(&self) -> Result<(), SystemError> {
  136. let mut writer = self.inner.write();
  137. let Inner::Connecting(conn) = writer.take().expect("Tcp Inner is None") else {
  138. log::error!("TcpSocket::finish_connect: not Connecting");
  139. return Err(EINVAL);
  140. };
  141. let (inner, err) = conn.into_result();
  142. writer.replace(inner);
  143. drop(writer);
  144. if let Some(err) = err {
  145. return Err(err);
  146. }
  147. return Ok(());
  148. }
  149. pub fn check_connect(&self) -> Result<(), SystemError> {
  150. match self.inner.read().as_ref().expect("Tcp Inner is None") {
  151. Inner::Connecting(_) => Err(EAGAIN_OR_EWOULDBLOCK),
  152. Inner::Established(_) => Ok(()), // TODO check established
  153. _ => Err(EINVAL), // TODO socket error options
  154. }
  155. }
  156. pub fn try_recv(&self, buf: &mut [u8]) -> Result<usize, SystemError> {
  157. self.inner
  158. .read()
  159. .as_ref()
  160. .map(|inner| {
  161. inner.iface().unwrap().poll();
  162. let result = match inner {
  163. Inner::Established(inner) => inner.recv_slice(buf),
  164. _ => Err(EINVAL),
  165. };
  166. inner.iface().unwrap().poll();
  167. result
  168. })
  169. .unwrap()
  170. }
  171. pub fn try_send(&self, buf: &[u8]) -> Result<usize, SystemError> {
  172. match self.inner.read().as_ref().expect("Tcp Inner is None") {
  173. Inner::Established(inner) => {
  174. let sent = inner.send_slice(buf);
  175. poll_ifaces();
  176. sent
  177. }
  178. _ => Err(EINVAL),
  179. }
  180. }
  181. fn update_events(&self) -> bool {
  182. match self.inner.read().as_ref().expect("Tcp Inner is None") {
  183. Inner::Init(_) => false,
  184. Inner::Connecting(connecting) => connecting.update_io_events(),
  185. Inner::Established(established) => {
  186. established.update_io_events(&self.pollee);
  187. false
  188. }
  189. Inner::Listening(listening) => {
  190. listening.update_io_events(&self.pollee);
  191. false
  192. }
  193. }
  194. }
  195. // should only call on accept
  196. fn is_acceptable(&self) -> bool {
  197. // (self.poll() & EP::EPOLLIN.bits() as usize) != 0
  198. self.inner.read().as_ref().unwrap().iface().unwrap().poll();
  199. EP::from_bits_truncate(self.poll() as u32).contains(EP::EPOLLIN)
  200. }
  201. }
  202. impl Socket for TcpSocket {
  203. fn wait_queue(&self) -> &WaitQueue {
  204. &self.wait_queue
  205. }
  206. fn get_name(&self) -> Result<Endpoint, SystemError> {
  207. match self.inner.read().as_ref().expect("Tcp Inner is None") {
  208. Inner::Init(Init::Unbound(_)) => Ok(Endpoint::Ip(UNSPECIFIED_LOCAL_ENDPOINT)),
  209. Inner::Init(Init::Bound((_, local))) => Ok(Endpoint::Ip(*local)),
  210. Inner::Connecting(connecting) => Ok(Endpoint::Ip(connecting.get_name())),
  211. Inner::Established(established) => Ok(Endpoint::Ip(established.local_endpoint())),
  212. Inner::Listening(listening) => Ok(Endpoint::Ip(listening.get_name())),
  213. }
  214. }
  215. fn bind(&self, endpoint: Endpoint) -> Result<(), SystemError> {
  216. if let Endpoint::Ip(addr) = endpoint {
  217. return self.do_bind(addr);
  218. }
  219. return Err(EINVAL);
  220. }
  221. fn connect(&self, endpoint: Endpoint) -> Result<(), SystemError> {
  222. if let Endpoint::Ip(addr) = endpoint {
  223. return self.start_connect(addr);
  224. }
  225. return Err(EINVAL);
  226. }
  227. fn poll(&self) -> usize {
  228. self.pollee.load(core::sync::atomic::Ordering::SeqCst)
  229. }
  230. fn listen(&self, backlog: usize) -> Result<(), SystemError> {
  231. self.do_listen(backlog)
  232. }
  233. fn accept(&self) -> Result<(Arc<Inode>, Endpoint), SystemError> {
  234. // could block io
  235. if self.is_nonblock() {
  236. self.try_accept()
  237. } else {
  238. loop {
  239. // log::debug!("TcpSocket::accept: wake up");
  240. match self.try_accept() {
  241. Err(EAGAIN_OR_EWOULDBLOCK) => {
  242. wq_wait_event_interruptible!(self.wait_queue, self.is_acceptable(), {})?;
  243. }
  244. result => break result,
  245. }
  246. }
  247. }
  248. .map(|(inner, endpoint)| (Inode::new(inner), Endpoint::Ip(endpoint)))
  249. }
  250. fn recv(&self, buffer: &mut [u8], _flags: PMSG) -> Result<usize, SystemError> {
  251. self.try_recv(buffer)
  252. }
  253. fn send(&self, buffer: &[u8], _flags: PMSG) -> Result<usize, SystemError> {
  254. self.try_send(buffer)
  255. }
  256. fn send_buffer_size(&self) -> usize {
  257. self.inner
  258. .read()
  259. .as_ref()
  260. .expect("Tcp Inner is None")
  261. .send_buffer_size()
  262. }
  263. fn recv_buffer_size(&self) -> usize {
  264. self.inner
  265. .read()
  266. .as_ref()
  267. .expect("Tcp Inner is None")
  268. .recv_buffer_size()
  269. }
  270. fn close(&self) -> Result<(), SystemError> {
  271. self.inner
  272. .read()
  273. .as_ref()
  274. .map(|inner| match inner {
  275. Inner::Connecting(_) => Err(EINPROGRESS),
  276. Inner::Established(es) => {
  277. es.close();
  278. es.release();
  279. Ok(())
  280. }
  281. _ => Ok(()),
  282. })
  283. .unwrap_or(Ok(()))
  284. }
  285. }
  286. impl InetSocket for TcpSocket {
  287. fn on_iface_events(&self) {
  288. if self.update_events() {
  289. let _result = self.finish_connect();
  290. // set error
  291. }
  292. }
  293. }