void withLock(std::mutex & m, Function f) {
  m.lock();
  f();
  m.unlock();
}
Ejemplo n.º 2
0
void    lockStatistics()
{
    gTatisticsCppMutex.lock();
}
 void lock()
 {
     check_for_hierarchy_violation();
     internal_mutex.lock();
     update_hierarchy_value();
 }
Ejemplo n.º 4
0
// Internal thread for updating the console.
void lConsole::Int_UpdateThread()
{
    static std::chrono::milliseconds UpdateDelay(500);
    while (true)
    {
        // Delay so we don't waste time updating.
        std::this_thread::sleep_for(UpdateDelay);

        // If we have a stream handle.
        if (StreamHandle == nullptr || !ShouldPrintScrollback)
            continue;

        // Clear the console.
#ifdef _WIN32
        // Aparently system("cls") is bad practice as it spawns a shell.
        COORD topLeft = { 0, 0 };
        HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
        CONSOLE_SCREEN_BUFFER_INFO screen;
        DWORD written;

        GetConsoleScreenBufferInfo(console, &screen);
        FillConsoleOutputCharacterA(
            console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
            );
        FillConsoleOutputAttribute(
            console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
            screen.dwSize.X * screen.dwSize.Y, topLeft, &written
            );
        SetConsoleCursorPosition(console, topLeft);
#else
        // But nix can use ANSI escapecodes.
        // CSI[2J to clear the console.
        // CSI[H to reset the cursor.
        fprintf(stdout, "\x1B[2J\x1B[H");
#endif

        // Save the old color settings.
        static CONSOLE_SCREEN_BUFFER_INFO OldTextColor;
        GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &OldTextColor);

        // For each line in the scrollback.
        ThreadSafe.lock();
        for (uint32_t i = 0; i < ScrollbackLineCount; ++i)
        {
            // Set the output strings color.
            SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CompatibleRGBA(ScrollbackLines[i].RGBA));

            // Search the string for progress bars.
            for (uint32_t c = 0; c < ProgressbarCount; ++c)
            {
                if (strstr(ScrollbackLines[i].String, Progressbars[c].ProgressToken))
                {
                    static char ProgressBuffer[257];
                    memset(ProgressBuffer, 0, 257);

                    // Create the buffer.
                    for (int32_t k = 0; k < (int32_t)min(INT32_MAX, strlen(ScrollbackLines[i].String)) - 1; ++k)
                    {
                        // Copy all the characters up until the token.
                        if (ScrollbackLines[i].String[k + 0] == Progressbars[c].ProgressToken[0] &&
                            ScrollbackLines[i].String[k + 1] == Progressbars[c].ProgressToken[1])
                        {
                            ProgressBuffer[k] = ScrollbackLines[i].String[k];
                        }
                        else
                        {
                            // Copy the progress bar into the buffer.
                            // TODO: Use the bar type.
                            strcpy(&ProgressBuffer[c], GetProgress(0, Progressbars[c].CurrentValue, Progressbars[c].EndValue));
                            break;
                        }
                    }

                    // Print the formated buffer.
                    printf(ProgressBuffer);
                    printf("\n");
                    goto LABEL_PRINT_DONE;
                }
            }

            // Print the string since there's no progress bar.
            printf(ScrollbackLines[i].String);
            printf("\n");

        LABEL_PRINT_DONE:;
        }

        // Reset the color.
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), OldTextColor.wAttributes);
        ThreadSafe.unlock();
    }
}
Ejemplo n.º 5
0
void QueryWorld::updateBuffer() {
    m_copyWorldLock.lock();
    m_queryWorld = m_copyWorld;
    m_copyWorldLock.unlock();
}
Ejemplo n.º 6
0
void DumpPacket(DWORD packetType, DWORD connectionId, DWORD opcode, BYTE opcodeSize, DWORD size, BYTE* buffer)
{
    mtx.lock();
    // gets the time
    time_t rawTime;
    time(&rawTime);
    DWORD tickCount = GetTickCount();

    if (!fileDump)
    {
        tm* date = localtime(&rawTime);
        // basic file name format:
        char fileName[MAX_PATH];
        // removes the DLL name from the path
        PathRemoveFileSpec(dllPath);
        // fills the basic file name format
        _snprintf(fileName, MAX_PATH,
            "wowsniff_%s_%u_%u_%d-%02d-%02d_%02d-%02d-%02d.pkt",
            hookInfo.locale, wowInfo.expansion, wowInfo.build,
            date->tm_year + 1900,
            date->tm_mon + 1,
            date->tm_mday,
            date->tm_hour,
            date->tm_min,
            date->tm_sec);

        // some info
        printf("Sniff dump: %s\n\n", fileName);

        char fullFileName[MAX_PATH];
        _snprintf(fullFileName, MAX_PATH, "%s\\%s", dllPath, fileName);

        fileDump = fopen(fullFileName, "wb");
        // PKT 3.1 header
        fwrite("PKT",                           3, 1, fileDump);  // magic
        fwrite((WORD*)&pkt_version,             2, 1, fileDump);  // major.minor version
        fwrite((BYTE*)&sniffer_id,              1, 1, fileDump);  // sniffer id
        fwrite((WORD*)&wowInfo.build,           2, 1, fileDump);  // client build
        fwrite(sessionKey,                      1, 2, fileDump);  // client build (aligned bytes)
        fwrite(hookInfo.locale,                 4, 1, fileDump);  // client lang
        fwrite(sessionKey,                     40, 1, fileDump);  // session key
        fwrite((DWORD*)&rawTime,                4, 1, fileDump);  // started time
        fwrite((DWORD*)&tickCount,              4, 1, fileDump);  // started tick's
        fwrite((DWORD*)&optionalHeaderLength,   4, 1, fileDump);  // opional header length
        fflush(fileDump);
    }

    fwrite((DWORD*)&packetType,             4, 1, fileDump);  // direction of the packet
    fwrite((DWORD*)&connectionId,           4, 1, fileDump);  // connection id
    fwrite((DWORD*)&tickCount,              4, 1, fileDump);  // timestamp of the packet
    fwrite((DWORD*)&optionalHeaderLength,   4, 1, fileDump);  // optional data size
    fwrite((DWORD*)&size,                   4, 1, fileDump);  // size of the packet + opcode lenght
    fwrite((DWORD*)&opcode,                 4, 1, fileDump);  // opcode

    fwrite(buffer + opcodeSize, size - opcodeSize, 1, fileDump);  // data

#if _DEBUG
    printf("%s Opcode: 0x%04X Size: %-8u\n", packetType == CMSG ? "CMSG" : "SMSG", opcode, size);
#endif

    fflush(fileDump);

    mtx.unlock();
}
Ejemplo n.º 7
0
// Console modification.
void lConsole::ChangeOutputstream(void *NewStream)
{
    ThreadSafe.lock();
    this->StreamHandle = NewStream;
    ThreadSafe.unlock();
}
Ejemplo n.º 8
0
// 멀티스레드를 위한 imageRequset
void imageRequset(string tempuri, int index)
{
	int resp_leng;
	string request, response;
	char buffer[BUFFERSIZE];
	struct sockaddr_in serveraddr;
	int sock = 0;
	WSADATA wsaData;
	vector<char> image;

	Uri *uri = new Uri;
	Uri resultURL = uri->Parse(tempuri);
	resultURL.Parse(tempuri);
	if (resultURL.getProtocol() == "http" || resultURL.getProtocol() == "")
	{
		hostent* hostname = gethostbyname(resultURL.getHost().c_str());
		// Init WinSock
		WSADATA wsa_Data;
		int wsa_ReturnCode = WSAStartup(0x101, &wsa_Data);
		// Get the local hostname
		struct hostent *host_entry;
		host_entry = gethostbyname(resultURL.getHost().c_str());
		char * ipaddress;
		ipaddress = inet_ntoa(*(struct in_addr *)*host_entry->h_addr_list);
		WSACleanup();

		int port = 0;
		if (resultURL.getPort() == "")
		{
			port = 80;
		}
		else
		{
			port = atoi(resultURL.getPort().c_str());
		}
		string path = resultURL.getPath();

		if (resultURL.getHost() == "sang12456.cafe24.com")
			request = "GET " + path + " HTTP/1.1\r\n\r\n";
		else
			request = "GET " + path + " HTTP/1.1\nHost: " + resultURL.getHost() + "\r\n\r\n";//"\nConnection : keep - alive\nCache - Control : max - age = 0\nAccept : text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, */*;q=0.8\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36\nAccept-Encoding: gzip, deflate, sdch\nAccept-Language: ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4\r\n\r\n";

																							 //init winsock
		if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
			return;

		//open socket
		if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
			return;

		//connect
		memset(&serveraddr, 0, sizeof(serveraddr));
		serveraddr.sin_family = AF_INET;
		serveraddr.sin_addr.s_addr = inet_addr(ipaddress);
		serveraddr.sin_port = htons(port);
		if (connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)
			return;

		//send request
		if (send(sock, request.c_str(), request.length(), 0) != request.length())
			return;

		//get response
		//cout << "response" << endl;
		response = "";
		resp_leng = BUFFERSIZE;

		do
		{
			resp_leng = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
			copy(buffer, buffer + resp_leng, back_inserter(image));
		} while (resp_leng != 0);

		//disconnect
		closesocket(sock);

		//cleanup
		WSACleanup();
	}
	else
		response = "not valid";

	if (image[9] == '2' && image[10] == '0' && image[11] == '0')
	{
		int imageLen = image.size();
		char *binary = new char[imageLen];
		memset(binary, 0, imageLen);
		int j = 0;
		for (unsigned int k = 0; k < image.size(); k++)
		{
			binary[j] = image[k];
			j++;
		}
		// 임계영역
		mtx.lock();

		char *temp;
		if ((temp = strstr(binary, "\n\n")) != NULL)
		{
			images.insert(pair<int, char*>(index, &temp[2]));
			imagecache.insert(pair<string, char*>(tempuri, &temp[2]));
		}
		else if ((temp = strstr(binary, "\r\n\r\n")) != NULL)
		{
			images.insert(pair<int, char*>(index, &temp[4]));
			imagecache.insert(pair<string, char*>(tempuri, &temp[4]));
		}
		imagecacheSize.insert(pair<string, int>(tempuri, image.size()));
		replace(ret, tempuri+"\"image", "image");
		imageSize.insert(pair<int, int>(index, image.size()));
		mtx.unlock();
		InvalidateRect(hwndMain, &rt, TRUE);
	}
}
Ejemplo n.º 9
0
/**
 * \brief  Test function
 * 
 * Sets a message and send it over USB
 *         Get the ACK sent back
 */
