Code Monkey home page Code Monkey logo

paexec's People

Contributors

dnebeker avatar elyuty avatar icnocop avatar ip-gpu avatar masaeedu avatar nyamisty avatar pgrawehr avatar poweradminllc avatar transistor1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

paexec's Issues

Paexec service stays on machines

It could be possible when at the end of the use of paexec, the program cleans the services and the file paexec in the c: directory.

It could be also a clean up switch like "-clean" to clean from services and from c drive the paexec entries.

no ?

PSExec works, but PAExec returns Error code 5 "Access Denied" when target is on different subnet.

I have been troubleshooting connection issues with an Ansible module that uses pypsexec (a python implementation of PAExec code), but have been getting Access Denied on most hosts but not all. From what I can tell, as long as the remote host is on the same subnet as the localhost, there is no issue. If I try connecting to another subnet, even if it's physically connected to the same network switch, the connection tends to fail when starting the PAExec service. At first I thought I missed something in the prerequisite security settings, but then everything works just fine from PSExec. I have tried moving a working instance to another subnet, and it continued to work with PAExec, so I don't know if having prior success leads to continued success. Will continue to troubleshoot and see if I can narrow this down a little more, any tips or ways to enable additional verbose/debug logging would be appreciated.

c:\Temp>psexec.exe /AcceptEula \\foo.contoso.com cmd.exe

PsExec v2.33 - Execute processes remotely
Copyright (C) 2001-2021 Mark Russinovich
Sysinternals - www.sysinternals.com


Microsoft Windows [Version 10.0.19041.804]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\Windows\system32>hostname
foo

C:\Windows\system32>exit
cmd.exe exited on foo.contoso.com with error code 0.

c:\Temp>paexec.exe /AcceptEula \\foo.contoso.com cmd.exe

PAExec v1.28 - Execute Programs Remotely
Copyright (c) 2012-2019 Power Admin LLC
www.poweradmin.com/PAExec


Connecting to foo.contoso.com...
Starting PAExec service on foo.contoso.com...
Failed to start service on foo.contoso.com Access is denied. [Err=0x5, 5]
Failed to stop PAExec service. The service has not been started. [Err=0x426, 1062]

PAExec returning exit code -6

c:\Temp>paexec.exe /AcceptEula \\bar.contoso.com cmd.exe

PAExec v1.28 - Execute Programs Remotely
Copyright (c) 2012-2019 Power Admin LLC
www.poweradmin.com/PAExec


Connecting to bar.contoso.com...
Starting PAExec service on bar.contoso.com...

Microsoft Windows [Version 10.0.19042.870]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\Windows\system32>hostname
bar

C:\WINDOWS\system32>exit
cmd.exe returned 0

PAExec returning exit code 0

Confirmed that PAExec works from subnet A to A with 100% of available computers to test. PAExec has failed at least 90% of the time with computers I've tested from subnet A to B with Access Denied, but the same tests succeed 100% of the time from PSExec. Sample size has been a couple dozen so far.

Hide window for executed process

If in admin console i run something as:

C:\>paexec -s "c:\Windows\System32\cmd.exe"

It will redirect input/output to original console window, but additionally will create one more console window (with no input output). Is there any option to hide this child window?

Buffer indexing overflow?

Admittedly I'm not super familiar with unmanaged code and C++/C, but it seems to me there is something wrong with this code in ConsoleRedir.cpp:

if(!ReadFile( pLP->pSettings->hStdErr, szBuffer, SIZEOF_BUFFER, &dwRead, &olR) || (dwRead == 0)) 
{
    ...
}
...
szBuffer[ dwRead / sizeof(szBuffer[0]) ] = _T('\0')

In C++, sizeof a char is always 1, so I don't understand what the point of the expression: sizeof(szBuffer[0]) is. That aside, since dwRead is the number of bytes you've read, you're going to be indexing 1 position past the end of the array when the buffer is full, which is unallocated memory.

I think you should be reading 1 less byte than the size of the buffer, i.e.:

if(!ReadFile( ..., SIZEOF_BUFFER - 1, ...) || (dwRead == 0)) 

Bad order of stopping service

You need to close the handle that you have open to the remote scm service that you called with OpenService() while deleting the service.
If a failure occurs when you DeleteService, you should close the handle before waiting. If you hang onto that handle, nothing will be able to delete the service.

Remote window appears on client PC during execution. Not a problem with PSEXEC

