diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 7d85b45bb1..a7339d54e5 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -2,6 +2,10 @@ All notable changes to the Zowe CLI package will be documented in this file. +## Recent Changes + +- BugFix: Solved daemon issue where Windows usernames were treated as case-sensitive when checking the daemon process owner during Zowe commands. + ## `7.11.0` - Enhancement: Added support for a CLI specific environment variable file. [#1484](https://github.com/zowe/zowe-cli/issues/1484) - BugFix: Enabled option to download output from a submitted job with the -d flag. The -e flag now enables changes to file extension as originally intended. [#729](https://github.com/zowe/zowe-cli/issues/729) diff --git a/packages/cli/src/daemon/DaemonDecider.ts b/packages/cli/src/daemon/DaemonDecider.ts index 290c6e9a05..c521edcd4c 100644 --- a/packages/cli/src/daemon/DaemonDecider.ts +++ b/packages/cli/src/daemon/DaemonDecider.ts @@ -87,6 +87,9 @@ export class DaemonDecider { this.initialParse(); if (this.startServer) { this.mUser = os.userInfo().username; + if (process.platform === "win32") { + this.mUser = this.mUser.toLowerCase(); + } this.mServer = net.createServer((c) => { new DaemonClient(c, this.mServer, this.mUser).run(); }); diff --git a/zowex/Cargo.lock b/zowex/Cargo.lock index d7cd23ce90..72dff18ebc 100644 --- a/zowex/Cargo.lock +++ b/zowex/Cargo.lock @@ -448,7 +448,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "zowe" -version = "1.0.2" +version = "1.0.3" dependencies = [ "atty", "base64", diff --git a/zowex/Cargo.toml b/zowex/Cargo.toml index ad0eb9ed07..73f58132b7 100644 --- a/zowex/Cargo.toml +++ b/zowex/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zowe" -version = "1.0.2" +version = "1.0.3" authors = ["Zowe Project"] edition = "2018" license = "EPL-2.0" diff --git a/zowex/src/comm.rs b/zowex/src/comm.rs index a09441b303..bd95f4ed18 100644 --- a/zowex/src/comm.rs +++ b/zowex/src/comm.rs @@ -12,17 +12,14 @@ // Functions related to daemon cummunication. use std::io; -use std::io::BufReader; use std::io::prelude::*; +use std::io::BufReader; use std::str; use std::thread; use std::time::Duration; #[cfg(target_family = "unix")] -use { - std::net::Shutdown, - std::os::unix::net::UnixStream -}; +use {std::net::Shutdown, std::os::unix::net::UnixStream}; extern crate atty; use atty::Stream; @@ -31,25 +28,23 @@ extern crate base64; use base64::encode; #[cfg(target_family = "windows")] - extern crate named_pipe; +extern crate named_pipe; #[cfg(target_family = "windows")] - use named_pipe::PipeClient; +use named_pipe::PipeClient; extern crate rpassword; use rpassword::read_password; -extern crate whoami; -use whoami::username; - // Zowe daemon executable modules use crate::defs::*; use crate::proc::*; +use crate::util::util_get_username; #[cfg(target_family = "unix")] - type DaemonClient = UnixStream; +type DaemonClient = UnixStream; #[cfg(target_family = "windows")] - type DaemonClient = PipeClient; +type DaemonClient = PipeClient; /** * Attempt to make a TCP connection to the daemon. @@ -65,7 +60,10 @@ use crate::proc::*; * A Result containing a stream upon success. * This function exits the process upon error. */ -pub fn comm_establish_connection(njs_zowe_path: &str, daemon_socket: &str) -> io::Result { +pub fn comm_establish_connection( + njs_zowe_path: &str, + daemon_socket: &str, +) -> io::Result { const RETRY_TO_SHOW_DIAG: i32 = 5; let mut conn_retries = 0; @@ -89,7 +87,8 @@ pub fn comm_establish_connection(njs_zowe_path: &str, daemon_socket: &str) -> io we_started_daemon = true; cmd_to_show = proc_start_daemon(njs_zowe_path); } else if we_started_daemon && conn_retries > THREE_MIN_OF_RETRIES { - println!("The Zowe daemon that we started is not running on socket: {}.", + println!( + "The Zowe daemon that we started is not running on socket: {}.", daemon_socket ); println!( @@ -101,7 +100,10 @@ pub fn comm_establish_connection(njs_zowe_path: &str, daemon_socket: &str) -> io } if conn_retries > THREE_MIN_OF_RETRIES { - println!("Terminating after {} connection retries.", THREE_MIN_OF_RETRIES); + println!( + "Terminating after {} connection retries.", + THREE_MIN_OF_RETRIES + ); std::process::exit(EXIT_CODE_CANNOT_CONNECT_TO_RUNNING_DAEMON); } @@ -116,7 +118,8 @@ pub fn comm_establish_connection(njs_zowe_path: &str, daemon_socket: &str) -> io } else { println!("Command = {}", daemon_proc_info.cmd); } - println!("Process name = {} pid = {} socket = {}\n", + println!( + "Process name = {} pid = {} socket = {}\n", daemon_proc_info.name, daemon_proc_info.pid, daemon_socket ); } @@ -127,7 +130,10 @@ pub fn comm_establish_connection(njs_zowe_path: &str, daemon_socket: &str) -> io "Attempting to connect to the Zowe daemon" }; if conn_retries > 0 { - println!("{} ({} of {})", retry_msg, conn_retries, THREE_MIN_OF_RETRIES); + println!( + "{} ({} of {})", + retry_msg, conn_retries, THREE_MIN_OF_RETRIES + ); } conn_retries += 1; }; @@ -187,18 +193,16 @@ pub fn comm_talk(message: &[u8], stream: &mut DaemonClient) -> io::Result { io::stderr().flush().unwrap(); } continue; - }, - result => { - match result { - Ok(ok_val) => { - p = ok_val; - }, - Err(err_val) => { - eprintln!("You may be running mismatched versions of Zowe executable and Zowe daemon."); - return Err(std::io::Error::new(std::io::ErrorKind::Other, err_val)) - } - } } + result => match result { + Ok(ok_val) => { + p = ok_val; + } + Err(err_val) => { + eprintln!("You may be running mismatched versions of Zowe executable and Zowe daemon."); + return Err(std::io::Error::new(std::io::ErrorKind::Other, err_val)); + } + }, }; if let Some(s) = p.stdout { @@ -225,6 +229,8 @@ pub fn comm_talk(message: &[u8], stream: &mut DaemonClient) -> io::Result { reply = Some(read_password().unwrap()); } + let executor = util_get_username(); + if let Some(s) = reply { let response: DaemonResponse = DaemonResponse { argv: None, @@ -232,7 +238,7 @@ pub fn comm_talk(message: &[u8], stream: &mut DaemonClient) -> io::Result { env: None, stdinLength: None, stdin: Some(s), - user: Some(encode(username())), + user: Some(encode(executor)), }; let v = serde_json::to_string(&response)?; #[cfg(target_family = "unix")] @@ -254,8 +260,8 @@ pub fn comm_talk(message: &[u8], stream: &mut DaemonClient) -> io::Result { // end of reading break; } - }, - Err(err_val) => { return Err(err_val) } + } + Err(err_val) => return Err(err_val), } // end match on read } // end loop diff --git a/zowex/src/defs.rs b/zowex/src/defs.rs index 4bd739a2da..f4c410013b 100644 --- a/zowex/src/defs.rs +++ b/zowex/src/defs.rs @@ -69,18 +69,18 @@ pub struct DaemonResponse { #[derive(Deserialize)] pub struct DaemonPidForUser { pub user: String, - pub pid: i32 + pub pid: i32, } pub enum CmdShell { - Bash, // Bourne Again SHell - Sh, // Standard Linux shell - Korn, // Korn shell - Zshell, // Z shell - Cshell, // C shell - Tenex, // TENEX C shell - PowerShellDotNet, // Newer cross-platform .NET Core PowerShell - PowerShellExe, // Legacy Windows executable PowerShell (version 5.x) - WindowsCmd, // Classic Windows CMD shell - Unknown // A command shell that we do not yet understand + Bash, // Bourne Again SHell + Sh, // Standard Linux shell + Korn, // Korn shell + Zshell, // Z shell + Cshell, // C shell + Tenex, // TENEX C shell + PowerShellDotNet, // Newer cross-platform .NET Core PowerShell + PowerShellExe, // Legacy Windows executable PowerShell (version 5.x) + WindowsCmd, // Classic Windows CMD shell + Unknown, // A command shell that we do not yet understand } diff --git a/zowex/src/main.rs b/zowex/src/main.rs index 47f39c1b87..a2c202556c 100644 --- a/zowex/src/main.rs +++ b/zowex/src/main.rs @@ -13,8 +13,8 @@ use std::env; use std::io; // other source modules that constitute this executable -mod defs; mod comm; +mod defs; mod proc; mod run; mod util; @@ -49,11 +49,11 @@ fn main() -> io::Result<()> { */ let exit_code: i32 = match run_zowe_command(&mut cmd_line_args) { Ok(ok_val) => ok_val, - Err(err_val) => err_val + Err(err_val) => err_val, }; /* Rust does not enable main() to return an exit code. * Thus, we explicitly exit the process with our desired exit code. */ std::process::exit(exit_code); -} \ No newline at end of file +} diff --git a/zowex/src/proc.rs b/zowex/src/proc.rs index 158e851e39..59465540d3 100644 --- a/zowex/src/proc.rs +++ b/zowex/src/proc.rs @@ -14,8 +14,8 @@ use std::env; use std::fs::File; use std::io::BufReader; -use std::process::{Command, Stdio}; use std::path::PathBuf; +use std::process::{Command, Stdio}; extern crate sysinfo; use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt}; @@ -23,9 +23,6 @@ use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt}; extern crate simple_error; use simple_error::SimpleError; -extern crate whoami; -use whoami::username; - // Zowe daemon executable modules use crate::defs::*; use crate::util::*; @@ -56,7 +53,9 @@ pub fn proc_get_cmd_shell() -> Result<(CmdShell, String), SimpleError> { let my_parent_pid: Pid = match process.parent() { Some(parent_id) => parent_id, None => { - return Err(SimpleError::new("Got invalid parent process ID from the process list.")); + return Err(SimpleError::new( + "Got invalid parent process ID from the process list.", + )); } }; @@ -70,53 +69,46 @@ pub fn proc_get_cmd_shell() -> Result<(CmdShell, String), SimpleError> { // Set any known command shell name if cmd_shell_nm.to_lowercase().starts_with("bash") { cmd_shell_type = CmdShell::Bash; - } else if cmd_shell_nm.to_lowercase().starts_with("sh") { - cmd_shell_type = CmdShell::Sh; - + cmd_shell_type = CmdShell::Sh; } else if cmd_shell_nm.to_lowercase().starts_with("ksh") { cmd_shell_type = CmdShell::Korn; - } else if cmd_shell_nm.to_lowercase().starts_with("zsh") { cmd_shell_type = CmdShell::Zshell; - } else if cmd_shell_nm.to_lowercase().starts_with("csh") { cmd_shell_type = CmdShell::Cshell; - } else if cmd_shell_nm.to_lowercase().starts_with("tcsh") { cmd_shell_type = CmdShell::Tenex; - } else if cmd_shell_nm.to_lowercase().starts_with("pwsh") { cmd_shell_type = CmdShell::PowerShellDotNet; - } else if cmd_shell_nm.to_lowercase().starts_with("powershell") { cmd_shell_type = CmdShell::PowerShellExe; - } else if cmd_shell_nm.to_lowercase().starts_with("cmd") { cmd_shell_type = CmdShell::WindowsCmd; - } else { cmd_shell_type = CmdShell::Unknown; } // after we find our parent pid, stop seaching process list break; - } // end found our parent process ID } // end iteration of process list to find our parent if !found_parent_pid { - return Err(SimpleError::new("Unable to find our parent process in the process list.")); + return Err(SimpleError::new( + "Unable to find our parent process in the process list.", + )); } // after we find my_pid, stop seaching process list break; - } // end found our own process ID - } // end iteration of process list to find our own process + } // end iteration of process list to find our own process if !found_my_pid { - return Err(SimpleError::new("Unable to find our current process in the process list.")); + return Err(SimpleError::new( + "Unable to find our current process in the process list.", + )); } Ok((cmd_shell_type, cmd_shell_nm)) @@ -142,10 +134,10 @@ pub fn proc_get_daemon_info() -> DaemonProcInfo { sys.refresh_all(); for (next_pid, next_process) in sys.processes() { // is this a zowe daemon process? - if next_process.name().to_lowercase().contains("node") && - next_process.cmd().len() > 2 && - next_process.cmd()[1].to_lowercase().contains("zowe") && - next_process.cmd()[2].to_lowercase() == LAUNCH_DAEMON_OPTION + if next_process.name().to_lowercase().contains("node") + && next_process.cmd().len() > 2 + && next_process.cmd()[1].to_lowercase().contains("zowe") + && next_process.cmd()[2].to_lowercase() == LAUNCH_DAEMON_OPTION { // ensure we have found the daemon for the current user if my_daemon_pid_opt.is_some() && &my_daemon_pid_opt.unwrap() == next_pid { @@ -186,7 +178,9 @@ fn read_pid_for_user() -> Option { let mut pid_file_path: PathBuf; match util_get_daemon_dir() { Ok(ok_val) => pid_file_path = ok_val, - Err(_err_val) => { return None; } + Err(_err_val) => { + return None; + } } pid_file_path.push("daemon_pid.json"); @@ -200,8 +194,10 @@ fn read_pid_for_user() -> Option { Ok(ok_val) => ok_val, Err(err_val) => { // we should not continue if we cannot open an existing pid file - println!("Unable to open file = {}\nDetails = {}", - pid_file_path.display(), err_val + println!( + "Unable to open file = {}\nDetails = {}", + pid_file_path.display(), + err_val ); std::process::exit(EXIT_CODE_FILE_IO_ERROR); } @@ -211,17 +207,24 @@ fn read_pid_for_user() -> Option { Ok(ok_val) => ok_val, Err(err_val) => { // we should not continue if we cannot read an existing pid file - println!("Unable to read file = {}\nDetails = {}", - pid_file_path.display(), err_val + println!( + "Unable to read file = {}\nDetails = {}", + pid_file_path.display(), + err_val ); std::process::exit(EXIT_CODE_FILE_IO_ERROR); } }; - if daemon_pid_for_user.user != username() { + let executor = util_get_username(); + + if daemon_pid_for_user.user != executor { // our pid file should only contain our own user name - println!("User name of '{}' in file '{}' does not match current user = '{}'.", - daemon_pid_for_user.user, pid_file_path.display(), username() + println!( + "User name of '{}' in file '{}' does not match current user = '{}'.", + daemon_pid_for_user.user, + pid_file_path.display(), + executor ); std::process::exit(EXIT_CODE_CANT_CONVERT_JSON); } diff --git a/zowex/src/run.rs b/zowex/src/run.rs index 9777d42c79..a121a1a777 100644 --- a/zowex/src/run.rs +++ b/zowex/src/run.rs @@ -24,22 +24,16 @@ use std::time::Duration; use atty::Stream; use base64::encode; -extern crate whoami; -use whoami::username; - #[cfg(target_family = "windows")] - extern crate home; +extern crate fslock; #[cfg(target_family = "windows")] - extern crate fslock; +extern crate home; #[cfg(target_family = "windows")] - use { - fslock::LockFile, - std::fs::File - }; +use {fslock::LockFile, std::fs::File}; // Zowe daemon executable modules -use crate::defs::*; use crate::comm::*; +use crate::defs::*; use crate::proc::*; use crate::util::*; @@ -72,9 +66,9 @@ pub fn run_zowe_command(zowe_cmd_args: &mut Vec) -> Result { } // These commands must be run by a background script. - if zowe_cmd_args.len() >= 2 && - zowe_cmd_args[0] == "daemon" && - (zowe_cmd_args[1] == "enable" || zowe_cmd_args[1] == "disable") + if zowe_cmd_args.len() >= 2 + && zowe_cmd_args[0] == "daemon" + && (zowe_cmd_args[1] == "enable" || zowe_cmd_args[1] == "disable") { return run_delayed_zowe_command(&njs_zowe_path, zowe_cmd_args); } @@ -138,9 +132,7 @@ fn run_nodejs_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) -> R .stderr(Stdio::inherit()) .output() { - Ok(new_proc) => { - new_proc.status.code().unwrap() - } + Ok(new_proc) => new_proc.status.code().unwrap(), Err(error) => { println!("Failed to run the following command:"); println!( @@ -188,10 +180,12 @@ fn run_delayed_zowe_command(njs_zowe_path: &str, zowe_cmd_args: &[String]) -> Re println!("{} Terminating.", error); return Err(EXIT_CODE_CANT_FIND_CMD_SHELL); } - }; if matches!(curr_cmd_shell, CmdShell::Unknown) { - println!("The command shell process named '{}' is unknown to the Zowe CLI. Terminating.", cmd_shell_nm); + println!( + "The command shell process named '{}' is unknown to the Zowe CLI. Terminating.", + cmd_shell_nm + ); return Err(EXIT_CODE_UNKNOWN_CMD_SHELL); } @@ -203,14 +197,20 @@ fn run_delayed_zowe_command(njs_zowe_path: &str, zowe_cmd_args: &[String]) -> Re // form the command script that we will launch let cmd_shell_to_launch: String = form_cmd_script_arg_vec( - zowe_cmd_args, njs_zowe_path, & curr_cmd_shell, - &mut script_string, &mut script_arg_vec + zowe_cmd_args, + njs_zowe_path, + &curr_cmd_shell, + &mut script_string, + &mut script_arg_vec, ); // The following line gives useful debugging info when it is uncommented. // println!("script_arg_vec = {:?}", script_arg_vec); - println!("The '{}' command will run in the background ...", arg_vec_to_string(zowe_cmd_args)); + println!( + "The '{}' command will run in the background ...", + arg_vec_to_string(zowe_cmd_args) + ); let run_result: Result = match Command::new(cmd_shell_to_launch) .args(script_arg_vec) .stdin(Stdio::inherit()) @@ -218,9 +218,7 @@ fn run_delayed_zowe_command(njs_zowe_path: &str, zowe_cmd_args: &[String]) -> Re .stderr(Stdio::inherit()) .spawn() { - Ok(..) => { - Ok(EXIT_CODE_SUCCESS) - } + Ok(..) => Ok(EXIT_CODE_SUCCESS), Err(err_val) => { println!("Failed to run the following command:"); println!( @@ -247,7 +245,10 @@ fn run_delayed_zowe_command(njs_zowe_path: &str, zowe_cmd_args: &[String]) -> Re * @returns * An empty Result upon success. Otherwise an error Result. */ -pub fn run_daemon_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) -> Result { +pub fn run_daemon_command( + njs_zowe_path: &str, + zowe_cmd_args: &mut Vec, +) -> Result { let cwd: PathBuf = match env::current_dir() { Ok(ok_val) => ok_val, Err(err_val) => { @@ -264,28 +265,31 @@ pub fn run_daemon_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) } } + let executor = util_get_username(); + // create the response structure for this message - let response: DaemonResponse = if !zowe_cmd_args.is_empty() && zowe_cmd_args[0] == SHUTDOWN_REQUEST { - // Sending Control-C shutdown request - let control_c: String = "\x03".to_string(); - DaemonResponse { - argv: None, - cwd: None, - env: None, - stdinLength: Some(0), - stdin: Some(control_c), - user: Some(encode(username())), - } - } else { - DaemonResponse { - argv: Some(zowe_cmd_args.to_vec()), - cwd: Some(cwd.into_os_string().into_string().unwrap()), - env: Some(util_get_zowe_env()), - stdinLength: Some(stdin.len() as i32), - stdin: None, - user: Some(encode(username())), - } - }; + let response: DaemonResponse = + if !zowe_cmd_args.is_empty() && zowe_cmd_args[0] == SHUTDOWN_REQUEST { + // Sending Control-C shutdown request + let control_c: String = "\x03".to_string(); + DaemonResponse { + argv: None, + cwd: None, + env: None, + stdinLength: Some(0), + stdin: Some(control_c), + user: Some(encode(executor)), + } + } else { + DaemonResponse { + argv: Some(zowe_cmd_args.to_vec()), + cwd: Some(cwd.into_os_string().into_string().unwrap()), + env: Some(util_get_zowe_env()), + stdinLength: Some(stdin.len() as i32), + stdin: None, + user: Some(encode(executor)), + } + }; let mut _resp: Vec; match serde_json::to_vec(&response) { @@ -295,7 +299,7 @@ pub fn run_daemon_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) _resp.push(b'\x0c'); _resp.append(&mut stdin); } - }, + } Err(err_val) => { println!("Failed convert response to JSON\nDetails = {}", err_val); return Err(EXIT_CODE_CANT_CONVERT_JSON); @@ -305,7 +309,7 @@ pub fn run_daemon_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) let mut tries = 0; let socket_string: String = match util_get_socket_string() { Ok(ok_val) => ok_val, - Err(err_val) => return Err(err_val) + Err(err_val) => return Err(err_val), }; #[cfg(target_family = "windows")] @@ -319,19 +323,27 @@ pub fn run_daemon_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) match lock_file.try_lock() { Ok(result) if !result => { if tries > THREE_MIN_OF_RETRIES { - println!("Terminating after {} connection retries.", THREE_MIN_OF_RETRIES); + println!( + "Terminating after {} connection retries.", + THREE_MIN_OF_RETRIES + ); return Err(EXIT_CODE_TIMEOUT_CONNECT_TO_RUNNING_DAEMON); } tries += 1; - println!("The Zowe daemon is in use, retrying ({} of {})", tries, THREE_MIN_OF_RETRIES); + println!( + "The Zowe daemon is in use, retrying ({} of {})", + tries, THREE_MIN_OF_RETRIES + ); // pause between attempts to connect thread::sleep(Duration::from_secs(THREE_SEC_DELAY)); continue; - }, - Ok(_result) => { locked = true; }, - Err (ref e) => { + } + Ok(_result) => { + locked = true; + } + Err(ref e) => { println!("Problem acquiring lock: {:?}", e); return Err(EXIT_CODE_CANNOT_ACQUIRE_LOCK); } @@ -342,7 +354,10 @@ pub fn run_daemon_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) match comm_establish_connection(njs_zowe_path, &socket_string) { Ok(ok_val) => stream = ok_val, Err(err_val) => { - println!("Unable to establish communication with daemon.\nDetails = {}", err_val); + println!( + "Unable to establish communication with daemon.\nDetails = {}", + err_val + ); return Err(EXIT_CODE_COMM_IO_ERROR); } } @@ -350,21 +365,30 @@ pub fn run_daemon_command(njs_zowe_path: &str, zowe_cmd_args: &mut Vec) match comm_talk(&_resp, &mut stream) { Ok(ok_val) => { return Ok(ok_val); - }, + } Err(ref err_val) => { if err_val.kind() == io::ErrorKind::ConnectionReset { if tries > THREE_MIN_OF_RETRIES { - println!("Terminating after {} connection retries.", THREE_MIN_OF_RETRIES); + println!( + "Terminating after {} connection retries.", + THREE_MIN_OF_RETRIES + ); return Err(EXIT_CODE_TIMEOUT_CONNECT_TO_RUNNING_DAEMON); } tries += 1; - println!("The Zowe daemon is in use, retrying ({} of {})", tries, THREE_MIN_OF_RETRIES); + println!( + "The Zowe daemon is in use, retrying ({} of {})", + tries, THREE_MIN_OF_RETRIES + ); // pause between attempts to connect thread::sleep(Duration::from_secs(THREE_SEC_DELAY)); } else { - println!("I/O error during daemon communication.\nDetails = {}", err_val); + println!( + "I/O error during daemon communication.\nDetails = {}", + err_val + ); return Err(EXIT_CODE_COMM_IO_ERROR); } } @@ -430,26 +454,31 @@ fn arg_vec_to_string(arg_vec: &[String]) -> String { fn form_cmd_script_arg_vec<'a>( zowe_cmd_args: &'a [String], njs_zowe_path: &'a str, - curr_cmd_shell: & CmdShell, + curr_cmd_shell: &CmdShell, script_string: &'a mut String, - script_arg_vec: &mut Vec<&'a str> + script_arg_vec: &mut Vec<&'a str>, ) -> String { const SCRIPT_WAIT_MSG: &str = "echo Wait to see the results below ... "; const SCRIPT_PROMPT_MSG_FIXED: &str = "echo Now press ENTER to see your command "; - if env::consts::OS == "windows" - { + if env::consts::OS == "windows" { return form_win_cmd_script_arg_vec( - zowe_cmd_args, njs_zowe_path, curr_cmd_shell, - SCRIPT_WAIT_MSG, SCRIPT_PROMPT_MSG_FIXED, - script_arg_vec + zowe_cmd_args, + njs_zowe_path, + curr_cmd_shell, + SCRIPT_WAIT_MSG, + SCRIPT_PROMPT_MSG_FIXED, + script_arg_vec, ); } form_bash_cmd_script_arg_vec( - zowe_cmd_args, njs_zowe_path, script_string, - SCRIPT_WAIT_MSG, SCRIPT_PROMPT_MSG_FIXED, - script_arg_vec + zowe_cmd_args, + njs_zowe_path, + script_string, + SCRIPT_WAIT_MSG, + SCRIPT_PROMPT_MSG_FIXED, + script_arg_vec, ) } @@ -485,7 +514,7 @@ fn form_bash_cmd_script_arg_vec<'a>( script_string: &'a mut String, script_wait_msg: &'a str, script_prompt_msg_fixed: &'a str, - script_arg_vec: &mut Vec<&'a str> + script_arg_vec: &mut Vec<&'a str>, ) -> String { // -c goes into the first argument script_arg_vec.push("-c"); @@ -545,23 +574,25 @@ fn form_bash_cmd_script_arg_vec<'a>( fn form_win_cmd_script_arg_vec<'a>( zowe_cmd_args: &'a [String], njs_zowe_path: &'a str, - curr_cmd_shell: & CmdShell, + curr_cmd_shell: &CmdShell, script_wait_msg: &'a str, script_prompt_msg_fixed: &'a str, - script_arg_vec: &mut Vec<&'a str> + script_arg_vec: &mut Vec<&'a str>, ) -> String { // add any required newlines to create some space script_arg_vec.push("/C"); script_arg_vec.push("echo."); script_arg_vec.push("&&"); - if matches!(curr_cmd_shell, CmdShell::PowerShellDotNet | CmdShell::PowerShellExe) { + if matches!( + curr_cmd_shell, + CmdShell::PowerShellDotNet | CmdShell::PowerShellExe + ) { // PowerShell needs extra newlines before the background process output to create space - for _count in [1,2,3,4,5,6] { + for _count in [1, 2, 3, 4, 5, 6] { script_arg_vec.push("echo."); script_arg_vec.push("&&"); } - } else if matches!(curr_cmd_shell, CmdShell::Bash | CmdShell::Sh) { // Bash shell on windows needs a delay and a newline in its spacing for next_arg in "sleep 1 && echo. &&".split_whitespace() { @@ -591,7 +622,10 @@ fn form_win_cmd_script_arg_vec<'a>( for next_arg in script_prompt_msg_fixed.split_whitespace() { script_arg_vec.push(next_arg); } - if matches!(curr_cmd_shell, CmdShell::PowerShellDotNet | CmdShell::PowerShellExe) { + if matches!( + curr_cmd_shell, + CmdShell::PowerShellDotNet | CmdShell::PowerShellExe + ) { // tell user that prompt will appear in the provided space for next_arg in "prompt in the space above.".split_whitespace() { script_arg_vec.push(next_arg); @@ -609,19 +643,25 @@ fn get_win_lock_file() -> Result { let mut lock_path: PathBuf; match util_get_daemon_dir() { Ok(ok_val) => lock_path = ok_val, - Err(err_val) => return Err(err_val) + Err(err_val) => return Err(err_val), } lock_path.push("daemon.lock"); if let Err(err_val) = File::create(&lock_path) { - println!("Unable to create zowe daemon lock file = {}.", &lock_path.display()); + println!( + "Unable to create zowe daemon lock file = {}.", + &lock_path.display() + ); println!("Reason = {}.", err_val); return Err(EXIT_CODE_FILE_IO_ERROR); } let lock_file: LockFile = match LockFile::open(&lock_path) { Ok(ok_val) => ok_val, Err(err_val) => { - println!("Unable to open zowe daemon lock file = {}.", &lock_path.display()); + println!( + "Unable to open zowe daemon lock file = {}.", + &lock_path.display() + ); println!("Reason = {}.", err_val); return Err(EXIT_CODE_FILE_IO_ERROR); } diff --git a/zowex/src/test.rs b/zowex/src/test.rs index 62ab4ac16c..6abb49f209 100644 --- a/zowex/src/test.rs +++ b/zowex/src/test.rs @@ -17,9 +17,9 @@ use std::thread; use std::time::Duration; #[cfg(target_family = "unix")] - use home::home_dir; +use home::home_dir; #[cfg(target_family = "windows")] - use whoami::username; +use whoami::username; // Zowe daemon executable modules use crate::defs::*; @@ -35,27 +35,40 @@ fn unit_test_util_get_socket_string() { match util_get_socket_string() { #[cfg(target_family = "windows")] Ok(ok_val) => { - let expected_pipe_path: String = format!("\\\\.\\pipe\\{}\\{}", username(), "ZoweDaemon"); - println!("--- test_util_get_socket_string: ok_val = {} expected_pipe_path = {}", ok_val, expected_pipe_path); + let expected_pipe_path: String = + format!("\\\\.\\pipe\\{}\\{}", util_get_username(), "ZoweDaemon"); + println!( + "--- test_util_get_socket_string: ok_val = {} expected_pipe_path = {}", + ok_val, expected_pipe_path + ); assert!(ok_val.contains(&expected_pipe_path)); } #[cfg(target_family = "unix")] Ok(ok_val) => { let mut expected_sock_path: String = "NotYetInitialized".to_string(); match home_dir() { - Some(path_buf_val) => expected_sock_path = format!("{}/.zowe/daemon/daemon.sock", path_buf_val.display()), + Some(path_buf_val) => { + expected_sock_path = + format!("{}/.zowe/daemon/daemon.sock", path_buf_val.display()) + } None => { - assert_eq!("util_get_socket_string should have gotten user home dir", + assert_eq!( + "util_get_socket_string should have gotten user home dir", "It got None" ); } } - println!("--- test_util_get_socket_string: ok_val = {} expected_sock_path = {}", ok_val, expected_sock_path); + println!( + "--- test_util_get_socket_string: ok_val = {} expected_sock_path = {}", + ok_val, expected_sock_path + ); assert!(ok_val.contains(&expected_sock_path)); } Err(err_val) => { - assert_eq!("util_get_socket_string should have worked", - "It Failed", "exit code = {}", err_val + assert_eq!( + "util_get_socket_string should have worked", "It Failed", + "exit code = {}", + err_val ); } } @@ -69,8 +82,10 @@ fn unit_test_util_get_socket_string() { assert!(ok_val.contains("\\\\.\\pipe\\FakePipePath")); } Err(err_val) => { - assert_eq!("util_get_socket_string should have worked", - "It Failed", "exit code = {}", err_val + assert_eq!( + "util_get_socket_string should have worked", "It Failed", + "exit code = {}", + err_val ); } } @@ -86,8 +101,10 @@ fn unit_test_util_get_socket_string() { assert!(ok_val.contains("/.zowe/daemon_test_dir/daemon.sock")); } Err(err_val) => { - assert_eq!("util_get_socket_string should have worked", - "It Failed", "exit code = {}", err_val + assert_eq!( + "util_get_socket_string should have worked", "It Failed", + "exit code = {}", + err_val ); } } @@ -117,12 +134,19 @@ fn integration_test_restart() { println!("--- test_restart: To initializes test, stop a running daemon."); let mut restart_cmd_args: Vec = vec![SHUTDOWN_REQUEST.to_string()]; if let Err(err_val) = run_daemon_command(&njs_zowe_path, &mut restart_cmd_args) { - assert_eq!("Shutdown should have worked", "Shutdown failed", "exit code = {}", err_val); + assert_eq!( + "Shutdown should have worked", "Shutdown failed", + "exit code = {}", + err_val + ); } // confirm that the daemon has stopped daemon_proc_info = proc_get_daemon_info(); - assert_eq!(daemon_proc_info.is_running, false, "The daemon did not stop."); + assert_eq!( + daemon_proc_info.is_running, false, + "The daemon did not stop." + ); } // now try the restart @@ -133,7 +157,10 @@ fn integration_test_restart() { // confirm that the daemon is running thread::sleep(Duration::from_secs(START_STOP_DELAY)); daemon_proc_info = proc_get_daemon_info(); - assert_eq!(daemon_proc_info.is_running, true, "The daemon is not running after restart."); + assert_eq!( + daemon_proc_info.is_running, true, + "The daemon is not running after restart." + ); let first_daemon_pid = daemon_proc_info.pid; println!("--- test_restart: Run a restart with a daemon already running."); @@ -143,9 +170,14 @@ fn integration_test_restart() { // confirm that a new and different daemon is running thread::sleep(Duration::from_secs(START_STOP_DELAY)); daemon_proc_info = proc_get_daemon_info(); - assert_eq!(daemon_proc_info.is_running, true, "A daemon should be running now."); - assert_ne!(daemon_proc_info.pid, first_daemon_pid, - "Last pid = {} should not equal current PID = {}", first_daemon_pid, daemon_proc_info.pid, + assert_eq!( + daemon_proc_info.is_running, true, + "A daemon should be running now." + ); + assert_ne!( + daemon_proc_info.pid, first_daemon_pid, + "Last pid = {} should not equal current PID = {}", + first_daemon_pid, daemon_proc_info.pid, ); // As a cleanup step, stop the daemon @@ -158,6 +190,8 @@ fn integration_test_restart() { // confirm that the daemon has stopped thread::sleep(Duration::from_secs(START_STOP_DELAY)); daemon_proc_info = proc_get_daemon_info(); - assert_eq!(daemon_proc_info.is_running, false, "The daemon should have stopped for the end of the test."); + assert_eq!( + daemon_proc_info.is_running, false, + "The daemon should have stopped for the end of the test." + ); } - diff --git a/zowex/src/util.rs b/zowex/src/util.rs index 3288399b1b..7ab2c302ed 100644 --- a/zowex/src/util.rs +++ b/zowex/src/util.rs @@ -21,15 +21,12 @@ use home::home_dir; extern crate pathsearch; use pathsearch::PathSearcher; -#[cfg(target_family = "windows")] - extern crate whoami; -#[cfg(target_family = "windows")] - use whoami::username; +extern crate whoami; +use whoami::username; // Zowe daemon executable modules use crate::defs::*; - /** * Get the file path to the command that runs the NodeJS version of Zowe. * @@ -58,11 +55,7 @@ pub fn util_get_nodejs_zowe_path() -> String { let mut njs_zowe_path: String = NOT_FOUND.to_string(); let path = env::var_os("PATH"); let path_ext = env::var_os("PATHEXT"); - for njs_zowe_path_buf in PathSearcher::new( - zowe_cmd, - path.as_deref(), - path_ext.as_deref(), - ) { + for njs_zowe_path_buf in PathSearcher::new(zowe_cmd, path.as_deref(), path_ext.as_deref()) { njs_zowe_path = njs_zowe_path_buf.to_string_lossy().to_string(); if njs_zowe_path.to_lowercase().eq(&my_exe_path.to_lowercase()) { // We do not want our own rust executable. Keep searching. @@ -107,7 +100,10 @@ pub fn util_get_daemon_dir() -> Result { if !daemon_dir.exists() { if let Err(err_val) = std::fs::create_dir_all(&daemon_dir) { - println!("Unable to create zowe daemon directory = {}.", &daemon_dir.display()); + println!( + "Unable to create zowe daemon directory = {}.", + &daemon_dir.display() + ); println!("Reason = {}.", err_val); return Err(EXIT_CODE_FILE_IO_ERROR); } @@ -121,7 +117,7 @@ pub fn util_get_socket_string() -> Result { let mut socket_path: PathBuf; match util_get_daemon_dir() { Ok(ok_val) => socket_path = ok_val, - Err(err_val) => return Err(err_val) + Err(err_val) => return Err(err_val), } socket_path.push("daemon.sock"); Ok(socket_path.into_os_string().into_string().unwrap()) @@ -129,7 +125,7 @@ pub fn util_get_socket_string() -> Result { #[cfg(target_family = "windows")] pub fn util_get_socket_string() -> Result { - let mut _socket = format!("\\\\.\\pipe\\{}\\{}", username(), "ZoweDaemon"); + let mut _socket = format!("\\\\.\\pipe\\{}\\{}", util_get_username(), "ZoweDaemon"); if let Ok(pipe_name) = env::var("ZOWE_DAEMON_PIPE") { _socket = format!("\\\\.\\pipe\\{}", pipe_name); @@ -138,7 +134,17 @@ pub fn util_get_socket_string() -> Result { } pub fn util_get_zowe_env() -> HashMap { - env::vars().filter(|&(ref k, _)| - k.starts_with("ZOWE_") - ).collect() + env::vars() + .filter(|(k, _)| k.starts_with("ZOWE_")) + .collect() +} + +#[cfg(target_family = "windows")] +pub fn util_get_username() -> String { + username().to_lowercase() +} + +#[cfg(not(target_family = "windows"))] +pub fn util_get_username() -> String { + username() }