Skip to content

Commit

Permalink
axstd: adapted network apps
Browse files Browse the repository at this point in the history
- TODO: UDP
  • Loading branch information
equation314 committed Jul 2, 2023
1 parent 439c667 commit c6ad3df
Show file tree
Hide file tree
Showing 19 changed files with 374 additions and 73 deletions.
12 changes: 6 additions & 6 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ jobs:
run: make ARCH=${{ matrix.arch }} A=apps/memtest
- name: Build exception
run: make ARCH=${{ matrix.arch }} A=apps/exception
- name: Build display
run: make ARCH=${{ matrix.arch }} A=apps/display
# - name: Build display
# run: make ARCH=${{ matrix.arch }} A=apps/display
- name: Build task/yield
run: make ARCH=${{ matrix.arch }} A=apps/task/yield
- name: Build task/parallel
Expand All @@ -63,16 +63,16 @@ jobs:
run: make ARCH=${{ matrix.arch }} A=apps/task/sleep
- name: Build task/priority
run: make ARCH=${{ matrix.arch }} A=apps/task/priority
- name: Build fs/shell
run: make ARCH=${{ matrix.arch }} A=apps/fs/shell
# - name: Build fs/shell
# run: make ARCH=${{ matrix.arch }} A=apps/fs/shell
- name: Build net/echoserver
run: make ARCH=${{ matrix.arch }} A=apps/net/echoserver
- name: Build net/httpclient
run: make ARCH=${{ matrix.arch }} A=apps/net/httpclient
- name: Build net/httpserver
run: make ARCH=${{ matrix.arch }} A=apps/net/httpserver
- name: Build net/udpserver
run: make ARCH=${{ matrix.arch }} A=apps/net/udpserver
# - name: Build net/udpserver
# run: make ARCH=${{ matrix.arch }} A=apps/net/udpserver