First: Love the program; the timeout features are amazing.

Issue: When executing a remote command "paexec \ cmd.exe /c mybatch.bat",
on the remote computer () when a user us logged in; A blank
window appears in their session.

When executing the same command in PSEXEC, this is not a problem.
No window appears and the command executes.

Maybe have an option in paexec that starts the window hidden/minimized?

TIA,

Joe

PAExec returning exit code -8

Running paexec.exe \\[computer] -c -f -s test.cmd returns the following error. Same error when providing credentials.

PAExec v1.29 - Execute Programs Remotely
Copyright (c) 2012-2021 Power Admin LLC
www.poweradmin.com/PAExec

Connecting to [computer]...
Failed to impersonate [] - continuing anyway. The handle is invalid. [Err=0x6, 6]
Starting PAExec service on [computer]...
Copying test.cmd remotely...

PAExec returning exit code -8

Cannot run Opera / Chrome with different credentials

Running two commands give different results:
PAExec.exe -u SafeStart -p *************** -d -i "C:\Program Files\Opera\launcher.exe" --private
and
PsExec.exe -u SafeStart -p *************** -d -i "C:\Program Files\Opera\launcher.exe" --private

With PsExec the application loads but for yet unknown reasons it does not load Opera fully functional. This command works properly with Internet Explorer and Firefox. But Chrome and Opera are starting but not working correctly. I also tried starting the application without using the launcher but got the same results.
psexec - starts with issues

When using PAExec I am getting an error and the application does not load at all.
application error

Here is the screen shot of the commands used for this test:
safestart opera

The system log did not show Error or Warning messages when trying this.

The user SafeStart has regular user rights and a profile that can run Opera. I rather not have this happening but tried this to be sure it would start correctly. Not loading a profile with the -d switch is better but also this does not work.

Most desirable outcome is to start Opera with a Guest user account or much better Guest Group user privileges.

PAExec can't handle quoted computer names

Quoting the computer argument...

paexec.exe "\\somecomputer" "someprogram.exe"

...results in paexec failing to recognise it, instead treating it as the cmd argument.

This is different from PsExec.exe, which handles quoted computer names correctly.

-i 0 argument wrongly parsed

Hi, i have trouble to run paexec in current session in windows server 2003 x64:
C:\TestPlayer>paexec.exe -u administrator -p 1 -i 0 cmd.exe

PAExec v1.26 - Execute Programs Remotely
Copyright (c) 2012-2013 Power Admin LLC
www.poweradmin.com/PAExec

Using SessionID 0 (interactive session)
Failed to set interactive token A required privilege is not held by the client.
[Err=0x522, 1314]
PAExec starting process ["0" cmd.exe] as administrator
Failed to start "0" cmd.exe. The system cannot find the file specified. [Err=0x2
, 2]

PAExec returning exit code -3

Current session is zero:
C:\TestPlayer>quser.exe
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
administrator console 0 Active . 27.03.2015 17:41

Usage permission - can the code be modified

Hi
Thanks for the great work. Power Admin tells us we could "anyone can use the software for private, public or commercial uses, including using it as part of a distributed commercial application"
https://www.poweradmin.com/paexec/paexec_eula.txt

But neither EULA nor any document tells we could modify the code, and then use the modified software "for private, public or commercial uses, including using it as part of a distributed commercial application".

May I ask, can we "modify" the code then use it as stated above?

Thanks a lot!

target IPC$ connection appears to be orphaned after -6 exit code / failure

Hello -

If I try to use PAExec.exe without passing any username & password, it will fail to connect to ADMIN$ and then fail to copy executable, then fail to connect to SCM, finally exiting with -6.

However after all programs are closed, "net use" shows an open connection to IPC$ on the target system.

As such, retrying PAExec this time passing correct admin username & password credentials, PAExec will again fail with exit code -6, "Multiple connections to a server or shared resource by the same user, etc" until the orphaned IPC$ connection is removed, ie. "net use * /delete".

This seems like a bug to me - I would expect the initial failure to close out of IPC$ before exiting.

Thanks!

  • James

Windows XP Service Pack 2 required?

Hi.

Thank you for PAExec.

When I try to run PAExec on Windows XP 32-bit, I get the following error:

PAExec.exe - Entry Point Not Found
The procedure entry point EncodePointer could not be located in the dynamic link library KERNEL32.dll
[OK]

I expected to be able to run PAExec.exe on Windows XP.

