Unsolved QWebSocket and Examples
-
Sorry if this has been tackled earlier. I am looking for some examples which are not just ping and echo.
Anyone know of any better examples built?
I ask because I am trying to port a Windows socket service to Qt and make it cross-platform. The examples in the 5.12 docs are amazing just works but I am not able to move further from that.I tried to search for writeups to read and tutorials in youtube but did not find anything substantial. Are there any open source examples that anybody can link which is a robust example.
I have pasted the socket.cpp which I am tackling. Being cross-platform getting rid of the registry details into a config file. All the logging into a new cross-platform library. There is a process of device locking, which I do a ifdef and keep it platform dependent.
Any suggestion is appreciated.
#include "stdafx.h" #include "WebSocketServer.h" #include "ThreadPool.h" //#include "Util.h" #include <process.h> WebSocketServer::WebSocketServer(PWSTR pszServiceName, BOOL fCanStop, BOOL fCanShutdown, BOOL fCanPauseContinue) : CServiceBase(pszServiceName, fCanStop, fCanShutdown, fCanPauseContinue) { init_resources(); //server_startup(); isMutexEnabled = true; brecieve = true; //m_AuthFile("", "", ""); m_fStopping = FALSE; // Create a manual-reset event that is not signaled at first to indicate // the stopped signal of the service. m_hStoppedEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (m_hStoppedEvent == NULL) { throw GetLastError(); } } void WebSocketServer::OnStart(DWORD dwArgc, PWSTR *lpszArgv) { // Log a service start message to the Application log. cout << "check 6" << endl; WriteEventLogEntry(L"WebSocketServer::OnStart", EVENTLOG_INFORMATION_TYPE); // Queue the main service function for execution in a worker thread. CThreadPool::QueueUserWorkItem(&WebSocketServer::ServiceWorkerThread, this); } void WebSocketServer::OnStop() { // Log a service stop message to the Application log. WriteEventLogEntry(L"CppWindowsService in OnStop", EVENTLOG_INFORMATION_TYPE); // Indicate that the service is stopping and wait for the finish of the // main service function (ServiceWorkerThread). m_fStopping = TRUE; if (WaitForSingleObject(m_hStoppedEvent, INFINITE) != WAIT_OBJECT_0) { throw GetLastError(); } } void WebSocketServer::ServiceWorkerThread(void) { cout << "check 7" << endl; WriteEventLogEntry(L"WebSocketServer::ServiceWorkerThread Before", EVENTLOG_INFORMATION_TYPE); // Periodically check if the service is stopping. while (!m_fStopping) { WriteEventLogEntry(L"WebSocketServer::ServiceWorkerThread", EVENTLOG_INFORMATION_TYPE); // Perform main service function here... ::Sleep(2000); // Simulate some lengthy operations. } WriteEventLogEntry(L"WebSocketServer::ServiceWorkerThread Before", EVENTLOG_INFORMATION_TYPE); // Signal the stopped event. SetEvent(m_hStoppedEvent); } void WebSocketServer::init(std::map<std::string, std::string> aMap,string strForProcessingDeviceLocking,vector<string> &filenames) { m_registryMap = aMap; m_stringforProcessingDeviceLocking = strForProcessingDeviceLocking; m_vectorforFilenames = filenames; m_mapAttributeValues.clear(); m_mapAttributeValues[1] = "walletn:0:cardn:count"; m_mapAttributeValues[2] = "walletn:0"; m_mapAttributeValues[3] = "walletn:0:ArcotID"; m_mapAttributeValues[4] = "walletn:0:userid"; m_mapAttributeValues[5] = "walletn:0:Org"; m_mapAttributeValues[6] = "walletn:0:alias"; m_mapAttributeValues[7] = "walletn:0:card"; m_mapAttributeValues[8] = "walletn:0:WalletName"; m_mapAttributeValues[9] = "walletn:0:cardn"; } WebSocketServer::~WebSocketServer() { } void WebSocketServer::init_resources() { ghMutex = CreateMutex( NULL, // default security attributes FALSE, // initially not owned NULL); // unnamed mutex if (ghMutex == NULL) { ////// cout << "CreateMutex error: is " << GetLastError() << endl; } } void WebSocketServer::server_startup() { string hostName; string portName; std::wstring strMessage3 = L"m_registryMap size" + to_wstring(m_registryMap.size()); LPCWSTR pcwstr3 = strMessage3.c_str(); WriteEventLogEntry((PWSTR)pcwstr3, EVENTLOG_INFORMATION_TYPE); if (m_registryMap.size() >= 2) { hostName = m_registryMap.find("HostName")->second; cout << "hostname " << hostName << endl; portName = m_registryMap.find("ServerPort")->second; cout << "portname" << portName << endl; } char *charName=(char*)portName.c_str(); unsigned short portNumber = (unsigned short)strtoul(charName, NULL, 0); unsigned short *usp = &portNumber; wchar_t wt[20]; swprintf(wt, sizeof(wt), L"%hu", *usp); std::wstring ws(wt); std::wstring strMessage2 = L"Serverport ::" + ws; wcout << "serverport ::" << ws << endl; LPCWSTR pcwstr2 = strMessage2.c_str(); WriteEventLogEntry((PWSTR)pcwstr2, EVENTLOG_INFORMATION_TYPE); WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR)// Initialize Winsock { WriteEventLogEntry(L"Error at WSAStartup()", EVENTLOG_ERROR_TYPE); } //create the SOCKET listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); std::wstring strMessage1 = L"listening local fd ::" + to_wstring(listenfd); LPCWSTR pcwstr1 = strMessage1.c_str(); WriteEventLogEntry((PWSTR)pcwstr1, EVENTLOG_INFORMATION_TYPE); struct sockaddr_in server = { 0 }; server.sin_family = AF_INET; inet_pton(AF_INET, hostName.c_str(), &(server.sin_addr)); server.sin_port = htons((u_short)portNumber); // Bind the socket. if (bind(listenfd, (SOCKADDR*)&server, sizeof(server)) == SOCKET_ERROR) { ////// cout << "Unable to start the WebSocket Server - Bind failed on [" << hostName.c_str() << ":" << portNumber << "]" << endl; WriteEventLogEntry(L"Unable to start the WebSocket Server - Bind failed", EVENTLOG_ERROR_TYPE); exit(0); } if (listen(listenfd, SOMAXCONN) == SOCKET_ERROR) { WriteEventLogEntry(L"Error listening on socket", EVENTLOG_ERROR_TYPE); return; } // cout << "Server is listening on socket... \n"; WriteEventLogEntry(L"Server is listening on socket..", EVENTLOG_INFORMATION_TYPE); // cout << int(server.sin_addr.s_addr & 0xFF) << "." << int((server.sin_addr.s_addr & 0xFF00) >> 8) << "." // << int((server.sin_addr.s_addr & 0xFF0000) >> 16) << "." << int((server.sin_addr.s_addr & 0xFF000000) >> 24) << ":" << ntohs(server.sin_port); } SOCKET WebSocketServer::accept_client() { //WriteEventLogEntry(L"WebSocketServer::accept_client()", EVENTLOG_INFORMATION_TYPE); std::wstring strMessage1 = L"Before Accept Socket API Call ::" + to_wstring(listenfd); LPCWSTR pcwstr1 = strMessage1.c_str(); //WriteEventLogEntry((PWSTR)pcwstr1, EVENTLOG_INFORMATION_TYPE); struct sockaddr clientinfo = { 0 }; SOCKET connectfd = accept(listenfd, &clientinfo, NULL); int err_WSAGetLastError = WSAGetLastError(); std::wstring strMessage2 = L"After Accept Socket API Call ::" + to_wstring(err_WSAGetLastError); LPCWSTR pcwstr2 = strMessage2.c_str(); //WriteEventLogEntry((PWSTR)pcwstr2, EVENTLOG_INFORMATION_TYPE); cout << "err_WSAGetLastError :" << err_WSAGetLastError << endl; //WriteEventLogEntry(L"WebSocketServer::accept_client() -1", EVENTLOG_INFORMATION_TYPE); struct sockaddr_in* ipv4info = (struct sockaddr_in*)&clientinfo; //WriteEventLogEntry(L"WebSocketServer::accept_client() 0", EVENTLOG_INFORMATION_TYPE); char ipAddress[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(ipv4info->sin_addr), ipAddress, INET_ADDRSTRLEN); //WriteEventLogEntry(L"WebSocketServer::accept_client() 1", EVENTLOG_INFORMATION_TYPE); std::wstring strMessage = L"Browser client connected on socket ::" + to_wstring(connectfd); LPCWSTR pcwstr = strMessage.c_str(); //WriteEventLogEntry((PWSTR)pcwstr, EVENTLOG_INFORMATION_TYPE); //WriteEventLogEntry(L"WebSocketServer::accept_client() 2", EVENTLOG_INFORMATION_TYPE); cout << "Browser client connected on socket :: " << connectfd << endl; cout << "Browser client connected: " << ipAddress << ":" << ntohs(ipv4info->sin_port); return connectfd; } unsigned __stdcall WebSocketServer::on_client_connected(void* pClass) { ////// cout << "0" << endl; //std::unique_ptr<WebSocketServer> p_webSocket(static_cast<WebSocketServer*>(pClass)); WebSocketServer* p_webSocket = static_cast<WebSocketServer*>(pClass); //p_foo->receiveMessages(); // Non-static member function! ////// cout << "p_websocket" << p_webSocket << endl; ////// cout << nClients << "p_webSocket->nClients" << endl; char* response = NULL; int length = 0; const string resource; SOCKET connectfd = *(SOCKET*)(&p_webSocket->connectDescriptors[nClients]); ////// cout << "p_webSocket->connectDescriptors[p_webSocket->nClients]" << p_webSocket->connectDescriptors[nClients] << endl; ////// cout << " &&& connectfd &&&" << connectfd << endl; try { string message; if (connectfd != 0) { p_webSocket->OnClientConnect(connectfd, recvbuf, &response, &length, keyaccess, authidcook, UserId, message); WebSocketServer::nClients += 1; } char * challenge1; string key1, key2, RequestName; map<string, string> m_resourcemap; //// cout << "recbuf ::" << endl; //// cout << recvbuf << endl; if (recvbuf != NULL) { challenge1 = p_webSocket->GetRequestname(recvbuf, &key1, &key2, &RequestName); ////// cout << "RequestName" << " " << RequestName << endl; m_resourcemap.clear(); p_webSocket->GetResoucemap(recvbuf, &m_resourcemap); string strSuccessRequest = status_code(StatusCode::success_Request_Resource_map_processed); p_webSocket->sendMessagetoClient(connectfd, strSuccessRequest); } ////// cout << "bef loop challenge1" << RequestName << endl; SDK_STATUS status = 0; SDK_STATUS status_devicelock = 0; string signedChallenge; string challenge; if (RequestName == READ_AUTH_ID) { p_webSocket->readAuthIDFromClient(p_webSocket, connectfd, m_resourcemap); p_webSocket->WriteEventLogEntry(L"Read AuthID From Client", EVENTLOG_INFORMATION_TYPE); } else if (RequestName == SIGNCHALLENGE_WITH_AUTH_ID) { p_webSocket->signChallengewithChallenge(p_webSocket, connectfd, m_resourcemap); p_webSocket->WriteEventLogEntry(L"SignChallenge Completed", EVENTLOG_INFORMATION_TYPE); } else if (RequestName == REMOVE_ARCOT_ID) { p_webSocket->removeAuthIDFromClient(p_webSocket, connectfd, m_resourcemap); p_webSocket->WriteEventLogEntry(L"Auth Id file Removed from the file System", EVENTLOG_INFORMATION_TYPE); } else if (RequestName == WRITE_AUTH_ID) { p_webSocket->writeAuthIDToClient(p_webSocket, connectfd, m_resourcemap); p_webSocket->WriteEventLogEntry(L"Written Auth ID to File on Client system", EVENTLOG_INFORMATION_TYPE); } else if (RequestName == SERVER_VERSION) { p_webSocket->serverVersion(p_webSocket, connectfd, m_resourcemap); p_webSocket->WriteEventLogEntry(L"Server version Client system", EVENTLOG_INFORMATION_TYPE); } else if (RequestName == ECHO) { ////// cout << "in echoed" << endl; } else { //string readstatus = p_webSocket->m_AuthFile.ReadAuthIDfile(); p_webSocket->sendMessagetoClient(connectfd, "Invalid Request - Function not implemented !!"); p_webSocket->WriteEventLogEntry(L"Invalid Request - Function not implemented !!", EVENTLOG_ERROR_TYPE); string strInvalidRequest = status_code(StatusCode::server_error_invalid_request); p_webSocket->sendMessagetoClient(connectfd, strInvalidRequest); ////// cout << "authid" << "Invalid Request - Function not implemented !!" << endl; } char buf[4096]; int nbytes = recv(connectfd, buf, sizeof(buf), 0); // cout << "nbytes" << nbytes << endl; // cout << "buf" << buf << endl; } catch (...) { closesocket(connectfd); p_webSocket->WriteEventLogEntry(L"Crash Occurred in Code, Closing Socket Connection", EVENTLOG_ERROR_TYPE); } closesocket(connectfd); ////// cout << "Client socket " << GetCurrentThread() << " connection closed.\nExiting server thread " << connectfd << "...\n" << endl; ////// cout << WebSocketServer::nClients << " WebSocketServer::nClients" << endl; ////// cout << nClients << "nClients" << endl; _endthreadex(0); return 0; } void WebSocketServer::readAuthIDFromClient(WebSocketServer* p_webSocket, SOCKET connectfd, map<string, string> m_resourcemap) { WriteEventLogEntry(L"Read AuthID Function", EVENTLOG_INFORMATION_TYPE); string userNameValue; string orgNameValue; string authid; try { // p_webSocket->acquire_mutex(); ////// cout << m_resourcemap.size() << " m_resourcemap.size() " << endl; if (m_resourcemap.size() >= 2) { userNameValue = m_resourcemap.find("userName")->second; ////// cout << "userNameValue" << userNameValue << endl; orgNameValue = m_resourcemap.find("orgName")->second; ////// cout << "orgNameValue" << orgNameValue << endl; } authid = p_webSocket->m_AuthFile.ReadAuthIDfile(userNameValue, orgNameValue, p_webSocket->m_stringforProcessingDeviceLocking); } catch (...) { authid = "Error"; } // cout << "AuthID" << authid << endl; p_webSocket->sendMessagetoClient(connectfd, authid); // p_webSocket->release_mutex(); } void WebSocketServer::signChallengewithChallenge(WebSocketServer* p_webSocket, SOCKET connectfd, map<string, string> m_resourcemap) { //p_webSocket->acquire_mutex(); ////// cout << " inside signchallenge function " << endl; WriteEventLogEntry(L"SignChallenge Function", EVENTLOG_INFORMATION_TYPE); string userNameValue; string orgNameValue; string userPin; string challengePin; string signedChallenge; SDK_STATUS status = 0; SDK_STATUS status_devicelock = 0; if (m_resourcemap.size() > 2) { userNameValue = m_resourcemap.find("userName")->second; //// cout << "userNameValue" << userNameValue << endl; orgNameValue = m_resourcemap.find("orgName")->second; //// cout << "orgNameValue" << orgNameValue << endl; challengePin = m_resourcemap.find("challenge")->second; //// cout << "challenge" << challengePin << endl; userPin = m_resourcemap.find("userPIN")->second; ////// cout << "userpin" << userPin << endl; //userPin = "12345678"; //harded to check without "http/1.1" } bool readStatus = false; string authIDFromClient = ""; try { authIDFromClient = p_webSocket->m_AuthFile.ReadAuthIDfile(userNameValue, orgNameValue, p_webSocket->m_stringforProcessingDeviceLocking); //// cout << "authIDFromClient" << authIDFromClient << endl; readStatus = true; } catch (...) { readStatus = false; p_webSocket->sendMessagetoClient(connectfd, authIDFromClient); } if (readStatus) { try { status = SignChallengeWithAuthID(challengePin, userPin, authIDFromClient, signedChallenge);// Sign Challenge Value // p_webSocket->release_mutex(); //// cout << status << " status " << endl; //// cout << signedChallenge << "SignedChallenge" << endl; if (status == SDKSTATUS_OK) { ////// cout << "Send the SignedChalleng to server" << endl; } else { signedChallenge = ""; ////// cout << "error " << endl; } } catch (...) { signedChallenge = ""; } } p_webSocket->sendMessagetoClient(connectfd, signedChallenge); } void WebSocketServer::removeAuthIDFromClient(WebSocketServer* p_webSocket,SOCKET connectfd, map<string, string> m_resourcemap) { WriteEventLogEntry(L"Remove Auth ID Function", EVENTLOG_INFORMATION_TYPE); string userNameValue; string orgNameValue; string status; try{ //p_webSocket->acquire_mutex(); ////// cout << m_resourcemap.size() << " p_webSocket->m_resourcemap.size() " << endl; if (m_resourcemap.size() >= 2) { userNameValue = m_resourcemap.find("userName")->second; ////// cout << "userNameValue" << userNameValue << endl; orgNameValue = m_resourcemap.find("orgName")->second; ////// cout << "orgNameValue" << orgNameValue << endl; } ////// cout << "calling authfil class to remove authid " << endl; status = p_webSocket->m_AuthFile.RemoveArcotID(userNameValue, orgNameValue, p_webSocket->m_stringforProcessingDeviceLocking); ////// cout << "got the status from remove authid function " << endl; } catch (...) { status = "false"; } ////// cout << "sending remvoe status " << status << endl; //p_webSocket->release_mutex(); p_webSocket->sendMessagetoClient(connectfd, status); ////// cout << "done with remove " << endl; } void WebSocketServer::writeAuthIDToClient(WebSocketServer* p_webSocket,SOCKET connectfd, map<string, string> m_resourcemap) { WriteEventLogEntry(L"Write Auth Id Function", EVENTLOG_INFORMATION_TYPE); string authidFromClient; string userNameValue; string orgNameValue; string status = "false"; ////// cout << "inside writeAuthID function " << endl; try { //p_webSocket->acquire_mutex(); ////// cout << m_resourcemap.size() << " p_webSocket->m_resourcemap.size() " << endl; if (m_resourcemap.size() >= 2) { authidFromClient = m_resourcemap.find("authid")->second; ////// cout << "authidFromClient" << authidFromClient << endl; userNameValue = m_resourcemap.find("userName")->second; ////// cout << "userNameValue" << userNameValue << endl; orgNameValue = m_resourcemap.find("orgName")->second; if (orgNameValue.length() == 0) { orgNameValue == DEFAULT_ORG; } ////// cout << "orgNameValue" << orgNameValue << endl; } ////// cout << " before calling authfile class to write authid " << endl; if (userNameValue.length() != 0) { status = p_webSocket->m_AuthFile.WriteAuthIDfile(authidFromClient, userNameValue, orgNameValue, p_webSocket->m_stringforProcessingDeviceLocking); } //p_webSocket->release_mutex(); } catch (...) { status = "false"; } p_webSocket->sendMessagetoClient(connectfd, status); ////// cout << "done with the writing authid !!" << endl; } void WebSocketServer::serverVersion(WebSocketServer* p_webSocket, SOCKET connectfd, map<string, string> m_resourcemap) { WriteEventLogEntry(L"Server Version Function", EVENTLOG_INFORMATION_TYPE); string verstionStatus = VERSION_NUMBER; // cout << "Before Version " << endl; p_webSocket->sendMessagetoClient(connectfd, verstionStatus); // cout << "After Version id sent" << endl; } void WebSocketServer::acquire_mutex() { if (!isMutexEnabled) return; if (WaitForSingleObject(ghMutex, INFINITE) != WAIT_OBJECT_0) { //printf("Error on WaitForSingleObject (thread %x)\n", GetCurrentThreadId()); ////// cout << "Error on WaitForSingleObject (thread " << GetCurrentThreadId() << ")\n" << endl; } } void WebSocketServer::release_mutex() { if (!isMutexEnabled) return; if (!ReleaseMutex(ghMutex)) { //printf("Error releasing Mutex on thread %x.\n", GetCurrentThreadId()); ////// cout << "Error releasing Mutex on thread " << GetCurrentThreadId() << ".\n" << endl; } } void WebSocketServer::OnClientConnect(SOCKET connectfd, char recvbuf[DEFAULT_BUFLEN], char** response, int* length, char keyaccess[DEFAULT_BUFLEN_ACCESS], char authidcook[DEFAULT_BUFLEN_ARCID], char UserId[DEFAULT_BUFLEN_USERID],string message) { int received; received = recv(connectfd, recvbuf, DEFAULT_BUFLEN, 0); ////// cout << received << " bytes received from client request.\n\n" << endl; int j = 0; int k; for (int i = 0; i < DEFAULT_BUFLEN; i++) { int count = 0; if (recvbuf[i] == 'e' && recvbuf[i + 1] == 'y' && recvbuf[i + 2] == ':') { k = i + 4; while (count <= 23) { keyaccess[j++] = recvbuf[k++]; count++; } } } string keyaccessstr(keyaccess, 0, 24); keyaccess[24] = keyaccessstr[24]; ////// cout << "keyaccess" << keyaccess << endl; for (int i = 0; i < DEFAULT_BUFLEN; i++) { if (recvbuf[i] == 'A' && recvbuf[i + 1] == 'u' && recvbuf[i + 2] == 't' && recvbuf[i + 3] == 'h' && recvbuf[i + 4] == 'I' && recvbuf[i + 5] == 'd' && recvbuf[i + 6] == '=') { for (int k = i + 5; k <= i + 1083; k++) { authidcook[j] = recvbuf[k]; j++; } } } char authidcookie[DEFAULT_BUFLEN_ARCID]; ////// cout << "authidcook" << authidcook << endl; char User[DEFAULT_BUFLEN_USERID]; //To Get User Id Value for (int i = 0; i < DEFAULT_BUFLEN; i++) { if (recvbuf[i] == 'U' && recvbuf[i + 1] == 's' && recvbuf[i + 2] == 'e' && recvbuf[i + 3] == 'r' && recvbuf[i + 4] == 'I' && recvbuf[i + 5] == 'd' && recvbuf[i + 6] == '=') { for (int k = i + 7; k <= i + 21; k++) { UserId[j] = recvbuf[k]; j++; } } } ////// cout << "UserId" << UserId << endl; char* request = _strdup(recvbuf); string key1, key2, resource; string origin = "null"; string location = "ws://127.0.0.1:49500/echo"; char * challenge; challenge = GetRequestname(request, &key1, &key2, &resource); string accesskey; wstring guid = L"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; std::string keyaccesStr(keyaccess); wstring keyaccessGuid(keyaccesStr.begin(), keyaccesStr.end()); keyaccessGuid.append(guid); printf("\n keyaccess + guid [%S] \n", keyaccessGuid.c_str()); //////// cout << "\n keyaccess + guid [" << keyaccessGuid.c_str() << "] \n"; string utf8String = wstring_to_utf8(keyaccessGuid); unsigned char digestStr2[SHA_DIGEST_LENGTH]; SHA1((unsigned char*)utf8String.c_str(), strlen(utf8String.c_str()), (unsigned char*)&digestStr2); char* utf8StrSha1Base64 = convertToBase64(digestStr2, SHA_DIGEST_LENGTH); string sha1DataStr(utf8StrSha1Base64); createResponse(connectfd,message, response, length, sha1DataStr, authidcook); ////// cout << "Hand Shake Completed" << endl; string strSuccessaccepted = status_code(StatusCode::success_accepted); sendMessagetoClient(connectfd, strSuccessaccepted); } void WebSocketServer::GetResoucemap(char* request,map<string,string> *amap) { (*amap).clear(); string strRequest = request; int indexofquestion = strRequest.find('?'); int indexofencoding = strRequest.find(" HTTP/1.1"); cout << " strRequested " << strRequest << endl; string strRequired = strRequest.substr(indexofquestion+1, indexofencoding - indexofquestion); cout << "after substr strRequested " << strRequired << endl; int strlengthofRequired = strRequired.size(); cout << strlengthofRequired << " strlengthofRequired" << endl; for (int i = 0; i <= 10 ; i++) { int indexofambersand = strRequired.find("&"); string strwithEqualSign = strRequired.substr(0, indexofambersand); int indexofequalSign = strwithEqualSign.find("="); string strkey = strwithEqualSign.substr(0, indexofequalSign); string strValue = strwithEqualSign.substr(indexofequalSign+1); strRequired = strRequired.substr(indexofambersand + 1); /* cout << strRequired.size() << "strRequired.size()" << endl; cout << strkey << " strKey" << endl; cout << strValue << " strValue" << endl; cout << strRequired << " strRequired" << endl;*/ (*amap)[strkey] = strValue; } } char * WebSocketServer::GetRequestname(char* request, string * key1, string * key2, string* resource) { int i; match_results<const char*> key1M, key2M, getresrcM; char* challenge = (char*)malloc(sizeof(char)); string wsrequest = request; //get challenge for (i = 0; i < 8; i++) challenge[i] = wsrequest[wsrequest.length() - 8 + i]; ////// cout << "challenge" << challenge << endl; tr1::regex rx1(key1pattern1); tr1::regex rx2(key2pattern); tr1::regex rx3(resourcePattern); //match Sec-WebSocket-Key1 tr1::regex_search(wsrequest.c_str(), key1M, rx1); *key1 = key1M[2]; //match Sec-WebSocket-Key1 tr1::regex_search(wsrequest.c_str(), key2M, rx2); *key2 = key2M[2]; //match GET (resource) tr1::regex_search(wsrequest.c_str(), getresrcM, rx3); *resource = getresrcM[2]; return challenge; } void WebSocketServer::sendMessagetoClient(SOCKET connectedfd, string message) { int strlength = message.length(); ////// cout << "message" << message << endl; unsigned char opcode; opcode = WS_OPCODE_TEXT; // fetch message length int messageLength = message.size(); // set max payload length per frame int bufferSize = 4096; // work out amount of frames to send, based on $bufferSize int frameCount = ceil((float)messageLength / bufferSize); if (frameCount == 0) frameCount = 1; // set last frame variables int maxFrame = frameCount - 1; int lastFrameBufferLength = (messageLength % bufferSize) != 0 ? (messageLength % bufferSize) : (messageLength != 0 ? bufferSize : 0); for (int i = 0; i < frameCount; i++) { // fetch fin, opcode and buffer length for frame unsigned char fin = i != maxFrame ? 0 : WS_FIN; opcode = i != 0 ? WS_OPCODE_CONTINUATION : opcode; size_t bufferLength = i != maxFrame ? bufferSize : lastFrameBufferLength; char *buf; size_t totalLength; // set payload length variables for frame if (bufferLength <= 125) { // int payloadLength = bufferLength; totalLength = bufferLength + 2; buf = new char[totalLength]; buf[0] = fin | opcode; buf[1] = bufferLength; memcpy(buf + 2, message.c_str(), message.size()); } else if (bufferLength <= 65535) { // int payloadLength = WS_PAYLOAD_LENGTH_16; totalLength = bufferLength + 4; buf = new char[totalLength]; buf[0] = fin | opcode; buf[1] = WS_PAYLOAD_LENGTH_16; buf[2] = bufferLength >> 8; buf[3] = bufferLength; memcpy(buf + 4, message.c_str(), message.size()); } else { // int payloadLength = WS_PAYLOAD_LENGTH_63; totalLength = bufferLength + 10; buf = new char[totalLength]; buf[0] = fin | opcode; buf[1] = WS_PAYLOAD_LENGTH_63; buf[2] = 0; buf[3] = 0; buf[4] = 0; buf[5] = 0; buf[6] = bufferLength >> 24; buf[7] = bufferLength >> 16; buf[8] = bufferLength >> 8; buf[9] = bufferLength; memcpy(buf + 10, message.c_str(), message.size()); } // send frame int left = totalLength; char *buf2 = buf; do { int sent = send(connectedfd, buf2, left, 0); if (sent == -1) { //// cout << "sent" << sent; // return false; } left -= sent; if (sent > 0) buf2 += sent; } while (left > 0); delete buf; } } void WebSocketServer::createResponse(SOCKET connectedfd, string challenge,char** response, int* length, string Accesskey, string authidcook) { string originName; string locationName; ////// cout << m_registryMap.size() << "m_registryMap.size()" << endl; // ////// cout << m_registryMap.key[] if (m_registryMap.size() >= 2) { originName = m_registryMap.find("Origin")->second; ////// cout << "originName" << originName << endl; locationName = m_registryMap.find("Location")->second; ////// cout << "locationName" << locationName << endl; } string authidcookstr = "arcot.wallet.memory=" + authidcook; std::string handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Accept-Encoding: gzip, deflate, sdch, br\r\n" "Sec-WebSocket-Accept: " + Accesskey + " \r\n" "Sec-WebSocket-Origin: " + originName + "\r\n" "Set-Cookie: " + authidcookstr + "\r\n" "Sec-WebSocket-Location: " + locationName + "\r\n\r\n"; printf(" handshake to client %s \n", handshake.c_str()); int left = handshake.size(); do { int sent = send(connectedfd, handshake.c_str(), handshake.size(), 0); if (sent == false) { ////// cout << " handshake not sent" << endl; } left -= sent; if (sent > 0) handshake = handshake.substr(sent); } while (left > 0); } void WebSocketServer::WriteEventLogEntryWebsocket(PWSTR pszMessage, WORD wType) { // = getRegKey("Software\\CA", "LogLevel"); std::wstring strloglevel=GetUrlFromRegistry(L"LogLevel"); std::string loglevel(strloglevel.begin(), strloglevel.end()); /* loglevel = L"DEBUG";*/ if (loglevel.compare("NOLOG") == 0) return; //Debug Level if ((loglevel.compare("DEBUG") == 0 && (wType == EVENTLOG_ERROR_TYPE || wType == EVENTLOG_INFORMATION_TYPE || wType == EVENTLOG_FULL_INFO)) || (loglevel.compare("INFO") == 0 && (wType == EVENTLOG_ERROR_TYPE || wType == EVENTLOG_INFORMATION_TYPE)) //Info Levevl || (loglevel.compare("ERROR") == 0 && wType == EVENTLOG_ERROR_TYPE)) //Info Level { HANDLE hEventSource = NULL; LPCWSTR lpszStrings[2] = { NULL, NULL }; LPCWSTR m_name = L"CA WebSocket Server Module Events"; hEventSource = RegisterEventSourceW(NULL, m_name); if (hEventSource) { lpszStrings[0] = m_name; lpszStrings[1] = pszMessage; ReportEventW(hEventSource, // Event log handle wType, // Event type 0, // Event category 0, // Event identifier NULL, // No security identifier 2, // Size of lpszStrings array 0, // No binary data lpszStrings, // Array of strings NULL // No binary data ); DeregisterEventSource(hEventSource); } } } std::wstring WebSocketServer::GetUrlFromRegistry(std::wstring key) { HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_CURRENT_USER, L"SOFTWARE\\CA", 0, KEY_READ, &hKey); bool bExistsAndSuccess(lRes == ERROR_SUCCESS); bool bDoesNotExistsSpecifically(lRes == ERROR_FILE_NOT_FOUND); std::wstring strUrl; GetStringRegKey(hKey, key, strUrl, L""); return strUrl; } LONG WebSocketServer::GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError; }