Exemplo n.º 1
0
/* Read the data from the dynamic virtual channel
 * reconstruct the original message and
 * verify its content
 */
DWORD WINAPI ReadThread( PVOID param )
{
    HANDLE hFile = (HANDLE)param;
    BYTE        ReadBuffer[CHANNEL_PDU_LENGTH];
    DWORD       dwRead;
    BYTE        b = 0;
    CHANNEL_PDU_HEADER *pHdr = (CHANNEL_PDU_HEADER *)ReadBuffer;
    BOOL        bSucc;
    HANDLE      hEvent;

    hEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
    printf("Read Thread Started\n" );

    for( ULONG msgSize = START_MSG_SIZE;
         msgSize < MAX_MSG_SIZE;
         msgSize += STEP_MSG_SIZE )
    {
        OVERLAPPED  Overlapped = {0};
        DWORD TotalRead = 0;
        do {

            Overlapped.hEvent = hEvent;
            //  read the whole message
            //
            bSucc = ReadFile(
                        hFile,
                        ReadBuffer,
                        sizeof( ReadBuffer ),
                        &dwRead,
                        &Overlapped );
            if ( !bSucc )
            {
                if ( GetLastError() == ERROR_IO_PENDING )
                {
                    DWORD dw = WaitForSingleObject( Overlapped.hEvent, INFINITE );
                    _ASSERT( WAIT_OBJECT_0 == dw );
                    bSucc = GetOverlappedResult(
                            hFile,
                            &Overlapped,
                            &dwRead,
                            FALSE );
                }
            }

            if ( !bSucc )
            {
                DWORD error = GetLastError();
                return error;
            }

            ULONG packetSize = dwRead - sizeof( *pHdr );
            TotalRead += packetSize;
            PBYTE pData = (PBYTE)( pHdr + 1 );
            for ( ULONG i = 0; i < packetSize; pData++, i++, b++ )
            {
                _ASSERT( *pData == b );
            }
            _ASSERT( msgSize == pHdr->length );
        } while( 0 == ( pHdr->flags & CHANNEL_FLAG_LAST ));

        _ASSERT( TotalRead == msgSize );
    }

    return 0;
}
Exemplo n.º 2
0
            /* no error on timeout */
            if (flag)
                NFQVerdictCacheFlush(t);
        } else {
#ifdef COUNTERS
            NFQMutexLock(t);
            t->errs++;
            NFQMutexUnlock(t);
#endif /* COUNTERS */
        }
    } else if(rv == 0) {
        SCLogWarning(SC_ERR_NFQ_RECV, "recv got returncode 0");
    } else {
#ifdef DBG_PERF
        if (rv > t->dbg_maxreadsize)
            t->dbg_maxreadsize = rv;
#endif /* DBG_PERF */

        //printf("NFQRecvPkt: t %p, rv = %" PRId32 "\n", t, rv);

        NFQMutexLock(t);
        if (t->qh != NULL) {
            ret = nfq_handle_packet(t->h, tv->data, rv);
        } else {
            SCLogWarning(SC_ERR_NFQ_HANDLE_PKT, "NFQ handle has been destroyed");
            ret = -1;
        }
        NFQMutexUnlock(t);

        if (ret != 0) {
            SCLogWarning(SC_ERR_NFQ_HANDLE_PKT, "nfq_handle_packet error %" PRId32 "", ret);
        }
    }
}
#else /* WIN32 version of NFQRecvPkt */
void NFQRecvPkt(NFQQueueVars *t, NFQThreadVars *tv) {
    int rv, ret;
    static int timeouted = 0;

    if (timeouted) {
        if (WaitForSingleObject(t->ovr.hEvent, 1000) == WAIT_TIMEOUT) {
            rv = -1;
            errno = EINTR;
            goto process_rv;
        }
        timeouted = 0;
    }

read_packet_again:

    if (!ReadFile(t->fd, tv->buf, sizeof(tv->buf), (DWORD*)&rv, &t->ovr)) {
        if (GetLastError() != ERROR_IO_PENDING) {
            rv = -1;
            errno = EIO;
        } else {
            if (WaitForSingleObject(t->ovr.hEvent, 1000) == WAIT_TIMEOUT) {
                rv = -1;
                errno = EINTR;
                timeouted = 1;
            } else {
                /* We needn't to call GetOverlappedResult() because it always
                 * fail with our error code ERROR_MORE_DATA. */
                goto read_packet_again;
            }
        }
    }

process_rv:

    if (rv < 0) {
        if (errno == EINTR) {
            /* no error on timeout */
        } else {
#ifdef COUNTERS
            t->errs++;
#endif /* COUNTERS */
        }
    } else if(rv == 0) {
        SCLogWarning(SC_ERR_NFQ_RECV, "recv got returncode 0");
    } else {
#ifdef DBG_PERF
        if (rv > t->dbg_maxreadsize)
            t->dbg_maxreadsize = rv;
#endif /* DBG_PERF */

        //printf("NFQRecvPkt: t %p, rv = %" PRId32 "\n", t, rv);

        NFQMutexLock(t);
        if (t->qh) {
            ret = nfq_handle_packet(t->h, buf, rv);
        } else {
            SCLogWarning(SC_ERR_NFQ_HANDLE_PKT, "NFQ handle has been destroyed");
            ret = -1;
        }
        NFQMutexUnlock(t);

        if (ret != 0) {
            SCLogWarning(SC_ERR_NFQ_HANDLE_PKT, "nfq_handle_packet error %" PRId32 "", ret);
        }
    }
}
Exemplo n.º 3
0
INT
copy(TCHAR source[MAX_PATH],
     TCHAR dest[MAX_PATH],
     INT append,
     DWORD lpdwFlags,
     BOOL bTouch)
{
    FILETIME srctime,NewFileTime;
    HANDLE hFileSrc;
    HANDLE hFileDest;
    LPBYTE buffer;
    DWORD  dwAttrib;
    DWORD  dwRead;
    DWORD  dwWritten;
    BOOL   bEof = FALSE;
    TCHAR TrueDest[MAX_PATH];
    TCHAR TempSrc[MAX_PATH];
    TCHAR * FileName;
    SYSTEMTIME CurrentTime;

    /* Check Breaker */
    if (CheckCtrlBreak(BREAK_INPUT))
        return 0;

    TRACE ("checking mode\n");

    if (bTouch)
    {
        hFileSrc = CreateFile (source, GENERIC_WRITE, FILE_SHARE_READ,
            NULL, OPEN_EXISTING, 0, NULL);
        if (hFileSrc == INVALID_HANDLE_VALUE)
        {
            ConOutResPrintf(STRING_COPY_ERROR1, source);
            nErrorLevel = 1;
            return 0;
        }

        GetSystemTime(&CurrentTime);
        SystemTimeToFileTime(&CurrentTime, &NewFileTime);
        if (SetFileTime(hFileSrc,(LPFILETIME) NULL, (LPFILETIME) NULL, &NewFileTime))
        {
            CloseHandle(hFileSrc);
            nErrorLevel = 1;
            return 1;

        }
        else
        {
            CloseHandle(hFileSrc);
            return 0;
        }
    }

    dwAttrib = GetFileAttributes (source);

    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        nErrorLevel = 1;
        return 0;
    }

    TRACE ("getting time\n");

    GetFileTime (hFileSrc, &srctime, NULL, NULL);

    TRACE ("copy: flags has %s\n",
        lpdwFlags & COPY_ASCII ? "ASCII" : "BINARY");

    /* Check to see if /D or /Z are true, if so we need a middle
       man to copy the file too to allow us to use CopyFileEx later */
    if (lpdwFlags & COPY_DECRYPT)
    {
        GetEnvironmentVariable(_T("TEMP"),TempSrc,MAX_PATH);
        _tcscat(TempSrc,_T("\\"));
        FileName = _tcsrchr(source,_T('\\'));
        FileName++;
        _tcscat(TempSrc,FileName);
        /* This is needed to be on the end to prevent an error
           if the user did "copy /D /Z foo bar then it would be copied
           too %TEMP%\foo here and when %TEMP%\foo when it sets it up
           for COPY_RESTART, this would mean it is copying to itself
           which would error when it tried to open the handles for ReadFile
           and WriteFile */
        _tcscat(TempSrc,_T(".decrypt"));
        if (!CopyFileEx(source, TempSrc, NULL, NULL, FALSE, COPY_FILE_ALLOW_DECRYPTED_DESTINATION))
        {
            nErrorLevel = 1;
            return 0;
        }
        _tcscpy(source, TempSrc);
    }


    if (lpdwFlags & COPY_RESTART)
    {
        _tcscpy(TrueDest, dest);
        GetEnvironmentVariable(_T("TEMP"),dest,MAX_PATH);
        _tcscat(dest,_T("\\"));
        FileName = _tcsrchr(TrueDest,_T('\\'));
        FileName++;
        _tcscat(dest,FileName);
    }


    if (!IsExistingFile (dest))
    {
        TRACE ("opening/creating\n");
        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else if (!append)
    {
        TRACE ("SetFileAttributes (%s, FILE_ATTRIBUTE_NORMAL);\n", debugstr_aw(dest));
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        TRACE ("DeleteFile (%s);\n", debugstr_aw(dest));
        DeleteFile (dest);

        hFileDest =	CreateFile (dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
    }
    else
    {
        LONG lFilePosHigh = 0;

        if (!_tcscmp (dest, source))
        {
            CloseHandle (hFileSrc);
            return 0;
        }

        TRACE ("opening/appending\n");
        SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);

        hFileDest =
            CreateFile (dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

        /* Move to end of file to start writing */
        SetFilePointer (hFileDest, 0, &lFilePosHigh,FILE_END);
    }


    if (hFileDest == INVALID_HANDLE_VALUE)
    {
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_PATH_NOT_FOUND);
        nErrorLevel = 1;
        return 0;
    }

    /* A page-aligned buffer usually give more speed */
    buffer = (LPBYTE)VirtualAlloc(NULL, BUFF_SIZE, MEM_COMMIT, PAGE_READWRITE);
    if (buffer == NULL)
    {
        CloseHandle (hFileDest);
        CloseHandle (hFileSrc);
        ConOutResPuts(STRING_ERROR_OUT_OF_MEMORY);
        nErrorLevel = 1;
        return 0;
    }

    do
    {
        ReadFile (hFileSrc, buffer, BUFF_SIZE, &dwRead, NULL);
        if (lpdwFlags & COPY_ASCII)
        {
            LPBYTE pEof = memchr(buffer, 0x1A, dwRead);
            if (pEof != NULL)
            {
                bEof = TRUE;
                dwRead = pEof-buffer+1;
                break;
            }
        }

        if (dwRead == 0)
            break;

        WriteFile (hFileDest, buffer, dwRead, &dwWritten, NULL);
        if (dwWritten != dwRead || CheckCtrlBreak(BREAK_INPUT))
        {
            ConOutResPuts(STRING_COPY_ERROR3);

            VirtualFree (buffer, 0, MEM_RELEASE);
            CloseHandle (hFileDest);
            CloseHandle (hFileSrc);
            nErrorLevel = 1;
            return 0;
        }
    }
    while (!bEof);

    TRACE ("setting time\n");
    SetFileTime (hFileDest, &srctime, NULL, NULL);

    if ((lpdwFlags & COPY_ASCII) && !bEof)
    {
        /* we're dealing with ASCII files! */
        buffer[0] = 0x1A;
        TRACE ("appending ^Z\n");
        WriteFile (hFileDest, buffer, sizeof(CHAR), &dwWritten, NULL);
    }

    VirtualFree (buffer, 0, MEM_RELEASE);
    CloseHandle (hFileDest);
    CloseHandle (hFileSrc);

    TRACE ("setting mode\n");
    SetFileAttributes (dest, dwAttrib);

    /* Now finish off the copy if needed with CopyFileEx */
    if (lpdwFlags & COPY_RESTART)
    {
        if (!CopyFileEx(dest, TrueDest, NULL, NULL, FALSE, COPY_FILE_RESTARTABLE))
        {
            nErrorLevel = 1;
            DeleteFile(dest);
            return 0;
        }
        /* Take care of file in the temp folder */
        DeleteFile(dest);

    }

    if (lpdwFlags & COPY_DECRYPT)
        DeleteFile(TempSrc);

    return 1;
}
Exemplo n.º 4
0
DWORD CHooks::RunScript(CString cmd, LPCTSTR currentDir, CString& error, bool bWait, bool bShow)
{
	DWORD exitcode = 0;
	SECURITY_ATTRIBUTES sa = { 0 };
	sa.nLength = sizeof(sa);
	sa.bInheritHandle = TRUE;

	CAutoFile hOut ;
	CAutoFile hRedir;
	CAutoFile hErr;

	// clear the error string
	error.Empty();

	// Create Temp File for redirection
	TCHAR szTempPath[MAX_PATH] = {0};
	TCHAR szOutput[MAX_PATH] = {0};
	TCHAR szErr[MAX_PATH] = {0};
	GetTortoiseGitTempPath(_countof(szTempPath), szTempPath);
	GetTempFileName(szTempPath, L"git", 0, szErr);

	// setup redirection handles
	// output handle must be WRITE mode, share READ
	// redirect handle must be READ mode, share WRITE
	hErr   = CreateFile(szErr, GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr);

	if (!hErr)
	{
		error = CFormatMessageWrapper();
		return (DWORD)-1;
	}

	hRedir = CreateFile(szErr, GENERIC_READ, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);

	if (!hRedir)
	{
		error = CFormatMessageWrapper();
		return (DWORD)-1;
	}

	GetTempFileName(szTempPath, L"git", 0, szOutput);
	hOut   = CreateFile(szOutput, GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr);

	if (!hOut)
	{
		error = CFormatMessageWrapper();
		return (DWORD)-1;
	}

	// setup startup info, set std out/err handles
	// hide window
	STARTUPINFO si = { 0 };
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
	si.hStdOutput = hOut;
	si.hStdError = hErr;
	si.wShowWindow = bShow ? SW_SHOW : SW_HIDE;

	PROCESS_INFORMATION pi = { 0 };
	if (!CreateProcess(nullptr, cmd.GetBuffer(), nullptr, nullptr, TRUE, CREATE_UNICODE_ENVIRONMENT, nullptr, currentDir, &si, &pi))
	{
		const DWORD err = GetLastError();  // preserve the CreateProcess error
		error = CFormatMessageWrapper(err);
		SetLastError(err);
		cmd.ReleaseBuffer();
		return (DWORD)-1;
	}
	cmd.ReleaseBuffer();

	CloseHandle(pi.hThread);

	// wait for process to finish, capture redirection and
	// send it to the parent window/console
	if (bWait)
	{
		DWORD dw;
		char buf[256] = { 0 };
		do
		{
			while (ReadFile(hRedir, &buf, sizeof(buf) - 1, &dw, nullptr))
			{
				if (dw == 0)
					break;
				error += CString(CStringA(buf,dw));
			}
			Sleep(150);
		} while (WaitForSingleObject(pi.hProcess, 0) != WAIT_OBJECT_0);

		// perform any final flushing
		while (ReadFile(hRedir, &buf, sizeof(buf) - 1, &dw, nullptr))
		{
			if (dw == 0)
				break;

			error += CString(CStringA(buf, dw));
		}
		WaitForSingleObject(pi.hProcess, INFINITE);
		GetExitCodeProcess(pi.hProcess, &exitcode);
	}
	CloseHandle(pi.hProcess);
	DeleteFile(szOutput);
	DeleteFile(szErr);

	return exitcode;
}
Exemplo n.º 5
0
/**
 *\fn           HDC AddImageDC(int id, const char *filename)
 *\brief        Ìí¼ÓJPGͼÏñDC
 *\param[in]    int id ͼÏñDCÐòºÅ
 *\param[in]    const char * filename JPGͼƬ·¾¶
 *\return       JPGͼÏñDC¾ä±ú
 */
