daily pastebin goal
4%
SHARE
TWEET

Untitled

a guest Oct 12th, 2017 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "stdafx.h"
  2. #define _WINSOCK_DEPRECATED_NO_WARNINGS
  3. #include "Winsock2.h" // necessary for sockets, Windows.h is not needed.
  4. #include "mswsock.h"
  5. #include "process.h"  // necessary for threading
  6. //
  7. // Global variables
  8. //
  9. TCHAR CommandBuf[81];
  10. HANDLE hCommandGot;       // event "the user has typed a command"
  11. HANDLE hStopCommandGot;   // event "the main thread has recognized that it was the stop command"
  12. HANDLE hCommandProcessed; // event "the main thread has finished the processing of command"
  13. HANDLE hConnectCommandGot;
  14. HANDLE hSendPassword;
  15.  
  16.  
  17. HANDLE hReadKeyboard;     // keyboard reading thread handle
  18. HANDLE hStdIn;            // stdin standard input stream handle
  19. WSADATA WsaData;          // filled during Winsock initialization
  20. DWORD Error;
  21. SOCKET hClientSocket = INVALID_SOCKET;
  22. sockaddr_in ClientSocketInfo;
  23. HANDLE hReceiveNet;       // TCP/IP info reading thread handle
  24. HANDLE hSendNet;
  25. BOOL SocketError;
  26. //
  27. // Prototypes
  28. //
  29. unsigned int __stdcall ReadKeyboard(void* pArguments);
  30. unsigned int __stdcall ReceiveNet(void* pArguments);
  31. unsigned int __stdcall SendNet(void* pArguments);
  32.  
  33. //****************************************************************************************************************
  34. //                                 MAIN THREAD
  35. //****************************************************************************************************************
  36. int _tmain(int argc, _TCHAR* argv[])
  37. {
  38.     //
  39.     // Initializations for multithreading
  40.     //
  41.     if (!(hCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
  42.         !(hStopCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) ||
  43.         !(hCommandProcessed = CreateEvent(NULL, TRUE, TRUE, NULL)) ||
  44.         !(hConnectCommandGot = CreateEvent(NULL, TRUE, FALSE, NULL)) )
  45.     {
  46.         _tprintf(_T("CreateEvent() failed, error %d\n"), GetLastError());
  47.         return 1;
  48.     }
  49.     //
  50.     // Prepare keyboard, start the thread
  51.     //
  52.     hStdIn = GetStdHandle(STD_INPUT_HANDLE);
  53.     if (hStdIn == INVALID_HANDLE_VALUE)
  54.     {
  55.         _tprintf(_T("GetStdHandle() failed, error %d\n"), GetLastError());
  56.         return 1;
  57.     }
  58.     if (!SetConsoleMode(hStdIn, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT))
  59.     {
  60.         _tprintf(_T("SetConsoleMode() failed, error %d\n"), GetLastError());
  61.         return 1;
  62.     }
  63.     if (!(hReadKeyboard = (HANDLE)_beginthreadex(NULL, 0, &ReadKeyboard, NULL, 0, NULL)))
  64.     {
  65.         _tprintf(_T("Unable to create keyboard thread\n"));
  66.         return 1;
  67.     }
  68.     //
  69.     // Initializations for socket
  70.     //
  71.     if (Error = WSAStartup(MAKEWORD(2, 0), &WsaData)) // Initialize Windows socket support
  72.     {
  73.         _tprintf(_T("WSAStartup() failed, error %d\n"), Error);
  74.         SocketError = TRUE;
  75.     }
  76.     else if ((hClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
  77.     {
  78.         _tprintf(_T("socket() failed, error %d\n"), WSAGetLastError());
  79.         SocketError = TRUE;
  80.     }
  81.     //
  82.     // Connect client to server
  83.     //
  84.     if (!SocketError)
  85.     {
  86.         ClientSocketInfo.sin_family = AF_INET;
  87.         ClientSocketInfo.sin_addr.s_addr = inet_addr("127.0.0.1");
  88.         ClientSocketInfo.sin_port = htons(1234);  // port number is selected just for example
  89.         if (connect(hClientSocket, (SOCKADDR*)&ClientSocketInfo, sizeof(ClientSocketInfo)) == SOCKET_ERROR)
  90.         {
  91.             _tprintf(_T("Unable to connect to server, error %d\n"), WSAGetLastError());
  92.             SocketError = TRUE;
  93.         }
  94.     }
  95.     //
  96.     // Start net receiving thread
  97.     //
  98.     if (!SocketError)
  99.     {
  100.         if (!(hReceiveNet = (HANDLE)_beginthreadex(NULL, 0, &ReceiveNet, NULL, 0, NULL)))
  101.         {
  102.             _tprintf(_T("Unable to create socket receiving thread\n"));
  103.             goto out;
  104.         }
  105.         if (!(hSendNet = (HANDLE)_beginthreadex(NULL, 0, &SendNet, NULL, 0, NULL)))
  106.         {
  107.             _tprintf(_T("Unable to create socket receiving thread\n"));
  108.             goto out;
  109.         }
  110.  
  111.     }
  112.     //start net sending thread
  113.    
  114.     //
  115.     // Main processing loop
  116.     //
  117.     while (TRUE)
  118.     {
  119.         if (WaitForSingleObject(hCommandGot, INFINITE) != WAIT_OBJECT_0)
  120.         { // Wait until the command has arrived (i.e. until CommandGot is signaled)
  121.             _tprintf(_T("WaitForSingleObject() failed, error %d\n"), GetLastError());
  122.             goto out;
  123.         }
  124.         ResetEvent(hCommandGot); // CommandGot back to unsignaled
  125.         if (!_tcsicmp(CommandBuf, _T("exit"))) // Case-insensitive comparation
  126.         {
  127.             SetEvent(hStopCommandGot); // To force the other threads to quit
  128.             break;
  129.         }
  130.         else if (!_tcsicmp(CommandBuf, _T("connect"))) // tuleb connectimine
  131.         {
  132.             _tprintf("Command connect accepted, nothing to do yet\n");
  133.             SetEvent(hConnectCommandGot); //event, et connect käsk anti käiku
  134.             SetEvent(hCommandProcessed); //event, et käsu täitmine on lõppenud
  135.  
  136.         }
  137.         else
  138.         {
  139.             _tprintf(_T("Command \"%s\" not recognized\n"), CommandBuf);
  140.             SetEvent(hCommandProcessed); // To allow the keyboard reading thread to continue
  141.         }
  142.     }
  143.     //
  144.     // Shut down
  145.     //
  146. out:
  147.     if (hReadKeyboard)
  148.     {
  149.         WaitForSingleObject(hReadKeyboard, INFINITE); // Wait until the end of keyboard thread
  150.         CloseHandle(hReadKeyboard);
  151.     }
  152.     if (hReceiveNet)
  153.     {
  154.         WaitForSingleObject(hReceiveNet, INFINITE); // Wait until the end of receive thread
  155.         CloseHandle(hReceiveNet);
  156.     }
  157.     if (hReceiveNet)
  158.     {
  159.         WaitForSingleObject(hSendNet, INFINITE); // Wait until the end of send thread
  160.         CloseHandle(hSendNet);
  161.     }
  162.  
  163.     if (hClientSocket != INVALID_SOCKET)
  164.     {
  165.         if (shutdown(hClientSocket, SD_RECEIVE) == SOCKET_ERROR)
  166.         {
  167.             if ((Error = WSAGetLastError()) != WSAENOTCONN) // WSAENOTCONN means that the connection was not established,
  168.                                                             // so the shut down was senseless
  169.                 _tprintf(_T("shutdown() failed, error %d\n"), WSAGetLastError());
  170.         }
  171.         closesocket(hClientSocket);
  172.     }
  173.     WSACleanup(); // clean Windows sockets support
  174.     CloseHandle(hStopCommandGot);
  175.     CloseHandle(hCommandGot);
  176.     CloseHandle(hCommandProcessed);
  177.     CloseHandle(hConnectCommandGot);
  178.     return 0;
  179. }
  180. //**************************************************************************************************************
  181. //                          KEYBOARD READING THREAD
  182. //**************************************************************************************************************
  183. unsigned int __stdcall ReadKeyboard(void* pArguments)
  184. {
  185.     DWORD nReadChars;
  186.     HANDLE KeyboardEvents[2];
  187.     KeyboardEvents[1] = hCommandProcessed;
  188.     KeyboardEvents[0] = hStopCommandGot;
  189.     DWORD WaitResult;
  190.     //
  191.     // Reading loop
  192.     //
  193.     while (TRUE)
  194.     {
  195.         WaitResult = WaitForMultipleObjects(2, KeyboardEvents,
  196.             FALSE, // wait until one of the events becomes signaled
  197.             INFINITE);
  198.         // Waiting until hCommandProcessed or hStopCommandGot becomes signaled. Initially hCommandProcessed
  199.         // is signaled, so at the beginning WaitForMultipleObjects() returns immediately with WaitResult equal
  200.         // with WAIT_OBJECT_0 + 1.
  201.         if (WaitResult == WAIT_OBJECT_0)
  202.             return 0;  // Stop command, i.e. hStopCommandGot is signaled
  203.         else if (WaitResult == WAIT_OBJECT_0 + 1)
  204.         { // If the signaled event is hCommandProcessed, the WaitResult is WAIT_OBJECT_0 + 1
  205.             _tprintf(_T("Insert command\n"));
  206.             if (!ReadConsole(hStdIn, CommandBuf, 80, &nReadChars, NULL))
  207.             { // The problem is that when we already are in this function, the only way to leave it
  208.               // is to type something and then press ENTER. So we cannot step into this function at any moment.
  209.               // WaitForMultipleObjects() prevents it.
  210.                 _tprintf(_T("ReadConsole() failed, error %d\n"), GetLastError());
  211.                 return 1;
  212.             }
  213.             CommandBuf[nReadChars - 2] = 0; // The command in buf ends with "\r\n", we have to get rid of them
  214.             ResetEvent(hCommandProcessed);
  215.             // Set hCommandProcessed to non-signaled. Therefore WaitForMultipleObjects() blocks the keyboard thread.
  216.             // When the main thread has ended the analyzing of command, it sets hCommandprocessed or hStopCommandGot
  217.             // to signaled and the keyboard thread can continue.
  218.             SetEvent(hCommandGot);
  219.             // Set hCommandGot event to signaled. Due to that WaitForSingleObject() in the main thread
  220.             // returns, the waiting stops and the analyzing of inserted command may begin
  221.         }
  222.         else
  223.         {   // waiting failed
  224.             _tprintf(_T("WaitForMultipleObjects()failed, error %d\n"), GetLastError());
  225.             return 1;
  226.         }
  227.     }
  228.     return 0;
  229. }
  230. //********************************************************************************************************************
  231. //                          TCP/IP INFO RECEIVING THREAD
  232. //********************************************************************************************************************
  233. unsigned int __stdcall ReceiveNet(void* pArguments)
  234. {
  235.     //
  236.     // Preparations
  237.     //
  238.     WSABUF DataBuf;  // Buffer for received data is a structure
  239.     char ArrayInBuf[2048];
  240.     DataBuf.buf = &ArrayInBuf[0];
  241.     DataBuf.len = 2048;
  242.     DWORD nReceivedBytes = 0, ReceiveFlags = 0;
  243.     HANDLE NetEvents[2];
  244.     NetEvents[0] = hStopCommandGot;
  245.     WSAOVERLAPPED Overlapped;
  246.     memset(&Overlapped, 0, sizeof Overlapped);
  247.     Overlapped.hEvent = NetEvents[1] = WSACreateEvent(); // manual and nonsignaled
  248.     DWORD Result, Error;
  249.     wchar_t *identifier = L"Identify";
  250.     wchar_t *DataPointer;
  251.     int loendur = 0;
  252.     //
  253.     // Receiving loop
  254.     //
  255.     while (TRUE)
  256.     {
  257.         Result = WSARecv(hClientSocket,
  258.             &DataBuf,
  259.             1,  // no comments here
  260.             &nReceivedBytes,
  261.             &ReceiveFlags, // no comments here
  262.             &Overlapped,
  263.             NULL);  // no comments here
  264.         if (Result == SOCKET_ERROR)
  265.         {  // Returned with socket error, let us examine why
  266.             if ((Error = WSAGetLastError()) != WSA_IO_PENDING)
  267.             {  // Unable to continue, for example because the server has closed the connection
  268.                 _tprintf(_T("WSARecv() failed, error %d\n"), Error);
  269.                 goto out;
  270.             }
  271.             DWORD WaitResult = WSAWaitForMultipleEvents(2, NetEvents, FALSE, WSA_INFINITE, FALSE); // wait for data
  272.             switch (WaitResult) // analyse why the waiting ended
  273.             {
  274.             case WAIT_OBJECT_0:
  275.                 // Waiting stopped because hStopCommandGot has become signaled, i.e. the user has decided to exit
  276.                 goto out;
  277.             case WAIT_OBJECT_0 + 1:
  278.                 // Waiting stopped because Overlapped.hEvent is now signaled, i.e. the receiving operation has ended.
  279.                 // Now we have to see how many bytes we have got.
  280.                 WSAResetEvent(NetEvents[1]); // to be ready for the next data package
  281.                 if (WSAGetOverlappedResult(hClientSocket, &Overlapped, &nReceivedBytes, FALSE, &ReceiveFlags))
  282.                 {
  283.                    
  284.                    
  285.                     _tprintf(_T("%d bytes received\n"), nReceivedBytes);
  286.                     // Here should follow the processing of received data
  287.                    
  288.                     DataPointer = (wchar_t*)(DataBuf.buf + 4);
  289.                    
  290.                     //_tprintf("%d\n", *(DataBuf.buf) ); //esimesel kohal on arv, palju baite seal on
  291.                     _tprintf("%ls\n", DataPointer ); //_T teeb wide characterideks (wchar_t) on cast e. võta selle tagumist asja, kui wide pointerit
  292.                     //Datapointer peaks välja printima terve sõna, aga prindib ainult 1 tähe
  293.                     for (loendur = 0; loendur < nReceivedBytes; loendur++)
  294.                     {
  295.                         _tprintf(_T("%02x "), *(DataBuf.buf+ loendur));
  296.                         //_tprintf(_T("%s"), (DataBuf.buf + loendur));
  297.                     }
  298.                     _tprintf("\n");
  299.                    
  300.                    
  301.                    
  302.                     if(!wcscmp(DataPointer, identifier)) //detectime, kas sisendiks tuli Identify
  303.                     {
  304.                         _tprintf("Identity detected!!\n");
  305.                         //siia peaks tulema event, et saatja saadaks parooli
  306.                         SetEvent(hSendPassword);
  307.                     }
  308.                    
  309.                     break;
  310.                 }
  311.                 else
  312.                 {   // Fatal problems
  313.                     _tprintf(_T("WSAGetOverlappedResult() failed, error %d\n"), GetLastError());
  314.                     goto out;
  315.                 }
  316.             default: // Fatal problems
  317.                 _tprintf(_T("WSAWaitForMultipleEvents() failed, error %d\n"), WSAGetLastError());
  318.                 goto out;
  319.             }
  320.         }
  321.         else
  322.         {  // Returned immediately without socket error
  323.             if (!nReceivedBytes)
  324.             {  // When the receiving function has read nothing and returned immediately, the connection is off  
  325.                 _tprintf(_T("Server has closed the connection\n"));
  326.                 goto out;
  327.             }
  328.             else
  329.             {
  330.                
  331.                 _tprintf(_T("%d bytes received\n"), nReceivedBytes);
  332.                 // Here should follow the processing of received data
  333.                
  334.             }
  335.         }
  336.     }
  337. out:
  338.     WSACloseEvent(NetEvents[1]);
  339.     return 0;
  340. }
  341.  
  342.  
  343.  
  344. //********************************************************************************************************************
  345. //                          TCP/IP INFO SENDING THREAD
  346. //********************************************************************************************************************
  347. unsigned int __stdcall SendNet(void* pArguments)
  348. {
  349.     HANDLE OutputEvents[2];
  350.     OutputEvents[0] = hStopCommandGot;
  351.     OutputEvents[1] = hConnectCommandGot;
  352.    
  353.     //sending loop starts here
  354.     while (true)
  355.     {
  356.         DWORD WaitResult = WaitForMultipleObjects(2, OutputEvents, FALSE, INFINITE);
  357.         switch (WaitResult) //vastavalt sellele, mis hetkel waitresult on, on tegevus
  358.         {
  359.             case WAIT_OBJECT_0: //siin lahkume threadist
  360.                 {
  361.                 return 0;
  362.                 }
  363.             case WAIT_OBJECT_0 + 1:
  364.             {
  365.                 //siin hakkab saatmine peale
  366.                 _tprintf("Siin hakkab peale serveriga ühenduse loomine\n");
  367.                 _tprintf("Siin peaks kontrollima, kas ühendus on juba loodud\n");
  368.                 _tprintf("Siin peaks ootama idenfity s6numi tulemist\n");
  369.  
  370.  
  371.  
  372.  
  373.  
  374.                 //siin saatmine lõppenud
  375.                 ResetEvent(hConnectCommandGot);
  376.             }
  377.             break;
  378.         }
  379.     }
  380.  
  381.     return 0;
  382. }
RAW Paste Data
Top