Fix: Can't get error from shell

This commit is contained in:
anseki 2015-03-04 02:30:41 +09:00
parent 9e8a318880
commit fc50c96368
5 changed files with 99 additions and 56 deletions

View file

@ -1,9 +1,13 @@
@echo off @echo off
setlocal setlocal
setlocal ENABLEDELAYEDEXPANSION
if "%1"=="noechoback" ( if "%1"=="noechoback" (
call :exprog call :exprog
if ERRORLEVEL 1 exit /b 1
) else ( ) else (
set /p INPUT=<CON >CON set /p INPUT=<CON >CON
if ERRORLEVEL 1 exit /b 1
) )
set /p ="'%INPUT%'"<NUL set /p ="'%INPUT%'"<NUL
endlocal endlocal
@ -12,19 +16,27 @@ exit /b 0
:exprog :exprog
:: where /q powershell :: where /q powershell
:: Win <Vista and <Server2008 don't have `WHERE`. :: Win <Vista and <Server2008 don't have `where`.
powershell /? >NUL 2>&1 powershell /? >NUL 2>&1
:: Win <7 and <Server2008R2 don't have PowerShell as default. :: Win <7 and <Server2008R2 don't have PowerShell as default.
:: Win XP and Server2003 have `ScriptPW` (`scriptpw.dll`). :: Win XP and Server2003 have `ScriptPW` (`scriptpw.dll`).
:: In the systems that don't have both, an error is thrown. :: In the systems that don't have both, an error is thrown.
if errorlevel 1 ( if ERRORLEVEL 1 (
set "EXCOMMAND=cscript //nologo "%~dp0read.cs.js"" set "EXECOMMAND=cscript //nologo "%~dp0read.cs.js""
) else ( ) else (
set "EXCOMMAND=powershell -Command "$text = read-host -AsSecureString; ^ set "EXECOMMAND=powershell -Command "$text = read-host -AsSecureString; ^
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR^($text^); ^ $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR^($text^); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto^($BSTR^)"" [System.Runtime.InteropServices.Marshal]::PtrToStringAuto^($BSTR^)""
) )
:: echo %EXCOMMAND%
for /f "usebackq delims=" %%i in (`%EXCOMMAND%`) do set "INPUT=%%i" :: Can't get `ERRORLEVEL` from sub-shell (`for`).
exit /b :: 2 `%ERRCODE%` lines are returned if an error is thrown.
set ERRCODE=ERR
set "EXECOMMAND=%EXECOMMAND% ^& if ERRORLEVEL 1 ^(echo %ERRCODE%^& echo %ERRCODE%^)"
:: echo %EXECOMMAND%
for /f "usebackq delims=" %%i in (`%EXECOMMAND%`) do (
if "%%i"=="%ERRCODE%" if "!INPUT!"=="%ERRCODE%" exit /b 1
set "INPUT=%%i"
)
exit /b 0

View file

@ -1,4 +1,14 @@
/* global WScript:false */
var oExec; var oExec;
WScript.StdOut.Write(WScript.CreateObject('ScriptPW.Password').GetPassword());
// exit-code is not returned even if an error is thrown.
try {
WScript.StdOut.Write(WScript.CreateObject('ScriptPW.Password').GetPassword());
} catch (e) {
WScript.StdErr.Write(e.description);
WScript.Quit(1);
}
oExec = WScript.CreateObject('WScript.Shell').Exec('cmd /c echo; >CON'); oExec = WScript.CreateObject('WScript.Shell').Exec('cmd /c echo; >CON');
while (oExec.Status === 0) { WScript.Sleep(100); } while (oExec.Status === 0) { WScript.Sleep(100); }

View file

@ -1,24 +1,23 @@
silentRead() { silent_read() {
stty --file=/dev/tty -echo echonl 2>/dev/null || \ stty --file=/dev/tty -echo echonl 2>/dev/null || \
stty -F /dev/tty -echo echonl 2>/dev/null || \ stty -F /dev/tty -echo echonl 2>/dev/null || \
stty -f /dev/tty -echo echonl 2>/dev/null || \ stty -f /dev/tty -echo echonl || exit 1
exit 1 IFS= read -r INPUT </dev/tty || exit 1
IFS= read -r INPUT </dev/tty
stty --file=/dev/tty echo -echonl 2>/dev/null || \ stty --file=/dev/tty echo -echonl 2>/dev/null || \
stty -F /dev/tty echo -echonl 2>/dev/null || \ stty -F /dev/tty echo -echonl 2>/dev/null || \
stty -f /dev/tty echo -echonl 2>/dev/null stty -f /dev/tty echo -echonl || exit 1
} }
if [ "$1" = "noechoback" ]; then if [ "$1" = "noechoback" ]; then
# Try `-s` option. *ksh have it that not `--silent`. Therefore, don't try it. # Try `-s` option. *ksh have it that not `--silent`. Therefore, don't try it.
if [ -n "$BASH_VERSION" ] || [ -n "$ZSH_VERSION" ]; then if [ -n "$BASH_VERSION" ] || [ -n "$ZSH_VERSION" ]; then
IFS= read -rs INPUT </dev/tty 2>/dev/null || silentRead IFS= read -rs INPUT </dev/tty 2>/dev/null || silent_read
printf '\n' >/dev/tty printf '\n' >/dev/tty
else else
silentRead silent_read
fi fi
else else
IFS= read -r INPUT </dev/tty 2>/dev/null || exit 1 IFS= read -r INPUT </dev/tty || exit 1
fi fi
printf '%s' "'$INPUT'" printf '%s' "'$INPUT'"
exit 0 exit 0

