For windows was pretty simple to redirect the std in a and out of a
child process for "cmd.exe " command prompt terminal to a socket using connected pipes passed to a new process in the STARTUPINFO structure.
BOOL b = ::CreatePipe((LPHANDLE)h_stdInRead,(LPHANDLE)hsdtInWriteTmp, &SecAttrib, 0);
b &= ::CreatePipe((LPHANDLE)hsdtOutReadTmp, (LPHANDLE)h_sdtOutWrite, &SecAttrib, 0);
b &= ::DuplicateHandle(hProcess, hsdtInWriteTmp, hProcess, h_this2Write, 0, 0, DUPLICATE_SAME_ACCESS);
b &= ::DuplicateHandle(hProcess, hsdtOutReadTmp, hProcess, h_this2Read, 0, 0, DUPLICATE_SAME_ACCESS);
hsdtInWriteTmp.Close();
hsdtOutReadTmp.Close();
si.dwFlags = 0;
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdInput = h_stdInRead;
si.hStdOutput = h_sdtOutWrite;
si.hStdError = h_sdtOutWrite;
si.wShowWindow = SW_HIDE;
si.lpDesktop = 0;
si.lpTitle = "blah" // Version();
CreateProcess(NULL, "cmd.exe", lps, NULL, 1, CREATE_NEW_CONSOLE, NULL, NULL, psi, ppi) ;
/*
...
...
*/
//handles only 1 connection
while(1)
{
if(sock >0)
{
if(receive(socket, buffer))
WriteFile(h_this2Write,..)
if(ReadFile(h_this2Read))
send(socket);
}
else
{
sock = wait_4_connection(); //accept and listen
}
In above code the context (current directory) of the terminal cmd.exe is not lost between connections, and I can run internal shell commands as start, call, cd, and so on ....
For Linux I've tried to mimic the shell using popen(), and to write and read in the handler returned by popen(), but I cannot run /bash shell commands as cd, cp, mkdir and so on because they are internal bin/bash commands. I would like to have a shell up, and to write and read from it trough it's stdin stdout, available in my app (pipes of file handlers).
Something like:
//handles only 1 connection
execl_and_get_sddin_and_out("bin/bash"); // keep it up
...
while(1)
{
if(sock >0)
{
if(receive(socket, buffer))
fwrite(shell_stdin,..)
if(fread(she__stdout))
send(socket);
}
else
{
sock = wait_4_connection(); //accept and listen
}
}
I tried these samples (but they don;t hold the shell up, and the command is sent to a shell, then the shell is closed):
Tying Standard Input and Output to a Socket Connection
http://src.gnu-darwin.org/DarwinSourceArchive/expanded/OpenSSH/OpenSSH-7.1/openssh/sshconnect.c
Does anyone has any idea how this can be accomplished.
Thank you.
Gyula.