Skip to content

Commit 8e25124

Browse files
committed
Clean code.
1 parent 2be7403 commit 8e25124

File tree

1 file changed

+20
-107
lines changed

1 file changed

+20
-107
lines changed

src/networking/nc/mod.rs

Lines changed: 20 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ extern crate mio;
22
extern crate clap;
33
extern crate libc;
44
extern crate socket2;
5-
// extern crate tempfile;
65

76
use std;
87
use failure;
@@ -26,11 +25,11 @@ use super::{UtilSetup, ArgsIter};
2625
use super::{MesaError};
2726

2827

29-
3028
pub(crate) const NAME: &str = "nc";
3129
pub(crate) const DESCRIPTION: &str = "netcat";
3230

3331
const BUFSIZE: usize = 16384;
32+
const PRINT_DEBUG_INFO: bool = false;
3433

3534
#[derive(Debug)]
3635
struct NcOptions {
@@ -59,28 +58,25 @@ fn mesaerr_result<T>(err_msg: &str) -> Result<T, MesaError> {
5958
}
6059

6160
fn build_ports(ports: &str) -> Result<Vec<u16>, MesaError>{
62-
return Ok(vec!(ports.parse::<u16>()?));
63-
//.expect(&format!("invalid port[s] {}", ports)));
64-
}
65-
66-
// fn usage(ret: bool, msg: &str) {
67-
// eprint!("{}", msg);
68-
// if ret {
69-
// std::process::exit(1);
70-
// }
71-
// }
61+
// TODO: suport XX-XX
62+
let port_list = match ports.parse::<u16>() {
63+
Ok(port) => port,
64+
Err(_) => {
65+
return mesaerr_result(&format!("invalid port[s] {}", ports));
66+
}
67+
};
7268

73-
// fn err_exit(msg: &str) {
74-
// eprint!("{}", msg);
75-
// std::process::exit(1);
76-
// }
69+
Ok(vec!(port_list))
70+
}
7771

7872
fn warn(msg: &str) {
7973
eprint!("{}", msg);
8074
}
8175

8276
fn debug_info(msg: &str) {
83-
println!("{}", msg);
77+
if PRINT_DEBUG_INFO {
78+
eprint!("{}", msg);
79+
}
8480
}
8581