View file

@ -11,7 +11,7 @@
var var
IS_WIN = process.platform === 'win32', IS_WIN = process.platform === 'win32',
SHELL_PATH = IS_WIN ? 'cmd.exe' : '/bin/sh', SHELL_PATH = IS_WIN ? 'cmd.exe' : '/bin/sh',
SHELL_COMMAND = __dirname + (IS_WIN ? '\\read.bat' : '/read.sh'), SHELL_CMD = __dirname + (IS_WIN ? '\\read.bat' : '/read.sh'),
ALGORITHM_CIPHER = 'aes-256-cbc', ALGORITHM_CIPHER = 'aes-256-cbc',
ALGORITHM_HASH = 'sha256', ALGORITHM_HASH = 'sha256',
@ -27,8 +27,7 @@ var
useShell = false, print, tempdir, salt = 0; useShell = false, print, tempdir, salt = 0;
function _readlineSync(display, options) { function _readlineSync(display, options) {
var input = '', buffer = new Buffer(bufSize), var input = '', res, buffer = new Buffer(bufSize), rsize;
rsize, err;
options = options || {}; options = options || {};
if (display !== '') { // null and undefined were excluded. if (display !== '') { // null and undefined were excluded.
@ -38,11 +37,12 @@ function _readlineSync(display, options) {
if (useShell || options.noEchoBack) { // Try reading via shell if (useShell || options.noEchoBack) { // Try reading via shell
input = _readlineShell(options); res = _readlineShell(options);
if (typeof input !== 'string') { if (res.error) {
if (display !== '') { stdout.write('\n', encoding); } // Return from prompt line. if (display !== '') { stdout.write('\n', encoding); } // Return from prompt line.
throw new Error('Can\'t read via shell'); throw newError(res.props);
} }
input = res.stdout;
} else { } else {
@ -53,21 +53,16 @@ function _readlineSync(display, options) {
try { try {
rsize = fs.readSync(stdin.fd, buffer, 0, bufSize); rsize = fs.readSync(stdin.fd, buffer, 0, bufSize);
} catch (e) { } catch (e) {
if (e.code === 'EOF') { break; } // pipe if (e.code === 'EOF') { break; }
// Try reading via shell // Try reading via shell
input = _readlineShell(options); res = _readlineShell(options);
if (typeof input === 'string') { break; } if (res.error) {
if (display !== '') { stdout.write('\n', encoding); } // Return from prompt line.
// Give up... throw newError(res.props);
if (e.code === 'EAGAIN') { // EAGAIN, resource temporarily unavailable
// util can't inherit Error.
err = new Error('The platform doesn\'t support interactive reading from stdin');
err.errno = e.errno;
err.code = e.code;
} }
if (display !== '') { stdout.write('\n', encoding); } // Return from prompt line. input += res.stdout;
throw err || e; break;
} }
if (rsize === 0) { break; } if (rsize === 0) { break; }
@ -81,8 +76,19 @@ function _readlineSync(display, options) {
return options.noTrim ? input.replace(/[\r\n]+$/, '') : input.trim(); return options.noTrim ? input.replace(/[\r\n]+$/, '') : input.trim();
} }
function newError(props) {
var err = new Error('The platform doesn\'t support interactive reading from stdin'),
key;
if (props) {
for (key in props) {
if (props.hasOwnProperty(key)) { err[key] = props[key]; }
}
}
return err;
}
function _readlineShell(options) { function _readlineShell(options) {
var shellStdout, args = [], var args = [], res = {},
execOptions = { execOptions = {
env: process.env, env: process.env,
stdio: [stdin], // ScriptPW needs piped stdin stdio: [stdin], // ScriptPW needs piped stdin
@ -95,14 +101,21 @@ function _readlineShell(options) {
stdin.pause(); // re-start in child process stdin.pause(); // re-start in child process
if (childProc.execFileSync) { if (childProc.execFileSync) {
shellStdout = childProc.execFileSync(SHELL_PATH, try {
[SHELL_COMMAND].concat(args), execOptions); res.stdout = childProc.execFileSync(SHELL_PATH,
shellStdout = shellStdout.replace(/^'|'$/g, ''); (IS_WIN ? ['/C', SHELL_CMD] : [SHELL_CMD]).concat(args), execOptions);
} catch (e) { // non-zero exit code
res = {error: true, props: {
method: 'execFileSync',
command: SHELL_CMD, args: args, stderr: e.stderr.trim()
}};
}
} else { } else {
shellStdout = _execSyncByFile(args, execOptions); res = _execSyncByFile(args, execOptions);
} }
if (!res.error) { res.stdout = res.stdout.replace(/^'|'$/g, ''); }
return shellStdout; return res;
} }
// piping via files (node v0.10-) // piping via files (node v0.10-)
@ -130,8 +143,9 @@ function _execSyncByFile(args, execOptions) {
return filepath; return filepath;
} }
var commandArgs, shellStdout, var cmdArgs, res = {},
pathStdout = getTempfile('readline-sync.stdout'), pathStdout = getTempfile('readline-sync.stdout'),
pathStderr = getTempfile('readline-sync.stderr'),
pathStatus = getTempfile('readline-sync.status'), pathStatus = getTempfile('readline-sync.status'),
pathDone = getTempfile('readline-sync.done'), pathDone = getTempfile('readline-sync.done'),
crypto = require('crypto'), shasum, decipher, password; crypto = require('crypto'), shasum, decipher, password;
@ -144,36 +158,44 @@ function _execSyncByFile(args, execOptions) {
if (IS_WIN) { if (IS_WIN) {
// The quote (") is escaped by node before parsed by shell. Then use ENV{Q}. // The quote (") is escaped by node before parsed by shell. Then use ENV{Q}.
process.env.Q = '"'; process.env.Q = '"';
commandArgs = ['/V:ON', '/S', '/C', // `()` for ignore space by echo
'%Q%' + SHELL_COMMAND + '%Q% ' + args.join(' ') + cmdArgs = ['/V:ON', '/S', '/C',
'(' + SHELL_PATH + ' /V:ON /S /C %Q%%Q%' + SHELL_CMD + '%Q% ' + args.join(' ') +
' & (echo !ERRORLEVEL!)>%Q%' + pathStatus + '%Q%%Q%) 2>%Q%' + pathStderr + '%Q%' +
' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' + ' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' +
' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' + ' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' +
' >%Q%' + pathStdout + '%Q%' + ' >%Q%' + pathStdout + '%Q%' +
' & (echo !ERRORLEVEL!)>%Q%' + pathStatus + '%Q% & (echo 1)>%Q%' + pathDone + '%Q%']; ' & (echo 1)>%Q%' + pathDone + '%Q%'];
} else { } else {
commandArgs = ['-c', cmdArgs = ['-c',
'DATA=`(' + SHELL_PATH + ' "' + SHELL_COMMAND + '" ' + args.join(' ') + ')`;' + '(' + SHELL_PATH + ' "' + SHELL_CMD + '" ' + args.join(' ') +
' RTN=$?; if [ $RTN -eq 0 ]; then (printf \'%s\' "$DATA"' + '; echo $?>"' + pathStatus + '") 2>"' + pathStderr + '"' +
' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' + ' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' +
' "' + ALGORITHM_CIPHER + '" "' + password + '"' + ' "' + ALGORITHM_CIPHER + '" "' + password + '"' +
' >"' + pathStdout + '") fi;' + ' >"' + pathStdout + '"' +
' expr $RTN + $? >"' + pathStatus + '"; echo 1 >"' + pathDone + '"']; '; echo 1 >"' + pathDone + '"'];
} }
childProc.spawn(SHELL_PATH, commandArgs, execOptions); childProc.spawn(SHELL_PATH, cmdArgs, execOptions);
while (fs.readFileSync(pathDone, {encoding: encoding}).trim() !== '1') {} while (fs.readFileSync(pathDone, {encoding: encoding}).trim() !== '1') {}
if (fs.readFileSync(pathStatus, {encoding: encoding}).trim() === '0') { if (fs.readFileSync(pathStatus, {encoding: encoding}).trim() === '0') {
shellStdout = res.stdout =
decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}), 'hex', encoding) + decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}), 'hex', encoding) +
decipher.final(encoding); decipher.final(encoding);
shellStdout = shellStdout.replace(/^'|'$/g, ''); } else {
res = {error: true, props: {
method: '_execSyncByFile',
command: SHELL_CMD, args: args,
stderr: fs.readFileSync(pathStderr, {encoding: encoding}).trim()
}};
} }
fs.unlinkSync(pathStdout); fs.unlinkSync(pathStdout);
fs.unlinkSync(pathStderr);
fs.unlinkSync(pathStatus); fs.unlinkSync(pathStatus);
fs.unlinkSync(pathDone); fs.unlinkSync(pathDone);
return shellStdout; return res;
} }
// for dev // for dev

View file

@ -1,6 +1,6 @@
{ {
"name": "readline-sync", "name": "readline-sync",
"version": "0.7.3", "version": "0.7.4",
"title": "readlineSync", "title": "readlineSync",
"description": "Synchronous Readline", "description": "Synchronous Readline",
"keywords": [ "keywords": [