Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2390 lines
62 KiB

  1. /*++
  2. Copyright (C) Microsoft Corporation, 1992 - 1999
  3. Module Name:
  4. Server.c
  5. Abstract:
  6. The server component of Remote. It spawns a child process
  7. and redirects the stdin/stdout/stderr of child to itself.
  8. Waits for connections from clients - passing the
  9. output of child process to client and the input from clients
  10. to child process.
  11. Author:
  12. Rajivendra Nath (rajnath) 2-Jan-1992
  13. Environment:
  14. Console App. User mode.
  15. Revision History:
  16. --*/
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <io.h>
  20. #include <string.h>
  21. #include "Remote.h"
  22. #define MAX_SESSION 10
  23. #define COMMANDFORMAT TEXT("%c%-15s [%-15s %s]\n%c")
  24. #define LOCALNAME TEXT("Local")
  25. #define LOCALCLIENT(x) (strcmp((char *)(x->Name),LOCALNAME)==0)
  26. #define RemoteInfo(prt,flg) {if (!(flg&&0x80000000)) prt;}
  27. #define CMDSTRING(OutBuff,InpBuff,Client,szTime) { \
  28. _stprintf \
  29. ( \
  30. &OutBuff[0],COMMANDFORMAT,\
  31. BEGINMARK,InpBuff, \
  32. Client->Name,szTime, \
  33. ENDMARK \
  34. ); \
  35. } \
  36. #ifdef UNICODE
  37. int MakeCommandString(
  38. TCHAR * pszOutput,
  39. TCHAR * pszInput,
  40. TCHAR * pszName,
  41. TCHAR * pszTime);
  42. #endif
  43. #define BUFFSIZE 256
  44. #ifdef INTERNALUSECOMPONENT
  45. VOID InitAd(BOOL IsAdvertise);
  46. VOID ShutAd(BOOL IsAdvertise);
  47. #endif
  48. static SOCKET listenSocket;
  49. SESSION_TYPE ClientList[MAX_SESSION];
  50. HANDLE ChildStdInp; //Server Writes to it
  51. HANDLE ChildStdOut; //Server Reads from it
  52. HANDLE ChildStdErr; //Server Reads from it
  53. HANDLE SaveFile; //File containing all that was
  54. //output by child process.
  55. //Each connection opens a handle to this file
  56. //and is sent through PipeWriteH.
  57. TCHAR SaveFileName[MAX_PATH+1]; //Name of above file - all new sessions need
  58. HANDLE ChldProc;
  59. HANDLE ListenThreadH;
  60. HANDLE SockListenThreadH;
  61. // GetFormattedTime -- returns pointer to formatted time
  62. //
  63. // returns pointer to static buffer which should be OK.
  64. //
  65. TCHAR * GetFormattedTime(VOID)
  66. {
  67. static TCHAR szTime[30];
  68. //
  69. // Get time and format to characters
  70. //
  71. GetTimeFormat( LOCALE_USER_DEFAULT,
  72. TIME_NOSECONDS | TIME_FORCE24HOURFORMAT | TIME_NOTIMEMARKER,
  73. NULL, // use current time
  74. NULL, // use default format
  75. szTime,
  76. 30 );
  77. return( (TCHAR *)&szTime );
  78. }
  79. HANDLE
  80. ForkChildProcess( // Creates a new process
  81. TCHAR *cmd, // Redirects its stdin,stdout
  82. PHANDLE in, // and stderr - returns the
  83. PHANDLE out, // corresponding pipe ends.
  84. PHANDLE err
  85. );
  86. HANDLE
  87. OldForkChildProcess( //Same as above except different
  88. TCHAR *cmd, //method for redirection...for
  89. PHANDLE in, //compatibility with.
  90. PHANDLE out,
  91. PHANDLE err
  92. );
  93. DWORD
  94. ListenForSession( //THREAD:Listens for new connections and
  95. TCHAR * pipe //spawns of new seesions - Updates the
  96. ); //Status in Client DataStructure.
  97. DWORD
  98. NewSession( //Manages the session with a client.
  99. SESSION_TYPE* Client
  100. );
  101. DWORD //2 THREAD:Each reads either
  102. GetChldOutput( //StdOut or StdErr of child and
  103. HANDLE rhandle //writes to SaveFile.
  104. );
  105. DWORD
  106. TransferFileToClient( //X THREADS:Reads the save
  107. SESSION_TYPE* Client //file and sendsoutput to a client.
  108. );
  109. DWORD
  110. GetClientInput( //X THREADS:Gets input from Child pipe
  111. SESSION_TYPE* Client //and sends to childs StdIn.
  112. );
  113. BOOL
  114. FilterCommand( //Filters input from client
  115. SESSION_TYPE *cl, //for commands intended for REMOTE
  116. TCHAR *buff,
  117. int dread
  118. );
  119. DWORD
  120. LocalSession(
  121. PVOID noarg
  122. );
  123. DWORD
  124. RemoteSession(
  125. SESSION_TYPE* Client
  126. );
  127. BOOL
  128. SrvCtrlHand(
  129. DWORD event
  130. );
  131. VOID
  132. SendStatus(
  133. HANDLE hClientPipe
  134. );
  135. VOID
  136. SockSendStatus(
  137. SOCKET MySocket
  138. );
  139. DWORD
  140. ShowPopup(
  141. TCHAR *mssg
  142. );
  143. VOID
  144. RemoveInpMark(
  145. TCHAR* Buff,
  146. DWORD Size
  147. );
  148. VOID
  149. CloseClient(
  150. SESSION_TYPE *Client
  151. );
  152. VOID
  153. InitClientList(
  154. );
  155. /*************************************************************/
  156. /*************************************************************/
  157. DWORD
  158. SockListenForSession( //THREAD:Listens for new connections and
  159. TCHAR* pipe //spawns of new seesions - Updates the
  160. ); //Status in Client DataStructure.
  161. DWORD
  162. SockNewSession( //Manages the session with a client.
  163. SESSION_TYPE* Client
  164. );
  165. DWORD
  166. SockTransferFileToClient( //X THREADS:Reads the save
  167. SESSION_TYPE* Client //file and sendsoutput to a client.
  168. );
  169. DWORD
  170. SockRemoteSession(
  171. SESSION_TYPE* Client
  172. );
  173. DWORD
  174. SockGetClientInput( //X THREADS:Gets input from Child pipe
  175. SESSION_TYPE* Client //and sends to childs StdIn.
  176. );
  177. BOOL
  178. SockAuthenticate(
  179. SOCKET MySocket
  180. );
  181. /*************************************************************/
  182. /*************************************************************/
  183. /*************************************************************/
  184. VOID
  185. Server( //Main routine for server.
  186. TCHAR* ChildCmd,
  187. TCHAR* PipeName
  188. )
  189. {
  190. WORD wVersionRequested = MAKEWORD(1,1);
  191. WSADATA wsaData;
  192. DWORD ThreadID ;//No use
  193. HANDLE WaitH[3];
  194. DWORD WaitObj;
  195. TCHAR tmpdir[MAX_PATH+1];
  196. int nRet;
  197. _tprintf(TEXT("**************************************\n")
  198. TEXT("*********** WSREMOTE ************\n")
  199. TEXT("*********** SERVER ************\n")
  200. TEXT("**************************************\n")
  201. TEXT("To Connect: WSRemote /C %s %s\n\n"),HostName,PipeName);
  202. InitClientList();
  203. //
  204. // Initialize WinSock
  205. //
  206. nRet = WSAStartup(wVersionRequested, &wsaData);
  207. if (nRet)
  208. {
  209. _tprintf(TEXT("Initialize WinSock Failed"));
  210. return ;
  211. }
  212. // Check version
  213. if (wsaData.wVersion != wVersionRequested)
  214. {
  215. _tprintf(TEXT("Wrong WinSock Version"));
  216. return;
  217. }
  218. //
  219. // set environment variable
  220. //
  221. SetEnvironmentVariable(TEXT("_REMOTE"), PipeName);
  222. //
  223. //Start the command as a child process
  224. //
  225. ChldProc=ForkChildProcess(ChildCmd,&ChildStdInp,&ChildStdOut,&ChildStdErr);
  226. //
  227. //Create a tempfile for storing Child process output.
  228. //
  229. {
  230. DWORD rc = GetTempPath(sizeof(tmpdir),tmpdir);
  231. if (!rc || rc > sizeof(tmpdir))
  232. {
  233. _stprintf(tmpdir,TEXT("%s"),TEXT("."));
  234. }
  235. if (!GetTempFileName(tmpdir,TEXT("REMOTE"),0,SaveFileName))
  236. GetTempFileName(TEXT("."),TEXT("REMOTE"),0,SaveFileName);
  237. }
  238. if ((SaveFile=CreateFile(
  239. (LPCTSTR)SaveFileName, /* address of name of the file */ \
  240. GENERIC_READ|GENERIC_WRITE, /* access (read/write) mode */ \
  241. FILE_SHARE_READ|FILE_SHARE_WRITE,/* share mode */ \
  242. (LPSECURITY_ATTRIBUTES)NULL, /* security descriptor */ \
  243. CREATE_ALWAYS, /* how to create */ \
  244. FILE_ATTRIBUTE_NORMAL, /* File Attribute */ /* file attributes */ \
  245. (HANDLE)NULL))==NULL)
  246. {
  247. TerminateProcess(ChldProc,0);
  248. ErrorExit(TEXT("Could not Create Output File"));
  249. }
  250. //
  251. //Start 2 threads to save the output from stdout and stderr of cmd to savefile.
  252. //
  253. if ((WaitH[0]=CreateThread(
  254. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  255. (DWORD)0, // Use same stack size.
  256. (LPTHREAD_START_ROUTINE)GetChldOutput, // Thread procedure.
  257. (LPVOID)ChildStdErr, // Parameter to pass.
  258. (DWORD)0, // Run immediately.
  259. (LPDWORD)&ThreadID))==NULL)
  260. {
  261. TerminateProcess(ChldProc,0);
  262. ErrorExit(TEXT("Failed to Create GetGhldOutput#1 Thread"));
  263. }
  264. if ((WaitH[1]=CreateThread(
  265. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  266. (DWORD)0, // Use same stack size.
  267. (LPTHREAD_START_ROUTINE)GetChldOutput, // Thread procedure.
  268. (LPVOID)ChildStdOut, // Parameter to pass.
  269. (DWORD)0, // Run immediately.
  270. (LPDWORD)&ThreadID))==NULL)
  271. {
  272. TerminateProcess(ChldProc,0);
  273. ErrorExit(TEXT("Failed to Create GetGhldOutput#2 Thread"));
  274. }
  275. //
  276. //Start Thread to listen for new Connections
  277. //
  278. if ((ListenThreadH=CreateThread((LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  279. (DWORD)0, // Use same stack size.
  280. (LPTHREAD_START_ROUTINE)ListenForSession, // Thread procedure.
  281. (LPVOID)PipeName, // Parameter to pass.
  282. (DWORD)0, // Run immediately.
  283. (LPDWORD)&ThreadID))==NULL)
  284. {
  285. TerminateProcess(ChldProc,0);
  286. ErrorExit(TEXT("Failed To Create ListenForSession Thread"));
  287. }
  288. //
  289. //Start Thread to listen for new Connections
  290. //
  291. if ((SockListenThreadH=CreateThread((LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  292. (DWORD)0, // Use same stack size.
  293. (LPTHREAD_START_ROUTINE)SockListenForSession, // Thread procedure.
  294. (LPVOID)PipeName, // Parameter to pass.
  295. (DWORD)0, // Run immediately.
  296. (LPDWORD)&ThreadID))==NULL)
  297. {
  298. TerminateProcess(ChldProc,0);
  299. ErrorExit(TEXT("Failed To Create SockListenForSession Thread"));
  300. }
  301. //
  302. //Start Local Thread
  303. //
  304. if ((ClientList[0].hThread=CreateThread((LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  305. (DWORD)0, // Use same stack size.
  306. (LPTHREAD_START_ROUTINE)LocalSession, // Thread procedure.
  307. (LPVOID)NULL, // Parameter to pass.
  308. (DWORD)0, // Run immediately.
  309. (LPDWORD)&ThreadID))==NULL)
  310. {
  311. TerminateProcess(ChldProc,0);
  312. ErrorExit(TEXT("Failed To Create ListenForSession Thread"));
  313. }
  314. SetConsoleCtrlHandler((PHANDLER_ROUTINE)SrvCtrlHand,TRUE);
  315. #ifdef INTERNALUSECOMPONENT
  316. InitAd(IsAdvertise);
  317. #endif
  318. WaitH[2]=ChldProc;
  319. WaitObj=WaitForMultipleObjects(3,WaitH,FALSE,INFINITE);
  320. switch (WaitObj-WAIT_OBJECT_0)
  321. {
  322. case 0: // Error Writing to savefile
  323. case 1:
  324. TerminateProcess(ChldProc,0);
  325. break;
  326. case 2: // Child Proc Terminated
  327. break;
  328. default: // Out of Some Resource
  329. _tprintf(TEXT("Out of Resource Error %d..Terminating\n"),GetLastError());
  330. break;
  331. }
  332. TerminateThread(ListenThreadH,0);
  333. // SOCK:
  334. TerminateThread(SockListenThreadH,0);
  335. #ifdef INTERNALUSECOMPONENT
  336. ShutAd(IsAdvertise);
  337. #endif
  338. CloseHandle(ChildStdInp);
  339. CloseHandle(ChildStdOut);
  340. CloseHandle(ChildStdErr);
  341. //WSACleanup
  342. WSACleanup();
  343. _tprintf(TEXT("\nCalling WSACleanup()..\n"));
  344. _tprintf(TEXT("\nRemote:Parent exiting. Child(%s) dead..\n"),ChildCmd);
  345. CloseHandle(SaveFile);
  346. {
  347. int i;
  348. for (i=0;i<MAX_SESSION;i++)
  349. CloseClient(&ClientList[i]);
  350. }
  351. if (!DeleteFile(SaveFileName))
  352. _tprintf(TEXT("Temp File %s not deleted..\n"),SaveFileName);
  353. return;
  354. }
  355. /*************************************************************/
  356. HANDLE
  357. ForkChildProcess( // Creates a new process
  358. TCHAR *cmd, // Redirects its stdin,stdout
  359. PHANDLE inH, // and stderr - returns the
  360. PHANDLE outH, // corresponding pipe ends.
  361. PHANDLE errH
  362. )
  363. {
  364. SECURITY_ATTRIBUTES lsa;
  365. STARTUPINFO si;
  366. PROCESS_INFORMATION pi;
  367. HANDLE ChildIn;
  368. HANDLE ChildOut;
  369. HANDLE ChildErr;
  370. lsa.nLength=sizeof(SECURITY_ATTRIBUTES);
  371. lsa.lpSecurityDescriptor=NULL;
  372. lsa.bInheritHandle=TRUE;
  373. //
  374. //Create Parent_Write to ChildStdIn Pipe
  375. //
  376. if (!CreatePipe(&ChildIn,inH,&lsa,0))
  377. ErrorExit(TEXT("Could Not Create Parent-->Child Pipe"));
  378. //
  379. //Create ChildStdOut to Parent_Read pipe
  380. //
  381. if (!CreatePipe(outH,&ChildOut,&lsa,0))
  382. ErrorExit(TEXT("Could Not Create Child-->Parent Pipe"));
  383. //
  384. //Create ChildStdOut to Parent_Read pipe
  385. //
  386. if (!CreatePipe(errH,&ChildErr,&lsa,0))
  387. ErrorExit(TEXT("Could Not Create Child-->Parent Pipe"));
  388. //
  389. // Lets Redirect Console StdHandles - easy enough
  390. //
  391. si.cb=sizeof(STARTUPINFO);
  392. si.lpReserved=NULL;
  393. si.lpTitle=NULL;
  394. si.lpDesktop=NULL;
  395. si.dwX=si.dwY=si.dwYSize=si.dwXSize=0;
  396. si.dwFlags=STARTF_USESTDHANDLES;
  397. si.hStdInput =ChildIn;
  398. si.hStdOutput=ChildOut;
  399. si.hStdError =ChildErr;
  400. si.wShowWindow=SW_SHOW;
  401. si.lpReserved2=NULL;
  402. si.cbReserved2=0;
  403. //
  404. //Create Child Process
  405. //
  406. if (!CreateProcess( NULL,
  407. cmd,
  408. NULL,
  409. NULL,
  410. TRUE,
  411. NORMAL_PRIORITY_CLASS,
  412. NULL,
  413. NULL,
  414. &si,
  415. &pi))
  416. {
  417. if (GetLastError()==2)
  418. _tprintf(TEXT("Executable %s not found\n"),cmd);
  419. ErrorExit(TEXT("Could Not Create Child Process"));
  420. }
  421. //
  422. //Close unneccesary Handles and Restore the crt handles
  423. //
  424. CloseHandle(ChildIn);
  425. CloseHandle(ChildOut);
  426. CloseHandle(ChildErr);
  427. return(pi.hProcess);
  428. }
  429. /*************************************************************/
  430. HANDLE
  431. OldForkChildProcess(
  432. TCHAR *cmd,
  433. PHANDLE inH,
  434. PHANDLE outH,
  435. PHANDLE errH
  436. )
  437. {
  438. SECURITY_ATTRIBUTES lsa;
  439. STARTUPINFO si;
  440. PROCESS_INFORMATION pi;
  441. HANDLE OldStdIn =GetStdHandle(STD_INPUT_HANDLE);
  442. HANDLE OldStdOut=GetStdHandle(STD_OUTPUT_HANDLE);
  443. HANDLE OldStdErr=GetStdHandle(STD_ERROR_HANDLE);
  444. HANDLE ChildStdIn;
  445. HANDLE ChildStdOut;
  446. HANDLE ChildStdErr;
  447. lsa.nLength=sizeof(SECURITY_ATTRIBUTES);
  448. lsa.lpSecurityDescriptor=NULL;
  449. lsa.bInheritHandle=TRUE;
  450. //Create Parent_Write to ChildStdIn Pipe
  451. if (!CreatePipe(&ChildStdIn,inH,&lsa,0))
  452. ErrorExit(TEXT("Could Not Create Parent-->Child Pipe"));
  453. //Create ChildStdOut to Parent_Read pipe
  454. if (!CreatePipe(outH,&ChildStdOut,&lsa,0))
  455. ErrorExit(TEXT("Could Not Create Child-->Parent Pipe"));
  456. //Create ChildStdOut to Parent_Read pipe
  457. if (!CreatePipe(errH,&ChildStdErr,&lsa,0))
  458. ErrorExit(TEXT("Could Not Create Child-->Parent Pipe"));
  459. //Make ChildStdIn and Out as standard handles and get it inherited by child
  460. if (!SetStdHandle(STD_INPUT_HANDLE,ChildStdIn))
  461. ErrorExit(TEXT("Could not change StdIn"));
  462. if (!SetStdHandle(STD_OUTPUT_HANDLE,ChildStdOut))
  463. ErrorExit(TEXT("Could Not change StdOut"));
  464. if (!SetStdHandle(STD_ERROR_HANDLE,ChildStdErr))
  465. ErrorExit(TEXT("Could Not change StdErr"));
  466. si.cb=sizeof(STARTUPINFO);
  467. si.lpReserved=NULL;
  468. si.lpTitle=NULL;
  469. si.lpDesktop=NULL;
  470. si.dwX=si.dwY=si.dwYSize=si.dwXSize=si.dwFlags=0L;
  471. si.wShowWindow=SW_SHOW;
  472. si.lpReserved2=NULL;
  473. si.cbReserved2=0;
  474. //Create Child Process
  475. if (!CreateProcess( NULL,
  476. cmd,
  477. NULL,
  478. NULL,
  479. TRUE,
  480. NORMAL_PRIORITY_CLASS,
  481. NULL,
  482. NULL,
  483. &si,
  484. &pi))
  485. ErrorExit(TEXT("Could Not Create Child Process"));
  486. //reset StdIn StdOut
  487. if (!SetStdHandle(STD_INPUT_HANDLE,OldStdIn))
  488. {
  489. TerminateProcess(pi.hProcess,1);
  490. ErrorExit(TEXT("Could not RESET StdIn"));
  491. }
  492. if (!SetStdHandle(STD_OUTPUT_HANDLE,OldStdOut))
  493. {
  494. TerminateProcess(pi.hProcess,1);
  495. ErrorExit(TEXT("Could not RESET StdIn"));
  496. }
  497. if (!SetStdHandle(STD_ERROR_HANDLE,OldStdErr))
  498. {
  499. TerminateProcess(pi.hProcess,1);
  500. ErrorExit(TEXT("Could not RESET StdIn"));
  501. }
  502. //Close unneccesary Handles
  503. CloseHandle(ChildStdIn);
  504. CloseHandle(ChildStdOut);
  505. CloseHandle(ChildStdErr);
  506. return(pi.hProcess);
  507. }
  508. /*************************************************************/
  509. #if _MSC_FULL_VER >= 13008827
  510. #pragma warning(push)
  511. #pragma warning(disable:4715) // Not all control paths return (due to infinite loop)
  512. #endif
  513. /*************************************************************/
  514. DWORD
  515. ListenForSession(
  516. TCHAR* pipename
  517. )
  518. {
  519. int i;
  520. DWORD ThreadID;
  521. HANDLE PipeH[2];
  522. SECURITY_DESCRIPTOR SecurityDescriptor;
  523. HANDLE TokenHandle;
  524. TOKEN_DEFAULT_DACL DefaultDacl;
  525. SECURITY_ATTRIBUTES lsa;
  526. TCHAR fullnameIn[BUFFSIZE];
  527. TCHAR fullnameOut[BUFFSIZE];
  528. _stprintf(fullnameIn,SERVER_READ_PIPE ,TEXT("."),pipename);
  529. _stprintf(fullnameOut,SERVER_WRITE_PIPE,TEXT("."),pipename);
  530. //
  531. // Initialize the security descriptor that we're going to
  532. // use.
  533. //
  534. InitializeSecurityDescriptor
  535. (
  536. &SecurityDescriptor,
  537. SECURITY_DESCRIPTOR_REVISION
  538. );
  539. (VOID) SetSecurityDescriptorDacl
  540. (
  541. &SecurityDescriptor,
  542. TRUE,
  543. NULL,
  544. FALSE
  545. );
  546. DefaultDacl.DefaultDacl = NULL;
  547. if (OpenProcessToken
  548. (
  549. GetCurrentProcess(),
  550. TOKEN_ADJUST_DEFAULT,
  551. &TokenHandle
  552. ))
  553. {
  554. //
  555. // Remove the default DACL on the token
  556. //
  557. SetTokenInformation
  558. (
  559. TokenHandle,
  560. TokenDefaultDacl,
  561. &DefaultDacl,
  562. sizeof( TOKEN_DEFAULT_DACL )
  563. );
  564. }
  565. lsa.nLength=sizeof(SECURITY_ATTRIBUTES);
  566. lsa.lpSecurityDescriptor=&SecurityDescriptor;
  567. lsa.bInheritHandle=TRUE;
  568. while(TRUE)
  569. {
  570. PipeH[0]=CreateNamedPipe
  571. (
  572. fullnameIn ,
  573. PIPE_ACCESS_INBOUND ,
  574. PIPE_TYPE_BYTE,
  575. PIPE_UNLIMITED_INSTANCES,
  576. 0,0,0,&lsa
  577. );
  578. PipeH[1]=CreateNamedPipe
  579. (
  580. fullnameOut,
  581. PIPE_ACCESS_OUTBOUND,
  582. PIPE_TYPE_BYTE,
  583. PIPE_UNLIMITED_INSTANCES,
  584. 0,0,0,&lsa
  585. );
  586. if (!ConnectNamedPipe(PipeH[0],NULL))
  587. {
  588. if (GetLastError()!=ERROR_PIPE_CONNECTED)
  589. {
  590. CloseHandle(PipeH[0]);
  591. CloseHandle(PipeH[1]);
  592. continue;
  593. }
  594. }
  595. if (!ConnectNamedPipe(PipeH[1],NULL))
  596. {
  597. if (GetLastError()!=ERROR_PIPE_CONNECTED)
  598. {
  599. CloseHandle(PipeH[0]);
  600. CloseHandle(PipeH[1]);
  601. continue;
  602. }
  603. }
  604. //
  605. //Look For a Free Slot & if not- then terminate connection
  606. //
  607. for (i=1;i<MAX_SESSION;i++)
  608. {
  609. //
  610. // Locate a Free Client block
  611. //
  612. if (!ClientList[i].Active)
  613. break;
  614. }
  615. if (i<MAX_SESSION)
  616. {
  617. //
  618. // Initialize the Client
  619. //
  620. ClientList[i].PipeReadH=PipeH[0];
  621. ClientList[i].PipeWriteH=PipeH[1];
  622. ClientList[i].Active=TRUE;
  623. ClientList[i].SendOutput=TRUE;
  624. ClientList[i].CommandRcvd=FALSE;
  625. }
  626. else
  627. {
  628. _tprintf(TEXT("Remote:Closing New Session - No more slots\n"));
  629. CloseHandle(PipeH[0]);
  630. CloseHandle(PipeH[1]);
  631. continue;
  632. }
  633. //
  634. //start new thread for this connection
  635. //
  636. if((ClientList[i].hThread=CreateThread (
  637. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  638. (DWORD)0, // Use same stack size.
  639. (LPTHREAD_START_ROUTINE)RemoteSession, // Thread procedure.
  640. (LPVOID)&ClientList[i], // Parameter to pass.
  641. (DWORD)0, // Run immediately.
  642. (LPDWORD)&ThreadID))==NULL)
  643. {
  644. CloseClient(&ClientList[i]);
  645. continue;
  646. }
  647. }
  648. return(0);
  649. }
  650. #if _MSC_FULL_VER >= 13008827
  651. #pragma warning(pop)
  652. #endif
  653. /*************************************************************/
  654. DWORD
  655. RemoteSession(
  656. SESSION_TYPE *MyClient
  657. )
  658. {
  659. DWORD ReadCnt;
  660. SESSION_STARTUPINFO ssi;
  661. TCHAR *headerbuff;
  662. TCHAR msg[BUFFSIZE];
  663. DWORD tmp;
  664. SESSION_STARTREPLY ssr;
  665. memset((TCHAR *)&ssi,0,sizeof(ssi));
  666. if ((MyClient->rSaveFile=CreateFile(
  667. SaveFileName,
  668. GENERIC_READ|GENERIC_WRITE,
  669. FILE_SHARE_READ|FILE_SHARE_WRITE,
  670. NULL,OPEN_EXISTING,
  671. FILE_ATTRIBUTE_NORMAL,NULL))==NULL)
  672. {
  673. CloseClient(MyClient);
  674. return(1);
  675. }
  676. {
  677. DWORD reply=0;
  678. ReadFixBytes(MyClient->PipeReadH,(TCHAR *)MyClient->Name,HOSTNAMELEN-1,0);
  679. //
  680. //Last four Bytes contains a code
  681. //
  682. memcpy((TCHAR *)&reply,(TCHAR *)&(MyClient->Name[11]),4);
  683. if (reply!=MAGICNUMBER)
  684. {
  685. //
  686. // Unknown client
  687. //
  688. CloseClient(MyClient);
  689. return(1);
  690. }
  691. ssr.MagicNumber=MAGICNUMBER;
  692. ssr.Size=sizeof(ssr);
  693. ssr.FileSize=GetFileSize( MyClient->rSaveFile, &tmp );
  694. WriteFile(MyClient->PipeWriteH,(TCHAR *)&ssr,sizeof(ssr),&tmp,NULL);
  695. }
  696. if (ReadFixBytes(MyClient->PipeReadH,(TCHAR *)&(ssi.Size),sizeof(ssi.Size),0)!=0)
  697. {
  698. CloseClient(MyClient);
  699. return(1);
  700. }
  701. if (ssi.Size>1024) //Sanity Check
  702. {
  703. _stprintf(msg,TEXT("%s"),"Server:Unknown Header..Terminating session\n");
  704. WriteFile(MyClient->PipeWriteH,msg,_tcslen(msg),&tmp,NULL);
  705. CloseClient(MyClient);
  706. return(1);
  707. }
  708. if ((headerbuff=(TCHAR *)calloc(ssi.Size,1))==NULL)
  709. {
  710. _stprintf(msg,TEXT("%s"),"Server:Not Enough Memory..Terminating session\n");
  711. WriteFile(MyClient->PipeWriteH,msg,_tcslen(msg),&tmp,NULL);
  712. CloseClient(MyClient);
  713. return(1);
  714. }
  715. ReadCnt=ssi.Size-sizeof(ssi.Size);
  716. if (ReadFixBytes(MyClient->PipeReadH,(TCHAR *)headerbuff,ReadCnt,0)!=0)
  717. {
  718. CloseClient(MyClient);
  719. return(1);
  720. }
  721. memcpy((TCHAR *)&ssi+sizeof(ssi.Size),headerbuff,sizeof(ssi)-sizeof(ssi.Size));
  722. free(headerbuff);
  723. /* Version */
  724. if (ssi.Version!=VERSION)
  725. {
  726. _stprintf(msg,TEXT("WSRemote Warning:Server Version=%d Client Version=%d\n"),VERSION,ssi.Version);
  727. WriteFile(MyClient->PipeWriteH,msg,_tcslen(msg),&tmp,NULL);
  728. }
  729. /* Name */
  730. {
  731. memcpy(MyClient->Name,ssi.ClientName,15);
  732. MyClient->Name[14]=0;
  733. }
  734. /* Lines */
  735. if (ssi.LinesToSend!=-1)
  736. {
  737. long PosFromEnd=ssi.LinesToSend*CHARS_PER_LINE;
  738. DWORD BytesToSend=MINIMUM((DWORD)PosFromEnd,ssr.FileSize);
  739. DWORD BytesRead;
  740. TCHAR *buff=(TCHAR *)calloc(BytesToSend+1,1);
  741. if (ssr.FileSize > (DWORD)PosFromEnd)
  742. {
  743. SetFilePointer( MyClient->rSaveFile,
  744. -PosFromEnd,
  745. (PLONG)NULL,
  746. FILE_END
  747. );
  748. }
  749. if (buff!=NULL)
  750. {
  751. if (!ReadFile(MyClient->rSaveFile,buff,BytesToSend,&BytesRead,NULL))
  752. {
  753. CloseClient(MyClient);
  754. return(1);
  755. }
  756. RemoveInpMark(buff,BytesRead);
  757. if (!WriteFile(MyClient->PipeWriteH,buff,BytesRead,&tmp,NULL))
  758. {
  759. CloseClient(MyClient);
  760. return(1);
  761. }
  762. }
  763. free(buff);
  764. }
  765. RemoteInfo(_tprintf(TEXT("\n**WSRemote:Connected To %s [%s]\n"),MyClient->Name,GetFormattedTime()),ssi.Flag);
  766. NewSession(MyClient);
  767. RemoteInfo(_tprintf(TEXT("\n**WSRemote:Disconnected From %s [%s]\n"),MyClient->Name,GetFormattedTime()),ssi.Flag);
  768. CloseClient(MyClient);
  769. return(0);
  770. }
  771. /*************************************************************/
  772. DWORD
  773. NewSession(
  774. SESSION_TYPE* MyClient
  775. )
  776. {
  777. DWORD ThreadId;
  778. HANDLE rwThread[3];
  779. MyClient->MoreData=CreateEvent
  780. (
  781. (LPSECURITY_ATTRIBUTES) NULL,/* address of security attributes */
  782. FALSE, /* flag for manual-reset event */
  783. TRUE, /* flag for initial state */
  784. NULL /* address of event-object name */
  785. );
  786. if ((rwThread[0]=CreateThread (
  787. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  788. (DWORD)0, // Use same stack size.
  789. (LPTHREAD_START_ROUTINE)GetClientInput, // Thread procedure.
  790. (LPVOID)MyClient, // Parameter to pass.
  791. (DWORD)0, // Run immediately.
  792. (LPDWORD)&ThreadId))==NULL)
  793. {
  794. return(GetLastError());
  795. }
  796. if ((rwThread[1]=CreateThread (
  797. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  798. (DWORD)0, // Use same stack size.
  799. (LPTHREAD_START_ROUTINE)TransferFileToClient, // Thread procedure.
  800. (LPVOID)MyClient, // Parameter to pass.
  801. (DWORD)0, // Run immediately.
  802. (LPDWORD)&ThreadId))==NULL)
  803. {
  804. CloseHandle(rwThread[0]);
  805. return(GetLastError());
  806. }
  807. rwThread[2]=ChldProc;
  808. WaitForMultipleObjects(3, rwThread,FALSE, INFINITE);
  809. TerminateThread(rwThread[0],1);
  810. TerminateThread(rwThread[1],1);
  811. CloseHandle(rwThread[0]);
  812. CloseHandle(rwThread[1]);
  813. return(0);
  814. }
  815. /*************************************************************/
  816. DWORD
  817. GetChldOutput(
  818. HANDLE readH
  819. )
  820. {
  821. TCHAR buff[BUFFSIZE];
  822. DWORD dread;
  823. DWORD tmp;
  824. while(ReadFile(readH,buff,BUFFSIZE-1,&dread,NULL))
  825. {
  826. buff[dread]='\0';
  827. if (!WriteFile(SaveFile,buff,dread,&tmp,NULL))
  828. {
  829. return(1);
  830. }
  831. //
  832. // Signal Reader Thread that more data
  833. //
  834. {
  835. int i;
  836. DWORD err; //REMOVE
  837. for (i=0;i<MAX_SESSION;i++)
  838. {
  839. if (ClientList[i].Active)
  840. {
  841. if (!SetEvent(ClientList[i].MoreData))
  842. err=GetLastError(); //REMOVE
  843. }
  844. }
  845. }
  846. }
  847. return(1);
  848. }
  849. /*************************************************************/
  850. DWORD
  851. TransferFileToClient(
  852. SESSION_TYPE *MyClient
  853. )
  854. {
  855. TCHAR buffin[BUFFSIZE],buffout[BUFFSIZE],cmdbuff[BUFFSIZE];
  856. DWORD tmp;
  857. DWORD dread=0,dwrite=0;
  858. BOOL incmd=FALSE;
  859. DWORD cmdP=0;
  860. DWORD i;
  861. TCHAR MyEchoStr[30];
  862. _stprintf(MyEchoStr,TEXT("[%-15s"),MyClient->Name);
  863. while(ReadFile(MyClient->rSaveFile,buffin,BUFFSIZE-1,&dread,NULL))
  864. {
  865. if (dread==0)
  866. {
  867. WaitForSingleObject(MyClient->MoreData,INFINITE);
  868. continue;
  869. }
  870. dwrite=0;
  871. for(i=0;i<dread;i++)
  872. {
  873. if (incmd)
  874. {
  875. if ((buffin[i]==ENDMARK)||(cmdP==BUFFSIZE-1))
  876. {
  877. incmd=FALSE;
  878. cmdbuff[cmdP]=0;
  879. if ((_tcsstr(cmdbuff,MyEchoStr)==NULL)||
  880. (!MyClient->CommandRcvd))
  881. {
  882. if (!WriteFile(
  883. MyClient->PipeWriteH,
  884. cmdbuff,cmdP,&tmp,NULL))
  885. {
  886. return(1);
  887. }
  888. }
  889. cmdP=0;
  890. }
  891. else
  892. {
  893. cmdbuff[cmdP++]=buffin[i];
  894. }
  895. }
  896. else
  897. {
  898. if (buffin[i]==BEGINMARK)
  899. {
  900. if (dwrite!=0)
  901. {
  902. if (!WriteFile(
  903. MyClient->PipeWriteH,
  904. buffout,dwrite,&tmp,NULL))
  905. {
  906. return(1);
  907. }
  908. dwrite=0;
  909. }
  910. incmd=TRUE;
  911. continue;
  912. }
  913. else
  914. {
  915. buffout[dwrite++]=buffin[i];
  916. }
  917. }
  918. }
  919. if (dwrite!=0)
  920. {
  921. if (!WriteFile(
  922. MyClient->PipeWriteH,
  923. buffout,dwrite,&tmp,NULL))
  924. {
  925. return(0);
  926. }
  927. }
  928. }
  929. return(1);
  930. }
  931. /*************************************************************/
  932. DWORD
  933. GetClientInput(
  934. SESSION_TYPE *MyClient
  935. )
  936. {
  937. TCHAR buff[BUFFSIZE];
  938. DWORD tmp,dread;
  939. #ifdef UNICODE
  940. while(ReadFileW(MyClient->PipeReadH,buff,BUFFSIZE,&dread,NULL))
  941. #else
  942. while(ReadFile(MyClient->PipeReadH,buff,BUFFSIZE,&dread,NULL))
  943. #endif
  944. {
  945. buff[dread]=0;
  946. MyClient->CommandRcvd=TRUE;
  947. if (FilterCommand(MyClient,buff,dread))
  948. continue;
  949. if (!WriteFile(ChildStdInp,buff,dread,&tmp,NULL))
  950. {
  951. ExitThread(0);
  952. }
  953. }
  954. return(1);
  955. }
  956. /*************************************************************/
  957. BOOL
  958. FilterCommand(
  959. SESSION_TYPE *cl,
  960. TCHAR *buff,
  961. int dread
  962. )
  963. {
  964. TCHAR inp_buff[4096];
  965. TCHAR tmpchar;
  966. TCHAR ch[3];
  967. DWORD tmp;
  968. int len;
  969. DWORD ThreadID; //Useless
  970. if (dread==0)
  971. return(FALSE);
  972. buff[dread]=0;
  973. if (buff[0]==COMMANDCHAR)
  974. {
  975. switch(buff[1])
  976. {
  977. case 'l':
  978. case 'L':
  979. if (bIPLocked == FALSE)
  980. {
  981. bIPLocked=TRUE;
  982. _tprintf(TEXT("**LOCK: No IP Sessions Allowed\n"));
  983. }
  984. else
  985. {
  986. bIPLocked=FALSE;
  987. _tprintf(TEXT("**LOCK: IP Sessions Now Allowed\n"));
  988. }
  989. break;
  990. case 'o':
  991. case 'O': cl->SendOutput=!cl->SendOutput;
  992. break;
  993. case 'k':
  994. case 'K':TerminateProcess(ChldProc,1);
  995. break;
  996. case 's':
  997. case 'S':
  998. SendStatus(cl->PipeWriteH);
  999. break;
  1000. case 'p':
  1001. case 'P':
  1002. {
  1003. TCHAR *mssg=(TCHAR *)calloc(4096,1); //Free it in called Proc
  1004. TCHAR *ack=TEXT("WSRemote:Popup Shown..\n");
  1005. if (mssg==NULL)
  1006. break;
  1007. _stprintf(mssg,TEXT("From %s [%s]\n\n%s\n"),cl->Name,GetFormattedTime(),&buff[2]);
  1008. CreateThread(
  1009. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  1010. (DWORD)0, // Use same stack size.
  1011. (LPTHREAD_START_ROUTINE)ShowPopup, // Thread procedure.
  1012. (LPVOID)mssg, // Parameter to pass.
  1013. (DWORD)0, // Run immediately.
  1014. (LPDWORD)&ThreadID
  1015. );
  1016. #ifdef UNICODE
  1017. WriteFileW(cl->PipeWriteH,ack,_tcslen(ack),&tmp,NULL);
  1018. #else
  1019. WriteFile(cl->PipeWriteH,ack,_tcslen(ack),&tmp,NULL);
  1020. #endif
  1021. break;
  1022. }
  1023. case 'm':
  1024. case 'M':
  1025. buff[dread-2]=0;
  1026. #ifdef UNICODE
  1027. MakeCommandString( inp_buff, buff, cl->Name, GetFormattedTime());
  1028. #else
  1029. CMDSTRING(inp_buff,buff,cl,GetFormattedTime());
  1030. #endif
  1031. len=_tcslen(inp_buff);
  1032. #ifdef UNICODE
  1033. WriteFileW(SaveFile,inp_buff,len,&tmp,NULL);
  1034. #else
  1035. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1036. #endif
  1037. break;
  1038. case '@':
  1039. buff[dread-2]=0;
  1040. #ifdef UNICODE
  1041. MakeCommandString( inp_buff, buff, cl->Name, GetFormattedTime());
  1042. #else
  1043. CMDSTRING(inp_buff,&buff[1],cl,GetFormattedTime());
  1044. #endif
  1045. len=_tcslen(inp_buff);
  1046. #ifdef UNICODE
  1047. WriteFileW(SaveFile,inp_buff,len,&tmp,NULL);
  1048. #else
  1049. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1050. #endif
  1051. //
  1052. // Remove the first @ sign
  1053. //
  1054. MoveMemory(buff,&buff[1],dread-1);
  1055. buff[dread-1]=' ';
  1056. return(FALSE); //Send it it to the chile process
  1057. break;
  1058. default :
  1059. _stprintf(inp_buff,TEXT("%s"),"** Unknown Command **\n");
  1060. #ifdef UNICODE
  1061. WriteFileW( cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1062. #else
  1063. WriteFile( cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1064. #endif
  1065. case 'h':
  1066. case 'H':
  1067. {
  1068. #ifdef UNICODE
  1069. _stprintf(inp_buff,TEXT("%cM: To Send Message\n"),COMMANDCHAR);
  1070. WriteFileW(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1071. _stprintf(inp_buff,TEXT("%cP: To Generate popup\n"),COMMANDCHAR);
  1072. WriteFileW(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1073. _stprintf(inp_buff,TEXT("%cK: To kill the server\n"),COMMANDCHAR);
  1074. WriteFileW(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1075. _stprintf(inp_buff,TEXT("%cH: This Help\n"),COMMANDCHAR);
  1076. WriteFileW(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1077. #else
  1078. _stprintf(inp_buff,TEXT("%cM: To Send Message\n"),COMMANDCHAR);
  1079. WriteFile(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1080. _stprintf(inp_buff,TEXT("%cP: To Generate popup\n"),COMMANDCHAR);
  1081. WriteFile(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1082. _stprintf(inp_buff,TEXT("%cK: To kill the server\n"),COMMANDCHAR);
  1083. WriteFile(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1084. _stprintf(inp_buff,TEXT("%cH: This Help\n"),COMMANDCHAR);
  1085. WriteFile(cl->PipeWriteH,inp_buff,_tcslen(inp_buff),&tmp,NULL);
  1086. #endif
  1087. break;
  1088. }
  1089. }
  1090. return(TRUE);
  1091. }
  1092. if ((buff[0]<26))
  1093. {
  1094. BOOL ret=FALSE;
  1095. #ifdef UNICODE
  1096. TCHAR * pszTime;
  1097. #endif
  1098. _stprintf(ch,TEXT("^%c"),buff[0]+64);
  1099. #ifdef UNICODE
  1100. pszTime = GetFormattedTime();
  1101. MakeCommandString( inp_buff, ch, cl->Name, pszTime);
  1102. #else
  1103. CMDSTRING(inp_buff,ch,cl,GetFormattedTime());
  1104. #endif
  1105. len=_tcslen(inp_buff);
  1106. if (buff[0]==CTRLC)
  1107. {
  1108. cl->CommandRcvd=FALSE;
  1109. GenerateConsoleCtrlEvent(CTRL_C_EVENT,0);
  1110. ret=TRUE; //Already sent to child
  1111. }
  1112. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1113. return(ret); //FALSE:send it to child StdIn
  1114. }
  1115. tmpchar=buff[dread-2]; //must be 13;but just incase
  1116. buff[dread-2]=0;
  1117. #ifdef UNICODE
  1118. MakeCommandString( inp_buff, buff, cl->Name, GetFormattedTime());
  1119. #else
  1120. CMDSTRING(inp_buff,buff,cl,GetFormattedTime());
  1121. #endif
  1122. buff[dread-2]=tmpchar;
  1123. len=_tcslen(inp_buff);
  1124. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1125. return(FALSE);
  1126. }
  1127. /*************************************************************/
  1128. BOOL
  1129. SockFilterCommand(
  1130. SESSION_TYPE *cl,
  1131. TCHAR *buff,
  1132. int dread
  1133. )
  1134. {
  1135. TCHAR inp_buff[4096];
  1136. TCHAR tmpchar;
  1137. TCHAR ch[3];
  1138. DWORD tmp;
  1139. int len;
  1140. DWORD ThreadID; //Useless
  1141. if (dread==0)
  1142. return(FALSE);
  1143. buff[dread]=0;
  1144. if (buff[0]==COMMANDCHAR)
  1145. {
  1146. switch(buff[1])
  1147. {
  1148. case 'o':
  1149. case 'O': cl->SendOutput=!cl->SendOutput;
  1150. break;
  1151. case 'k':
  1152. case 'K':TerminateProcess(ChldProc,1);
  1153. break;
  1154. case 's':
  1155. case 'S':
  1156. SockSendStatus(cl->Socket);
  1157. break;
  1158. case 'p':
  1159. case 'P':
  1160. {
  1161. TCHAR *mssg=(TCHAR *)calloc(4096,1); //Free it in called Proc
  1162. TCHAR *ack=TEXT("WSRemote:Popup Shown..\n");
  1163. if (mssg==NULL)
  1164. break;
  1165. _stprintf(mssg,TEXT("From %s [%s]\n\n%s\n"),cl->Name,GetFormattedTime(),&buff[2]);
  1166. CreateThread(
  1167. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  1168. (DWORD)0, // Use same stack size.
  1169. (LPTHREAD_START_ROUTINE)ShowPopup, // Thread procedure.
  1170. (LPVOID)mssg, // Parameter to pass.
  1171. (DWORD)0, // Run immediately.
  1172. (LPDWORD)&ThreadID
  1173. );
  1174. WriteSocket(cl->Socket,ack,_tcslen(ack),&tmp);
  1175. break;
  1176. }
  1177. case 'm':
  1178. case 'M':
  1179. buff[dread-2]=0;
  1180. #ifdef UNICODE
  1181. MakeCommandString( inp_buff, buff, cl->Name, GetFormattedTime());
  1182. #else
  1183. CMDSTRING(inp_buff,buff,cl,GetFormattedTime());
  1184. #endif
  1185. len=_tcslen(inp_buff);
  1186. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1187. break;
  1188. case '@':
  1189. buff[dread-2]=0;
  1190. #ifdef UNICODE
  1191. MakeCommandString( inp_buff, buff, cl->Name, GetFormattedTime());
  1192. #else
  1193. CMDSTRING(inp_buff,&buff[1],cl,GetFormattedTime());
  1194. #endif
  1195. len=_tcslen(inp_buff);
  1196. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1197. //
  1198. // Remove the first @ sign
  1199. //
  1200. MoveMemory(buff,&buff[1],dread-1);
  1201. buff[dread-1]=' ';
  1202. return(FALSE); //Send it it to the chile process
  1203. break;
  1204. default :
  1205. _stprintf(inp_buff,TEXT("%s"),"** Unknown Command **\n");
  1206. WriteSocket(cl->Socket,inp_buff,_tcslen(inp_buff),&tmp);
  1207. case 'h':
  1208. case 'H':
  1209. _stprintf(inp_buff,TEXT("%cM: To Send Message\n"),COMMANDCHAR);
  1210. WriteSocket(cl->Socket,inp_buff,_tcslen(inp_buff),&tmp);
  1211. _stprintf(inp_buff,TEXT("%cP: To Generate popup\n"),COMMANDCHAR);
  1212. WriteSocket(cl->Socket,inp_buff,_tcslen(inp_buff),&tmp);
  1213. _stprintf(inp_buff,TEXT("%cK: To kill the server\n"),COMMANDCHAR);
  1214. WriteSocket(cl->Socket,inp_buff,_tcslen(inp_buff),&tmp);
  1215. _stprintf(inp_buff,TEXT("%cH: This Help\n"),COMMANDCHAR);
  1216. WriteSocket(cl->Socket,inp_buff,_tcslen(inp_buff),&tmp);
  1217. break;
  1218. }
  1219. return(TRUE);
  1220. }
  1221. if ((buff[0]<26))
  1222. {
  1223. BOOL ret=FALSE;
  1224. _stprintf(ch,TEXT("^%c"),buff[0]+64);
  1225. #ifdef UNICODE
  1226. MakeCommandString( inp_buff, ch, cl->Name, GetFormattedTime());
  1227. #else
  1228. CMDSTRING(inp_buff,ch,cl,GetFormattedTime());
  1229. #endif
  1230. len=_tcslen(inp_buff);
  1231. if (buff[0]==CTRLC)
  1232. {
  1233. cl->CommandRcvd=FALSE;
  1234. GenerateConsoleCtrlEvent(CTRL_C_EVENT,0);
  1235. ret=TRUE; //Already sent to child
  1236. }
  1237. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1238. return(ret); //FALSE:send it to child StdIn
  1239. }
  1240. tmpchar=buff[dread-2]; //must be 13;but just incase
  1241. buff[dread-2]=0;
  1242. #ifdef UNICODE
  1243. MakeCommandString( inp_buff, buff, cl->Name, GetFormattedTime());
  1244. #else
  1245. CMDSTRING(inp_buff,buff,cl,GetFormattedTime());
  1246. #endif
  1247. buff[dread-2]=tmpchar;
  1248. len=_tcslen(inp_buff);
  1249. WriteFile(SaveFile,inp_buff,len,&tmp,NULL);
  1250. return(FALSE);
  1251. }
  1252. /*************************************************************/
  1253. VOID
  1254. SendStatus(
  1255. HANDLE hClientPipe
  1256. )
  1257. {
  1258. TCHAR buff[1024];
  1259. int i;
  1260. DWORD tmp;
  1261. TCHAR *env=(TCHAR *)GetEnvironmentStrings();
  1262. DWORD ver=GetVersion();
  1263. _stprintf(buff,TEXT("Command = %s\n"),ChildCmd);
  1264. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1265. _stprintf(buff,TEXT("Server = %s PIPE=%s\n"),HostName,PipeName);
  1266. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1267. _stprintf(buff,TEXT("IP Blocking= %d\n"),(DWORD)bIPLocked);
  1268. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1269. _stprintf(buff,TEXT("Username= %s Password=%s\n"),Username,Password);
  1270. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1271. _stprintf(buff,TEXT("Build = %d \n"),((WORD *)&ver)[1]);
  1272. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1273. for (i=1;i<MAX_SESSION;i++)
  1274. {
  1275. if (ClientList[i].Active)
  1276. {
  1277. _stprintf(buff,TEXT("ACTIVE SESSION=%s\n"),ClientList[i].Name);
  1278. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1279. }
  1280. }
  1281. _stprintf(buff,TEXT("====================\n"),Server,PipeName);
  1282. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1283. _stprintf(buff,TEXT("ENVIRONMENT VARIABLES\n"),Server,PipeName);
  1284. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1285. _stprintf(buff,TEXT("====================\n"),Server,PipeName);
  1286. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1287. __try
  1288. {
  1289. while (*env!=0)
  1290. {
  1291. _stprintf(buff,TEXT("%s\n"),env);
  1292. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1293. while(*(env++)!=0);
  1294. }
  1295. }
  1296. __except(EXCEPTION_EXECUTE_HANDLER)
  1297. {
  1298. _stprintf(buff,TEXT("Exception Generated Getting Environment Block\n"),env);
  1299. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1300. }
  1301. _stprintf(buff,TEXT("====================\n"),Server,PipeName);
  1302. WriteFile(hClientPipe,buff,_tcslen(buff),&tmp,NULL);
  1303. return;
  1304. }
  1305. /*************************************************************/
  1306. VOID
  1307. SockSendStatus(
  1308. SOCKET MySocket
  1309. )
  1310. {
  1311. TCHAR buff[1024];
  1312. int i;
  1313. DWORD tmp;
  1314. TCHAR *env=(TCHAR *)GetEnvironmentStrings();
  1315. DWORD ver=GetVersion();
  1316. _stprintf(buff,TEXT("Command = %s\n"),ChildCmd);
  1317. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1318. _stprintf(buff,TEXT("Server = %s Port=%s\n"),HostName,PipeName);
  1319. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1320. _stprintf(buff,TEXT("IP Blocking= %d\n"),(DWORD)bIPLocked);
  1321. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1322. _stprintf(buff,TEXT("Username= %s Password=%s\n"),Username,Password);
  1323. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1324. _stprintf(buff,TEXT("Build = %d \n"),((WORD *)&ver)[1]);
  1325. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1326. for (i=1;i<MAX_SESSION;i++)
  1327. {
  1328. if (ClientList[i].Active)
  1329. {
  1330. _stprintf(buff,TEXT("ACTIVE SESSION=%s from IP %s \n"),ClientList[i].Name, ClientList[i].szIP );
  1331. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1332. }
  1333. }
  1334. _stprintf(buff,TEXT("====================\n"),Server,PipeName);
  1335. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1336. _stprintf(buff,TEXT("ENVIRONMENT VARIABLES\n"),Server,PipeName);
  1337. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1338. _stprintf(buff,TEXT("====================\n"),Server,PipeName);
  1339. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1340. __try
  1341. {
  1342. while (*env!=0)
  1343. {
  1344. _stprintf(buff,TEXT("%s\n"),env);
  1345. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1346. while(*(env++)!=0);
  1347. }
  1348. }
  1349. __except(EXCEPTION_EXECUTE_HANDLER)
  1350. {
  1351. _stprintf(buff,TEXT("Exception Generated Getting Environment Block\n"),env);
  1352. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1353. }
  1354. _stprintf(buff,TEXT("====================\n"),Server,PipeName);
  1355. WriteSocket(MySocket,buff,_tcslen(buff),&tmp);
  1356. return;
  1357. }
  1358. /*************************************************************/
  1359. DWORD
  1360. ShowPopup(
  1361. TCHAR *mssg
  1362. )
  1363. {
  1364. MessageBox(GetActiveWindow(),mssg,TEXT("***WSREMOTE***"),MB_OK|MB_SETFOREGROUND);
  1365. free(mssg);
  1366. return(0);
  1367. }
  1368. /*************************************************************/
  1369. BOOL SrvCtrlHand(
  1370. DWORD event
  1371. )
  1372. {
  1373. if (event==CTRL_BREAK_EVENT)
  1374. {
  1375. TerminateProcess(ChldProc,1);
  1376. return(TRUE);
  1377. }
  1378. else if (event==CTRL_C_EVENT)
  1379. return(TRUE);
  1380. return(FALSE);
  1381. }
  1382. /*************************************************************/
  1383. DWORD LocalSession(PVOID noarg)
  1384. {
  1385. //Local is ClientList[0]
  1386. TCHAR *name=(TCHAR *)ClientList[0].Name;
  1387. _tcscpy(name,LOCALNAME);
  1388. if ((ClientList[0].rSaveFile=CreateFile(SaveFileName,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL))==NULL)
  1389. {
  1390. _tprintf(TEXT("WSRemote:Cannot open ReadHandle to Savefile:%d\n"),GetLastError());
  1391. ClientList[0].Active=FALSE;
  1392. return(1);
  1393. }
  1394. ClientList[0].PipeReadH=GetStdHandle(STD_INPUT_HANDLE);
  1395. ClientList[0].PipeWriteH=GetStdHandle(STD_OUTPUT_HANDLE);
  1396. ClientList[0].SendOutput=TRUE;
  1397. ClientList[0].Active=TRUE;
  1398. NewSession(&ClientList[0]);
  1399. CloseClient(&ClientList[0]);
  1400. return(0);
  1401. }
  1402. VOID
  1403. CloseClient(
  1404. SESSION_TYPE *Client
  1405. )
  1406. {
  1407. int nRet;
  1408. ZeroMemory(Client->Name,HOSTNAMELEN);
  1409. if (Client->PipeReadH!=INVALID_HANDLE_VALUE)
  1410. {
  1411. CloseHandle(Client->PipeReadH);
  1412. Client->PipeReadH=INVALID_HANDLE_VALUE;
  1413. }
  1414. if (Client->PipeWriteH!=INVALID_HANDLE_VALUE)
  1415. {
  1416. CloseHandle(Client->PipeWriteH);
  1417. Client->PipeWriteH=INVALID_HANDLE_VALUE;
  1418. }
  1419. if (Client->rSaveFile!=INVALID_HANDLE_VALUE)
  1420. {
  1421. CloseHandle(Client->rSaveFile);
  1422. Client->rSaveFile=INVALID_HANDLE_VALUE;
  1423. }
  1424. if (Client->MoreData!=NULL)
  1425. {
  1426. CloseHandle(Client->MoreData);
  1427. Client->MoreData=NULL;
  1428. }
  1429. if (Client->Socket!=INVALID_SOCKET)
  1430. {
  1431. nRet = shutdown(Client->Socket, SD_BOTH);
  1432. if (nRet == SOCKET_ERROR)
  1433. _tprintf(TEXT("** shutdown()..error %d"), WSAGetLastError());
  1434. closesocket(Client->Socket);
  1435. Client->Socket=INVALID_SOCKET;
  1436. }
  1437. ZeroMemory(Client->szIP,16);
  1438. Client->Active=FALSE; //Keep it last else synch problem.
  1439. return;
  1440. }
  1441. VOID
  1442. InitClientList(
  1443. )
  1444. {
  1445. int i;
  1446. for (i=0;i<MAX_SESSION;i++)
  1447. {
  1448. ZeroMemory(ClientList[i].Name,HOSTNAMELEN);
  1449. ClientList[i].PipeReadH=INVALID_HANDLE_VALUE;
  1450. ClientList[i].PipeWriteH=INVALID_HANDLE_VALUE;
  1451. ClientList[i].rSaveFile=INVALID_HANDLE_VALUE;
  1452. ClientList[i].MoreData=NULL;
  1453. ClientList[i].Socket=INVALID_SOCKET;
  1454. ClientList[i].Active=FALSE;
  1455. ClientList[i].CommandRcvd=FALSE;
  1456. ClientList[i].SendOutput=FALSE;
  1457. ClientList[i].hThread=NULL;
  1458. ZeroMemory(ClientList[i].szIP,16);
  1459. }
  1460. return;
  1461. }
  1462. VOID
  1463. RemoveInpMark(
  1464. TCHAR* Buff,
  1465. DWORD Size
  1466. )
  1467. {
  1468. DWORD i;
  1469. for (i=0;i<Size;i++)
  1470. {
  1471. switch (Buff[i])
  1472. {
  1473. case BEGINMARK:
  1474. Buff[i]=' ';
  1475. break;
  1476. case ENDMARK:
  1477. if (i<2)
  1478. {
  1479. Buff[i]= ' ';
  1480. }
  1481. else
  1482. {
  1483. Buff[i] =Buff[i-1];
  1484. Buff[i-1]=Buff[i-2];
  1485. Buff[i-2]=' ';
  1486. }
  1487. break;
  1488. default:
  1489. break;
  1490. }
  1491. }
  1492. }
  1493. /*************************************************************/
  1494. DWORD
  1495. SockListenForSession(
  1496. TCHAR* szListenPort
  1497. )
  1498. {
  1499. // Bind and Listen
  1500. DWORD ThreadID;
  1501. SOCKADDR_IN saServer;
  1502. int nRet;
  1503. unsigned short usPort;
  1504. int i;
  1505. // Accept
  1506. SOCKET socketClient;
  1507. SOCKADDR_IN SockAddr;
  1508. int nLen;
  1509. int iWSAErr;
  1510. TCHAR * pszInetAddress = NULL;
  1511. //
  1512. // Create a TCP/IP stream socket
  1513. //
  1514. listenSocket = socket ( AF_INET,
  1515. SOCK_STREAM,
  1516. IPPROTO_TCP);
  1517. if (listenSocket == INVALID_SOCKET)
  1518. {
  1519. _tprintf (TEXT("Could not create listen socket: %d"), WSAGetLastError() );
  1520. return FALSE;
  1521. }
  1522. //
  1523. // Get the port number
  1524. // TODO: Check szListenPort for Alpha Chars
  1525. //
  1526. usPort = (unsigned short)_ttoi( szListenPort );
  1527. if (usPort == 0)
  1528. {
  1529. _tprintf (TEXT("**Invalid Listen Port: %s\n"),szListenPort);
  1530. _tprintf (TEXT("**No Socket Connections Allowed....\n"));
  1531. nRet = shutdown(listenSocket, SD_BOTH);
  1532. if (nRet == SOCKET_ERROR)
  1533. _tprintf(TEXT("** shutdown()..error %d"), WSAGetLastError());
  1534. closesocket(listenSocket);
  1535. return FALSE;
  1536. }
  1537. saServer.sin_port = htons(usPort);
  1538. //
  1539. // Fill in the rest of the address structure
  1540. //
  1541. saServer.sin_family = AF_INET;
  1542. saServer.sin_addr.s_addr = INADDR_ANY;
  1543. //
  1544. // Bind our name to the socket
  1545. //
  1546. nRet = bind( listenSocket,
  1547. (LPSOCKADDR)&saServer,
  1548. sizeof(struct sockaddr));
  1549. if (nRet == SOCKET_ERROR)
  1550. {
  1551. _tprintf (TEXT("bind() error: %d"), WSAGetLastError() );
  1552. nRet = shutdown(listenSocket, SD_BOTH);
  1553. if (nRet == SOCKET_ERROR)
  1554. _tprintf(TEXT("** shutdown()..error %d"), WSAGetLastError());
  1555. closesocket(listenSocket);
  1556. return FALSE;
  1557. }
  1558. //
  1559. // Set the Socket to listen
  1560. //
  1561. nRet = listen(listenSocket, SOMAXCONN);
  1562. if (nRet == SOCKET_ERROR)
  1563. {
  1564. _tprintf (TEXT("listen error() error: %d"), WSAGetLastError() );
  1565. nRet = shutdown(listenSocket, SD_BOTH);
  1566. if (nRet == SOCKET_ERROR)
  1567. _tprintf(TEXT("** shutdown()..error %d"), WSAGetLastError());
  1568. closesocket(listenSocket);
  1569. return FALSE;
  1570. }
  1571. while (1)
  1572. {
  1573. // Block on Accept()
  1574. nLen = sizeof(SOCKADDR_IN);
  1575. socketClient = accept (listenSocket,
  1576. (LPSOCKADDR)&SockAddr,
  1577. &nLen);
  1578. if (socketClient == INVALID_SOCKET)
  1579. {
  1580. //Accept Failed
  1581. _tprintf (TEXT("accept error() error: %d"), WSAGetLastError() );
  1582. break;
  1583. }// if
  1584. #ifdef UNICODE
  1585. pszInetAddress = inet_ntoaw(SockAddr.sin_addr);
  1586. #else
  1587. pszInetAddress = inet_ntoa(SockAddr.sin_addr);
  1588. #endif
  1589. _tprintf( TEXT("\nCONNECT on socket: %d\nFROM ip: %s"),
  1590. socketClient,
  1591. pszInetAddress );
  1592. //
  1593. //Look For a Free Slot & if not- then terminate connection
  1594. //
  1595. for (i=1;i<MAX_SESSION;i++)
  1596. {
  1597. //
  1598. // Locate a Free Client block
  1599. //
  1600. if (!ClientList[i].Active)
  1601. break;
  1602. }// for
  1603. if ( (i<MAX_SESSION) && (bIPLocked == FALSE) )
  1604. {
  1605. //
  1606. // Initialize the Client
  1607. //
  1608. ClientList[i].PipeReadH=INVALID_HANDLE_VALUE;
  1609. ClientList[i].PipeWriteH=INVALID_HANDLE_VALUE;
  1610. ClientList[i].Active=TRUE;
  1611. ClientList[i].SendOutput=TRUE;
  1612. ClientList[i].CommandRcvd=FALSE;
  1613. // SOCK
  1614. ClientList[i].Socket=socketClient;
  1615. _tcscpy(ClientList[i].szIP,pszInetAddress);
  1616. #ifdef UNICODE
  1617. free( pszInetAddress );
  1618. #endif
  1619. //
  1620. //start new thread for this connection
  1621. //
  1622. if((ClientList[i].hThread=CreateThread (
  1623. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  1624. (DWORD)0, // Use same stack size.
  1625. (LPTHREAD_START_ROUTINE)SockRemoteSession, // Thread procedure.
  1626. (LPVOID)&ClientList[i], // Parameter to pass.
  1627. (DWORD)0, // Run immediately.
  1628. (LPDWORD)&ThreadID))==NULL)
  1629. {
  1630. CloseClient(&ClientList[i]);
  1631. continue;
  1632. }// if
  1633. }
  1634. else
  1635. {
  1636. _tprintf(TEXT("WSRemote:Closing New Session - No more slots or IP is Locked Out\n"));
  1637. nRet = shutdown(socketClient, SD_BOTH);
  1638. if (nRet == SOCKET_ERROR)
  1639. _tprintf(TEXT("** shutdown()..error %d"), WSAGetLastError());
  1640. closesocket(socketClient);
  1641. continue;
  1642. }//if
  1643. }// while
  1644. iWSAErr = WSAGetLastError();
  1645. _tprintf (TEXT("FATAL ERROR, Exiting SockListenForSession: %d"),
  1646. iWSAErr );
  1647. return 0;
  1648. }
  1649. /*************************************************************/
  1650. DWORD
  1651. SockRemoteSession(
  1652. SESSION_TYPE *MyClient
  1653. )
  1654. {
  1655. //Declare Variables
  1656. //
  1657. DWORD ReadCnt;
  1658. DWORD tmp;
  1659. SESSION_STARTUPINFO ssi;
  1660. TCHAR * headerbuff;
  1661. TCHAR msg[BUFFSIZE];
  1662. SESSION_STARTREPLY ssr;
  1663. DWORD reply =0;
  1664. BOOL bRet;
  1665. if ((MyClient->rSaveFile=CreateFile(
  1666. SaveFileName,
  1667. GENERIC_READ|GENERIC_WRITE,
  1668. FILE_SHARE_READ|FILE_SHARE_WRITE,
  1669. NULL,OPEN_EXISTING,
  1670. FILE_ATTRIBUTE_NORMAL,NULL))==NULL)
  1671. {
  1672. CloseClient(MyClient);
  1673. return(1);
  1674. }
  1675. bRet = SockAuthenticate(MyClient->Socket);
  1676. if (bRet == FALSE)
  1677. {
  1678. _tprintf(TEXT("\nAuth:Bad Username or Password\n"));
  1679. CloseClient(MyClient);
  1680. return(1);
  1681. }
  1682. // ReadSocket( MyClient->Socket,
  1683. // (TCHAR *)MyClient->Name,
  1684. // HOSTNAMELEN-1,
  1685. // &dwBytesRead);
  1686. SockReadFixBytes(MyClient->Socket,(TCHAR *)MyClient->Name,HOSTNAMELEN-1,0);
  1687. //
  1688. //Last four Bytes contains a code
  1689. //
  1690. memcpy((TCHAR *)&reply,(TCHAR *)&(MyClient->Name[11]),4);
  1691. if (reply!=MAGICNUMBER)
  1692. {
  1693. //
  1694. // Unknown client
  1695. //
  1696. CloseClient(MyClient);
  1697. return(1);
  1698. }
  1699. ssr.MagicNumber=MAGICNUMBER;
  1700. ssr.Size=sizeof(ssr);
  1701. ssr.FileSize=GetFileSize( MyClient->rSaveFile, &tmp );
  1702. send(MyClient->Socket,(const char *)&ssr,sizeof(ssr),0);
  1703. if (SockReadFixBytes(MyClient->Socket,(TCHAR *)&(ssi.Size),sizeof(ssi.Size),0)!=0)
  1704. {
  1705. CloseClient(MyClient);
  1706. return(1);
  1707. }
  1708. if (ssi.Size>1024) //Sanity Check
  1709. {
  1710. _stprintf(msg,TEXT("%s"),"Server:Unknown Header..Terminating session\n");
  1711. WriteSocket(MyClient->Socket,msg,_tcslen(msg),&tmp);
  1712. CloseClient(MyClient);
  1713. return(1);
  1714. }
  1715. if ((headerbuff=(TCHAR *)calloc(ssi.Size,1))==NULL)
  1716. {
  1717. _stprintf(msg,TEXT("%s"),"Server:Not Enough Memory..Terminating session\n");
  1718. WriteSocket(MyClient->Socket,msg,_tcslen(msg),&tmp);
  1719. CloseClient(MyClient);
  1720. return(1);
  1721. }
  1722. ReadCnt=ssi.Size-sizeof(ssi.Size);
  1723. if (SockReadFixBytes(MyClient->Socket,(TCHAR *)headerbuff,ReadCnt,0)!=0)
  1724. {
  1725. CloseClient(MyClient);
  1726. return(1);
  1727. }
  1728. memcpy((TCHAR *)&ssi+sizeof(ssi.Size),headerbuff,sizeof(ssi)-sizeof(ssi.Size));
  1729. free(headerbuff);
  1730. /* Version */
  1731. if (ssi.Version!=VERSION)
  1732. {
  1733. _stprintf(msg,TEXT("WSRemote Warning:Server Version=%d Client Version=%d\n"),VERSION,ssi.Version);
  1734. WriteSocket(MyClient->Socket,msg,_tcslen(msg),&tmp);
  1735. }
  1736. /* Name */
  1737. {
  1738. memcpy(MyClient->Name,ssi.ClientName,15);
  1739. MyClient->Name[14]=0;
  1740. }
  1741. /* Lines */
  1742. if (ssi.LinesToSend!=-1)
  1743. {
  1744. long PosFromEnd=ssi.LinesToSend*CHARS_PER_LINE;
  1745. DWORD BytesToSend=MINIMUM((DWORD)PosFromEnd,ssr.FileSize);
  1746. DWORD BytesRead;
  1747. TCHAR *buff=(TCHAR *)calloc(BytesToSend+1,1);
  1748. if (ssr.FileSize > (DWORD)PosFromEnd)
  1749. {
  1750. SetFilePointer( MyClient->rSaveFile,
  1751. -PosFromEnd,
  1752. (PLONG)NULL,
  1753. FILE_END
  1754. );
  1755. }
  1756. if (buff!=NULL)
  1757. {
  1758. if (!ReadFile(MyClient->rSaveFile,buff,BytesToSend,&BytesRead,NULL))
  1759. {
  1760. CloseClient(MyClient);
  1761. return(1);
  1762. }
  1763. RemoveInpMark(buff,BytesRead);
  1764. if (!WriteSocket(MyClient->Socket,buff,BytesRead,&tmp))
  1765. {
  1766. CloseClient(MyClient);
  1767. return(1);
  1768. }
  1769. }
  1770. free(buff);
  1771. }
  1772. RemoteInfo(_tprintf(TEXT("\n**WSRemote:Connected To %s ip=%s [%s]\n"),MyClient->Name,MyClient->szIP,GetFormattedTime()),ssi.Flag);
  1773. SockNewSession(MyClient);
  1774. RemoteInfo(_tprintf(TEXT("\n**WSRemote:Disconnected From %s ip=%s [%s]\n"),MyClient->Name,MyClient->szIP,GetFormattedTime()),ssi.Flag);
  1775. CloseClient(MyClient);
  1776. return(0);
  1777. }
  1778. /*************************************************************/
  1779. DWORD
  1780. SockNewSession(
  1781. SESSION_TYPE* MyClient
  1782. )
  1783. {
  1784. DWORD ThreadId;
  1785. HANDLE rwThread[3];
  1786. MyClient->MoreData=CreateEvent
  1787. (
  1788. (LPSECURITY_ATTRIBUTES) NULL,/* address of security attributes */
  1789. FALSE, /* flag for manual-reset event */
  1790. TRUE, /* flag for initial state */
  1791. NULL /* address of event-object name */
  1792. );
  1793. if ((rwThread[0]=CreateThread (
  1794. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  1795. (DWORD)0, // Use same stack size.
  1796. (LPTHREAD_START_ROUTINE)SockGetClientInput, // Thread procedure.
  1797. (LPVOID)MyClient, // Parameter to pass.
  1798. (DWORD)0, // Run immediately.
  1799. (LPDWORD)&ThreadId))==NULL)
  1800. {
  1801. return(GetLastError());
  1802. }
  1803. if ((rwThread[1]=CreateThread (
  1804. (LPSECURITY_ATTRIBUTES)NULL, // No security attributes.
  1805. (DWORD)0, // Use same stack size.
  1806. (LPTHREAD_START_ROUTINE)SockTransferFileToClient, // Thread procedure.
  1807. (LPVOID)MyClient, // Parameter to pass.
  1808. (DWORD)0, // Run immediately.
  1809. (LPDWORD)&ThreadId))==NULL)
  1810. {
  1811. CloseHandle(rwThread[0]);
  1812. return(GetLastError());
  1813. }
  1814. rwThread[2]=ChldProc;
  1815. WaitForMultipleObjects(3, rwThread,FALSE, INFINITE);
  1816. TerminateThread(rwThread[0],1);
  1817. TerminateThread(rwThread[1],1);
  1818. CloseHandle(rwThread[0]);
  1819. CloseHandle(rwThread[1]);
  1820. return(0);
  1821. }
  1822. /*************************************************************/
  1823. DWORD
  1824. SockGetClientInput(
  1825. SESSION_TYPE *MyClient
  1826. )
  1827. {
  1828. TCHAR buf[BUFFSIZE];
  1829. DWORD tmp,
  1830. dread;
  1831. memset(buf, 0, sizeof(buf));
  1832. while(ReadSocket(MyClient->Socket,buf,BUFFSIZE,&dread))
  1833. {
  1834. buf[sizeof(buf)]=0;
  1835. MyClient->CommandRcvd=TRUE;
  1836. if (0 == buf[0] )
  1837. return(1);
  1838. if (SockFilterCommand(MyClient,buf,dread))
  1839. continue;
  1840. if (!WriteFile(ChildStdInp,buf,dread,&tmp,NULL))
  1841. {
  1842. ExitThread(0);
  1843. }
  1844. memset(buf, 0, sizeof(buf));
  1845. }
  1846. return(1);
  1847. }
  1848. /*************************************************************/
  1849. DWORD
  1850. SockTransferFileToClient(
  1851. SESSION_TYPE *MyClient
  1852. )
  1853. {
  1854. TCHAR buffin[BUFFSIZE],
  1855. buffout[BUFFSIZE],
  1856. cmdbuff[BUFFSIZE];
  1857. DWORD tmp;
  1858. DWORD dread=0,dwrite=0;
  1859. BOOL incmd=FALSE;
  1860. DWORD cmdP=0;
  1861. DWORD i;
  1862. TCHAR MyEchoStr[30];
  1863. _stprintf(MyEchoStr,TEXT("[%-15s"),MyClient->Name);
  1864. while(ReadFile(MyClient->rSaveFile,buffin,BUFFSIZE-1,&dread,NULL))
  1865. {
  1866. if (dread==0)
  1867. {
  1868. WaitForSingleObject(MyClient->MoreData,INFINITE);
  1869. continue;
  1870. }
  1871. dwrite=0;
  1872. for(i=0;i<dread;i++)
  1873. {
  1874. if (incmd)
  1875. {
  1876. if ((buffin[i]==ENDMARK)||(cmdP==BUFFSIZE-1))
  1877. {
  1878. incmd=FALSE;
  1879. cmdbuff[cmdP]=0;
  1880. if ((_tcsstr(cmdbuff,MyEchoStr)==NULL)||
  1881. (!MyClient->CommandRcvd))
  1882. {
  1883. //if (!send (MyClient->Socket, cmdbuff, cmdP, 0));
  1884. //if (!SendBuffer(MyClient, cmdbuff, cmdP))
  1885. if (!WriteSocket(MyClient->Socket, cmdbuff,cmdP,&tmp))
  1886. {
  1887. return(1);
  1888. }
  1889. }
  1890. cmdP=0;
  1891. }
  1892. else
  1893. {
  1894. cmdbuff[cmdP++]=buffin[i];
  1895. }
  1896. }
  1897. else
  1898. {
  1899. if (buffin[i]==BEGINMARK)
  1900. {
  1901. if (dwrite!=0)
  1902. {
  1903. //if (!send (MyClient->Socket, buffout, dwrite, 0));
  1904. //if (!SendBuffer(MyClient, buffout, dwrite))
  1905. if (!WriteSocket(
  1906. MyClient->Socket,
  1907. buffout,dwrite,&tmp))
  1908. {
  1909. return(1);
  1910. }
  1911. dwrite=0;
  1912. }
  1913. incmd=TRUE;
  1914. continue;
  1915. }
  1916. else
  1917. {
  1918. buffout[dwrite++]=buffin[i];
  1919. }
  1920. }
  1921. }
  1922. if (dwrite!=0)
  1923. {
  1924. //if (!send (MyClient->Socket, buffout, dwrite, 0));
  1925. //if (!SendBuffer(MyClient, buffout, dwrite))
  1926. if (!WriteSocket(
  1927. MyClient->Socket,
  1928. buffout,dwrite,&tmp))
  1929. {
  1930. return(0);
  1931. }
  1932. }
  1933. }
  1934. return(1);
  1935. }
  1936. BOOL
  1937. SockAuthenticate(
  1938. SOCKET MySocket
  1939. )
  1940. {
  1941. BOOL bRead;
  1942. DWORD dread;
  1943. int bufflen;
  1944. int iCmp;
  1945. TCHAR EncodeBuffer[1024];
  1946. TCHAR CheckEncodeBuffer[1024];
  1947. TCHAR UserBuffer[1024];
  1948. TCHAR * String = UserBuffer;
  1949. TCHAR * pEncodeBuffer;
  1950. TCHAR * pCheckEncodeBuffer;
  1951. SetLastError(0);
  1952. memset(CheckEncodeBuffer, 0, sizeof(CheckEncodeBuffer));
  1953. _stprintf(
  1954. UserBuffer, TEXT("%s:%s"),
  1955. Username,
  1956. Password);
  1957. pCheckEncodeBuffer = CheckEncodeBuffer + _tcslen(CheckEncodeBuffer);
  1958. Base64Encode(UserBuffer, _tcslen(UserBuffer), pCheckEncodeBuffer);
  1959. bufflen = _tcslen(pCheckEncodeBuffer);
  1960. memset(EncodeBuffer, 0, sizeof(EncodeBuffer));
  1961. bRead = ReadSocket(MySocket,EncodeBuffer,bufflen,&dread);
  1962. pEncodeBuffer = EncodeBuffer;
  1963. iCmp = _tcscmp(pEncodeBuffer, pCheckEncodeBuffer);
  1964. if (iCmp != 0)
  1965. return FALSE;
  1966. return TRUE;
  1967. }
  1968. #ifdef UNICODE
  1969. int MakeCommandString(
  1970. TCHAR * pszOutput,
  1971. TCHAR * pszInput,
  1972. TCHAR * pszName,
  1973. TCHAR * pszTime
  1974. )
  1975. {
  1976. int nStrLen =_stprintf( pszOutput,
  1977. TEXT("\xfe%-15s [%-15s %s]\n\xff"),
  1978. pszInput,
  1979. pszName,
  1980. pszTime );
  1981. return nStrLen;
  1982. }
  1983. #endif