If Windows XP Service Pack 2 is required, it should probably be documented somewhere.

Thank you.

Connecting to Windows 10 Insider Fast 10.0.16275 results in error "the stub received bad data"

I'm using two machines neither of which is part of a domain, and connecting to the remote machine using the credentials of the builtin admin account.

Everything works properly until the call to CreateService on the remote machine. This isn't unique to PAExec. PSExec suffers from the exact same issue.

This is clearly a harbinger of things to come when Windows 10 RS3 is officially released.

I'm happy to work on a fix if I could figure out the underlying problem. I'm opening the issue in the hopes that those more informed than I about windows 10 RS3 security or other breaking changes will weigh in.

Kill remote process while running via PAExec?

Hello -

This is not an issue per-se, rather a question. Is it possible to kill the remote process while it is still running, via PAExec?

I'm executing some long-running processes, and sometimes it is desirable to be able to "cancel" -however killing PAExec doesn't stop the remote process.

Thanks for your help!

  • James

parameter -x is not recognized / does not work

when executing paexec in SYSTEM context and trying to use parameter -x, paexec behaves as if an unknown / invalid parameter was used.
Without -x paexec is useless when trying to execute in SYSTEM context.

Request: Run as TrustedInstaller

Thanks for your great work.
I have a request about let psexec run program as TrustedInstaller.
There are a lot of folder or registory key is owned by TrustedInstaller, such as C:¥Program Files, HKCR ....,
Every time one need to modify them need extra step to take owner, add permissions, then restore ower/permissons, it's boring.

There are an utility named devxexec which can do this,

And there another utility named RunAsTI,

What about we integrate this function into PAExec. I can implement it when i am free.

I think the basic idea is create a service with id TrustedInstaller or clone token from somewhere.

Regards

How to capture the console output (stdout/stderr) in the same console window when running a command ?

Hi,

I'm looking for an option (let's call it -cc for "capture console"), to be able to see a console app's output directly in the paexec.exe console. Actual design (with -i) pops a new console, even when running from the same session, which means the current one (the one runnning PAExec) sees nothing ... ;(
Is it possible, does it already exist ? I guess even psexec doesn't have it ...

Let me know.

Best regards to the team.

Specifying running as Network Server still requires a password

With PsExec, you can use "NT AUTHORITY\Network Service" as the user and it won't ask for a password. You can't do this with PaExec. Can that functionality be added or even just add it as a flag (e.g. "-ns") like you can if you want to use the System account (-s)?

64bit executable or compile instructions

It appears the PAExec as downloaded is a 32bit application which is leading to problems running on remote 64bit Windows server images.

Specifically; I'm trying to run "bcdedit" remotely on a 64bit machine using the following command line on a host computer:
paexec.exe \\<ipaddress> -u <user> -p <password> -n 5 cmd
both the host and the target are running 64bit windows.

bcdedit is not found in the system32 directory. Further debug indicates that the cmd environment is running as 32bit because the environment variable PROCESSOR_ARCHITECTURE returns x86 not AMD64.
PROCESSOR_ARCHITECTURE=x86

I have verified on the running target that bcdedit is present on the system. I think the WOW32 environment is blocking access to BCDEDIT because it is a 64bit tool on this system.

I tried compiling PAExec myself under visual studio 2019; but I'm having the typical growing pains of not having the correct compiler options and complaining about missing header files.

Add support for short paths

I'd like to request support for short paths.

For example,
paexec.exe -u Username -p Password /C "C:\DOCUME~1\Username\LOCALS~1\Temp\test.cmd >C:\DOCUME~1\Username\LOCALS~1\Temp\test.txt 2>&1"

Currently, paexec.exe returns:
One or more source files were not found.

That command works with psexec.exe without issues.

Otherwise, how can I execute the command with spaces and redirect stdout and stderr to a file?

Thank you.

Windows CMD prompt auto-completion

Likely more of a feature request but TAB when using "paexec \remote cmd.exe" does not apear to forward the tab directly. It aphears to process it locally instead. So the auto completion does not function in the Windows CMD prompt.

Fyi - Psexec does function this way.

Remote window 2003 server sp2 appears username or password incorrect on client PC during execution. Not a problem with winexe on linux