- uses: ./.github/workflows/actions/setup-musl
with:
Expand Down
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion apps/net/echoserver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ authors = ["Yuekai Jia <[email protected]>"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libax = { path = "../../../ulib/libax", features = ["multitask", "net"] }
axstd = { path = "../../../ulib/axstd", features = ["multitask", "net"] }
22 changes: 10 additions & 12 deletions apps/net/echoserver/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
#![no_main]

#[macro_use]
extern crate libax;
extern crate axstd;
extern crate alloc;

use alloc::vec::Vec;
use core::str::FromStr;

use libax::io::{self, prelude::*};
use libax::net::{IpAddr, TcpListener, TcpStream};
use libax::thread;
use axstd::io::{self, prelude::*};
use axstd::net::{TcpListener, TcpStream};
use axstd::thread;

const LOCAL_IP: &str = "10.0.2.15";
const LOCAL_PORT: u16 = 5555;
Expand All @@ -26,7 +25,7 @@ fn reverse(buf: &[u8]) -> Vec<u8> {
lines.join(&b'\n')
}

fn echo_server(mut stream: TcpStream) -> io::Result {
fn echo_server(mut stream: TcpStream) -> io::Result<()> {
let mut buf = [0u8; 1024];
loop {
let n = stream.read(&mut buf)?;
Expand All @@ -37,19 +36,18 @@ fn echo_server(mut stream: TcpStream) -> io::Result {
}
}

fn accept_loop() -> io::Result {
let (addr, port) = (IpAddr::from_str(LOCAL_IP).unwrap(), LOCAL_PORT);
let mut listener = TcpListener::bind((addr, port).into())?;
fn accept_loop() -> io::Result<()> {
let mut listener = TcpListener::bind((LOCAL_IP, LOCAL_PORT))?;
println!("listen on: {}", listener.local_addr().unwrap());

let mut i = 0;
loop {
match listener.accept() {
Ok((stream, addr)) => {
info!("new client {}: {}", i, addr);
println!("new client {}: {}", i, addr);
thread::spawn(move || match echo_server(stream) {
Err(e) => error!("client connection error: {:?}", e),
Ok(()) => info!("client {} closed successfully", i),
Err(e) => println!("client connection error: {:?}", e),
Ok(()) => println!("client {} closed successfully", i),
});
}
Err(e) => return Err(e),
Expand Down
4 changes: 2 additions & 2 deletions apps/net/httpclient/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ authors = ["Yuekai Jia <[email protected]>", "Dashuai Wu <wudashuaijss@foxma
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libax = { path = "../../../ulib/libax", features = ["net"] }
axstd = { path = "../../../ulib/axstd", features = ["net"] }

[features]
default = []
dns = []
dns = ["axstd/dns"]
3 changes: 1 addition & 2 deletions apps/net/httpclient/expect_info.out
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ created net interface "eth0":
gateway: 10.0.2.2
Primary CPU 0 init OK.
Hello, simple http client!
dest IP: [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+

dest: [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+:80 ([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+:80)
HTTP/1.1 200 OK
Server: nginx
Date:
Expand Down
4 changes: 1 addition & 3 deletions apps/net/httpclient/expect_info_dns.out
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ created net interface "eth0":
gateway: 10.0.2.2
Primary CPU 0 init OK.
Hello, simple http client!
dest domain: ident.me
dest IP: [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+

dest: ident.me:80 ([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+:80)
HTTP/1.1 200 OK
Server: nginx
Date:
Expand Down
32 changes: 12 additions & 20 deletions apps/net/httpclient/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,28 @@
#![no_main]

#[macro_use]
extern crate libax;
extern crate axstd;

extern crate alloc;
use axstd::io::{self, prelude::*};
use axstd::net::{TcpStream, ToSocketAddrs};

use alloc::vec::Vec;
use libax::io::{self, prelude::*};
use libax::net::{SocketAddr, TcpStream, ToSocketAddrs};
#[cfg(feature = "dns")]
const DEST: &str = "ident.me:80";
#[cfg(not(feature = "dns"))]
const DEST: &str = "49.12.234.183:80";

const DEST_HOST: &str = "ident.me";
const DEST_IP: &str = "49.12.234.183";
const REQUEST: &str = "\
GET / HTTP/1.1\r\n\
Host: ident.me\r\n\
Accept: */*\r\n\
\r\n";

fn get_addr() -> SocketAddr {
let dest = if cfg!(feature = "dns") {
println!("dest domain: {}", DEST_HOST);
DEST_HOST
} else {
DEST_IP
};
let addr_iter = (dest, 80).to_socket_addrs().unwrap().collect::<Vec<_>>();
println!("dest IP: {}\n", addr_iter[0].addr);
addr_iter[0]
}
fn client() -> io::Result<()> {
for addr in DEST.to_socket_addrs()? {
println!("dest: {} ({})", DEST, addr);
}

fn client() -> io::Result {
let mut stream = TcpStream::connect(get_addr())?;
let mut stream = TcpStream::connect(DEST)?;
stream.write(REQUEST.as_bytes())?;
let mut buf = [0; 2048];
let n = stream.read(&mut buf)?;
Expand Down
2 changes: 1 addition & 1 deletion apps/net/httpserver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ authors = ["Yuekai Jia <[email protected]>"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libax = { path = "../../../ulib/libax", features = ["multitask", "net"] }
axstd = { path = "../../../ulib/axstd", features = ["multitask", "net"] }
30 changes: 19 additions & 11 deletions apps/net/httpserver/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@
#![no_main]

#[macro_use]
extern crate libax;
extern crate axstd;
extern crate alloc;

use core::str::FromStr;

use libax::io::{self, prelude::*};
use libax::net::{IpAddr, TcpListener, TcpStream};
use libax::thread;
use axstd::io::{self, prelude::*};
use axstd::net::{TcpListener, TcpStream};
use axstd::thread;

const LOCAL_IP: &str = "10.0.2.15";
const LOCAL_PORT: u16 = 5555;
Expand Down Expand Up @@ -50,7 +48,18 @@ const CONTENT: &str = r#"<html>
</html>
"#;

fn http_server(mut stream: TcpStream) -> io::Result {
macro_rules! info {
($($arg:tt)*) => {
match option_env!("LOG") {
Some("info") | Some("debug") | Some("trace") => {
print!("[INFO] {}\n", format_args!($($arg)*));
}
_ => {}
}
};
}

fn http_server(mut stream: TcpStream) -> io::Result<()> {
let mut buf = [0u8; 1024];
stream.read(&mut buf)?;

Expand All @@ -60,9 +69,8 @@ fn http_server(mut stream: TcpStream) -> io::Result {
Ok(())
}

fn accept_loop() -> io::Result {
let (addr, port) = (IpAddr::from_str(LOCAL_IP).unwrap(), LOCAL_PORT);
let mut listener = TcpListener::bind((addr, port).into())?;
fn accept_loop() -> io::Result<()> {
let mut listener = TcpListener::bind((LOCAL_IP, LOCAL_PORT))?;
println!("listen on: http://{}/", listener.local_addr().unwrap());

let mut i = 0;
Expand All @@ -71,7 +79,7 @@ fn accept_loop() -> io::Result {
Ok((stream, addr)) => {
info!("new client {}: {}", i, addr);
thread::spawn(move || match http_server(stream) {
Err(e) => error!("client connection error: {:?}", e),
Err(e) => info!("client connection error: {:?}", e),
Ok(()) => info!("client {} closed successfully", i),
});
}
Expand Down
10 changes: 5 additions & 5 deletions modules/axlog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ pub use log::{debug, error, info, trace, warn};
/// the end of the message.
#[macro_export]
macro_rules! ax_print {
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::__print_impl(format_args!($fmt $(, $($arg)+)?));
($($arg:tt)*) => {
$crate::__print_impl(format_args!($($arg)*));
}
}

/// Prints to the console, with a newline.
#[macro_export]
macro_rules! ax_println {
() => { ax_print!("\n") };
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::__print_impl(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
() => { $crate::ax_print!("\n") };
($($arg:tt)*) => {
$crate::__print_impl(format_args!("{}\n", format_args!($($arg)*)));
}
}

Expand Down
2 changes: 1 addition & 1 deletion scripts/test/app_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ if [ -z "$1" ]; then
"apps/task/parallel"
"apps/task/sleep"
"apps/task/priority"
# "apps/net/httpclient"
"apps/net/httpclient"
"apps/c/helloworld"
"apps/c/memtest"
"apps/c/sqlite3"
Expand Down
1 change: 1 addition & 0 deletions ulib/axstd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ use-ramdisk = ["axfeat/use-ramdisk"]

# Networking
net = ["arceos_api/net", "axfeat/net"]
dns = []

# Display
display = ["axfeat/display"]
Expand Down
1 change: 1 addition & 0 deletions ulib/axstd/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod stdio;
pub use axio::prelude;
pub use axio::{BufRead, BufReader, Error, Read, Seek, SeekFrom, Write};

#[doc(hidden)]
pub use self::stdio::__print_impl;

/// A specialized [`Result`] type for I/O operations.
Expand Down
8 changes: 4 additions & 4 deletions ulib/axstd/src/io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
/// [`println!`]: crate::println
#[macro_export]
macro_rules! print {
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::io::__print_impl(format_args!($fmt $(, $($arg)+)?));
($($arg:tt)*) => {
$crate::io::__print_impl(format_args!($($arg)*));
}
}

/// Prints to the standard output, with a newline.
#[macro_export]
macro_rules! println {
() => { $crate::print!("\n") };
($fmt: literal $(, $($arg: tt)+)?) => {
$crate::io::__print_impl(format_args!(concat!($fmt, "\n") $(, $($arg)+)?));
($($arg:tt)*) => {
$crate::io::__print_impl(format_args!("{}\n", format_args!($($arg)*)));
}
}

Expand Down
9 changes: 7 additions & 2 deletions ulib/axstd/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! # The [ArceOS] Standard Library
//! # The ArceOS Standard Library
//!
//! The ArceOS Standard Library is a mini-std library, with an interface similar
//! The [ArceOS] Standard Library is a mini-std library, with an interface similar
//! to rust [std], but calling the functions directly in ArceOS modules, instead
//! of using libc and system calls.
//!
Expand All @@ -27,6 +27,7 @@
//! - `fs`: Enable file system support.
//! - `use-ramdisk`: Use the RAM disk to emulate the block device.
//! - `net`: Enable networking support.
//! - `dns`: Enable DNS lookup support.
//! - `display`: Enable graphics support.
//! - `bus-mmio`: Use device tree to probe all MMIO devices.
//! - `bus-pci`: Use PCI bus to probe all PCI devices.
Expand All @@ -43,6 +44,7 @@
//! [ArceOS]: https://github.com/rcore-os/arceos

#![cfg_attr(all(not(test), not(doc)), no_std)]
#![feature(ip_in_core)]
#![feature(doc_cfg)]
#![feature(doc_auto_cfg)]

Expand All @@ -57,3 +59,6 @@ pub mod io;
pub mod os;
pub mod thread;
pub mod time;

#[cfg(feature = "net")]
pub mod net;
30 changes: 30 additions & 0 deletions ulib/axstd/src/net/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! Networking primitives for TCP/UDP communication.

mod socket_addr;
mod tcp;
// mod udp;

pub use self::socket_addr::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, ToSocketAddrs};
pub use self::tcp::{TcpListener, TcpStream};

use crate::io;

fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
where
F: FnMut(io::Result<&SocketAddr>) -> io::Result<T>,
{
let addrs = match addr.to_socket_addrs() {
Ok(addrs) => addrs,
Err(e) => return f(Err(e)),
};
let mut last_err = None;
for addr in addrs {
match f(Ok(&addr)) {
Ok(l) => return Ok(l),
Err(e) => last_err = Some(e),
}
}
Err(last_err.unwrap_or_else(|| {
axerrno::ax_err_type!(InvalidInput, "could not resolve to any addresses")
}))
}
Loading

0 comments on commit c6ad3df

Please sign in to comment.