int main()
{
    /* Opens the connection in non blocking mode */
#ifdef _WIN32
    fd = open("COM7", O_RDWR | O_NOCTTY);
#else
    fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY);
#endif
    /* Check for error */
    if (fd < 0) {
        fprintf(stderr, "[TEST FAILED]: Unable to open connection\n");
        return EXIT_FAILURE;
    }

    /* Sets blocking mode */
#ifdef _WIN32
    //To make blocking:
    unsigned long off = 0;
    if (ioctlsocket(fd, FIONBIO, &off) != 0)
        {
            /* Handle failure. */
        }
#else
    fcntl(fd, F_SETFL, 0);
#endif

    /* clear the set */
    FD_ZERO(&set); 
    /* add our file descriptor to the set */
    FD_SET(fd, &set); 

    /* Defines ACK thread */
    std::thread ack_thread(waitForACK);
	
    /* Creates a device shape */
    DeviceShape ds(9, 9, 9);

    ds.on(4, 4, 4);
    /* Turns on one LED */
    for (int i = 0; i < 9 ; i++) {
        ds.on(i,i,8-i);
        ds.on(i,i,i);
        ds.on(i,8-i,i);
        ds.on(8-i, i, i);
    }
    
    /* Creates a Request */ 
    Request myRequest(1, 92, SET_LEDSTATS);

    /* Encodes data into the buffers created by the Request */
    uint8_t  *ledBuffer = new uint8_t [ds.getSizeInBytes()];
    ds.toArray(ledBuffer);
    myRequest.encode(ledBuffer);

    /* Prints the message */

#if DEBUG
    std::cout << "My Request : " << myRequest.toStringDebug() << "\n";