Connecting to 192.168.11.121...
Failed to connect to \192.168.11.121\ADMIN$. username or password incorrect。 [Err=0x52E, 1326]
Failed to copy [D:\test\paexec.exe] to [\192.168.11.121\ADMIN$\PAExec-341732-DESKTOP-123DO.exe] -- going to try to continue anyway. username or password incorrect。 [Err=0x52E, 1326]
Starting PAExec service on 192.168.11.121...
Failed to connect to \192.168.11.121\IPC$. username or password incorrect。 [Err=0x52E, 1326]

the username and password correct !

not a problem with winexe on linux.
https://sourceforge.net/p/winexe

Redirect process output to caller's stdout/stderr

I'm not a C programmer and really like the program. I wonder if it would be possible to redirect the output of the started process to the stdout or stderr of the caller, so it would read like

PAExec v1.25 - Execute Programs Remotely
Copyright (c) 2012-2013 Power Admin LLC
www.poweradmin.com/PAExec

PAExec starting process ["foo.cmd"] as current user
Launch (launchGLE=1300) params: path=["foo.cmd"] user=[{non-null}], pEnv=[{env}], dir=[{null}], stdin=[x0], stdout=[x0], stderr=[x0]

--- started process output start
bla bla bla
...
--- started process output end

PAExec returning exit code 0

Check computer name DNS resolution

With Psexec, the command is not launched if the computername that is targeted is not the same that the joined computer (DNS resolution error), but Paexec don't care...
In situ : we have a lot of VPN users, and DNS are not always up to date. "Sometimes", if I launch a command on \computername1, the command is executed on another computer that just take the same IP from our VPN...
Maybe it could be an option of PAExec program ("-checkDNS"), or push the "original computername" variable that we could compare with the remote command...
Hope the request is clear :)

Very slow to start PsExecSvc, and user/password is not used in OpenSCManager, so cause "Access Denied"

Hi, everyone should take a look at this: Services and RPC/TCP which is my study result.

I found PAExec(also PsExec) have a problem on Windows7,10+.

  • it takes about 60 seconds to finish start PAExecSvc! This is easy to reproduce. Just run this command in Windows7/10+
PAExec \\remote-machine -u user -p password cmd
  • Another ridiculous problem is: when this tool call OpenSCManager internally,
    it completely ignores the user/password input from command line! so cause Access denied.

A way to to reproduce this problem is use your Windows 7 or 10's IP address as remote-machine, ex. 192.168.99.101.

  1. Turn off firewall so ensure TCP 445 and TCP 135 will accept unsolicited incoming.
  2. Open a normal CMD, NOT elevated Admin CMD.
  3. Ensure you have access to \192.168.99.101\Admin$
net use * /d /y
net use \\192.168.99.101\Admin$ /user:user password
  1. Run following typical PAExec command
PAExec \\192.168.99.101 -u user -p password cmd

You will get "Access Denied" soon.

But if you do all this in a Admin CMD, it works.

What happened?

The user/password input from command line does get used in first half of the tool:

net use \\remote-machine\ADMIN$ /user:user password
copy PsExecSvc.exe to \\remote-machine\ADMIN$

But the later half is

OpenSCManager(remote-machine)   #This does not use the identity of previous net command
SCMCreateService
...

So, i suggest add a caveat in the README.md to set client's registry to not attempt to use RPC/TCP.

For detail, please read the link i mentioned at first.

Does not start process when running as GMSA

I specified same command line arguments as with psexec.exe.
psexec -i -u domain\gMsaTest01$ -p ~ cmd.exe
Using psexec.exe opens command prompt as GMSA user. paexec returns error:
Error logging in as domain\gMsaTest01$. The user name or password is incorrect. [Err=0x52E, 1326].
I tried without argument -p ~ and pressed enter when prompted for password. Same error. psexec works in both cases.
My conclusion is that paexec does not implement password fetching of GMSA account.

Handle leak in error paths in SendRequest()

The function SendRequest() creates an unnamed event.

!	HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	OVERLAPPED ol = {0};
	ol.hEvent = hEvent;

HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

There are several error paths where the SendRequest() function exits early and does not call CloseHandle on the event.