8682
impl NcOptions {
@@ -101,7 +97,6 @@ impl NcOptions {
10197
let zflag = matches.is_present("z");
10298
let kflag = matches.is_present("k");
10399

104-
105100
/* Cruft to make sure options are clean, and used properly. */
106101
let positionals: Vec<&str> = if matches.is_present("positionals") {
107102
matches.values_of("positionals").unwrap().collect()
@@ -126,19 +121,14 @@ impl NcOptions {
126121
} else {
127122
if !lflag {
128123
return mesaerr_result(msg);
129-
// usage(true, msg);
130-
// return None;
131124
}
132125
uport = String::from(positionals[0]);
133-
// host = String::from("localhost");
134126
}
135127
} else if positionals.len() >= 2 {
136128
host = String::from(positionals[0]);
137129
uport = String::from(positionals[1]);
138130
} else {
139131
return mesaerr_result(msg);
140-
// usage(true, msg);
141-
// return None;
142132
}
143133

144134
if lflag && s_addr.is_some() {
@@ -175,9 +165,8 @@ impl NcOptions {
175165
unix_dg_tmp_socket = if s_addr.is_some() {
176166
s_addr.clone().unwrap()
177167
} else {
178-
let nf = NamedTempFile::new()?; //.expect("failed to create temporary file");
168+
let nf = NamedTempFile::new()?;
179169
let path = String::from(nf.path().to_str().unwrap());
180-
// nf.persist(&path).expect("failed to create temporary file");
181170
path
182171
};
183172
}
@@ -208,7 +197,6 @@ impl NcOptions {
208197

209198
fn remove_item<T: Eq+Debug>(v: &mut Vec<T>, item: T) {
210199
debug_info(&format!("remove_item {:?}", item));
211-
// let index = v.iter().position(|t| *t == item).unwrap();
212200
match v.iter().position(|t| *t == item) {
213201
Some(i) => v.remove(i),
214202
None => return
@@ -312,8 +300,9 @@ impl <'a> NcCore<'a> {
312300
sleep(self.opts.interval.unwrap());
313301
}
314302

315-
self.poll.poll(&mut events, None)?;
316-
// .expect("polling error");
303+
if let Err(_) = self.poll.poll(&mut events, None) {
304+
return mesaerr_result("polling error");
305+
}
317306

318307
/* timeout happened */
319308
if events.is_empty() {
@@ -683,17 +672,6 @@ impl <'a> NcCore<'a> {
683672

684673
fn local_listen(opts: &NcOptions) -> Result<Socket, MesaError> {
685674
debug_info("local_listen");
686-
// let mut addrs_iter = (&opts.host as &str, opts.portlist[0]).to_socket_addrs();//let mut addrs_iter = "127.9.0.1".to_socket_addrs();//(&(opts.host) as &str, opts.portlist[0]).to_socket_addrs();
687-
// if addrs_iter.is_err() {
688-
// err_exit("get_matches")
689-
// }
690-
691-
// let mut addrs_iter = match {
692-
// Ok(expr) => expr,
693-
// Err(error) => {
694-
// panic!("to_socket_addrs: {:?}", error)
695-
// }
696-
// };
697675

698676
let addrs_iter = (&opts.host as &str, opts.portlist[0]).to_socket_addrs()?;
699677

@@ -733,12 +711,6 @@ fn local_listen(opts: &NcOptions) -> Result<Socket, MesaError> {
733711

734712
fn remote_connect(opts: &NcOptions, port: u16) -> Result<Socket, MesaError>{
735713
let addrs_iter = (&opts.host as &str, port).to_socket_addrs()?;
736-
// let mut addrs_iter = match (&opts.host as &str, port).to_socket_addrs() {
737-
// Ok(expr) => expr,
738-
// Err(error) => {
739-
// panic!("to_socket_addrs: {:?}", error)
740-
// }
741-
// };
742714

743715
for addr in addrs_iter{
744716
let sock_domain = match addr {
@@ -756,10 +728,8 @@ fn remote_connect(opts: &NcOptions, port: u16) -> Result<Socket, MesaError>{
756728

757729
if opts.s_addr.is_some() || opts.pflag {
758730
// TODO: implement
759-
760731
}
761732

762-
763733
// TODO: maybe sometimes no timeout
764734
match sock.connect_timeout(&socket2::SockAddr::from(addr), Duration::new(1, 0)) {
765735
Ok(_) => return Ok(sock),
@@ -774,25 +744,8 @@ fn remote_connect(opts: &NcOptions, port: u16) -> Result<Socket, MesaError>{
774744
}
775745
}
776746
}
777-
778-
779-
780-
781-
// if opts.uflag {
782-
// // UdpSocket
783-
// match UdpSocket::bind(addr) {
784-
// Ok(sock) => return sock.as_raw_fd(),
785-
// Err(_) => continue
786-
// }
787-
// } else {
788-
// match TcpListener::bind(addr) {
789-
// Ok(listener) => return listener.as_raw_fd(),
790-
// Err(_) => continue
791-
// };
792-
// }
793747
}
794748
mesaerr_result("local_listen failed")
795-
// err_exit("local_listen failed");
796749
}
797750

798751
/*
@@ -807,12 +760,7 @@ fn unix_bind(path: &str, opts: &NcOptions) -> Result<Socket, MesaError> {
807760
};
808761

809762
let sock = Socket::new(Domain::unix(), sock_type, None)?;
810-
// .expect("failed to create unix socket");
811-
812763
sock.bind(&socket2::SockAddr::unix(path)?)?;
813-
814-
//.expect("invalid unix socket path")).expect("bind error");
815-
816764
Ok(sock)
817765
}
818766

@@ -822,11 +770,8 @@ fn unix_bind(path: &str, opts: &NcOptions) -> Result<Socket, MesaError> {
822770
*/
823771
fn unix_listen(path: &str) -> Result<Socket, MesaError> {
824772
let sock = Socket::new(Domain::unix(), socket2::Type::stream(), None)?;
825-
// .expect("failed to create unix socket");
826773
sock.bind(&socket2::SockAddr::unix(path)?)?;
827-
//.expect("invalid unix socket path")).expect("bind error");
828774
sock.listen(5)?;
829-
//. .expect("listen error");
830775
Ok(sock)
831776
}
832777

@@ -844,6 +789,7 @@ fn server(opts: &NcOptions) -> Result<(), MesaError> {
844789
if opts.family != AF_UNIX {
845790
sock = local_listen(opts)?;
846791
}
792+
// TODO: implement
847793
// /*
848794
// * For UDP and -k, don't connect the socket, let it
849795
// * receive datagrams from multiple socket pairs.
@@ -862,13 +808,11 @@ fn server(opts: &NcOptions) -> Result<(), MesaError> {
862808
let mut netinbuf: [u8; BUFSIZE] = [0; BUFSIZE];
863809
let (_, sockaddr) = sock.peek_from(&mut netinbuf)?;
864810
sock.connect(&sockaddr)?;
865-
//.expect("connect error");
866811

867812
if opts.vflag {
868813
eprintln!("Connection from {:?} received!", sockaddr);
869814
}
870815

871-
// readwrite(&mut sock, opts);
872816
NcCore::run(&mut sock, opts)?;
873817
} else {
874818
debug_info(&format!("sock = {:?}", sock));
@@ -877,12 +821,11 @@ fn server(opts: &NcOptions) -> Result<(), MesaError> {
877821
eprintln!("Connection from {:?} received!", sockaddr);
878822
}
879823

880-
// readwrite(&mut sock_conn, opts);
881824
NcCore::run(&mut sock_conn, opts)?;
882-
883-
// sock_conn.shutdown(std::net::Shutdown::Both);
825+
// TODO: sock_conn.shutdown(std::net::Shutdown::Both);
884826
}
885827

828+
// TODO: implement
886829
// if opts.family != AF_UNIX {
887830

888831
// }
@@ -905,11 +848,9 @@ fn unix_connect(path: &str, opts: &NcOptions) -> Result<Socket, MesaError> {
905848
unix_bind(&opts.unix_dg_tmp_socket, opts)?
906849
} else {
907850
Socket::new(Domain::unix(), socket2::Type::stream(), None)?
908-
//.expect("failed to create unix socket")
909851
};
910852

911853
sock.connect(&socket2::SockAddr::unix(path)?)?;
912-
//.expect("invalid unix socket path")).expect("bind error");
913854

914855
Ok(sock)
915856
}
@@ -928,7 +869,6 @@ fn unix_client(opts: &NcOptions) -> Result<(), MesaError> {
928869

929870
if opts.uflag {
930871
std::fs::remove_file(&opts.unix_dg_tmp_socket)?;
931-
// .expect("failed to remove the unix tmp socket file");
932872
}
933873

934874
Ok(())
@@ -941,29 +881,21 @@ fn nonunix_client(opts: &NcOptions) -> Result<(), MesaError> {
941881
Err(_) => continue,
942882
};
943883

944-
// sock.set_nonblocking(true);
945-
946884
// if opts.vflag || opts.zflag {
947885
// // TODO: implement
948886
// }
949887

950888
// TODO: Fflag && !zflag
951-
// readwrite(&mut sock, opts);
952889
NcCore::run(&mut sock, opts)?;
953-
954890
}
955891
Ok(())
956892
}
957893

958-
959-
960894
pub fn execute<S, T>(_setup: &mut S, args: T) -> Result<(), MesaError>
961895
where
962896
S: UtilSetup,
963897
T: ArgsIter,
964898
{
965-
println!("this is netcat");
966-
967899
let mut help_msg: Vec<u8> = Vec::new();
968900
let app = util_app!(NAME)
969901
.arg(Arg::with_name("l")
@@ -995,28 +927,9 @@ where
995927
let help_msg = String::from_utf8(help_msg)?;
996928
let matches = app.get_matches_from_safe(args)?;
997929

998-
999930
// println!("matches = {:?}", matches);
1000931
let opts = NcOptions::parse(matches, &help_msg)?;
1001932

1002-
// println!("opts = {:?}", opts);
1003-
// if opts.is_none() {
1004-
// // app.write_help(&mut io::stdout());
1005-
// // print!("{}", help_msg);
1006-
// // return Err(failure::err_msg(help_msg));
1007-
// // return Err(OsString::from(help_msg));
1008-
// // return Err(MesaError::from(failure::err_msg("a").compat()));
1009-
1010-
// }
1011-
1012-
1013-
// let opts = match opts {
1014-
// Ok(opts) => opts,
1015-
// Err() => {
1016-
// return mesaerr_result(&help_msg);
1017-
// }
1018-
// };
1019-
1020933
if opts.lflag {
1021934
return server(&opts);
1022935
} else {

0 commit comments

Comments
 (0)