HDC CXTDC::AddImageDC(int id, const char *filename)
{
    DeleteDC(IMAGEDC, id);

    SECURITY_ATTRIBUTES sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE)	return NULL;

    DWORD dwFileSize = GetFileSize(hFile, NULL);

    HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize);
    if (NULL == hGlobal) return false;

    LPVOID pvData = GlobalLock(hGlobal);// Ëø¶¨ÄÚ´æ
    if (NULL == pvData)
    {
        GlobalFree(hGlobal);
        return NULL;
    }

    DWORD dwReadLen = 0;
    if (!ReadFile(hFile, pvData, dwFileSize, &dwReadLen, NULL))
    {
        GlobalFree(hGlobal);
        CloseHandle(hFile);
        return false;
    }

    if (dwReadLen != dwFileSize)
    {
        GlobalFree(hGlobal);
        CloseHandle(hFile);
        return false;
    }

    GlobalUnlock(hGlobal);
    CloseHandle(hFile);

    CComPtr<IStream> spStream = NULL;
    HRESULT hr = ::CreateStreamOnHGlobal(hGlobal, TRUE, &spStream);// ½¨Á¢IStream
    if (!SUCCEEDED(hr))
    {
        GlobalFree(hGlobal);
        return NULL;
    }

    CComPtr<IPicture> spPicture;
    hr = OleLoadPicture(spStream, dwFileSize, FALSE, IID_IPicture, (LPVOID*)&spPicture);// ½¨Á¢IPicture
    if (!SUCCEEDED(hr))
    {
        GlobalFree(hGlobal);
        return NULL;
    }

    GlobalFree(hGlobal);

    OLE_HANDLE picHandle = NULL;
    spPicture->get_Handle(&picHandle);

    XTDC xtDC;
    xtDC.dc = CreateCompatibleDC(NULL);
    xtDC.image = (HGDIOBJ)picHandle;
    xtDC.oldImage = SelectObject(xtDC.dc, xtDC.image);

    imageDcMap_[id] = xtDC;

    return xtDC.dc;
}
bool Crypter::crypt(const char *infile, const char *outfile){
	// variables

	DWORD dwOldProt, bytes;

	// open it and get the size
	HANDLE hFile = CreateFile(infile, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
	if (!hFile){
		MYPRINTF("Unable to open file\n");
		return false;
	}
	DWORD dwFileSize = GetFileSize(hFile, 0);

	// load in memory
	LPBYTE fileBuffer = (LPBYTE) malloc(dwFileSize);
	ReadFile(hFile, fileBuffer, dwFileSize, &bytes, 0);

	CloseHandle(hFile);

	PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER) fileBuffer;
	// check if it is valid PE, i would say that this is merely a proper check, for a proper one you would need to calculate all the RVA's and see if they are valid
	if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
		MYPRINTF("IMAGE_DOS_SIGNATURE\n");
		return false;
	}

	PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS) (fileBuffer + dosHeader->e_lfanew);
	if(ntHeaders->Signature != IMAGE_NT_SIGNATURE){
		MYPRINTF("IMAGE_NT_SIGNATURE\n");
		return false;
	}


	PIMAGE_SECTION_HEADER sectionHeader = (PIMAGE_SECTION_HEADER) SECHDROFFSET(fileBuffer);