bool SendRequest(LPCWSTR remoteServer, HANDLE& hPipe, RemMsg& msgOut, RemMsg& msgReturned, Settings& settings)
{
...

	HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	OVERLAPPED ol = {0};
	ol.hEvent = hEvent;

	if (!fSuccess) 
	{
		gle = GetLastError();
		if(ERROR_IO_PENDING != gle)
		{
			Log(StrFormat(L"Error communicating with %s.", remoteServer), gle);
			CloseHandle(hPipe);
			hPipe = INVALID_HANDLE_VALUE;
+			CloseHandle(hEvent);
			return false;
		}
	}

	while(true)
	{
		if(WAIT_OBJECT_0 == WaitForSingleObject(ol.hEvent, 0))
		{
			GetOverlappedResult(hPipe, &ol, &cbWritten, FALSE);
			break;
		}
		if(gbStop)
+		{
+			CloseHandle(hEvent);
			return false;
+		}
		Sleep(100);
	}
	
	bool bFirstRead = true;
	do 
	{ 
		BYTE buffer[16384] = {0};
		
		ol.Offset = 0;
		ol.OffsetHigh = 0;

		DWORD cbRead = 0;
		// Read from the pipe. 
		fSuccess = ReadFile( 
			hPipe,			// pipe handle 
			buffer,			// buffer to receive reply 
			sizeof(buffer), // size of buffer 
			&cbRead,  // number of bytes read 
			&ol);    

		if(!fSuccess) 
		{
			gle = GetLastError();
			if(ERROR_IO_PENDING != gle)
			{
				Log(StrFormat(L"Error reading response from %s.", remoteServer), gle);
				CloseHandle(hPipe);
				hPipe = INVALID_HANDLE_VALUE;
+				CloseHandle(hEvent);
				return false;
			}
		}

		while(true)
		{
			if(WAIT_OBJECT_0 == WaitForSingleObject(ol.hEvent, 0))
			{
				GetOverlappedResult(hPipe, &ol, &cbRead, FALSE);
				break;
			}
			if(gbStop)
+			{
				return false;
+				CloseHandle(hEvent);
+			}
			Sleep(100);
		}

		if(bFirstRead)
		{
			if(cbRead < sizeof(WORD))
			{
				gle = GetLastError();
				Log(StrFormat(L"Received too little data from %s.", remoteServer), gle);
				CloseHandle(hPipe);
				hPipe = INVALID_HANDLE_VALUE;
+				CloseHandle(hEvent);
				return false;
			}
			msgReturned.SetFromReceivedData(buffer, cbRead);
			bFirstRead = false;
		}
		else
			msgReturned.m_payload.insert(msgReturned.m_payload.end(), buffer, buffer + cbRead);
	} while( msgReturned.m_expectedLen != msgReturned.m_payload.size());

	CloseHandle(hEvent);
	return true; 
}

PAExec 1.26 Cant Handle Special Characters in Passwords .

*PAExec is cool and it connects to sever without a problem when my password was in this pattern "xyz123$$" (without quotes).

*But when I changed my password to this pattern "8]D3"&=-$6L5R}_#8m" (without quotes) , It doesn't connect, It shows Error code 6 which is not a correct one because I have connected to the same application with another password . I can connect the server using remote with same password but not with PAExec.

*There is no document given to how the password pattern should be or which special characters will be accepted and parsed by PAExec.

Really the Application is very helpful but please fix this .

Consider not using WNetAddConnection2

I don't think that you have to use WNetAddConnection2. Which means you don't have to check for open connections either.
Another thing: You shouldn't support non-unicode.

Instead consider this:
LogonUserW(username, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, &token);

if(!ImpersonateLoggedOnUser(token))
return GetLastError();

CopyFileW(local_file, remote_file, false);

Registry mapping differs between paexec and psexec

Hello,

Using Windows 10 (latest 1803 build up to date) x64, paexec does not correctly map HKLM\Software key between normal and system accounts.

Exemple:
paexec -i -s reg add HKLM\Software\Test /v Some /t REG_SZ /d Value /f will create the TEST key in WOW6432Node subkey.
Hence,
paexec -i -s reg query HKLM\Software\Test will work.
reg query HKLM\Software\Test will return an error since it won't find the Test key.

Running the same commands with psexec will work.

Best regards.

license of sha1sum.exe

The source code in GitHub includes sha1sum.exe, which seems to come from GNU Text Utilities and is covered by GNU GPL. This is causing issues when I try to use your software in corporate environment, since the PAExec license clearly cannot apply to sha1sum.exe, since it allows you to do more than GPL, and our intellectual property department has a hard time understanding that sha1sum.exe is not really a part of PAExec.

Would it be possible to address this somehow in the license, e.g. say the license does not apply to sha1sum.exe and GPL applies to that one file, or perhaps remove sha1sum.exe from the sources?

Thank you, and also thank you for providing your great software for free to everyone.

