From d3ec393af0dc0e50c33ba63c1d8f77a7d49f11cc Mon Sep 17 00:00:00 2001 From: Maxime Chevalier-Boisvert Date: Mon, 6 Nov 2023 21:58:41 -0500 Subject: [PATCH] Copy client address in net_accept() --- ncc/examples/telnet_server.c | 2 ++ vm/src/sys/net.rs | 20 ++++++++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/ncc/examples/telnet_server.c b/ncc/examples/telnet_server.c index c8d5b1a..10853d4 100644 --- a/ncc/examples/telnet_server.c +++ b/ncc/examples/telnet_server.c @@ -11,6 +11,8 @@ void on_new_conn(u64 socket_id) char client_addr[128]; u64 conn_sock = net_accept(socket_id, client_addr, sizeof(client_addr), on_incoming_data); + + printf("client address: %s\n", client_addr); } void on_incoming_data(u64 socket_id, u64 num_bytes) diff --git a/vm/src/sys/net.rs b/vm/src/sys/net.rs index abfaa15..667a261 100644 --- a/vm/src/sys/net.rs +++ b/vm/src/sys/net.rs @@ -82,7 +82,7 @@ fn listen_thread( // Syscall to create a TCP listening socket to accept incoming connections // u64 socket_id = net_listen( -// const char* listen_addr, // Network interface address to listen on, null for any address +// const char* listen_addr, // Network interface address to listen on, null for any address // callback on_new_connection, // Called on new incoming connection // ) pub fn net_listen( @@ -179,8 +179,9 @@ pub fn net_accept( ) -> Value { let socket_id = socket_id.as_u64(); - let client_addr_buf = client_addr_buf.as_u64(); - let addr_buf_len = addr_buf_len.as_u64(); + let client_addr_buf = client_addr_buf.as_usize(); + let addr_buf_ptr: *mut u8 = vm.get_heap_ptr(client_addr_buf); + let addr_buf_len = addr_buf_len.as_usize(); let on_incoming_data = on_incoming_data.as_u64(); let mut net_state = &mut vm.sys_state.net_state; @@ -195,9 +196,16 @@ pub fn net_accept( let stream = socket.incoming.pop_front().unwrap(); let socket_fd = stream.as_raw_fd(); - // TODO - // TODO: we need to write the client address into the buffer - // TODO + // TODO: handle the error case here + // The connection could have dropped + // Copy the client address into the buffer + let peer_addr = stream.peer_addr().unwrap(); + let mut addr_str = peer_addr.to_string().into_bytes(); + addr_str.push(0); + let num_bytes = std::cmp::min(addr_str.len(), addr_buf_len); + unsafe { + std::ptr::copy_nonoverlapping(addr_str.as_ptr(), addr_buf_ptr, num_bytes); + } // Assign a socket id to the socket let socket_id = net_state.next_id;