#endif

    //     uint8_t* reqLinear = new uint8_t[SIZE_REQUEST];
    //     reqLinear={0};
    
    //     /* Resets the connection */
    //     RequestMessage resetConnection(1, RESET);
    //     resetConnection.encodeCrc();
    //     resetConnection.getListBuffer()[0].toArray(reqLinear);

    // #if DEBUG
    //     std::cout << "Reset Connection : " << resetConnection.toStringDebug() << "\n";
    // #endif

    /* Sents it over USB */
    //    write(fd, reqLinear, SIZE_REQUEST);
    // message_lock.lock();
    // message_queue.push(buffLinear);
    // message_lock.unlock();

    uint8_t* buffLinear = new uint8_t[SIZE_BUFFER]();
    
    /* Sends the Request */
    for (int i = 0; i<myRequest.NbBuffers(); i++) {

        /* Prints */
#if DEBUG
        std::cout << "My Request buffer " << i << " : " 
                  << myRequest.getListBuffer()[i].toStringDebug(i) << "\n";
#endif

        /* Sends it over USB */
        myRequest.getListBuffer()[i].toArray(buffLinear);

#if DEBUG
        printBuffer("BUFFER ", buffLinear, SIZE_BUFFER);
#endif
        /* Send it over USB */
        if (write(fd, buffLinear, SIZE_BUFFER) == -1)
            std::cout << "error while sending buffer number " << i << " over USB \n";

        message_lock.lock();
        message_queue.push(buffLinear);
        message_lock.unlock();

    }    

    std::cout << "[TEST PASSED]\n";
    ack_thread.detach();
    close(fd);

    delete [] buffLinear;
    //    delete [] reqLinear;
    delete [] ledBuffer;
    
    return 0;
}
Ejemplo n.º 10
0
int callback(CSocket::connection &conn, char *recvbytes, size_t size, CServerSocket &sock)
{
	//std::this_thread::sleep_for(std::chrono::seconds(1));

	static const char okSignal[] = { "OK Signal" };

	std::stringstream ss0;

	ss0.write(okSignal, sizeof(okSignal));

	conn.send(ss0);
	
	std::stringstream ss/*(std::ios::binary | std::ios::in | std::ios::out)*/;

	conn.receive(ss, 0x7FFFF);
	dataStruct::dataStructT data2;


	cereal::PortableBinaryInputArchive input(ss);

	input(data2);

	std::time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

	std::string str = std::string(ctime(&tt));

	str.pop_back();

	std::replace(str.begin(), str.end(), ':', '_');

	std::fstream file(str + ".txt", std::ios::out | std::ios::in | std::ios::binary | std::ios::trunc);

	//std::cout << "Arquivo => " << str + ".txt" << std::endl;

	cereal::JSONOutputArchive out(file);

	out(cereal::make_nvp("PC", data2));

	
	conn.send(ss0);

	auto removeduplicates = [](std::deque<std::string> &deq)
	{
		//std::cout << deq.size() << std::endl;

		/*std::sort(deq.begin(), deq.end());
		deq.erase(std::unique(deq.begin(), deq.end()), deq.end());*/

		std::set<std::string> s;
		unsigned size = deq.size();
		for (unsigned i = 0; i < size; ++i) s.insert(deq[i]);
		deq.assign(s.begin(), s.end());

		//std::cout << deq.size() << std::endl;
	};

	std::deque<std::string> sendToUser;

	for (auto &i : data2) {
		for (auto &asd : i.second) {
			if (asd.first.find("Hardware IDs") != std::string::npos)
			{
				svdrvsmutex.lock();
				auto list = dvrs->getDriverPath(asd.second);
				svdrvsmutex.unlock();

				if (list.size() == 0)
					continue;

				removeduplicates(list);

				sendToUser.insert(sendToUser.end(), list.begin(), list.end());
				break;
			}
		}
	}


	auto sendFolder = [&](const std::string &path) {
		HANDLE hFind;
		WIN32_FIND_DATA data;

		auto pos = path.find_last_of('/');

		std::string folder = (pos != std::string::npos)? std::string(&(path.c_str()[++pos])) : std::to_string(rand());

		if (folder.size() == 0) {
			folder = std::to_string(rand());
		}


		sendFoldersAndFiles f(1, folder);
		std::stringstream fstr(std::ios::binary | std::ios::in | std::ios::out);
		cereal::PortableBinaryOutputArchive output(fstr);
		output(f);

		hFind = FindFirstFile((path + "/*").c_str(), &data);
		if (hFind != INVALID_HANDLE_VALUE)
		{
			do
			{
				std::string cFileName = data.cFileName;
				std::string fullPath = path + std::string("/") + cFileName;

				if (cFileName != "." && cFileName != "..") {
					if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
					{
						std::fstream fs(fullPath, std::ios::in | std::ios::binary);

						if (!fs.is_open()) {
							std::cout << "Falha ao abrir " << fullPath << std::endl;
							continue;
						}

						if(CServer::debug) std::cout << "header" << std::endl;
						conn.send(fstr);
						std::this_thread::sleep_for(std::chrono::milliseconds(10));

						{
							std::stringstream okSign;
							conn.receive(okSign, 0x400);
							std::this_thread::sleep_for(std::chrono::milliseconds(10));
						}

						if (CServer::debug) std::cout << cFileName << std::endl;

						std::atomic<int> signal = 0;
						std::atomic<bool> contnthr = true;

						std::thread sndthr(thrdsnd, std::ref(conn.tranfBytesSize), std::ref(conn), std::ref(contnthr), std::ref(signal));
						conn.autoSendFile(cFileName, fs, tstsendfile, 1024 * 64, signal);

						std::this_thread::sleep_for(std::chrono::milliseconds(15));
						contnthr = false;
						//std::this_thread::sleep_for(std::chrono::milliseconds(25));

						if (sndthr.joinable()) {
							sndthr.join();
						}
					}
				}
			} while (FindNextFile(hFind, &data));
			FindClose(hFind);
		}
	};

	removeduplicates(sendToUser);



	for (auto &l : sendToUser) {
		sendFolder(l);
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}

	{
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
		sendFoldersAndFiles f(1, "/");

		std::stringstream ssendstr(std::ios::binary | std::ios::in | std::ios::out);

		cereal::PortableBinaryOutputArchive output(ssendstr);

		output(f);



		conn.send(ssendstr);
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}
	return 0;
}
Ejemplo n.º 11
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
	HDC hdc;
	PAINTSTRUCT ps;
	int len = 0;

	hwndMain = hWnd;
	HBITMAP hBMP, hOldBmp;

	HPALETTE      hPalette, hOldPalette;
	HDC           hMemDC;
	BITMAP        bm;
	HFONT font, oldfont;
	RECT rect;
	int width;
	int height;

	if (GetWindowRect(hWnd, &rect))
	{
		rect.left = 10;
		rect.top = 45;
		width = rect.right - rect.left;
		height = rect.bottom - rect.top;
	}
	rt = rect;
	rect.top += 20;

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

	switch (iMessage)
	{
	case WM_CREATE:
		// edit control
		hEdit = CreateWindow("edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER |
			ES_AUTOHSCROLL, 250, 10, 300, 25, hWnd, (HMENU)NULL, g_hInst, NULL);
		origLVEditWndProc = (WNDPROC)SetWindowLong(hEdit, GWL_WNDPROC, (DWORD)LVEditWndProc);

	case WM_KEYDOWN:
	{
		switch (wParam)
		{
		case VK_PRIOR:
			scroll += 50;
			InvalidateRect(hwndMain, &rt, TRUE);
			break;
		case VK_NEXT:
			scroll -= 50;
			InvalidateRect(hwndMain, &rt, TRUE);
			break;
		}
	}

	case WM_PAINT:
	{
		int imageCount = 0;
		hdc = BeginPaint(hWnd, &ps);
		//FillRect(hdc, &rt, (HBRUSH)GetStockObject(WHITE_BRUSH));
		rect.top += scroll;

		// dll에서 InvalidateRect를 통해서 WM_PAINT 메시지를 보낸다.
		// 이때 찾은 Path는 path.txt 파일에 기록되고 이를 읽어 Window에 보여준다.
		if (curState == FILESTATE)
		{
			// 임계영역
			mtx1.lock();
			ret.clear();
			string line;
			ifstream myfile("path.txt");
			if (myfile.is_open())
			{
				while (getline(myfile, line))
				{
					ret.push_back(line);
				}
				myfile.close();
			}
			mtx1.unlock();
		}

		// bmp local image load with double buffering
		if (LoadBitmapFromBMPFile("nexon.bmp", &hBMP, &hPalette, 0))
		{
			GetObject(hBMP, sizeof(BITMAP), &bm);
			hMemDC = CreateCompatibleDC(hdc);
			hOldBmp = (HBITMAP)SelectObject(hMemDC, hBMP);
			hOldPalette = SelectPalette(hdc, hPalette, FALSE);
			RealizePalette(hdc);
			BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight,
				hMemDC, 0, 0, SRCCOPY);
			SelectObject(hMemDC, hOldBmp);
			DeleteObject(hBMP);
			SelectPalette(hdc, hOldPalette, FALSE);
			DeleteObject(hPalette);
		}

		Graphics graphics(hdc);
		Graphics memGraphics(hMemDC);
		for (unsigned int i = 0; i < ret.size(); i++)
		{
			// 텍스트 tag일 경우
			if (ret[i] != "image")
			{
				int fontSize = 15;
				if (ret[i].substr(ret[i].length() - 2, 2) == "h1")
				{
					fontSize = 30;
					font = CreateFont(fontSize, 0, 0, 0, FW_ULTRABOLD, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 2)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
				}
				else if (ret[i].substr(ret[i].length() - 2, 2) == "h2")
				{
					fontSize = 25;
					font = CreateFont(fontSize, 0, 0, 0, FW_BOLD, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 2)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
				}
				else if (ret[i].substr(ret[i].length() - 2, 2) == "h3")
				{
					fontSize = 20;
					font = CreateFont(fontSize, 0, 0, 0, FW_BOLD, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 2)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
				}
				else if (ret[i].substr(ret[i].length() - 2, 2) == "h4")
				{
					fontSize = 15;
					font = CreateFont(fontSize, 0, 0, 0, FW_BOLD, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 2)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
				}
				else if (ret[i].substr(ret[i].length() - 2, 2) == "h5")
				{
					fontSize = 10;
					font = CreateFont(fontSize, 0, 0, 0, FW_BOLD, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 2)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
				}
				else if (ret[i].substr(ret[i].length() - 2, 2) == "h6")
				{
					fontSize = 5;
					font = CreateFont(fontSize, 0, 0, 0, FW_BOLD, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 2)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
				}
				else if (ret[i].substr(ret[i].length() - 5, 5) == "title")
				{
					fontSize = 35;
					font = CreateFont(fontSize, 0, 0, 0, FW_HEAVY, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 5)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
				}
				else if (ret[i].substr(ret[i].length() - 9, 9) == "hyperText")
				{
					fontSize = 15;
					font = CreateFont(fontSize, 0, 0, 0, FW_BOLD, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					SetTextColor(hdc, RGB(0, 0, 255));
					oldfont = (HFONT)SelectObject(hdc, font);
					DrawText(hdc, (ret[i].substr(0, ret[i].length() - 9)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
					SetTextColor(hdc, RGB(0, 0, 0));
				}
				else
				{
					if (ret[i].substr(ret[i].length() - 5, 5) == "image")
					{
						imageCount++;
						//continue;
					}
					fontSize = 15;
					font = CreateFont(fontSize, 0, 0, 0, 0, 0, 0, 0, HANGEUL_CHARSET, 0, 0, 0, 0, "돋움");
					oldfont = (HFONT)SelectObject(hdc, font);
					if (ret[i].substr(ret[i].length() - 6, 6) == "center")
					{
						DrawText(hdc, (ret[i].substr(0, ret[i].length() - 6)).c_str(), -1, &rect, DT_CENTER | DT_WORDBREAK | DT_NOCLIP);
					}
					else if (ret[i].substr(ret[i].length() - 1, 1) == "p")
					{
						DrawText(hdc, (ret[i].substr(0, ret[i].length() - 2)).c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
					}
					else
					{
						DrawText(hdc, ret[i].c_str(), -1, &rect, DT_LEFT | DT_WORDBREAK | DT_NOCLIP);
					}
				}
				SelectObject(hdc, oldfont);
				DeleteObject(font);
				rect.top += fontSize + 30;
			}
			else if (ret[i] == "image")
			{
				// image tag일 경우
				unordered_map<int, int>::iterator FindImageSize = imageSize.find(imageCount);
				// 찾았다면
				if (FindImageSize != imageSize.end())
				{
					DWORD dwImageSize = FindImageSize->second;
					BYTE* pImageBuffer = NULL;
					unordered_map<int, char*>::iterator FindImage = images.find(imageCount);
					// 찾았다면
					if (FindImage != images.end())
					{
						pImageBuffer = (BYTE*)(FindImage->second);
						HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwImageSize);
						void* pData = GlobalLock(hGlobal);
						memcpy(pData, pImageBuffer, dwImageSize);
						GlobalUnlock(hGlobal);
						IStream* pStream = NULL;
						if (CreateStreamOnHGlobal(hGlobal, TRUE, &pStream) == S_OK)
						{
							//Image *pImage = Image::FromStream(pStream);
							shared_ptr<Image> pImage(Image::FromStream(pStream));
							graphics.DrawImage(pImage.get(), rect.left, rect.top);
							rect.top += pImage->GetHeight();
						}
						::GlobalFree(hGlobal);
					}				
				}			
				imageCount++;
			}
		}
		maxHeight = rect.top;
		EndPaint(hWnd, &ps);
		return 0;
	}
	case WM_DESTROY:
	{
		PostQuitMessage(0);
		return 0;
	}
	}
	return DefWindowProc(hWnd, iMessage, wParam, lParam);
}
Ejemplo n.º 12
0
bool client_func(const mg_connection& connection,enum mg_event event)
{
	if(event==MG_AUTH)
		return true;
	if(event!=MG_REQUEST)
		return false;

	std::string method=connection.request_method;
	std::string request=connection.uri;
	std::string json_set_prefix="/json_set/";
	std::string json_get_prefix="/json_get";

	std::cout<<"Request:  "<<request<<std::endl;

	try
	{
		if(msl::starts_with(request,json_set_prefix))
		{
			std::cout<<"  Set JSON "+method+" Request."<<std::endl;

			std::string json_set_str=request.substr(json_set_prefix.size(),request.size()-json_set_prefix.size());

			if(method=="POST")
				json_set_str=std::string(connection.content,connection.content_len);

			std::cout<<json_set_str<<std::endl;

			msl::json json=msl::deserialize(json_set_str);

			std::cout<<"  Parsing JSON Object:"<<std::endl;

			for(auto ii:json.getMemberNames())
			{
				switch(json[ii].type())
				{
					case Json::arrayValue:
						std::cout<<"    Adding \""<<ii<<"\" as array."<<std::endl;
						break;
					case Json::objectValue:
						std::cout<<"    Adding \""<<ii<<"\" as object."<<std::endl;
						break;
					case Json::nullValue:
						std::cout<<"    Adding \""<<ii<<"\" as null."<<std::endl;
						break;
					case Json::intValue:
						std::cout<<"    Adding \""<<ii<<"\" as int."<<std::endl;
						break;
					case Json::uintValue:
						std::cout<<"    Adding \""<<ii<<"\" as uint."<<std::endl;
						break;
					case Json::realValue:
						std::cout<<"    Adding \""<<ii<<"\" as real."<<std::endl;
						break;
					case Json::stringValue:
						std::cout<<"    Adding \""<<ii<<"\" as string."<<std::endl;
						break;
					case Json::booleanValue:
						std::cout<<"    Adding \""<<ii<<"\" as bool."<<std::endl;
						break;
					default:
						std::cout<<"    Skipping \""<<ii<<"\" with invalid type."<<std::endl;
						continue;
						break;
				}

				database_lock.lock();
				database[ii]=json[ii];
				database_lock.unlock();
			}

			msl::client_reply(connection,"","text/plain");
			return true;
		}
		else if(msl::starts_with(request,json_get_prefix))
		{
			std::cout<<"  Get JSON "+method+" Request."<<std::endl;

			std::string json_get_str=request.substr(json_get_prefix.size(),request.size()-json_get_prefix.size());

			if(method=="POST")
				json_get_str=std::string(connection.content,connection.content_len);

			std::vector<std::string> paths=get_paths(json_get_str);

			std::cout<<json_get_str<<std::endl;

			std::cout<<"  Parsing JSON Path:"<<std::endl;

			database_lock.lock();
			auto json_get_object=database;
			database_lock.unlock();

			for(auto path:paths)
			{
				json_get_object=json_get_object[path];

				switch(json_get_object.type())
				{
					case Json::arrayValue:
						std::cout<<"    Getting \""<<path<<"\" as array."<<std::endl;
						break;
					case Json::objectValue:
						std::cout<<"    Getting \""<<path<<"\" as object."<<std::endl;
						break;
					case Json::nullValue:
						std::cout<<"    Getting \""<<path<<"\" as null."<<std::endl;
						break;
					case Json::intValue:
						std::cout<<"    Getting \""<<path<<"\" as int."<<std::endl;
						break;
					case Json::uintValue:
						std::cout<<"    Getting \""<<path<<"\" as uint."<<std::endl;
						break;
					case Json::realValue:
						std::cout<<"    Getting \""<<path<<"\" as real."<<std::endl;
						break;
					case Json::stringValue:
						std::cout<<"    Getting \""<<path<<"\" as string."<<std::endl;
						break;
					case Json::booleanValue:
						std::cout<<"    Getting \""<<path<<"\" as bool."<<std::endl;
						break;
					default:
						std::cout<<"    Exiting \""<<path<<"\" with invalid type."<<std::endl;
						return false;
				}
			}

			msl::client_reply(connection,msl::serialize(json_get_object),"application/javascript");
			return true;
		}
	}
	catch(std::exception& e)
	{
		std::cout<<"  Error:  "<<e.what()<<std::endl;
	}
	catch(...)
	{
		std::cout<<"  Error:  Unknown error occured."<<std::endl;
	}

	return false;
}
Ejemplo n.º 13
0
 void set(T _newvalue) {
     //mutex lock - not read and write at the same time
     mtx.lock();
     value = _newvalue;
     mtx.unlock();
 }
Ejemplo n.º 14
0
		void STimer::Stop()
		{
			_mutex.lock();
			_stop = true;
			_mutex.unlock();
		}
Ejemplo n.º 15
0
void MemoryPool::clear() {
    locker_.lock();
    for (auto &item : pool_) { delete[] reinterpret_cast<byte_type *>(item.second); }
    locker_.unlock();
}
Ejemplo n.º 16
0
static InitFunction initFunction([] ()
{
	g_hooksDLL->SetHookCallback(StringHash("loadsFrame"), [] (void*)
	{
		g_netLibrary->RunFrame();

		/*g_loadScreenMutex.lock();

		if (g_loadScreen.get())
		{
			g_loadScreen->UpdateFrame();
		}

		g_loadScreenMutex.unlock();*/
	});

	g_hooksDLL->SetHookCallback(StringHash("loadsClean"), [] (void*)
	{
		g_loadScreenMutex.lock();

		if (g_loadScreen.GetRef())
		{
			g_loadScreen = nullptr;
		}

		g_loadScreenMutex.unlock();
	});
});
#endif
#endif
Ejemplo n.º 17
0
// Will analyse every buffer from usrpT
// each buffer has a size nDetect. nStorage is the size of the total transmission
void detection(uint nDetect, int nStorage){
  bool isDetected=false;
  int nCurrent=0;
  short *storage_short;
  storage_short=new short [nStorage];
  short *p=0;
  float power;
  int i2=0,count_trans=0;
  std::vector<std::thread> processingV;
  int count=0;
  while(1){
    std::this_thread::yield();
    if (isDetected){
      // Store the elements in storage_short
      if (nCurrent<nStorage){
	// Fill storage_short
	i2=0;
	int conj_rx;
	while ((nCurrent<nStorage) && (i2<2*((int) nDetect))){	  
	  conj_rx=pow(-1,nCurrent);
	  //DispVal(conj_rx);
	  storage_short[nCurrent]=(p[i2])*conj_rx;
	  nCurrent++; i2++;
	};
	// Relase the just stored element
	std::this_thread::yield();
	delete[] (usrpQ.front());
	mtxUsrp.lock();
	usrpQ.pop();
	mtxUsrp.unlock();
	std::this_thread::yield();

	//Wait for a new element
	sem_wait(&usrpReady);
	p=usrpQ.front();
      }
      else{
	// End of transmission
	//count_trans=0;
	isDetected=false;
	nCurrent=0;

	processingV.push_back(std::thread(processing, storage_short, nStorage, count));
	count++;
	storage_short=new short[nStorage];
      }
    }
    else{
      // Wait for new element
      sem_wait(&usrpReady);
      p=usrpQ.front();
      // Test of detection
      power=powerTotArray(p, (int)2*nDetect);
      //if(power>50000)DispVal(power);

      count_trans++;//Avoid transient power amplification

      //Power threshold 60GHz=1000

      if ( power>1000 && count_trans>10000 && count<1){
	// If detection, keep the element
	std::cout<<"Detected Transmission\n";
	//exit(1);
	isDetected=true;
      }
      else{
	// Release the element
	std::this_thread::yield();
	delete[] (usrpQ.front());
	mtxUsrp.lock();
	usrpQ.pop();
	mtxUsrp.unlock();
	std::this_thread::yield();
      }
    }
  }
  for (auto& th : processingV) th.join();
}
Ejemplo n.º 18
0
int handle(int socket, const string& str, const User& user)
{
	vector<string> tokens;
	string answer;
	string cmd;
	string arg_1;
	string arg_2;

	tokens = preProcess(str);

	switch(tokens.size())
	{
		case 0:
			answer = INVALID_CMD_ERR;
			break;

		case 1:
			cmd = lower(tokens[0]);
			if(cmd == EXIT_CMD)
				answer = OK;
			if(cmd == HELP_CMD)
				answer = HELP;
			else
				answer = INVALID_CMD_ERR;
			break;

		case 2:		
			cmd = lower(tokens[0]);
			arg_1 = tokens[1];
			if(cmd == JOIN_GROUP_CMD)
				answer = OK;
			break;

		//number of args >= 3
		default:
			cmd = lower(tokens[0]);
			arg_1 = tokens[1];
			if(cmd == SEND_MSG_CMD)
			{
				string msg_content = join(tokens, " ", 2);
				Message msg(user.getName(), arg_1, msg_content);
				cout << "message: " << msg.getContent() << endl;

				chat_mtx.lock();
				if(!chat.hasUser(msg.getSrcUserName()))
					answer = NO_SRC_USER_ERR;
				else if(!chat.hasUser(msg.getDstUserName()))
					answer = NO_DST_USER_ERR;
				else if(!chat.addMessage(msg))
					answer = MSG_EXISTS_ERR;
				else
					answer = MSG_QUEUED;
				chat_mtx.unlock();
			}
			else
				answer = INVALID_CMD_ERR;
			break;
	}

	if(send(socket, answer) < 0)
		error("send");	
	if(send(socket, "hur brbrb\n") < 0)
		error("send");	

	return 0;
}
Ejemplo n.º 19
0
// Worker thread
void HttpClient::networkThread()
{    
    HttpRequest *request = nullptr;
    
    auto scheduler = Director::getInstance()->getScheduler();
    
    while (true) 
    {
        if (s_need_quit)
        {
            break;
        }
        
        // step 1: send http request if the requestQueue isn't empty
        request = nullptr;
        
        s_requestQueueMutex.lock();
        
        //Get request task from queue
        
        if (!s_requestQueue->empty())
        {
            request = s_requestQueue->at(0);
            s_requestQueue->erase(0);
        }
        
        s_requestQueueMutex.unlock();
        
        if (nullptr == request)
        {
            // Wait for http request tasks from main thread
            std::unique_lock<std::mutex> lk(s_SleepMutex); 
            s_SleepCondition.wait(lk);
            continue;
        }
        
        // step 2: libcurl sync access
        
        // Create a HttpResponse object, the default setting is http access failed
        HttpResponse *response = new HttpResponse(request);
        
        processResponse(response, s_errorBuffer);
        

        // add response packet into queue
        s_responseQueueMutex.lock();
        s_responseQueue->pushBack(response);
        s_responseQueueMutex.unlock();
        
        if (nullptr != s_pHttpClient) {
            scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this));
        }
    }
    
    // cleanup: if worker thread received quit signal, clean up un-completed request queue
    s_requestQueueMutex.lock();
    s_requestQueue->clear();
    s_requestQueueMutex.unlock();
    
    
    if (s_requestQueue != nullptr) {
        delete s_requestQueue;
        s_requestQueue = nullptr;
        delete s_responseQueue;
        s_responseQueue = nullptr;
    }
    
}
Ejemplo n.º 20
0
int KiekkoNetwork::InitializeNetwork()
{
	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
	{
		printf("WSAStartup(...) failed! Error code : %d\n", WSAGetLastError());
		return 1;
	}

	struct addrinfo hints;

	ZeroMemory(&hints, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

	struct addrinfo *result = NULL;
	if (getaddrinfo(SERVER.c_str(), PORT, &hints, &result) != 0)
	{
		printf("getaddrinfo(...) failed! Error code: %d\n", WSAGetLastError());
		WSACleanup();
		return 1;
	}

	struct addrinfo* ptr = NULL;

	for (ptr = result; ptr != NULL; ptr=ptr->ai_next)
	{
		ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
	
		if (ConnectSocket == INVALID_SOCKET)
		{
			printf("socket(...) failed! Error code : %d\n", WSAGetLastError());
			WSACleanup();
			return 1;
		}
		
		if (connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR)
		{
			printf("connect(...) failed! Error code : %d\n", WSAGetLastError());
			closesocket(ConnectSocket);
			ConnectSocket = INVALID_SOCKET;
			continue;
		}
		else
			printf("Connect success!\n", WSAGetLastError());
		break;
	}
	
	freeaddrinfo(result);
	if (ConnectSocket == INVALID_SOCKET)
	{
		printf("Unable to connect to server!\n");
		WSACleanup();
		return 1;
	}


	recvThreadMutex.lock();
	std::thread th(ReceiveThread, ConnectSocket, recvLength);
	th.detach();

	SendPackage temp;
	temp.ownPos = 125.0;

	if (SendMsg(temp))
		return 1;

	return 0;
}
Ejemplo n.º 21
0
void lConsole::ToggleScrollbackPrinting()
{
    ThreadSafe.lock();
    this->ShouldPrintScrollback = !this->ShouldPrintScrollback;
    ThreadSafe.unlock();
}
Ejemplo n.º 22
0
// Worker thread
void HttpClient::networkThread()
{    
    HttpRequest *request = nullptr;
    
    auto scheduler = Director::getInstance()->getScheduler();
    
    while (true) 
    {
        if (s_need_quit)
        {
            break;
        }
        
        // step 1: send http request if the requestQueue isn't empty
        request = nullptr;
        
        s_requestQueueMutex.lock();
        
        //Get request task from queue
        
        if (!s_requestQueue->empty())
        {
            request = s_requestQueue->at(0);
            s_requestQueue->erase(0);
        }
        
        s_requestQueueMutex.unlock();
        
        if (nullptr == request)
        {
            // Wait for http request tasks from main thread
            std::unique_lock<std::mutex> lk(s_SleepMutex); 
            s_SleepCondition.wait(lk);
            continue;
        }
        
        // step 2: libcurl sync access
        
        // Create a HttpResponse object, the default setting is http access failed
        HttpResponse *response = new HttpResponse(request);
        
        // request's refcount = 2 here, it's retained by HttpRespose constructor
        request->release();
        // ok, refcount = 1 now, only HttpResponse hold it.
        
        long responseCode = -1;
        int retValue = 0;

        // Process the request -> get response packet
        switch (request->getRequestType())
        {
            case HttpRequest::Type::GET: // HTTP GET
                retValue = processGetTask(request,
                                          writeData, 
                                          response->getResponseData(), 
                                          &responseCode,
                                          writeHeaderData,
                                          response->getResponseHeader());
                break;
            
            case HttpRequest::Type::POST: // HTTP POST
                retValue = processPostTask(request,
                                           writeData, 
                                           response->getResponseData(), 
                                           &responseCode,
                                           writeHeaderData,
                                           response->getResponseHeader());
                break;

            case HttpRequest::Type::PUT:
                retValue = processPutTask(request,
                                          writeData,
                                          response->getResponseData(),
                                          &responseCode,
                                          writeHeaderData,
                                          response->getResponseHeader());
                break;

            case HttpRequest::Type::DELETE:
                retValue = processDeleteTask(request,
                                             writeData,
                                             response->getResponseData(),
                                             &responseCode,
                                             writeHeaderData,
                                             response->getResponseHeader());
                break;
            
            default:
                CCASSERT(true, "CCHttpClient: unkown request type, only GET and POSt are supported");
                break;
        }
                
        // write data to HttpResponse
        response->setResponseCode(responseCode);
        
        if (retValue != 0) 
        {
            response->setSucceed(false);
            response->setErrorBuffer(s_errorBuffer);
        }
        else
        {
            response->setSucceed(true);
        }

        
        // add response packet into queue
        s_responseQueueMutex.lock();
        s_responseQueue->pushBack(response);
        s_responseQueueMutex.unlock();
        
        if (nullptr != s_pHttpClient) {
            scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this));
        }
    }
    
    // cleanup: if worker thread received quit signal, clean up un-completed request queue
    s_requestQueueMutex.lock();
    s_requestQueue->clear();
    s_requestQueueMutex.unlock();
    
    
    if (s_requestQueue != nullptr) {
        delete s_requestQueue;
        s_requestQueue = nullptr;
        delete s_responseQueue;
        s_responseQueue = nullptr;
    }
    
}
Ejemplo n.º 23
0
GameHost_Private* start_game_host(uint32_t ageMcpId)
{
    PGconn* postgres = PQconnectdb(DS::String::Format(
                    "host='%s' port='%s' user='******' password='******' dbname='%s'",
                    DS::Settings::DbHostname(), DS::Settings::DbPort(),
                    DS::Settings::DbUsername(), DS::Settings::DbPassword(),
                    DS::Settings::DbDbaseName()).c_str());
    if (PQstatus(postgres) != CONNECTION_OK) {
        fprintf(stderr, "Error connecting to postgres: %s", PQerrorMessage(postgres));
        PQfinish(postgres);
        return 0;
    }

    PostgresStrings<1> parms;
    parms.set(0, ageMcpId);
    PGresult* result = PQexecParams(postgres,
            "SELECT \"AgeUuid\", \"AgeFilename\", \"AgeIdx\", \"SdlIdx\", \"Temporary\""
            "    FROM game.\"Servers\" WHERE idx=$1",
            1, 0, parms.m_values, 0, 0, 0);
    if (PQresultStatus(result) != PGRES_TUPLES_OK) {
        fprintf(stderr, "%s:%d:\n    Postgres SELECT error: %s\n",
                __FILE__, __LINE__, PQerrorMessage(postgres));
        PQclear(result);
        PQfinish(postgres);
        return 0;
    }
    if (PQntuples(result) == 0) {
        fprintf(stderr, "[Game] Age MCP %u not found\n", ageMcpId);
        PQclear(result);
        PQfinish(postgres);
        return 0;
    } else {
        DS_DASSERT(PQntuples(result) == 1);

        GameHost_Private* host = new GameHost_Private();
        host->m_instanceId = PQgetvalue(result, 0, 0);
        host->m_ageFilename = PQgetvalue(result, 0, 1);
        host->m_ageIdx = strtoul(PQgetvalue(result, 0, 2), 0, 10);
        host->m_gameMaster = 0;
        host->m_serverIdx = ageMcpId;
        host->m_postgres = postgres;
        host->m_temp = strcmp("t", PQgetvalue(result, 0, 4)) == 0;

        // Fetch the age states
        Auth_FetchSDL sdlFetch;
        AuthClient_Private fakeClient;
        sdlFetch.m_client = &fakeClient;
        sdlFetch.m_ageFilename = host->m_ageFilename;
        sdlFetch.m_sdlNodeId = strtoul(PQgetvalue(result, 0, 3), 0, 10);
        PQclear(result);

        s_authChannel.putMessage(e_AuthFetchSDL, reinterpret_cast<void*>(&sdlFetch));
        DS::FifoMessage reply = fakeClient.m_channel.getMessage();
        if (reply.m_messageType != DS::e_NetSuccess) {
            fputs("[Game] Error fetching Age SDL\n", stderr);
            PQfinish(postgres);
            delete host;
            return 0;
        }
        host->m_sdlIdx = sdlFetch.m_sdlNodeId;
        host->m_globalState = sdlFetch.m_globalState;

        // Load the local state and see if it needs to be updated
        try {
            host->m_localState = SDL::State::FromBlob(sdlFetch.m_localState);
        } catch (DS::EofException&) {
            fprintf(stderr, "[SDL] Error parsing Age SDL state for %s\n",
                    host->m_ageFilename.c_str());
            PQfinish(postgres);
            delete host;
            return 0;
        }
        if (host->m_localState.update()) {
            DS::Blob local = host->m_localState.toBlob();
            dm_local_sdl_update(host, local);
            host->m_ageSdlHook = SDL::State::FromBlob(local);
        } else {
            host->m_ageSdlHook = SDL::State::FromBlob(sdlFetch.m_localState);
        }
        host->m_ageSdlHook.merge(host->m_globalState);

        s_gameHostMutex.lock();
        s_gameHosts[ageMcpId] = host;
        s_gameHostMutex.unlock();

        // Fetch initial server state
        PostgresStrings<1> parms;
        parms.set(0, host->m_serverIdx);
        PGresult* result = PQexecParams(host->m_postgres,
                "SELECT \"Descriptor\", \"ObjectKey\", \"SdlBlob\""
                "    FROM game.\"AgeStates\" WHERE \"ServerIdx\"=$1",
                1, 0, parms.m_values, 0, 0, 0);
        if (PQresultStatus(result) != PGRES_TUPLES_OK) {
            fprintf(stderr, "%s:%d:\n    Postgres SELECT error: %s\n",
                    __FILE__, __LINE__, PQerrorMessage(host->m_postgres));
        } else {
            int count = PQntuples(result);

            for (int i=0; i<count; ++i) {
                DS::BlobStream bsObject(DS::Base64Decode(PQgetvalue(result, i, 1)));
                DS::Blob sdlblob = DS::Base64Decode(PQgetvalue(result, i, 2));
                MOUL::Uoid key;
                key.read(&bsObject);
                try {
                    SDL::State state = SDL::State::FromBlob(sdlblob);
                    state.update();

                    GameState gs;
                    gs.m_isAvatar = false;
                    gs.m_persist = true;
                    gs.m_state = state;
                    host->m_states[key][PQgetvalue(result, i, 0)] = gs;
                } catch (DS::EofException) {
                    fprintf(stderr, "[SDL] Error parsing state %s for [%04X]%s\n",
                            PQgetvalue(result, i, 0), key.m_type, key.m_name.c_str());
                }
            }
        }
        PQclear(result);

        std::thread threadh(&dm_gameHost, host);
        threadh.detach();
        return host;
    }
}
void threadfunction_mutex_lock(int arg) 
{
  coutLock.lock();
    cout << "mutex lock: " << arg << ", this_thread::get_id=" << this_thread::get_id() << "\n";
  coutLock.unlock();
}
Ejemplo n.º 25
0
void QueryWorld::updateCopyWorld(const World& world) {
    m_copyWorldLock.lock();
    m_copyWorld = world;
    m_copyWorldLock.unlock();
}
Ejemplo n.º 26
0
void AddActiveSocket(int *s, int id)
{
	socketlistmtx.lock();
	purkka->activeSocket[id] = s;
	socketlistmtx.unlock();
}
Ejemplo n.º 27
0
Archivo: debug.cpp Proyecto: ZeroCM/zcm
void zcm_debug_lock(void) { mut.lock(); }
Ejemplo n.º 28
0
void dijkstra_pq_thread(CSRGraph *g, int *dist, std::priority_queue<Priority_struct, std::vector<Priority_struct>, Compare_priority> &pq, int threadNum, std::mutex *dist_locks)
{
    while(!pq.empty())
    {
        queue_lock.lock();

        if(pq.empty())
        {
            queue_lock.unlock();
            break;
        }

        Priority_struct temp_struct = pq.top();
        int u = temp_struct.node_name;
        pq.pop();
	
    printf("Popped\n");
    for(int i=0; i< pq.size();i++){
	printf(" %d", pq[i]);
    }
    printf("\n");

        int udist = dist[u];

        queue_lock.unlock();

        std::vector<int> neighbors = CSRGraph_getNeighbors(g, u);

        int neighbor;
        for(neighbor=0;neighbor < neighbors.size(); neighbor++)
        {
            int v = neighbors[neighbor];
            int uvdist = CSRGraph_getDistance(g, u, v);
            int alt = udist + uvdist;

            dist_locks[v].lock();
            if(alt < dist[v])
            {
                dist[v] = alt;
                dist_locks[v].unlock();

                Priority_struct temp2;
                temp2.node_name=v;
                temp2.node_weight = uvdist;

                queue_lock.lock();                
                pq.push(temp2);
		
    printf("Pushed\n");
    for(int i=0; i< pq.size();i++){
	printf(" %d", pq[i]);
    }
    printf("\n");
                queue_lock.unlock();                    
            }
            else
            {
                dist_locks[v].unlock();
            }
        }
    }

    //printf("Thread %d ended.\n", threadNum);
}
Ejemplo n.º 29
0
 void lockmap(){
     mu.lock();
 }