PAExec hangs (don't exit) when have redirected stdInput to pipe

If PAExec as STDInput has pipe, the program hangs up in the blocking call of ReadFile and does not exit at completion of a command. Perhaps, it is better to make so:

// Listens our console, and if the user types in something,
// we will pass it to the remote machine.
// ReadConsole return after pressing the ENTER
UINT WINAPI ListenRemoteStdInputPipeThread(void* p)
{
//giThreadsWorking already incremented
ListenParam* pLP = (ListenParam*)p;

HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
char szInputBuffer[SIZEOF_BUFFER] = {0};
DWORD nBytesRead = 0;
DWORD nBytesWrote = 0;

HANDLE hWritePipe = CreateEvent(NULL, TRUE, FALSE, NULL);

DWORD oldMode = 0;
GetConsoleMode(hInput, &oldMode);
//DWORD newMode = oldMode & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
//SetConsoleMode(hInput, newMode);

bool bWaitForKeyPress = true;
//detect if input redirected from file (in which case we don't want to wait for keyboard hits)
HANDLE hEvent = NULL;

DWORD fileType = GetFileType(hInput);
if (FILE_TYPE_CHAR != fileType) {
//	DWORD inputSize = GetFileSize(hInput, NULL);
//	if (INVALID_FILE_SIZE != inputSize)
		bWaitForKeyPress = false;
		if (fileType == FILE_TYPE_PIPE)
		     hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

}
while(false == gbStop)
{
	if(bWaitForKeyPress)
	{
		bool bBail = false;
		while(0 == _kbhit())
		{
			if(WAIT_OBJECT_0 == WaitForSingleObject(pLP->hStop, 0))
			{
				bBail = true;
				break;
			}
			Sleep(100);
		}
		if(bBail)
			break;
	}

	nBytesRead = 0;
	//if ( !ReadConsole( hInput, szInputBuffer, SIZEOF_BUFFER, &nBytesRead, NULL ) ) -- returns UNICODE which is not what we want
	if (fileType == FILE_TYPE_PIPE) {
		OVERLAPPED olR = { 0 };
		olR.hEvent = hEvent;
		if (!ReadFile(hInput, szInputBuffer, SIZEOF_BUFFER - 1, &nBytesRead,  &olR) || (nBytesRead == 0))
		{
			DWORD dwErr = GetLastError();
			if (dwErr == ERROR_NO_DATA)
				break;
		}

		if (gbStop)
			break;

		HANDLE waits[2];
		waits[0] = pLP->hStop;
		waits[1] = olR.hEvent;
		DWORD ret = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
		if (ret == WAIT_OBJECT_0)
			break; //need to exit
		_ASSERT(ret == WAIT_OBJECT_0 + 1); //data in buffer now
		GetOverlappedResult(hInput, &olR, &nBytesRead, FALSE);
	}
	else if (!ReadFile( hInput, szInputBuffer, SIZEOF_BUFFER - 1, &nBytesRead, NULL))
	{
		DWORD dwErr = GetLastError();
		if ( dwErr == ERROR_NO_DATA)
			break;
	}

	if(gbStop)
		break;

	if(bWaitForKeyPress)
	{
		//suppress the input from being printed in the output since it was already shown locally
		EnterCriticalSection(&pLP->cs);
		szInputBuffer[nBytesRead] = '\0';
		pLP->inputSentToSuppressInOutput.push_back(szInputBuffer);
		LeaveCriticalSection(&pLP->cs);
	}

	// Send it to remote process' stdin
	OVERLAPPED olW = {0};
	olW.hEvent = hWritePipe;

	if (!WriteFile( pLP->pSettings->hStdIn, szInputBuffer, nBytesRead, &nBytesWrote, &olW))
	{
		DWORD gle = GetLastError();
		break;
	}

	if(gbStop)
		break;
	 
	HANDLE waits[2];
	waits[0] = pLP->hStop;
	waits[1] = olW.hEvent;
	DWORD ret = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
	if(ret == WAIT_OBJECT_0)
		break; //need to exit
	_ASSERT(ret == WAIT_OBJECT_0 + 1); //write finished

	FlushFileBuffers(pLP->pSettings->hStdIn);
} 

CloseHandle(hWritePipe);
if (hEvent) CloseHandle(hEvent);
SetConsoleMode(hInput, oldMode);

InterlockedDecrement(&pLP->workerThreads);

return 0;

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.