#define TEXT_SECTION ".text"
	while(memcmp(sectionHeader->Name, TEXT_SECTION, strlen(TEXT_SECTION))) // get the ".text" section header
		sectionHeader++;

	DWORD dwVSize                  = sectionHeader->Misc.VirtualSize; // the virtual size of the section, later this will be used as chunksize in our stub, after proper alignment
	DWORD dwSectionSize    = sectionHeader->SizeOfRawData; // speaks for itself
	DWORD dwStubSize; // the stubsize, in bytes
	if (Crypter::evadeSandbox){
		dwStubSize               = (DWORD) _end_evade_sandbox - (DWORD) _xor_block_evade_sandbox; // the stubsize, in bytes
	} else {
		dwStubSize               = (DWORD) _end - (DWORD) _xor_block; // the stubsize, in bytes
	}

	LPBYTE sectionBuffer = (LPBYTE) malloc(dwSectionSize); // allocate memory enough to hold our raw section data
	memcpy(sectionBuffer, fileBuffer + sectionHeader->PointerToRawData, dwSectionSize); // ... copy the data

	_xor_chunk(sectionBuffer, dwSectionSize, 256); // aaand encrypt it! you can use different block sizes here - 8, 16, 32, 64, 128, 256, 512...
	memset(sectionBuffer + sectionHeader->Misc.VirtualSize, 0, (dwSectionSize - sectionHeader->Misc.VirtualSize)); // fill with zeros after the end of actual data
	// copy back the data
	memcpy(fileBuffer + sectionHeader->PointerToRawData, sectionBuffer, dwSectionSize); // ... copy the data
	free(sectionBuffer);

	DWORD oep = ntHeaders->OptionalHeader.AddressOfEntryPoint + ntHeaders->OptionalHeader.ImageBase; // the original entry point, this is a linear address
	DWORD seg = sectionHeader->VirtualAddress + ntHeaders->OptionalHeader.ImageBase; // the section address, you guessed right, this too is a linear one
	DWORD bsz = 256; // you know what this is

	while(dwVSize % bsz) // we need to align it to block size
		dwVSize++;

	if (Crypter::evadeSandbox){
		VirtualProtect(_xor_block_evade_sandbox, dwStubSize, PAGE_EXECUTE_READWRITE, &dwOldProt); // to be able to update the stub...
	} else {
		VirtualProtect(_xor_block, dwStubSize, PAGE_EXECUTE_READWRITE, &dwOldProt); // to be able to update the stub...
	}

	// and update it, blah, blah, blah...
	if (Crypter::evadeSandbox){
		memcpy((void *)((unsigned long) _stub_evade_sandbox + OEP_o), &oep, 4);
		memcpy((void *)((unsigned long) _stub_evade_sandbox + SEG_o), &seg, 4);
		memcpy((void *)((unsigned long) _stub_evade_sandbox + BSZ_o), &bsz, 4);
		memcpy((void *)((unsigned long) _stub_evade_sandbox +  SZ_o), &dwVSize, 4);
	} else {
		memcpy((void *)((unsigned long) _stub + OEP_o), &oep, 4);
		memcpy((void *)((unsigned long) _stub + SEG_o), &seg, 4);
		memcpy((void *)((unsigned long) _stub + BSZ_o), &bsz, 4);
		memcpy((void *)((unsigned long) _stub +  SZ_o), &dwVSize, 4);
	}

	
	Crypter::section = new char [6];
	Random::createRandomName(COUNTOF(Crypter::section), Crypter::section);
	char* resDll;
	DWORD szResDll;
	if (Crypter::evadeSandbox){
		if (!Crypter::insertSectionConfigInPE(fileBuffer, dwFileSize, _xor_block_evade_sandbox, dwStubSize + sizeof(int), (PVOID*)(&resDll), &szResDll )){
			MYPRINTF("problem with injection\n");
			delete Crypter::section;
			return false;
		}	
	} else {
		if (!Crypter::insertSectionConfigInPE(fileBuffer, dwFileSize, _xor_block, dwStubSize + sizeof(int), (PVOID*)(&resDll), &szResDll )){
			MYPRINTF("problem with injection\n");
			delete Crypter::section;
			return false;
		}
	}

	free(fileBuffer);

	fileBuffer = (LPBYTE)resDll;

	dosHeader = (PIMAGE_DOS_HEADER) fileBuffer;
	// check if it is valid PE, i would say that this is merely a proper check, for a proper one you would need to calculate all the RVA's and see if they are valid
	if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
		MYPRINTF("IMAGE_DOS_SIGNATURE\n");
		delete Crypter::section;
		return false;
	}

	ntHeaders = (PIMAGE_NT_HEADERS) (fileBuffer + dosHeader->e_lfanew);
	if(ntHeaders->Signature != IMAGE_NT_SIGNATURE) {
		MYPRINTF("IMAGE_NT_SIGNATURE\n");
		delete Crypter::section;
		return false;
	}
	ntHeaders->OptionalHeader.DllCharacteristics = ntHeaders->OptionalHeader.DllCharacteristics & ~IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;

	sectionHeader = (PIMAGE_SECTION_HEADER) SECHDROFFSET(fileBuffer);
	while(memcmp(sectionHeader->Name, Crypter::section, strlen(Crypter::section))) // get the ".fpbcfg" section header
		sectionHeader++;

	sectionHeader->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE; 
	// R/W/E, executable code, initialized data. although my experience shows that you are just fine with R/W...
	if (Crypter::evadeSandbox){
		ntHeaders->OptionalHeader.AddressOfEntryPoint = sectionHeader->VirtualAddress + ((DWORD)_stub_evade_sandbox - (DWORD)_xor_block_evade_sandbox);
	} else {
		ntHeaders->OptionalHeader.AddressOfEntryPoint = sectionHeader->VirtualAddress + ((DWORD)_stub - (DWORD)_xor_block);
	}
	

	sectionHeader = (PIMAGE_SECTION_HEADER) SECHDROFFSET(fileBuffer);
	while(memcmp(sectionHeader->Name, TEXT_SECTION, strlen(TEXT_SECTION))) // get the ".text" section header
		sectionHeader++;

	sectionHeader->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE; 
	// R/W/E, executable code, initialized data. although my experience shows that you are just fine with R/W...

	bool res = true;
	if (!Crypter::saveFile(outfile, resDll, szResDll)){
		res = false;
		MYPRINTF("Unable to save file\n");
	}

	free(fileBuffer);
	delete Crypter::section;

	return res;
}
Exemplo n.º 7
0
static int
hx_get_child_data(hx_logsys_t *log,
                hx_process_t *child,
                unsigned char *buffer,
                long *buflen)
{
   const char    *rname = "hx_get_child_data ()";

   long rem = *buflen;
   long totRead = 0;

   unsigned char *pbuf = buffer;
   unsigned char *errStr;

   int timeout;
   int retval;

#ifdef _HX_WIN32_

   DWORD read = 0;
   HANDLE out;

#elif defined(_HX_UNIX_)

   int out;

#endif

   hx_log_msg(log, HX_LCALL, rname, "Called");

   /* Retrieve the server timeout from the
      config table */
   timeout = atoi((unsigned char *)hx_get_conf_val(log, IDX_SERVER_TIMEOUT));

#ifdef _HX_WIN32_

   out = child->childHandles[HX_STDOUT];

   while(1)
   {
      retval = ReadFile(out, pbuf, rem, &read, NULL);

      if(!retval || read == 0)
      {
         /* End of file Encountered */
         break;
      }

      pbuf += read;
      rem  -= read;
      totRead += read;

      if(rem <= 0)
         return HX_MOREDATA;
   }

#elif defined (_HX_UNIX_)

   out = child->parentStreams[HX_STDOUT];

   while(1)
   {
      retval = hx_readNonBlock(out, timeout, pbuf, rem);

      if(!retval || retval < 0)
      {
         /* End of file Encountered */
         if(retval < 0)
         {
            switch(retval)
            {
               case HX_ERR_CHILDREAD_TIMED_OUT:
                  errStr = "Child process read timed out";
                  break;
               case HX_ERR_CHILDWRITE_TIMED_OUT:
                  errStr = "Child process write timed out";
                  break;
               case HX_ERR_CHILDREAD:
                  errStr = "Error reading from child pipe";
                  break;
               case HX_ERR_IOCTL:
                  errStr = "Error performing ioctl on pipe";
                  break;
               case HX_ERR_SELECT:
                  errStr = "Error performing select";
                  break;
               default:
                  errStr = "Unkown error reading from pipe";
                  break;
            }

            hx_log_msg(log,
                      HX_LERRO,
                      rname,
                      "%s [%s]",
                      errStr,
                      strerror(errno));
         }
         break;
      }

      pbuf += retval;
      rem  -= retval;
      totRead += retval;

      if(rem <= 0)
         return HX_MOREDATA;
   }

#endif

   *buflen = totRead;

   if(!retval)
      return HX_ENDOFDATA;
   else
      return retval;
}
Exemplo n.º 8
0
static bool CompileShader(wchar_t *shaderFixPath, wchar_t *fileName, const char *shaderModel, UINT64 hash, wstring shaderType, FILETIME* timeStamp,
	_Outptr_ D3D10Base::ID3DBlob** pCode)
{
	*pCode = nullptr;
	wchar_t fullName[MAX_PATH];
	wsprintf(fullName, L"%s\\%s", shaderFixPath, fileName);

	HANDLE f = CreateFile(fullName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (f == INVALID_HANDLE_VALUE)
	{
		LogInfo("    ReloadShader shader not found: %ls\n", fullName);

		return true;
	}


	DWORD srcDataSize = GetFileSize(f, 0);
	char *srcData = new char[srcDataSize];
	DWORD readSize;
	FILETIME curFileTime;

	if (!ReadFile(f, srcData, srcDataSize, &readSize, 0)
		|| !GetFileTime(f, NULL, NULL, &curFileTime)
		|| srcDataSize != readSize)
	{
		LogInfo("    Error reading txt file.\n");

		return true;
	}
	CloseHandle(f);

	// Check file time stamp, and only recompile shaders that have been edited since they were loaded.
	// This dramatically improves the F10 reload speed.
	if (!CompareFileTime(timeStamp, &curFileTime))
	{
		return false;
	}
	*timeStamp = curFileTime;

	LogInfo("   >Replacement shader found. Re-Loading replacement HLSL code from %ls\n", fileName);
	LogInfo("    Reload source code loaded. Size = %d\n", srcDataSize);
	LogInfo("    compiling replacement HLSL code with shader model %s\n", shaderModel);


	D3D10Base::ID3DBlob* pByteCode = nullptr;
	D3D10Base::ID3DBlob* pErrorMsgs = nullptr;
	HRESULT ret = D3D10Base::D3DCompile(srcData, srcDataSize, "wrapper1349", 0, ((D3D10Base::ID3DInclude*)(UINT_PTR)1),
		"main", shaderModel, D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &pByteCode, &pErrorMsgs);

	delete srcData; srcData = 0;

	// bo3b: pretty sure that we do not need to copy the data. That data is what we need to pass to CreateVertexShader
	// Example taken from: http://msdn.microsoft.com/en-us/library/windows/desktop/hh968107(v=vs.85).aspx
	//char *pCode = 0;
	//SIZE_T pCodeSize;
	//if (pCompiledOutput)
	//{
	//	pCodeSize = pCompiledOutput->GetBufferSize();
	//	pCode = new char[pCodeSize];
	//	memcpy(pCode, pCompiledOutput->GetBufferPointer(), pCodeSize);
	//	pCompiledOutput->Release(); pCompiledOutput = 0;
	//}

	LogInfo("    compile result of replacement HLSL shader: %x\n", ret);

	if (gLogFile && pErrorMsgs)
	{
		LPVOID errMsg = pErrorMsgs->GetBufferPointer();
		SIZE_T errSize = pErrorMsgs->GetBufferSize();
		LogInfo("--------------------------------------------- BEGIN ---------------------------------------------\n");
		fwrite(errMsg, 1, errSize - 1, gLogFile);
		LogInfo("---------------------------------------------- END ----------------------------------------------\n");
		pErrorMsgs->Release();
	}

	if (FAILED(ret))
	{
		if (pByteCode)
		{
			pByteCode->Release();
			pByteCode = 0;
		}
		return true;
	}


	// Write replacement .bin if necessary
	if (G->CACHE_SHADERS && pByteCode)
	{
		wchar_t val[MAX_PATH];
		wsprintf(val, L"%ls\\%08lx%08lx-%ls_replace.bin", shaderFixPath, (UINT32)(hash >> 32), (UINT32)(hash), shaderType.c_str());
		FILE *fw;
		_wfopen_s(&fw, val, L"wb");
		if (gLogFile)
		{
			char fileName[MAX_PATH];
			wcstombs(fileName, val, MAX_PATH);
			if (fw)
				LogInfo("    storing compiled shader to %s\n", fileName);
			else
				LogInfo("    error writing compiled shader to %s\n", fileName);
		}
		if (fw)
		{
			fwrite(pByteCode->GetBufferPointer(), 1, pByteCode->GetBufferSize(), fw);
			fclose(fw);
		}
	}
Exemplo n.º 9
0
void AdbManager::internal_scan_timeout(void* arg)
{
	g_adb_manager->mLocalTimer = NULL;
	//scan
	for (int i = 0; i < 1 && g_adb_manager->mShouldScan; i++)
	{
		HANDLE                pipe_read, pipe_write;
		SECURITY_ATTRIBUTES   sa;
		STARTUPINFO           startup;
		PROCESS_INFORMATION   pinfo;
		char                  program_path[MAX_PATH];
		int                   ret;

		ZeroMemory(&sa, sizeof(sa));
		sa.nLength = sizeof(sa);
		sa.lpSecurityDescriptor = NULL;
		sa.bInheritHandle = TRUE;

		/* create pipe, and ensure its read handle isn't inheritable */
		ret = MyCreatePipeEx(&pipe_read, &pipe_write, &sa, 0);
		if (!ret) {
			fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError());
			break;
		}

		SetHandleInformation(pipe_read, HANDLE_FLAG_INHERIT, 0);

		ZeroMemory(&startup, sizeof(startup));
		startup.cb = sizeof(startup);
		startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
		startup.hStdOutput = pipe_write;
		startup.hStdError = pipe_write;// GetStdHandle(STD_ERROR_HANDLE);
		startup.dwFlags = STARTF_USESTDHANDLES;

		ZeroMemory(&pinfo, sizeof(pinfo));

		/* get path of current program */
		GetModuleFileName(NULL, program_path, sizeof(program_path));
		char * ch = strrchr(program_path, '\\');
		//if (ch){ ch++; strcpy(ch, "adb.exe devices"); }
		if (ch){ ch++; strcpy(ch, "adb.exe devices"); }

		ret = CreateProcess(
			NULL,                              /* program path  */
			program_path,
			/* the fork-server argument will set the
			debug = 2 in the child           */
			NULL,                   /* process handle is not inheritable */
			NULL,                    /* thread handle is not inheritable */
			TRUE,                          /* yes, inherit some handles */
			DETACHED_PROCESS, /* the new process doesn't have a console */
			NULL,                     /* use parent's environment block */
			NULL,                    /* use parent's starting directory */
			&startup,                 /* startup info, i.e. std handles */
			&pinfo);

		CloseHandle(pipe_write);

		if (!ret) {
			fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError());
			CloseHandle(pipe_read);
			break;
		}

		CloseHandle(pinfo.hThread);


		char  temp[65536];
		int total_count = 0;
		DWORD  count;
		ULONGLONG start_time = GetTickCount64();
		OVERLAPPED overlapped;
		ZeroMemory(&overlapped, sizeof(OVERLAPPED));
		do{
			count = 0;
			ret = ReadFile(pipe_read, temp + total_count, sizeof(temp)-total_count, &count, &overlapped);
			total_count += count;
			//if (GetTickCount64() - start_time > 10 * 1000){ break; }
			if (!ret) {
				int err = GetLastError();
				if (err == ERROR_IO_PENDING)
				{ 
					Sleep(1000);
					GetOverlappedResult(pipe_read, &overlapped, &count, FALSE);
					total_count += count;
					continue; 
				}
				fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", err);
				break;
			}
			else{
				Sleep(100);
			}
		} while (1);
		CloseHandle(pipe_read);
		TerminateProcess(pinfo.hProcess, 0);
		CloseHandle(pinfo.hProcess);
		g_adb_manager->parse_device(temp);
		break;
	}
	g_adb_manager->internal_start_scan();
}
Exemplo n.º 10
0
//=============================================================================
// チャンクのチェック
//=============================================================================
HRESULT Sound::CheckChunk(HANDLE file,DWORD format,DWORD *pChunkSize,DWORD *pChunkDataPosition)
{
	HRESULT hr = S_OK;
	DWORD read;
	DWORD chunkType;
	DWORD chunkDataSize;
	DWORD RIFFDataSize = 0;
	DWORD fileType;
	DWORD bytesRead = 0;
	DWORD offset = 0;

	if (SetFilePointer(file,0,NULL,FILE_BEGIN) == INVALID_SET_FILE_POINTER)
	{// ファイルポインタを先頭に移動
		return HRESULT_FROM_WIN32(GetLastError());
	}

	while (hr == S_OK)
	{
		if (ReadFile(file,&chunkType,sizeof(DWORD),&read,NULL) == 0)
		{// チャンクの読み込み
			hr = HRESULT_FROM_WIN32(GetLastError());
		}

		if (ReadFile(file,&chunkDataSize,sizeof(DWORD),&read,NULL) == 0)
		{// チャンクデータの読み込み
			hr = HRESULT_FROM_WIN32(GetLastError());
		}

		switch (chunkType)
		{
		case 'FFIR':
			RIFFDataSize = chunkDataSize;
			chunkDataSize = 4;
			if (ReadFile(file,&fileType,sizeof(DWORD),&read,NULL) == 0)
			{// ファイルタイプの読み込み
				hr = HRESULT_FROM_WIN32(GetLastError());
			}
			break;

		default:
			if (SetFilePointer(file,chunkDataSize,NULL,FILE_CURRENT) == INVALID_SET_FILE_POINTER)
			{// ファイルポインタをチャンクデータ分移動
				return HRESULT_FROM_WIN32(GetLastError());
			}
		}

		offset += sizeof(DWORD) * 2;
		if (chunkType == format)
		{
			*pChunkSize = chunkDataSize;
			*pChunkDataPosition = offset;

			return S_OK;
		}

		offset += chunkDataSize;
		if (bytesRead >= RIFFDataSize)
		{
			return S_FALSE;
		}
	}

	return S_OK;
}
Exemplo n.º 11
0
BOOL ReadBlock(HANDLE hPortalHandle, unsigned int block, unsigned char data[0x10],
			   BOOL isNEWskylander) {
   RWBlock req, res;
   BOOL running = TRUE;
   BOOL gotData;
   OVERLAPPED ovlr;
   DWORD err;
   unsigned char followup;

   if(block >= 0x40) {
	   return FALSE;
   }

   printf(".");

   for(int retries = 0; retries < 3; retries++)
   {
	   // Send query request
	   memset(req.buf, 0, rw_buf_size);
	   req.buf[1] = 'Q';
	   if(isNEWskylander) {
		   followup = 0x11;
		   if(block == 0) {
			   req.buf[2] = 0x21;
		   } else {
			   req.buf[2] = followup;
		   }
	   } else {
		   followup = 0x10;
		   if(block == 0) {
			   req.buf[2] = 0x20;
		   } else {
			   req.buf[2] = followup;
		   }
	   }

	   req.buf[3] = (unsigned char)block;

	   memset(&(res.buf), 0, rw_buf_size);


	   // Must set the Offset and OffsetHigh members of the OVERLAPPED structure to zero.
	   memset(&ovlr, 0, sizeof(ovlr));

	   ovlr.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // read event

	   int i=0;
	   gotData = FALSE;


	   Write(hPortalHandle, &req);
	   // Don't wait.  Start polling for result immediately

	   for(; i<40; ++i) // try up to 40 reads
	   { 
		   BOOL b = ReadFile(hPortalHandle, res.buf, rw_buf_size, &(res.dwBytesTransferred), &ovlr);
		   if(!b)
		   { 
			   /* failed to get data immediately*/
			   err = GetLastError();
			   if(err == ERROR_IO_PENDING)
			   { 
				   /* wait for data */
				   b = GetOverlappedResult(hPortalHandle, &ovlr, &res.dwBytesTransferred, TRUE);
				   if(!b)
				   { 
					   /* wait failed */
					   break;
				   } 
			   } 
			   else
			   { 
				   /* some other error */
				   break;
			   } 
		   } 
		   if(res.dwBytesTransferred > 0)
		   { 
			   /* has data */
			   if(res.buf[1] == 'Q' && res.buf[3] == (unsigned char)block) {
				   // Got our query back
				   if(res.buf[2] == followup) {
					   /* got the query back with no error */
					   gotData = TRUE;
					   break;
				   }
			   }

			   res.buf[0] = 0; // make sure we are using report 0
		   } 
	   } /* read loop */

	   CloseHandle(ovlr.hEvent);

	   if(gotData) {
		   break;
	   }
	   
   } // retries

   if(gotData) {
	   memcpy(data, res.buf + 4, 0x10);
   }

   return gotData;
}
Exemplo n.º 12
0
//MailSlot of flush DNS cache Monitor
bool __fastcall FlushDNSMailSlotMonitor(
	void)
{
//System security setting
	std::shared_ptr<char> ACL_Buffer(new char[FILE_BUFFER_SIZE]());
	memset(ACL_Buffer.get(), 0, FILE_BUFFER_SIZE);
	SECURITY_ATTRIBUTES SecurityAttributes;
	SECURITY_DESCRIPTOR SecurityDescriptor;
	memset(&SecurityAttributes, 0, sizeof(SECURITY_ATTRIBUTES));
	memset(&SecurityDescriptor, 0, sizeof(SECURITY_DESCRIPTOR));
	PSID SID_Value = nullptr;

	InitializeSecurityDescriptor(&SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
	InitializeAcl((PACL)ACL_Buffer.get(), FILE_BUFFER_SIZE, ACL_REVISION);
	ConvertStringSidToSidW(SID_ADMINISTRATORS_GROUP, &SID_Value);
	AddAccessAllowedAce((PACL)ACL_Buffer.get(), ACL_REVISION, GENERIC_ALL, SID_Value);
	SetSecurityDescriptorDacl(&SecurityDescriptor, true, (PACL)ACL_Buffer.get(), false);
	SecurityAttributes.lpSecurityDescriptor = &SecurityDescriptor;
	SecurityAttributes.bInheritHandle = true;

//Create mailslot.
	HANDLE hSlot = CreateMailslotW(MAILSLOT_NAME, FILE_BUFFER_SIZE - 1U, MAILSLOT_WAIT_FOREVER, &SecurityAttributes);
	if (hSlot == INVALID_HANDLE_VALUE)
	{
		LocalFree(SID_Value);

		PrintError(LOG_LEVEL_2, LOG_ERROR_SYSTEM, L"Create mailslot error", GetLastError(), nullptr, 0);
		return false;
	}

	ACL_Buffer.reset();
	LocalFree(SID_Value);

//Initialization
	std::shared_ptr<wchar_t> lpszBuffer(new wchar_t[FILE_BUFFER_SIZE]());
	wmemset(lpszBuffer.get(), 0, FILE_BUFFER_SIZE);
	DWORD cbMessage = 0;
	BOOL Result = 0;

//MailSlot monitor
	for (;;)
	{
		Sleep(LOOP_INTERVAL_TIME_NO_DELAY);

	//Reset parameters.
		wmemset(lpszBuffer.get(), 0, FILE_BUFFER_SIZE);
		cbMessage = 0;

	//Read message from mailslot.
		Result = ReadFile(hSlot, lpszBuffer.get(), FILE_BUFFER_SIZE, &cbMessage, nullptr);
		if (Result == FALSE)
		{
			PrintError(LOG_LEVEL_3, LOG_ERROR_SYSTEM, L"MailSlot read messages error", GetLastError(), nullptr, 0);

			CloseHandle(hSlot);
			return false;
		}
		else if (memcmp(lpszBuffer.get(), MAILSLOT_MESSAGE_FLUSH_DNS, sizeof(wchar_t) * wcslen(MAILSLOT_MESSAGE_FLUSH_DNS)) == 0)
		{
			FlushAllDNSCache();
		}
		else {
			Sleep(LOOP_INTERVAL_TIME_MONITOR);
		}
	}

//Monitor terminated
	CloseHandle(hSlot);
	PrintError(LOG_LEVEL_2, LOG_ERROR_SYSTEM, L"MailSlot module Monitor terminated", 0, nullptr, 0);
	return false;
}
Exemplo n.º 13
0
BOOL AddIcon(LPSTR szIFileName, LPSTR szEFileName)
{
	HANDLE hFile = CreateFile(szIFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	if(hFile == INVALID_HANDLE_VALUE)
	{
		return FALSE;
	}
	LPICONDIR lpid;
	lpid = (LPICONDIR)malloc(sizeof(ICONDIR));
	if(lpid == NULL)
	{
		return FALSE;
	}
	DWORD dwBytesRead;
	ReadFile(hFile, &lpid->idReserved, sizeof(WORD), &dwBytesRead, NULL);
	ReadFile(hFile, &lpid->idType, sizeof(WORD), &dwBytesRead, NULL);
	ReadFile(hFile, &lpid->idCount, sizeof(WORD), &dwBytesRead, NULL);
	lpid = (LPICONDIR)realloc(lpid, (sizeof(WORD) * 3) + (sizeof(ICONDIRENTRY) * lpid->idCount));
	if(lpid == NULL)
	{
		return FALSE;
	}
	ReadFile(hFile, &lpid->idEntries[0], sizeof(ICONDIRENTRY) * lpid->idCount, &dwBytesRead, NULL);
	LPGRPICONDIR lpgid;
	lpgid = (LPGRPICONDIR)malloc(sizeof(GRPICONDIR));
	if(lpgid == NULL)
	{
		return FALSE;
	}
	lpgid->idReserved = lpid->idReserved;
	lpgid->idType = lpid->idType;
	lpgid->idCount = lpid->idCount;
	lpgid = (LPGRPICONDIR)realloc(lpgid, (sizeof(WORD) * 3) + (sizeof(GRPICONDIRENTRY) * lpgid->idCount));
	if(lpgid == NULL)
	{
		return FALSE;
	}
	for(int i = 0; i < lpgid->idCount; i++)
	{
		lpgid->idEntries[i].bWidth = lpid->idEntries[i].bWidth;
		lpgid->idEntries[i].bHeight = lpid->idEntries[i].bHeight;
		lpgid->idEntries[i].bColorCount = lpid->idEntries[i].bColorCount;
		lpgid->idEntries[i].bReserved = lpid->idEntries[i].bReserved;
		lpgid->idEntries[i].wPlanes = lpid->idEntries[i].wPlanes;
		lpgid->idEntries[i].wBitCount = lpid->idEntries[i].wBitCount;
		lpgid->idEntries[i].dwBytesInRes = lpid->idEntries[i].dwBytesInRes;
		lpgid->idEntries[i].nID = i + 1;
	}
	HANDLE hUpdate;
	hUpdate = BeginUpdateResource(szEFileName, TRUE);
	if(hUpdate == NULL)
	{
		CloseHandle(hFile);
		return FALSE;
	}
	for(i = 0; i < lpid->idCount; i++)
	{
		LPBYTE lpBuffer = (LPBYTE)malloc(lpid->idEntries[i].dwBytesInRes);
		if(lpBuffer == NULL)
		{
			CloseHandle(hFile);
			return FALSE;
		}
		SetFilePointer(hFile, lpid->idEntries[i].dwImageOffset, NULL, FILE_BEGIN);
		ReadFile(hFile, lpBuffer, lpid->idEntries[i].dwBytesInRes, &dwBytesRead, NULL);
		if(UpdateResource(hUpdate, RT_ICON, MAKEINTRESOURCE(lpgid->idEntries[i].nID), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), &lpBuffer[0], lpid->idEntries[i].dwBytesInRes) == FALSE)
		{
			CloseHandle(hFile);
			free(lpBuffer);
			return FALSE;
		}
		free(lpBuffer);
	}
	CloseHandle(hFile);
	if(UpdateResource(hUpdate, RT_GROUP_ICON, MAKEINTRESOURCE(1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), &lpgid[0], (sizeof(WORD) * 3) + (sizeof(GRPICONDIRENTRY) * lpgid->idCount)) == FALSE)
	{
		return FALSE;
	}
	if(EndUpdateResource(hUpdate, FALSE) == FALSE)
	{
		return FALSE;
	}
	return TRUE;
}
Exemplo n.º 14
0
void QueryDpcTimer(HWND m_hWnd,ULONG ID,CMyList *m_list)
{
	DWORD dwReadByte;
	int i=0;
	int ItemNum = m_list->GetItemCount();

	SHFILEINFO shfileinfo;
	DpcTimerImg.Create(16,16, ILC_COLOR32, 2, 80);
	HIMAGELIST hImageList = NULL;

	SetDlgItemTextW(m_hWnd,ID,L"正在扫描DpcTimer,请稍后...");

	if (DpcTimer)
	{
		VirtualFree(DpcTimer,sizeof(MyDpcTimer)*MAX_DPCTIMER_COUNT*2,MEM_RESERVE | MEM_COMMIT);
		DpcTimer = 0;
	}
	DpcTimer = (PMyDpcTimer)VirtualAlloc(0,sizeof(MyDpcTimer)*MAX_DPCTIMER_COUNT*2,MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
	if (DpcTimer)
	{
		memset(DpcTimer,0,sizeof(MyDpcTimer)*MAX_DPCTIMER_COUNT*2);

		ReadFile((HANDLE)LIST_DPC_TIMER,DpcTimer,sizeof(MyDpcTimer)*MAX_DPCTIMER_COUNT*2,&dwReadByte,0);

		for (i=0;i< (int)DpcTimer->ulCount;i++)
		{
			WCHAR lpwzTextOut[100];
			memset(lpwzTextOut,0,sizeof(lpwzTextOut));
			wsprintfW(lpwzTextOut,L"共有 %d 个数据,正在扫描第 %d 个,请稍后...",DpcTimer->ulCount,i);
			SetDlgItemTextW(m_hWnd,ID,lpwzTextOut);

			WCHAR lpwzKTimer[256] = {0};
			WCHAR lpwzKDpc[256] = {0};
			WCHAR lpwzPeriod[256] = {0};
			WCHAR lpwzDpcRoutineAddress[256] = {0};
			WCHAR lpwzFullSysName[256] = {0};

			memset(lpwzKTimer,0,sizeof(lpwzKTimer));
			memset(lpwzKDpc,0,sizeof(lpwzKDpc));
			memset(lpwzPeriod,0,sizeof(lpwzPeriod));
			memset(lpwzDpcRoutineAddress,0,sizeof(lpwzDpcRoutineAddress));
			memset(lpwzFullSysName,0,sizeof(lpwzFullSysName));

			MultiByteToWideChar(
				CP_ACP,
				0, 
				DpcTimer->MyTimer[i].lpszModule,
				-1, 
				lpwzFullSysName, 
				strlen(DpcTimer->MyTimer[i].lpszModule)
				);
//********************************************************************
			WCHAR lpwzDosFullPath[256];
			WCHAR lpwzWinDir[256];
			WCHAR lpwzSysDisk[256];

			memset(lpwzWinDir,0,sizeof(lpwzWinDir));
			memset(lpwzSysDisk,0,sizeof(lpwzSysDisk));
			memset(lpwzDosFullPath,0,sizeof(lpwzDosFullPath));

			GetWindowsDirectoryW(lpwzWinDir,sizeof(lpwzWinDir));
			memcpy(lpwzSysDisk,lpwzWinDir,4);

			if (wcsstr(lpwzFullSysName,L"\\??\\"))
			{
				//开始这种路径的处理
				memset(lpwzDosFullPath,0,sizeof(lpwzDosFullPath));
				wcsncpy(lpwzDosFullPath,lpwzFullSysName+wcslen(L"\\??\\"),wcslen(lpwzFullSysName)-wcslen(L"\\??\\"));
				goto Next;
			}
			if (wcsstr(lpwzFullSysName,L"\\WINDOWS\\system32\\"))
			{
				memset(lpwzDosFullPath,0,sizeof(lpwzDosFullPath));
				wcscat(lpwzDosFullPath,lpwzSysDisk);
				wcscat(lpwzDosFullPath,lpwzFullSysName);
				//MessageBoxW(lpwzDosFullPath,lpwzFullSysName,0);
				goto Next;
			}
			if (wcsstr(lpwzFullSysName,L"\\SystemRoot\\"))
			{
				WCHAR lpwzTemp[256];
				memset(lpwzTemp,0,sizeof(lpwzTemp));
				memset(lpwzDosFullPath,0,sizeof(lpwzDosFullPath));
				wcscat(lpwzTemp,lpwzSysDisk);
				wcscat(lpwzTemp,L"\\WINDOWS\\");
				wcscat(lpwzDosFullPath,lpwzTemp);
				wcsncpy(lpwzDosFullPath+wcslen(lpwzTemp),lpwzFullSysName+wcslen(L"\\SystemRoot\\"),wcslen(lpwzFullSysName) - wcslen(L"\\SystemRoot\\"));
				goto Next;
			}
			if (!wcsstr(lpwzFullSysName,L"\\"))
			{
				memset(lpwzDosFullPath,0,sizeof(lpwzDosFullPath));
				wcscat(lpwzDosFullPath,lpwzSysDisk);
				wcscat(lpwzDosFullPath,L"\\WINDOWS\\system32\\drivers\\");
				wcscat(lpwzDosFullPath,lpwzFullSysName);
				goto Next;
			}
Next:

//********************************************************************
			wsprintfW(lpwzKTimer,L"0x%08X",DpcTimer->MyTimer[i].TimerAddress);
			wsprintfW(lpwzKDpc,L"0x%08X",DpcTimer->MyTimer[i].DpcAddress);
			wsprintfW(lpwzPeriod,L"%d",DpcTimer->MyTimer[i].Period);
			wsprintfW(lpwzDpcRoutineAddress,L"0x%08X",DpcTimer->MyTimer[i].DpcRoutineAddress);

			if (_wcsnicmp(lpwzDosFullPath,L"Unknown",wcslen(lpwzDosFullPath)) == 0)
			{
				m_list->InsertItem(i,lpwzKTimer,RGB(255,20,147));
			}else
			{
				m_list->InsertItem(i,lpwzKTimer,RGB(77,77,77));
			}
			m_list->SetItemText(i,1,lpwzKDpc);
			m_list->SetItemText(i,2,lpwzPeriod);
			m_list->SetItemText(i,3,lpwzDpcRoutineAddress);
			m_list->SetItemText(i,4,lpwzDosFullPath);


			hImageList=(HIMAGELIST)::SHGetFileInfo(lpwzDosFullPath,0,&shfileinfo,sizeof(shfileinfo),SHGFI_ICON);
			DpcTimerImg.Add(shfileinfo.hIcon);
			m_list->SetImageList(&DpcTimerImg);
			m_list->SetItemImageId(i,i);
			DestroyIcon(shfileinfo.hIcon);
		}
	}else{
		WCHAR lpwzTextOut[100];
		memset(lpwzTextOut,0,sizeof(lpwzTextOut));
		wsprintfW(lpwzTextOut,L"申请内存错误, 请重新运行A盾\r\n错误代码:%d\n",GetLastError());
		MessageBox(0,lpwzTextOut,0,0);
	}
	WCHAR lpwzTextOut[100];
	memset(lpwzTextOut,0,sizeof(lpwzTextOut));
	wsprintfW(lpwzTextOut,L"DpcTimer扫描完毕,共有 %d 个数据",i);
	SetDlgItemTextW(m_hWnd,ID,lpwzTextOut);
}
Exemplo n.º 15
0
int __cdecl main(int argc, char *argv[])
{
    HANDLE hFile = NULL;
    DWORD dwByteCount = 0;
    DWORD dwBytesWritten;
    BOOL bRc = FALSE;
    char szBuffer[100];
    DWORD dwBytesRead = 0;
    FILE *pFile = NULL;


    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    // create a test file
    hFile = CreateFile(szTextFile, 
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        Fail("SetEndOfFile: ERROR -> Unable to create file \"%s\".\n", 
            szTextFile);
    }

    bRc = WriteFile(hFile, szStringTest, 20, &dwBytesWritten, NULL);
    if (bRc != TRUE)
    {
        Trace("SetEndOfFile: ERROR -> Uable to write to \"%s\".\n", 
            szTextFile);
        bRc = CloseHandle(hFile);
        if (bRc != TRUE)
        {
            Trace("SetEndOfFile: ERROR -> Unable to close file \"%s\".\n", 
                szTextFile);
        }
        PAL_TerminateEx(FAIL);
        return FAIL;
    }

    bRc = CloseHandle(hFile);
    if (bRc != TRUE)
    {
        Fail("SetEndOfFile: ERROR -> Unable to close file \"%s\".\n", 
            szTextFile);
    }

    // open the test file
    hFile = CreateFile(szTextFile, 
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        Fail("SetEndOfFile: ERROR -> Unable to open file \"%s\".\n", 
            szTextFile);
    }

    // read a bit of the file to move the file pointer
    dwByteCount = 10;
    bRc = ReadFile(hFile, szBuffer, dwByteCount, &dwBytesRead, NULL);
    if (bRc != TRUE)
    {
        Trace("SetEndOfFile: ERROR -> Uable to read from \"%s\".\n", 
            szTextFile);
        bRc = CloseHandle(hFile);
        if (bRc != TRUE)
        {
            Trace("SetEndOfFile: ERROR -> Unable to close file \"%s\".\n", 
                szTextFile);
        }
        PAL_TerminateEx(FAIL);
        return FAIL;
    }

    bRc = SetEndOfFile(hFile);
    if (bRc != TRUE)
    {
        Trace("SetEndOfFile: ERROR -> Uable to set end of file.\n");
        bRc = CloseHandle(hFile);
        if (bRc != TRUE)
        {
            Trace("SetEndOfFile: ERROR -> Unable to close file \"%s\".\n", 
                szTextFile);
        }
        PAL_TerminateEx(FAIL);
        return FAIL;
    }

    bRc = CloseHandle(hFile);
    if (bRc != TRUE)
    {
        Fail("SetEndOfFile: ERROR -> Unable to close file \"%s\".\n", 
            szTextFile);
    }

    // open and read the test file
    pFile = fopen(szTextFile, "r");
    if (pFile == NULL)
    {
        Fail("SetEndOfFile: ERROR -> fopen was unable to open file \"%s\".\n", 
            szTextFile);
    }

    // since we truncated the file at 10 characters, 
    // try reading 20 just to be safe
    memset(szBuffer, 0, 100);
    fgets(szBuffer, 20, pFile);
    fclose(pFile);
    if (strlen(szBuffer) != dwByteCount)
    {
        Fail("SetEndOfFile: ERROR -> file apparently not truncated at "
            "correct position.\n");
    }
    if (strncmp(szBuffer, szStringTest, dwByteCount) != 0)
    {
        Fail("SetEndOfFile: ERROR -> truncated file contents doesn't "
            "compare with what should be there\n");
    }

    PAL_Terminate();
    return PASS;
}
Exemplo n.º 16
0
int VerifyMoneyHubList(const char *path, const char* CHKFileName, char *message)
{
	HANDLE hFile = INVALID_HANDLE_VALUE;
	unsigned char *content;
	int contentLength;
	int ret;

	//assert(path && message);

	std::string strFile = CHKFileName;

	// 读文件
	hFile = CreateFile(strFile.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		// 读取文件长度
		DWORD dwLength = GetFileSize(hFile, NULL);
		unsigned char* lpBuffer = new unsigned char[dwLength + 1];

		if(lpBuffer==NULL)
		{
			strcpy(message,"内存空间满");
			return -3001;
		}

		DWORD dwRead = 0;
		if(!ReadFile(hFile, lpBuffer, dwLength, &dwRead, NULL))
		{
			delete []lpBuffer;
			strcpy(message,"读财金汇软件的完整性信息失败");
			return -3002;
		}
		CloseHandle(hFile);

		content=new unsigned char[dwRead];

		if (content==NULL)
		{
			delete []lpBuffer;
			strcpy(message,"内存空间满");
			return -3001;
		}

		contentLength=unPackCHK(lpBuffer,dwRead,content);

		delete []lpBuffer;

		if (contentLength<0)
		{
			strcpy(message,"检验财金汇软件的完整性信息失败");
			return -3003;
		}

		ret=CheckMoneyHubList(content,contentLength,path,message);

		delete []content;

		return ret;


	} else {
		strcpy(message,"找不到财金汇软件的完整性信息");
		return -3000;
	}

}
Exemplo n.º 17
0
bool RawSound::loadWaveFile(const char *waveFile)
{
#ifdef WIN32
	if (!waveFile) return false;

#ifdef IRWAS_OGRE_CLIENT
	IrcApp *app = getApp();
#endif  // IRWAS_OGRE_CLIENT

	// free memory if previous wave data exists
	freeWaveData();

	HANDLE fh;
	DWORD dwReadSize;
	static LPCSTR lpSound;

	// open file
	fh=CreateFile(
		waveFile,
		GENERIC_READ,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if (fh==INVALID_HANDLE_VALUE)
	{
#ifdef SIGVERSE_OGRE_CLIENT
		Sgv::Log::println("** ERROR ** cannot open wave file : %s [%s:%d]", waveFile, __FILE__, __LINE__);
#else
#ifdef IRWAS_OGRE_CLIENT
		app->printLog("** ERROR ** cannot open wave file : %s [%s:%d]\n", waveFile, __FILE__, __LINE__);
#endif // IRWAS_OGRE_CLIENT
#endif // SIGVERSE_OGRE_CLIENT
		return false;
    }

	// alloc memory for contents of file
	m_datalen = (int)GetFileSize(fh, NULL);
	m_data = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, m_datalen);
	if (!m_data)
	{
#ifdef SIGVERSE_OGRE_CLIENT
		Sgv::Log::println("** ERROR ** cannot alloc %d bytes of memory for wave data [%s:%d]", m_datalen, __FILE__, __LINE__);
#else
#ifdef IRWAS_OGRE_CLIENT
		app->printLog("** ERROR ** cannot alloc %d bytes of memory for wave data [%s:%d]\n", m_datalen, __FILE__, __LINE__);
#endif // IRWAS_OGRE_CLIENT
#endif // SIGVERSE_OGRE_CLIENT
		return false;
	}

	// read file
	if (!ReadFile(fh, (LPVOID)m_data, m_datalen, &dwReadSize, NULL))
	{
#ifdef SIGVERSE_OGRE_CLIENT
		Sgv::Log::println("** ERROR ** cannot read wave file [%s:%d]", __FILE__, __LINE__);
#else
#ifdef IRWAS_OGRE_CLIENT
		app->printLog("** ERROR ** cannot read wave file [%s:%d]\n", __FILE__, __LINE__);
#endif // IRWAS_OGRE_CLIENT
#endif // SIGVERSE_OGRE_CLIENT
		return false;
	}

	if ((int)dwReadSize != m_datalen)
	{
#ifdef SIGVERSE_OGRE_CLIENT
		Sgv::Log::println("** ERROR ** file size and read size is different. (fileSize=%d, readSize=%d) [%s:%d]", m_datalen, dwReadSize, __FILE__, __LINE__);
#else
#ifdef IRWAS_OGRE_CLIENT
		app->printLog("** ERROR ** file size and read size is different. (fileSize=%d, readSize=%d) [%s:%d]\n", m_datalen, dwReadSize, __FILE__, __LINE__);
#endif // IRWAS_OGRE_CLIENT
#endif // SIGVERSE_OGRE_CLIENT
		return false;
	}

	// everything is ok. close file handle
	CloseHandle(fh);

	return true;

#else  // WIN32
	if (!waveFile) return false;

	// free memory if previous wave data exists
	freeWaveData();

	FILE *fp = fopen(waveFile, "r");
	if (!fp) {
		fprintf(stderr, "failed to open file (%s)\n", waveFile);
		return false;
	}

	struct stat st;
	int ret = stat(waveFile, &st);
	if (ret != 0) {
		fprintf(stderr, "failed to get file size\n");
		return false;
	}

	int fileSize = st.st_size;
	printf("size : %d bytes\n", fileSize);

	if (fileSize > 0) {
		char *buf = new char[fileSize];
		if (!buf) {
			fprintf(stderr, "out of memory\n");
			return false;
		}

		int readBytes = fread(buf, sizeof(char), fileSize, fp);
		if (readBytes == fileSize) {
			fprintf(stderr, "successfully loaded (%s)\n", waveFile);

			// store
			m_data = buf;
			m_datalen = fileSize;
		}
	}

	return true;
#endif
}
Exemplo n.º 18
0
int CGitIgnoreItem::FetchIgnoreList(const CString &projectroot, const CString &file, bool isGlobal)
{
	if (this->m_pExcludeList)
	{
		git_free_exclude_list(m_pExcludeList);
		m_pExcludeList=NULL;
	}
	free(m_buffer);
	m_buffer = nullptr;

	this->m_BaseDir.Empty();
	if (!isGlobal)
	{
		CString base = file.Mid(projectroot.GetLength() + 1);
		base.Replace(_T('\\'), _T('/'));

		int start = base.ReverseFind(_T('/'));
		if(start > 0)
		{
			base = base.Left(start);
			this->m_BaseDir = CUnicodeUtils::GetMulti(base, CP_UTF8) + "/";
		}
	}
	{

		if(g_Git.GetFileModifyTime(file, &m_LastModifyTime))
			return -1;

		if(git_create_exclude_list(&this->m_pExcludeList))
			return -1;


		CAutoFile hfile = CreateFile(file,
			GENERIC_READ,
			FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL);


		if (!hfile)
			return -1 ;

		DWORD size=0,filesize=0;

		filesize=GetFileSize(hfile, NULL);

		if(filesize == INVALID_FILE_SIZE)
			return -1;

		m_buffer = new BYTE[filesize + 1];

		if (m_buffer == NULL)
			return -1;

		if (!ReadFile(hfile, m_buffer, filesize, &size, NULL))
			return GetLastError();

		BYTE *p = m_buffer;
		int line = 0;
		for (DWORD i = 0; i < size; ++i)
		{
			if (m_buffer[i] == '\n' || m_buffer[i] == '\r' || i == (size - 1))
			{
				if (m_buffer[i] == '\n' || m_buffer[i] == '\r')
					m_buffer[i] = 0;
				if (i == size - 1)
					m_buffer[size] = 0;

				if(p[0] != '#' && p[0] != 0)
					git_add_exclude((const char*)p,
										this->m_BaseDir,
										m_BaseDir.GetLength(),
										this->m_pExcludeList, ++line);

				p = m_buffer + i + 1;
			}
		}
	}
	return 0;
}
Exemplo n.º 19
0
int CheckMoneyHubList(unsigned char *buffer, int length, const char *path, char *message)
{
	HANDLE hFile = INVALID_HANDLE_VALUE;
	char fileName[1024];
	//	int nameLength;
	unsigned char md[20];
	SHA_CTX	c;
	//	unsigned char *content;
	//	int contentLength;
	int bufferLength;
	unsigned char *ptr;
	int pos;

	//assert(buffer && path && message);

	ptr=buffer;
	bufferLength=ptr[0]|(ptr[1]<<8)|(ptr[2]<<16)|(ptr[3]<<24);

	if (bufferLength+4!=length)
	{
		strcpy(message,"检验信息格式错误");
		return -3010;
	}
	ptr+=4;
	pos=4;
	while (pos<length)
	{
		std::string strFile = path;

		bufferLength=ptr[0]|(ptr[1]<<8);
		if (pos+2+bufferLength>length)
		{
			strcpy(message,"检验信息格式错误");
			return -3011;
		}
		ptr=ptr+2;
		pos=pos+2;

		memcpy(fileName,ptr,bufferLength);
		fileName[bufferLength]=0;
		ptr+=bufferLength;
		pos+=bufferLength;

		strFile =strFile + fileName;

		hFile = CreateFile(strFile.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if (hFile != INVALID_HANDLE_VALUE)
		{
			// 读取文件长度
			DWORD dwLength = GetFileSize(hFile, NULL);
			char* lpBuffer = new char[dwLength + 1];

			if(lpBuffer==NULL)
			{
				strcpy(message,"内存空间满");
				return -3001;
			}

			DWORD dwRead = 0;
			if(!ReadFile(hFile, lpBuffer, dwLength, &dwRead, NULL))
			{
				delete []lpBuffer;
				sprintf(message,"读文件[%s]失败",strFile.c_str());
				return -3002;
			}

			CloseHandle(hFile);

			SHA1_Init(&c);
			SHA1_Update(&c,(const void *)lpBuffer,dwRead);
			SHA1_Final(md, &c);

			delete []lpBuffer;

			if (memcmp(md,ptr,20)!=0)
			{
				sprintf(message,"文件[%s]被篡改",strFile.c_str());
				return -3012;
			}

			ptr+=20;
			pos+=20;
		} else {
			sprintf(message,"找不到文件[%s]",strFile.c_str());
			return -3013;
		}
	}
	if (pos<length)
	{
		strcpy(message,"检验信息格式错误");
		return -3014;
	}

	strcpy(message,"成功");
	return 0;
}
Exemplo n.º 20
0
// This method is assumed to be called with m_SharedMutex locked.
int CGitHeadFileList::GetPackRef(const CString &gitdir)
{
	CString PackRef = g_AdminDirMap.GetAdminDir(gitdir) + _T("packed-refs");

	__int64 mtime;
	if (g_Git.GetFileModifyTime(PackRef, &mtime))
	{
		//packed refs is not existed
		this->m_PackRefFile.Empty();
		this->m_PackRefMap.clear();
		return 0;
	}
	else if(mtime == m_LastModifyTimePackRef)
	{
		return 0;
	}
	else
	{
		this->m_PackRefFile = PackRef;
		this->m_LastModifyTimePackRef = mtime;
	}

	m_PackRefMap.clear();

	CAutoFile hfile = CreateFile(PackRef,
		GENERIC_READ,
		FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
		nullptr,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		nullptr);

	if (!hfile)
		return -1;

	DWORD filesize = GetFileSize(hfile, nullptr);
	if (filesize == 0)
		return -1;

	DWORD size = 0;
	std::unique_ptr<char[]> buff(new char[filesize]);
	ReadFile(hfile, buff.get(), filesize, &size, nullptr);

	if (size != filesize)
		return -1;

	CString hash;
	CString ref;
	for (DWORD i = 0; i < filesize;)
	{
		hash.Empty();
		ref.Empty();
		if (buff[i] == '#' || buff[i] == '^')
		{
			while (buff[i] != '\n')
			{
				++i;
				if (i == filesize)
					break;
			}
			++i;
		}

		if (i >= filesize)
			break;

		while (buff[i] != ' ')
		{
			hash.AppendChar(buff[i]);
			++i;
			if (i == filesize)
				break;
		}

		++i;
		if (i >= filesize)
			break;

		while (buff[i] != '\n')
		{
			ref.AppendChar(buff[i]);
			++i;
			if (i == filesize)
				break;
		}

		if (!ref.IsEmpty())
			m_PackRefMap[ref] = hash;

		while (buff[i] == '\n')
		{
			++i;
			if (i == filesize)
				break;
		}
	}
	return 0;
}
Exemplo n.º 21
0
int CGitHeadFileList::ReadHeadHash(CString gitdir)
{
	CAutoWriteLock lock(m_SharedMutex);
	m_Gitdir = g_AdminDirMap.GetAdminDir(gitdir);

	m_HeadFile = m_Gitdir;
	m_HeadFile += _T("HEAD");

	if( g_Git.GetFileModifyTime(m_HeadFile, &m_LastModifyTimeHead))
		return -1;

	CAutoFile hfile = CreateFile(m_HeadFile,
		GENERIC_READ,
		FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
		nullptr,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		nullptr);

	if (!hfile)
		return -1;

	DWORD size = 0;
	unsigned char buffer[40];
	ReadFile(hfile, buffer, 4, &size, nullptr);
	if (size != 4)
		return -1;
	buffer[4] = 0;
	if (strcmp((const char*)buffer, "ref:") == 0)
	{
		m_HeadRefFile.Empty();
		DWORD filesize = GetFileSize(hfile, nullptr);
		if (filesize < 5)
			return -1;

		unsigned char *p = (unsigned char*)malloc(filesize - 4);
		if (!p)
			return -1;

		ReadFile(hfile, p, filesize - 4, &size, nullptr);
		CGit::StringAppend(&m_HeadRefFile, p, CP_UTF8, filesize - 4);
		free(p);

		CString ref = m_HeadRefFile.Trim();
		int start = 0;
		ref = ref.Tokenize(_T("\n"), start);
		m_HeadRefFile = m_Gitdir + m_HeadRefFile;
		m_HeadRefFile.Replace(_T('/'), _T('\\'));

		__int64 time;
		if (g_Git.GetFileModifyTime(m_HeadRefFile, &time, nullptr))
		{
			m_HeadRefFile.Empty();
			if (GetPackRef(gitdir))
				return -1;
			if (m_PackRefMap.find(ref) == m_PackRefMap.end())
				return -1;

			m_Head = m_PackRefMap[ref];
			return 0;
		}

		CAutoFile href = CreateFile(m_HeadRefFile,
			GENERIC_READ,
			FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
			nullptr,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			nullptr);

		if (!href)
		{
			m_HeadRefFile.Empty();

			if (GetPackRef(gitdir))
				return -1;

			if (m_PackRefMap.find(ref) == m_PackRefMap.end())
				return -1;

			m_Head = m_PackRefMap[ref];
			return 0;
		}

		ReadFile(href, buffer, 40, &size, nullptr);
		if (size != 40)
			return -1;

		m_Head.ConvertFromStrA((char*)buffer);

		m_LastModifyTimeRef = time;
	}
	else
	{
		ReadFile(hfile, buffer + 4, 40 - 4, &size, NULL);
		if (size != 36)
			return -1;

		m_HeadRefFile.Empty();

		m_Head.ConvertFromStrA((char*)buffer);
	}

	return 0;
}
Exemplo n.º 22
0
BOOL CDlgExportHistory::ExportHistory(LPCSTR pszFile, fs::list <fsDLHistoryRecord*> &vpHist, BOOL bAppend)
{
    HANDLE hFile = CreateFile (pszFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
                               FILE_ATTRIBUTE_NORMAL, NULL);

    if (hFile == INVALID_HANDLE_VALUE)
        return FALSE;

    CString str;

    if (bAppend && GetLastError () == ERROR_ALREADY_EXISTS)
    {




        DWORD  dwSize = GetFileSize (hFile, NULL);
        if (dwSize > 10000)
        {
            SetFilePointer (hFile, dwSize - 10000, NULL, FILE_BEGIN);
            dwSize = 10000;
        }

        DWORD dw;
        LPSTR psz = new char [dwSize+1];
        ReadFile (hFile, psz, dwSize, &dw, NULL);
        psz [dwSize] = 0;

        int nLen = lstrlen (psz);

        if (nLen != (int) dwSize)
        {

            CloseHandle (hFile);
            return FALSE;
        }


        LPSTR psz2 = psz + nLen - 7;
        while (psz2 != psz)
        {
            if (_memicmp (psz2, "</body>", 7) == 0)
            {
                *psz2 = 0;
                break;
            }

            *psz2--;
        }

        if (psz2 == psz)
        {

            CloseHandle (hFile);
            return FALSE;
        }



        SetFilePointer (hFile, (psz2 - psz) - nLen, NULL, FILE_END);
        SetEndOfFile (hFile);

        delete [] psz;
    }
    else
    {


        SetEndOfFile (hFile);
        str = "<html>\n";
        str += "<style type=\"text/css\">\n";
        str += "<!--\n";
        str += "H3 { font-size: 19px; font-family: Tahoma; color: #cc0000;}\n";
        str += "TR { font-size: 12px; font-family: Tahoma; color: #000033}\n";
        str += "TD { font-size: 12px; font-family: Tahoma; color: #000033}\n";
        str += "A,A:visited,A:active { text-decoration: none; }\n";
        str += "A:hover { text-decoration: underline; }\n";
        str += "-->\n";
        str += "</style>\n";
        str += "<body>\n";
        str += "<h3>";
        str += LS (L_FDMHIST);
        str += "</h3>\n";

    }

    for (int i = 0; i < vpHist.size (); i++)
    {
        fsDLHistoryRecord* rec = vpHist [i];

        str += "<table width=\"75%\" border=\"1\">\n";
        str += "<tr><td width=\"180\">";
        str += LS (L_URLOFDOWNLOAD);
        str += ":</td>";
        str += "<td><a href=\"";
        str += rec->strURL;
        str += "\"> ";
        str += rec->strURL;
        str += "</a></td></tr>\n";

        if (rec->dateDownloaded.dwHighDateTime) {
            str += "<tr><td>";
            str += LS (L_DLDEDTOFILE);
            str += ":</td><td>";
            str += rec->strSavedTo;
            str += "</td></tr>\n";
            str += "<tr><td>";
            str += LS (L_SIZEOFFILE);
            str += ":</td><td>";
            str += BytesToString (rec->uFileSize);
            str += "</td></tr>\n";
            str += "<tr><td>";
            str += LS (L_DLDWASCOMPLETED);
            str += ":</td><td>";
            str += TimeToStr (rec->dateDownloaded);
            str += "</td></tr>\n";
        }
        else {
            str += "<tr><td>";
            str += LS (L_DLDWASDELETED);
            str += ":</td><td>";
            str += TimeToStr (rec->dateRecordAdded);
            str += "</td></tr>\n";
        }

        if (rec->strComment != "")
        {
            CString str2 = rec->strComment;
            str2.Replace ("\n", "<br>");
            str += "<tr><td>";
            str += LS (L_DESC);
            str += ":</td><td>";
            str += str2;
            str += "</td></tr>\n";
        }

        str += "</table><br>\n";
    }


    str += "</body></html>";

    DWORD dw;
    WriteFile (hFile, str, str.GetLength (), &dw, NULL);

    CloseHandle (hFile);

    return TRUE;
}
Exemplo n.º 23
0
HRESULT PackedResource::Create( const char *strFilename )
#endif
{
#ifdef _XBOX1
    BOOL bHasResourceOffsetsTable = FALSE;

    // Find the media file
    CHAR strResourcePath[512];
    if( FAILED(FindMediaFile(strResourcePath, strFilename, sizeof(strResourcePath))))
        return E_FAIL;
    else
        strFilename = strResourcePath;
#endif

    // Open the file
    HANDLE hFile;
    DWORD dwNumBytesRead;
    hFile = CreateFile( strFilename, GENERIC_READ, FILE_SHARE_READ, NULL,
                               OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL );
    if( hFile == INVALID_HANDLE_VALUE )
    {
        RARCH_ERR( "PackedResource::Create(): File <%s> not found.\n", strFilename );
        return E_FAIL;
    }

    // Read in and verify the XPR magic header
    XPR_HEADER xprh;
    bool retval = ReadFile( hFile, &xprh, sizeof( XPR_HEADER ), &dwNumBytesRead, NULL );

#if defined(_XBOX1)
    if( xprh.dwMagic == XPR0_MAGIC_VALUE )
    {
        bHasResourceOffsetsTable = FALSE;
    }
    else if( xprh.dwMagic == XPR1_MAGIC_VALUE )
    {
        bHasResourceOffsetsTable = TRUE;
    }
    else
#elif defined(_XBOX360)
    if(!retval)
    {
        RARCH_ERR("Error reading XPR header in file %s.\n", strFilename );
        CloseHandle( hFile );
        return E_FAIL;
    }

    if( xprh.dwMagic != XPR2_MAGIC_VALUE )
#endif
    {
        RARCH_ERR( "Invalid Xbox Packed Resource (.xpr) file: Magic = 0x%08lx\n", xprh.dwMagic );
        CloseHandle( hFile );
        return E_FAIL;
    }

    // Compute memory requirements
#if defined(_XBOX1)
    m_dwSysMemDataSize = xprh.dwHeaderSize - sizeof(XPR_HEADER);
    m_dwVidMemDataSize = xprh.dwTotalSize - xprh.dwHeaderSize;
#elif defined(_XBOX360)
    m_dwSysMemDataSize = xprh.dwHeaderSize;
    m_dwVidMemDataSize = xprh.dwDataSize;
#endif

    // Allocate memory
    m_pSysMemData = (BYTE*)malloc(m_dwSysMemDataSize);
    if( m_pSysMemData == NULL )
    {
        RARCH_ERR( "Could not allocate system memory.\n" );
        m_dwSysMemDataSize = 0;
        return E_FAIL;
    }

    m_pVidMemData = ( BYTE* )AllocateContiguousMemory( m_dwVidMemDataSize,
#if defined(_XBOX1)
D3DTEXTURE_ALIGNMENT
#elif defined(_XBOX360)
XALLOC_PHYSICAL_ALIGNMENT_4K
#endif
    );

    if( m_pVidMemData == NULL )
    {
        RARCH_ERR( "Could not allocate physical memory.\n" );
        m_dwSysMemDataSize = 0;
        m_dwVidMemDataSize = 0;
        free(m_pSysMemData);
        m_pSysMemData = NULL;
        return E_FAIL;
    }

    // Read in the data from the file
    if( !ReadFile( hFile, m_pSysMemData, m_dwSysMemDataSize, &dwNumBytesRead, NULL ) ||
        !ReadFile( hFile, m_pVidMemData, m_dwVidMemDataSize, &dwNumBytesRead, NULL ) )
    {
        RARCH_ERR( "Unable to read Xbox Packed Resource (.xpr) file\n" );
        CloseHandle( hFile );
        return E_FAIL;
    }

    // Done with the file
    CloseHandle( hFile );

#ifdef _XBOX1
    if (bHasResourceOffsetsTable)
    {
#endif

    // Extract resource table from the header data
    m_dwNumResourceTags = *( DWORD* )( m_pSysMemData + 0 );
    m_pResourceTags = ( XBRESOURCE* )( m_pSysMemData + 4 );

    // Patch up the resources
    for( DWORD i = 0; i < m_dwNumResourceTags; i++ )
    {
        m_pResourceTags[i].strName = ( CHAR* )( m_pSysMemData + ( DWORD )m_pResourceTags[i].strName );
#ifdef _XBOX360
        // Fixup the texture memory
        if( ( m_pResourceTags[i].dwType & 0xffff0000 ) == ( RESOURCETYPE_TEXTURE & 0xffff0000 ) )
        {
            D3DTexture* pTexture = ( D3DTexture* )&m_pSysMemData[m_pResourceTags[i].dwOffset];

            // Adjust Base address according to where memory was allocated
            XGOffsetBaseTextureAddress( pTexture, m_pVidMemData, m_pVidMemData );
        }
#endif
    }

#ifdef _XBOX1
    }
#endif

#ifdef _XBOX1
    // Use user-supplied number of resources and the resource tags
    if( dwNumResourceTags != 0 || pResourceTags != NULL )
    {
        m_pResourceTags     = pResourceTags;
        m_dwNumResourceTags = dwNumResourceTags;
    }
#endif

    m_bInitialized = TRUE;

    return S_OK;
}
Exemplo n.º 24
0
/*
 * request - send a configuration request to the server, wait for a response
 */
static int
request(
	struct conf_peer *conf
	)
{
	struct sock_timeval tvout;
	struct req_pkt reqpkt;
	size_t	req_len;
	size_t	total_len;	/* req_len plus keyid & digest */
	fd_set	fdset;
	l_fp	ts;
	char *	pch;
	char *	pchEnd;
	l_fp *	pts;
	keyid_t *pkeyid;
	int n;
#ifdef SYS_WINNT
	HANDLE	hReadWriteEvent = NULL;
	BOOL	ret;
	DWORD	NumberOfBytesWritten, NumberOfBytesRead, dwWait;
	OVERLAPPED overlap;
#endif /* SYS_WINNT */

	checkparent();		/* make sure our guy is still running */

	if (sockfd == INVALID_SOCKET)
		openntp();
	
#ifdef SYS_WINNT
	hReadWriteEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
#endif /* SYS_WINNT */

	/*
	 * Try to clear out any previously received traffic so it
	 * doesn't fool us.  Note the socket is nonblocking.
	 */
	tvout.tv_sec =  0;
	tvout.tv_usec = 0;
	FD_ZERO(&fdset);
	FD_SET(sockfd, &fdset);
	while (select(sockfd + 1, &fdset, (fd_set *)0, (fd_set *)0, &tvout) >
	       0) {
		recv(sockfd, (char *)&reqpkt, sizeof(reqpkt), 0);
		FD_ZERO(&fdset);
		FD_SET(sockfd, &fdset);
	}

	/*
	 * Make up a request packet with the configuration info
	 */
	memset(&reqpkt, 0, sizeof(reqpkt));

	reqpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0);
	reqpkt.auth_seq = AUTH_SEQ(1, 0);	/* authenticated, no seq */
	reqpkt.implementation = IMPL_XNTPD;	/* local implementation */
	reqpkt.request = REQ_CONFIG;		/* configure a new peer */
	reqpkt.err_nitems = ERR_NITEMS(0, 1);	/* one item */
	reqpkt.mbz_itemsize = MBZ_ITEMSIZE(sizeof(*conf));
	/* Make sure mbz_itemsize <= sizeof reqpkt.data */
	if (sizeof(*conf) > sizeof(reqpkt.data)) {
		msyslog(LOG_ERR,
			"Bletch: conf_peer is too big for reqpkt.data!");
		resolver_exit(1);
	}
	memcpy(reqpkt.data, conf, sizeof(*conf));

	if (sys_authenticate && req_hashlen > 16) {
		pch = reqpkt.data; 
		/* 32-bit alignment */
		pch += (sizeof(*conf) + 3) & ~3;
		pts = (void *)pch;
		pkeyid = (void *)(pts + 1);
		pchEnd = (void *)pkeyid;
		req_len = pchEnd - (char *)&reqpkt;
		pchEnd = (void *)(pkeyid + 1);
		pchEnd += req_hashlen;
		total_len = pchEnd - (char *)&reqpkt;
		if (total_len > sizeof(reqpkt)) {
			msyslog(LOG_ERR,
				"intres total_len %u limit is %u (%u octet digest)\n",
				total_len, sizeof(reqpkt),
				req_hashlen);
			resolver_exit(1);
		}
	} else {
		pts = &reqpkt.tstamp;
		pkeyid = &reqpkt.keyid;
		req_len = REQ_LEN_NOMAC;
	}

	*pkeyid = htonl(req_keyid);
	get_systime(&ts);
	L_ADDUF(&ts, SKEWTIME);
	HTONL_FP(&ts, pts);
	if (sys_authenticate) {
		n = authencrypt(req_keyid, (void *)&reqpkt, req_len);
		if ((size_t)n != req_hashlen + sizeof(reqpkt.keyid)) {
			msyslog(LOG_ERR,
				"intres maclen %d expected %u\n",
				n, req_hashlen + sizeof(reqpkt.keyid));
			resolver_exit(1);
		}
		req_len += n;
	}

	/*
	 * Done.  Send it.
	 */
#ifndef SYS_WINNT
	n = send(sockfd, (char *)&reqpkt, req_len, 0);
	if (n < 0) {
		msyslog(LOG_ERR, "send to NTP server failed: %m");
		return 0;	/* maybe should exit */
	}
#else
	/* In the NT world, documentation seems to indicate that there
	 * exist _write and _read routines that can be used to do blocking
	 * I/O on sockets. Problem is these routines require a socket
	 * handle obtained through the _open_osf_handle C run-time API
	 * of which there is no explanation in the documentation. We need
	 * nonblocking write's and read's anyway for our purpose here.
	 * We're therefore forced to deviate a little bit from the Unix
	 * model here and use the ReadFile and WriteFile Win32 I/O API's
	 * on the socket
	 */
	overlap.Offset = overlap.OffsetHigh = (DWORD)0;
	overlap.hEvent = hReadWriteEvent;
	ret = WriteFile((HANDLE)sockfd, (char *)&reqpkt, req_len,
			NULL, (LPOVERLAPPED)&overlap);
	if ((ret == FALSE) && (GetLastError() != ERROR_IO_PENDING)) {
		msyslog(LOG_ERR, "send to NTP server failed: %m");
		return 0;
	}
	dwWait = WaitForSingleObject(hReadWriteEvent, (DWORD) TIMEOUT_SEC * 1000);
	if ((dwWait == WAIT_FAILED) || (dwWait == WAIT_TIMEOUT)) {
		if (dwWait == WAIT_FAILED)
		    msyslog(LOG_ERR, "WaitForSingleObject failed: %m");
		return 0;
	}
	if (!GetOverlappedResult((HANDLE)sockfd, (LPOVERLAPPED)&overlap,
				(LPDWORD)&NumberOfBytesWritten, FALSE)) {
		msyslog(LOG_ERR, "GetOverlappedResult for WriteFile fails: %m");
		return 0;
	}
#endif /* SYS_WINNT */


	/*
	 * Wait for a response.  A weakness of the mode 7 protocol used
	 * is that there is no way to associate a response with a
	 * particular request, i.e. the response to this configuration
	 * request is indistinguishable from that to any other.  I should
	 * fix this some day.  In any event, the time out is fairly
	 * pessimistic to make sure that if an answer is coming back
	 * at all, we get it.
	 */
	for (;;) {
		FD_ZERO(&fdset);
		FD_SET(sockfd, &fdset);
		tvout.tv_sec = TIMEOUT_SEC;
		tvout.tv_usec = TIMEOUT_USEC;

		n = select(sockfd + 1, &fdset, (fd_set *)0,
			   (fd_set *)0, &tvout);

		if (n < 0) {
			if (errno != EINTR)
				msyslog(LOG_ERR, "select() fails: %m");
			return 0;
		} else if (n == 0) {
#ifdef DEBUG
			if (debug)
				msyslog(LOG_INFO, "ntp_intres select() returned 0.");
#endif
			return 0;
		}

#ifndef SYS_WINNT
		n = recv(sockfd, (char *)&reqpkt, sizeof(reqpkt), 0);
		if (n <= 0) {
			if (n < 0) {
				msyslog(LOG_ERR, "recv() fails: %m");
				return 0;
			}
			continue;
		}
#else /* Overlapped I/O used on non-blocking sockets on Windows NT */
		ret = ReadFile((HANDLE)sockfd, (char *)&reqpkt, sizeof(reqpkt),
			       NULL, (LPOVERLAPPED)&overlap);
		if ((ret == FALSE) && (GetLastError() != ERROR_IO_PENDING)) {
			msyslog(LOG_ERR, "ReadFile() fails: %m");
			return 0;
		}
		dwWait = WaitForSingleObject(hReadWriteEvent, (DWORD) TIMEOUT_SEC * 1000);
		if ((dwWait == WAIT_FAILED) || (dwWait == WAIT_TIMEOUT)) {
			if (dwWait == WAIT_FAILED) {
				msyslog(LOG_ERR, "WaitForSingleObject for ReadFile fails: %m");
				return 0;
			}
			continue;
		}
		if (!GetOverlappedResult((HANDLE)sockfd, (LPOVERLAPPED)&overlap,
					(LPDWORD)&NumberOfBytesRead, FALSE)) {
			msyslog(LOG_ERR, "GetOverlappedResult fails: %m");
			return 0;
		}
		n = NumberOfBytesRead;
#endif /* SYS_WINNT */

		/*
		 * Got one.  Check through to make sure it is what
		 * we expect.
		 */
		if (n < RESP_HEADER_SIZE) {
			msyslog(LOG_ERR, "received runt response (%d octets)",
				n);
			continue;
		}

		if (!ISRESPONSE(reqpkt.rm_vn_mode)) {
#ifdef DEBUG
			if (debug > 1)
			    msyslog(LOG_INFO, "received non-response packet");
#endif
			continue;
		}

		if (ISMORE(reqpkt.rm_vn_mode)) {
#ifdef DEBUG
			if (debug > 1)
			    msyslog(LOG_INFO, "received fragmented packet");
#endif
			continue;
		}

		if ( ( (INFO_VERSION(reqpkt.rm_vn_mode) < 2)
		       || (INFO_VERSION(reqpkt.rm_vn_mode) > NTP_VERSION))
		     || INFO_MODE(reqpkt.rm_vn_mode) != MODE_PRIVATE) {
#ifdef DEBUG
			if (debug > 1)
			    msyslog(LOG_INFO,
				    "version (%d/%d) or mode (%d/%d) incorrect",
				    INFO_VERSION(reqpkt.rm_vn_mode),
				    NTP_VERSION,
				    INFO_MODE(reqpkt.rm_vn_mode),
				    MODE_PRIVATE);
#endif
			continue;
		}

		if (INFO_SEQ(reqpkt.auth_seq) != 0) {
#ifdef DEBUG
			if (debug > 1)
			    msyslog(LOG_INFO,
				    "nonzero sequence number (%d)",
				    INFO_SEQ(reqpkt.auth_seq));
#endif
			continue;
		}

		if (reqpkt.implementation != IMPL_XNTPD ||
		    reqpkt.request != REQ_CONFIG) {
#ifdef DEBUG
			if (debug > 1)
			    msyslog(LOG_INFO,
				    "implementation (%d) or request (%d) incorrect",
				    reqpkt.implementation, reqpkt.request);
#endif
			continue;
		}

		if (INFO_NITEMS(reqpkt.err_nitems) != 0 ||
		    INFO_MBZ(reqpkt.mbz_itemsize) != 0 ||
		    INFO_ITEMSIZE(reqpkt.mbz_itemsize) != 0) {
#ifdef DEBUG
			if (debug > 1)
			    msyslog(LOG_INFO,
				    "nitems (%d) mbz (%d) or itemsize (%d) nonzero",
				    INFO_NITEMS(reqpkt.err_nitems),
				    INFO_MBZ(reqpkt.mbz_itemsize),
				    INFO_ITEMSIZE(reqpkt.mbz_itemsize));
#endif
			continue;
		}

		n = INFO_ERR(reqpkt.err_nitems);
		switch (n) {
		    case INFO_OKAY:
			/* success */
			return 1;
		
		    case INFO_ERR_NODATA:
			/*
			 * newpeer() refused duplicate association, no
			 * point in retrying so call it success.
			 */
			return 1;
		
		    case INFO_ERR_IMPL:
			msyslog(LOG_ERR,
				"ntp_intres.request: implementation mismatch");
			return 0;
		
		    case INFO_ERR_REQ:
			msyslog(LOG_ERR,
				"ntp_intres.request: request unknown");
			return 0;
		
		    case INFO_ERR_FMT:
			msyslog(LOG_ERR,
				"ntp_intres.request: format error");
			return 0;

		    case INFO_ERR_AUTH:
			msyslog(LOG_ERR,
				"ntp_intres.request: permission denied");
			return 0;

		    default:
			msyslog(LOG_ERR,
				"ntp_intres.request: unknown error code %d", n);
			return 0;
		}
	}
}
Exemplo n.º 25
0
void MAP::LoadMapTile(HANDLE hFile)
{
	//MapTile속성 읽기..
	//	속성이 0이면 못 가는 곳.
	//	1이면 그냥 가는 곳...
	//	그외는 이벤트 ID.
	//
	int x1 = m_sizeMap.cx;
	int z1 = m_sizeMap.cy;
	DWORD dwNum;
	short** pEvent;
	pEvent = new short*[m_sizeMap.cx];
	for(int a=0;a<m_sizeMap.cx;a++)
		pEvent[a] = new short[m_sizeMap.cx];
	// 잠시 막아놓고..
	for(int x=0;x<m_sizeMap.cx;x++)
		ReadFile(hFile, pEvent[x], sizeof(short)*m_sizeMap.cy, &dwNum, NULL);
	
	m_pMap = new CMapInfo*[m_sizeMap.cx];

	for( int i = 0; i < m_sizeMap.cx; i++)
	{
		m_pMap[i] = new CMapInfo[m_sizeMap.cy];
	}

	int count = 0;
	for(int i = 0; i < m_sizeMap.cy; i++)
	{
		for( int j = 0; j < m_sizeMap.cx; j++)
		{
			m_pMap[j][i].m_sEvent	= (short)pEvent[j][i];
			//m_pMap[j][i].m_sEvent	= (short)1;
			if(m_pMap[j][i].m_sEvent >= 1)
			{
				count++;
			}
		//	m_pMap[j][i].m_lUser	= 0;
		//	m_pMap[j][i].m_dwType = 0;
		}
	}
	TRACE("move = %d\n", count);

/*	FILE* stream = fopen("c:\\move1.txt", "w");

	for(int z=m_sizeMap.cy-1; z>=0; z--)
	{
		for(int x=0; x<m_sizeMap.cx; x++)
		{
			int v = m_pMap[x][z].m_sEvent;
			fprintf(stream, "%d",v);
		}
		fprintf(stream, "\n");
	}
	fclose(stream);	*/


	if( pEvent ) {
		for(int i=0; i<m_sizeMap.cx; i++) {
			delete[] pEvent[i];
			pEvent[i] = NULL;
		}
		delete[] pEvent;
		pEvent = NULL;
	}
}
Exemplo n.º 26
0
int CLogCache::SaveCache()
{
	if (!m_bEnabled)
		return 0;

	int ret =0;
	BOOL bIsRebuild=false;

	if (this->m_HashMap.empty()) // is not sufficient, because "working copy changes" are always included
		return 0;

	if( this->m_GitDir.IsEmpty())
		return 0;

	if (this->m_pCacheIndex && m_pCacheIndex->m_Header.m_ItemCount == 0) // check for empty log list (issue #915)
		return 0;

	SLogCacheIndexFile *pIndex =  NULL;
	if(this->m_pCacheIndex)
	{
		pIndex = (SLogCacheIndexFile *)malloc(sizeof(SLogCacheIndexFile)
					+sizeof(SLogCacheIndexItem) * (m_pCacheIndex->m_Header.m_ItemCount) );
		if(pIndex ==NULL)
			return -1;

		memcpy(pIndex,this->m_pCacheIndex,
			sizeof(SLogCacheIndexFile) + sizeof(SLogCacheIndexItem) *( m_pCacheIndex->m_Header.m_ItemCount-1)
			);
	}

	this->CloseDataHandles();
	this->CloseIndexHandles();

	SLogCacheIndexHeader header;
	CString file = this->m_GitDir + INDEX_FILE_NAME;
	do
	{
		m_IndexFile = CreateFile(file,
						GENERIC_READ|GENERIC_WRITE,
						0,
						NULL,
						OPEN_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(m_IndexFile == INVALID_HANDLE_VALUE)
		{
			ret = -1;
			break;
		}

		file = m_GitDir + DATA_FILE_NAME;

		m_DataFile = CreateFile(file,
						GENERIC_READ|GENERIC_WRITE,
						0,
						NULL,
						OPEN_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(m_DataFile == INVALID_HANDLE_VALUE)
		{
			ret = -1;
			break;
		}


		{

			memset(&header,0,sizeof(SLogCacheIndexHeader));
			DWORD num=0;
			if((!ReadFile(m_IndexFile,&header, sizeof(SLogCacheIndexHeader),&num,0)) ||
				!CheckHeader(&header)
				)
			{
				RebuildCacheFile();
				bIsRebuild =true;
			}
		}
		if(!bIsRebuild)
		{
			SLogCacheDataFileHeader header;
			DWORD num=0;
			if((!ReadFile(m_DataFile,&header,sizeof(SLogCacheDataFileHeader),&num,0)||
				!CheckHeader(&header)))
			{
				RebuildCacheFile();
				bIsRebuild=true;
			}
		}

		if(bIsRebuild)
			header.m_ItemCount=0;

		SetFilePointer(m_DataFile,0,0,2);
		SetFilePointer(m_IndexFile,0,0,2);

		for (auto i = m_HashMap.begin(); i != m_HashMap.end(); ++i)
		{
			if(this->GetOffset((*i).second.m_CommitHash,pIndex) ==0 || bIsRebuild)
			{
				if((*i).second.m_IsDiffFiles && !(*i).second.m_CommitHash.IsEmpty())
				{
					LARGE_INTEGER offset;
					offset.LowPart=0;
					offset.HighPart=0;
					LARGE_INTEGER start;
					start.QuadPart = 0;
					SetFilePointerEx(this->m_DataFile,start,&offset,1);
					if (this->SaveOneItem((*i).second, (LONG)offset.QuadPart))
					{
						TRACE(_T("Save one item error"));
						SetFilePointerEx(this->m_DataFile,offset, &offset,0);
						continue;
					}

					SLogCacheIndexItem item;
					item.m_Hash = (*i).second.m_CommitHash;
					item.m_Offset=offset.QuadPart;

					DWORD num;
					WriteFile(m_IndexFile,&item,sizeof(SLogCacheIndexItem),&num,0);
					++header.m_ItemCount;
				}
			}
		}
		FlushFileBuffers(m_IndexFile);

		m_IndexFileMap = CreateFileMapping(m_IndexFile, NULL, PAGE_READWRITE,0,0,NULL);
		if(m_IndexFileMap == INVALID_HANDLE_VALUE)
		{
			ret =-1;
			break;
		}

		m_pCacheIndex = (SLogCacheIndexFile*)MapViewOfFile(m_IndexFileMap,FILE_MAP_WRITE,0,0,0);
		if(m_pCacheIndex == NULL)
		{
			ret = -1;
			break;
		}

		m_pCacheIndex->m_Header.m_ItemCount = header.m_ItemCount;
		Sort();
		FlushViewOfFile(m_pCacheIndex,0);

	}while(0);

	this->CloseDataHandles();
	this->CloseIndexHandles();

	free(pIndex);
	return ret;
}
Exemplo n.º 27
0
// returns 0 iff read not complete, >0 bytes read, <0 on error
int
console_read(console_t console, char *buf, int buflen) {
    int i, err;
    DWORD dw=0;
    int lastError;
    int n = 0;

    do {
	// finish the previous overlapped read
	assertb( console->read_pending );
	if( console->read_result ) {
	    dw = console->read_result;
	}
	else {
	    i = GetOverlappedResult(console->read_handle, &console->read_overlap, 
				    &dw, FALSE);
	    if( !i && GetLastError() == ERROR_IO_INCOMPLETE ) {
		n = 0;
		err = 0;
		break;
	    }
	    assertb_syserr(i);
	    console->read_pending = 0;
	}

	n = 0;
	while(1) {
	    i = MIN((int)dw, buflen - n);
	    memcpy(buf + n, console->read_buf, i);
	    if( i < dw ) {
		i = dw - i;
		console->read_result = 5;
		memcpy(console->read_buf, console->read_buf + i, i);
		SetEvent(console->read_event);
		break;
	    }

	    // start a new overlapped read
	    memset(&console->read_overlap, 0, sizeof(console->read_overlap));
	    ResetEvent(console->read_event);
	    console->read_overlap.hEvent = console->read_event;
	    console->read_result = 0;

	    dw = sizeof(console->read_buf);
	    debug(DEBUG_INFO,
		  ("console_read reading dw=%ld\n", dw));
	    i = ReadFile(console->read_handle, console->read_buf, sizeof(console->read_buf), 
			 &dw, &console->read_overlap);
	    lastError = GetLastError();

	    debug(DEBUG_INFO,
		  ("console_read"
		   " i=%d"
		   " dw=%ld"
		   " GetLastError()=%d"
		   " ERROR_IO_PENDING=%d"
		   " IsSet(read_event)=%d"
		   "\n"
		   , i, (long)dw, lastError, ERROR_IO_PENDING
		   , (int)(WaitForSingleObject(console->read_overlap.hEvent, 0) == WAIT_OBJECT_0)
		   ));
	    if( i ) {
		continue;
	    }
	    else if( lastError == ERROR_IO_PENDING ) {
		console->read_pending = 1;
		console->read_result = 0;
		break;
	    }
	    else {
		assertb_syserr(0);
	    }
	}
	
	err = 0;
    } while(0);

    return err ? err : n;
}
Exemplo n.º 28
0
int main(int argc, char* argv[]){
	// Declare variables-------------------------------------------------------------
	HashTable Index;				// Inverted index
	InitialiseHashTable(&Index);
	char text[MAXLEN];
	int test = 0;
	
	// 1. Check input parameters--------------------------------------------------------
	if (argc != 3 ){ 				// check number of arguments
		fprintf(stderr,"Error: Incorrect number of input argument\n");
		return -1;
	}else if(!IsFile(argv[1])){		// check if file is valid
		fprintf(stderr,"Error: File %s is invalid\n", argv[1]);
		return -1;
	}else if(!IsDir(argv[2])){		// check if directory is valid
		fprintf(stderr,"Error: Directory %s cannot be found\n", argv[2]);
		return -1;
	}
	
	// 2. Reconstruct Inverted Index-----------------------------------------------------
	printf("Please wait while the query engine is loading. It might take a few minutes... \n");
	if(!ReadFile(&Index, argv[1])){
		CleanUpHash(&Index);
		return -1;
	}
	
	
	// 3. Command Line interface and query -----------------------------------------------
	
	for(int j=0; j<9; j++){
		
		// Create text array for automated testing
		
		switch (j){
			case 0:
				printf("\n3.%d Test invalid input syntax\n",j+1);
				printf("QUERY :> AND dog\n");
				strcpy(text,"AND dog\n");
				break;
			case 1:
				printf("\n3.%d Test invalid input syntax\n", j+1);
				printf("QUERY :> cat OR AND dog\n");
				strcpy(text,"cat OR AND dog\n");
				break;
			case 2:
				printf("\n3.%d Test no result\n", j+1);
				printf("QUERY :> thisisrandom\n");
				strcpy(text,"thisisrandom\n");
				break;
			case 3:
				printf("\n3.%d Test single entry\n", j+1);
				printf("QUERY :> incredible\n");
				strcpy(text,"incredible\n");
				break;
			case 4:
				printf("\n3.%d Test uppercase\n", j+1);
				printf("QUERY :> Incredible\n");
				strcpy(text,"Incredible\n");
				break;
			case 5:
				printf("\n3.%d Test AND\n", j+1);
				printf("QUERY :> Dartmouth AND College AND Computer AND Science\n");
				strcpy(text,"Dartmouth AND College AND Computer AND Science\n");
				break;
			case 6:
				printf("\n3.%d Test space as AND\n", j+1);
				printf("QUERY :> Dartmouth College Computer Science\n");
				strcpy(text,"Dartmouth College Computer Science\n");
				break;
			case 7:
				printf("\n3.%d Test OR\n", j+1);
				printf("QUERY :> Dartmouth OR Computer\n");
				strcpy(text,"Dartmouth OR Computer\n");
				break;
			case 8:
				printf("\n3.%d Test combined\n", j+1);
				printf("QUERY :> Dartmouth College AND Hanlon OR Mathematics AND Computer Science AND Philosophy OR incredibles Pixar\n");
				strcpy(text,"Dartmouth College AND Hanlon OR Mathematics AND Computer Science AND Philosophy OR incredibles Pixar\n");
				break;
		
		}
		// a) declare variables
		int unionflag, flag, size_temp, size_intersect, size_final, count;
		char wordarray[MAXLEN][MAXLEN];
		int temparray[MAXSIZE][2], intersect[MAXSIZE][2], final[MAXSIZE][2];
		
		// b) instantiate variables
		size_temp = size_intersect = size_final = unionflag = flag = 0;
		count = StringToWord(wordarray,text);
		
		// c) query
		for(int i=0; i<count; i++){
			if(i==0 && strcmp(wordarray[i],"AND") && strcmp(wordarray[i],"OR")){ 	// if it's the first word and is not invalid
				NormalizeWord(wordarray[i]);
				size_intersect = FindHash(wordarray[i], intersect, Index);
				continue;
			}else if(i==0){ 	// if it is first word and invalid
				flag = 1; break;
			}else if(unionflag){
				if(strcmp(wordarray[i],"AND") && strcmp(wordarray[i],"OR")){
					NormalizeWord(wordarray[i]);
					size_intersect = FindHash(wordarray[i], intersect, Index);
					unionflag = 0;
					continue;
				}else{
					flag = 1; break;
				}
			}
			
			if (!strcmp(wordarray[i],"AND")){	// if it's AND
				if(CheckOperator(wordarray,i,count)){
					NormalizeWord(wordarray[i+1]);
					size_temp = FindHash(wordarray[i+1], temparray, Index);
					size_intersect = FindIntersection(intersect, size_intersect, temparray, size_temp);
					i++;
					continue;
				}else{
					flag = 1; break;
				}
			}else if(!strcmp(wordarray[i],"OR")){ // if it's OR
				if(CheckOperator(wordarray,i,count)){
					size_final = FindUnion(final, size_final, intersect, size_intersect);
					size_intersect = 0;
					unionflag = 1;
					continue;
				}else{
					flag = 1; break;
				}
			}else{
				NormalizeWord(wordarray[i]);
				size_temp = FindHash(wordarray[i], temparray, Index);
				size_intersect = FindIntersection(intersect, size_intersect, temparray, size_temp);
				continue;
			}
		}
Exemplo n.º 29
0
int launch_server(int server_port)
{
#ifdef HAVE_WIN32_PROC
    /* we need to start the server in the background                    */
    /* we create a PIPE that will be used to wait for the server's "OK" */
    /* message since the pipe handles must be inheritable, we use a     */
    /* security attribute                                               */
    HANDLE                pipe_read, pipe_write;
    SECURITY_ATTRIBUTES   sa;
    STARTUPINFO           startup;
    PROCESS_INFORMATION   pinfo;
    char                  program_path[ MAX_PATH ];
    int                   ret;

    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    /* create pipe, and ensure its read handle isn't inheritable */
    ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
    if (!ret) {
        fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
        return -1;
    }

    SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );

    ZeroMemory( &startup, sizeof(startup) );
    startup.cb = sizeof(startup);
    startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
    startup.hStdOutput = pipe_write;
    startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
    startup.dwFlags    = STARTF_USESTDHANDLES;

    ZeroMemory( &pinfo, sizeof(pinfo) );

    /* get path of current program */
    GetModuleFileName( NULL, program_path, sizeof(program_path) );

    ret = CreateProcess(
            program_path,                              /* program path  */
            "adb fork-server server",
                                    /* the fork-server argument will set the
                                       debug = 2 in the child           */
            NULL,                   /* process handle is not inheritable */
            NULL,                    /* thread handle is not inheritable */
            TRUE,                          /* yes, inherit some handles */
            DETACHED_PROCESS, /* the new process doesn't have a console */
            NULL,                     /* use parent's environment block */
            NULL,                    /* use parent's starting directory */
            &startup,                 /* startup info, i.e. std handles */
            &pinfo );

    CloseHandle( pipe_write );

    if (!ret) {
        fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
        CloseHandle( pipe_read );
        return -1;
    }

    CloseHandle( pinfo.hProcess );
    CloseHandle( pinfo.hThread );

    /* wait for the "OK\n" message */
    {
        char  temp[3];
        DWORD  count;

        ret = ReadFile( pipe_read, temp, 3, &count, NULL );
        CloseHandle( pipe_read );
        if ( !ret ) {
            fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
            return -1;
        }
        if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
            fprintf(stderr, "ADB server didn't ACK\n" );
            return -1;
        }
    }
#elif defined(HAVE_FORKEXEC)
    char    path[PATH_MAX];
    int     fd[2];

    // set up a pipe so the child can tell us when it is ready.
    // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
    if (pipe(fd)) {
        fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
        return -1;
    }
    get_my_path(path, PATH_MAX);
    pid_t pid = fork();
    if(pid < 0) return -1;

    if (pid == 0) {
        // child side of the fork

        // redirect stderr to the pipe
        // we use stderr instead of stdout due to stdout's buffering behavior.
        adb_close(fd[0]);
        dup2(fd[1], STDERR_FILENO);
        adb_close(fd[1]);

        // child process
        int result = execl(path, "adb", "fork-server", "server", NULL);
        // this should not return
        fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
    } else  {
        // parent side of the fork

        char  temp[3];

        temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
        // wait for the "OK\n" message
        adb_close(fd[1]);
        int ret = adb_read(fd[0], temp, 3);
        int saved_errno = errno;
        adb_close(fd[0]);
        if (ret < 0) {
            fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
            return -1;
        }
        if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
            fprintf(stderr, "ADB server didn't ACK\n" );
            return -1;
        }

        setsid();
    }
#else
#error "cannot implement background server start on this platform"
#endif
    return 0;
}
Exemplo n.º 30
-1
void PipeServer()
{
   HANDLE hPipeToSrv;
   HANDLE hPipeFromSrv;

   LPTSTR pipeNameToSrv= _T("\\\\.\\pipe\\ToSrvPipe");

   hPipeToSrv = CreateNamedPipe( 
      pipeNameToSrv ,
      PIPE_ACCESS_DUPLEX,
      PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
      PIPE_UNLIMITED_INSTANCES,
      nBuff,
      nBuff,
      50,//Timeout - always send straight away.
      NULL);
   if( hPipeToSrv == INVALID_HANDLE_VALUE)
      return;

   LPTSTR pipeNameFromSrv= __T("\\\\.\\pipe\\FromSrvPipe");

   hPipeFromSrv = CreateNamedPipe( 
      pipeNameFromSrv ,
      PIPE_ACCESS_DUPLEX,
      PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
      PIPE_UNLIMITED_INSTANCES,
      nBuff,
      nBuff,
      50,//Timeout - always send straight away.
      NULL);
   if( hPipeFromSrv == INVALID_HANDLE_VALUE)
      return;

   BOOL bConnected;
   BOOL bSuccess;
   DWORD cbBytesRead;
   DWORD cbBytesWritten;
   CHAR chRequest[ nBuff ];
   CHAR chResponse[ nBuff ];

   int jj=0;

   for(;;)
   {
      printf( "Obtaining pipe\n" );
      bConnected = ConnectNamedPipe(hPipeToSrv, NULL) ? 
         TRUE : (GetLastError()==ERROR_PIPE_CONNECTED );
      printf( "Obtained to-srv %i\n", bConnected );
      bConnected = ConnectNamedPipe(hPipeFromSrv, NULL) ? 
         TRUE : (GetLastError()==ERROR_PIPE_CONNECTED );
      printf( "Obtained from-srv %i\n", bConnected );
      if( bConnected )
      {
         for(;;)
         {
            printf( "About to read\n" );
            bSuccess = ReadFile( hPipeToSrv, chRequest, nBuff, &cbBytesRead, NULL);

            chRequest[ cbBytesRead] = '\0'; 

            if( !bSuccess || cbBytesRead==0 )
               break;

            printf( "Rxd %s\n", chRequest );

            DoSrv( chRequest );
            jj++;
            while( true )
            {
               int nWritten = DoSrvMore( chResponse, nBuff );
               if( nWritten <= 1 )
                  break;
               WriteFile( hPipeFromSrv, chResponse, nWritten-1, &cbBytesWritten, NULL);
            }
            //FlushFileBuffers( hPipeFromSrv );
         }
         FlushFileBuffers( hPipeToSrv );
         DisconnectNamedPipe( hPipeToSrv );
         FlushFileBuffers( hPipeFromSrv );
         DisconnectNamedPipe( hPipeFromSrv );
         break;
      }
      else
      {
         CloseHandle( hPipeToSrv );
         CloseHandle( hPipeFromSrv );
      }
   }
   CloseHandle( hPipeToSrv );
   CloseHandle( hPipeFromSrv );
}