Ejemplo n.º 30
0
void storeDataX(uhd::rx_streamer::sptr rx_stream, uhd::usrp::multi_usrp::sptr dev, size_t buffer_size, uint nDetect){



  // Create storage for a single buffer from USRP
  short *buff_short;
  buff_short=new short[2*buffer_size]; 
 
  short *storage_short;
  storage_short=new short [2*nDetect];

  uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
	  
    std::cout << "Stop the transmitter by pressing ctrl-c \n";
	  
      stream_cmd.num_samps = buffer_size;
      stream_cmd.stream_now = true;
    
       stream_cmd.stream_mode=uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;

       dev->issue_stream_cmd(stream_cmd);


  uhd::rx_metadata_t md;
  size_t n_rx_samps=0;

  int n_rx_last;

  while (1){
    n_rx_samps=0;
    // Fill the storage buffer loop
    while (n_rx_samps<nDetect){
      n_rx_last=0;
      // Fill buff_short
      while (n_rx_last==0) {
	n_rx_last=rx_stream->recv(&buff_short[0], buffer_size, md, 3.0);
	//std::this_thread::yield();
      };

      sec_count++;
      // Check if no overflow
      if (n_rx_last!=(int)buffer_size) {
	std::cerr << "I expect the buffer size to be always the same!\n";
	std::cout<<"Read only:"<<n_rx_last<<"\n";
	std::cout<<"Buffer:"<<buffer_size<<"\n";
	exit(1); 
      };
      
      // Fill storage
      int i1=2*n_rx_samps;
      int i2=0;   
      while ((i1<(int) (2*nDetect)) && (i2<2*((int) buffer_size))){	  
	storage_short[i1]=buff_short[i2];
	i1++; i2++;
      };
      
      //storage_short=buff_short;
      n_rx_samps=n_rx_samps+n_rx_last;
      //std::cout << "n_rx_samps=" << n_rx_samps  << std::endl;	 
    }//storage_short now full


    mtxQ.lock();
    bufferQ.push(buff_short);
    mtxQ.unlock();
    //delete buff_short;
    buff_short=new short [2*buffer_size]; // Change memory cell used

    //usleep(1000000/4);
    sem_post( &isReady); // Gives the start to detection part

  }//end while 1
}