Example #1
0
wchar_t *wcscat(wchar_t *dest, const wchar_t *src)
{
    static wcscat_t real_wcscat = NULL;
    size_t max_bytes;
    uint dest_len, src_len;

    if (!real_memcpy)
	real_memcpy = (memcpy_t) getLibraryFunction("memcpy");
    if (!real_wcscat)
	real_wcscat = (wcscat_t) getLibraryFunction("wcscat");

    if (_libsafe_exclude)
	return real_wcscat(dest, src);

    if ((max_bytes = _libsafe_stackVariableP(dest)) == 0) {
	LOG(5, "wcscat(<heap var> , <src>)\n");
	return real_wcscat(dest, src);
    }

    LOG(4, "wcscat(<stack var> , <src>) stack limit=%d\n", max_bytes);
    dest_len = wcsnlen(dest, max_bytes/sizeof(wchar_t));
    src_len = wcsnlen(src, max_bytes/sizeof(wchar_t));

    if (dest_len + src_len + 1 >= max_bytes/sizeof(wchar_t))
	_libsafe_die("Overflow caused by wcscat()");

    real_memcpy(dest + dest_len, src, src_len + 1);

    return dest;
}
Example #2
0
		std::vector<std::wstring> GetStringArray( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName )
		{
			std::vector<std::wstring> result;
			HKEY hKey = NULL;

			if( RegOpenKeyEx(base, subKeyName, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
			{
				DWORD dataLength = 0;
				if(RegQueryValueEx(hKey, valueName, 0, NULL, NULL, &dataLength) == ERROR_SUCCESS)
				{
					int bufferSize = dataLength + 2*sizeof(wchar_t);
					int buffLength = bufferSize / sizeof(wchar_t);
					wchar_t * buffer = (wchar_t *) malloc(bufferSize);
					ZeroMemory(buffer, bufferSize);

					if(RegQueryValueEx(hKey, valueName, 0, NULL, (LPBYTE) buffer, &dataLength) == ERROR_SUCCESS)
					{
						std::wstring str;
						size_t index = 0;
						size_t len = wcsnlen(&buffer[index], buffLength);

						while(len > 0 && len < buffLength - index)
						{
							str = &buffer[index];
							result.push_back(str);
							index += len + 1;
							len = wcsnlen(&buffer[index], buffLength - index);
						}
					}
					free(buffer);
				}
				RegCloseKey(hKey);
			}
			return result;
		}
Example #3
0
bool PasswordModule::GeneratePassHash(const wchar_t *userName, const wchar_t *passWord, std::string &passWordHash)
{
    if (wcsnlen(userName, 51) > 50 || wcsnlen(passWord, 51) > 50) {
        sLog.Error("PasswordModule", "username or password is simply to long");
        return false;
    }

    std::wstring salt(userName);

    Utils::Strings::trim(salt, true, true);     // comparable to the ".strip" function in python.
    Utils::Strings::toLowerCase(salt);

    int saltLen = (int)salt.size() * 2;
    uint8 * saltChar = (uint8*)&salt[0];

    std::wstring init(passWord);
    init += salt;

    int saltInitLen = (int)init.size() * 2;
    uint8 * saltInitChar = (uint8*)&init[0];

    #ifndef WIN32
        saltChar = wchar_tToUtf16(saltChar, salt.size());
        saltInitChar = wchar_tToUtf16(saltInitChar, init.size());
    #endif

    ShaModule::SHAobject shaObj;

    ShaModule::sha_init(&shaObj);
    ShaModule::sha_update(&shaObj, saltInitChar, saltInitLen);

    int daylySaltLen = SHA_DIGEST_SIZE + saltLen;

    // allocate buffer for the hashing, this way its only allocated once.
    uint8 * uDaylySalt = (uint8 *)malloc(daylySaltLen);   // first part of the data string
    uint8 * uDaylySaltPart = &uDaylySalt[SHA_DIGEST_SIZE];      // second part of the data string

    for (int i = 0; i < 1000; i++)
    {
        ShaModule::sha_digest(&shaObj, uDaylySalt);
        memcpy(uDaylySaltPart, saltChar, saltLen);

        ShaModule::sha_init(&shaObj);
        ShaModule::sha_update(&shaObj, uDaylySalt, daylySaltLen);
    }

    free(uDaylySalt);

    ShaModule::sha_final(mDigest, &shaObj);

    if (passWordHash.size() != 0)
        passWordHash = "";

    passWordHash.append((char*)mDigest, SHA_DIGEST_SIZE);

    return true;
}
Example #4
0
static collate_chain_t *
chainsearch(struct xlocale_collate *table, const wchar_t *key, int *len)
{
	int low = 0;
	int high = table->info->chain_count - 1;;
	int next, compar, l;
	collate_chain_t *p;
	collate_chain_t *tab = table->chain_pri_table;

	if (high < 0)
		return (NULL);

	while (low <= high) {
		next = (low + high) / 2;
		p = tab + next;
		compar = *key - *p->str;
		if (compar == 0) {
			l = wcsnlen(p->str, COLLATE_STR_LEN);
			compar = wcsncmp(key, p->str, l);
			if (compar == 0) {
				*len = l;
				return (p);
			}
		}
		if (compar > 0)
			low = next + 1;
		else
			high = next - 1;
	}
	return (NULL);
}
bool
CameraCalib::InitGlutUI(int argc, WCHAR* argvW[]) {
	srand(unsigned int(time(NULL)));

	const size_t len = wcsnlen(argvW[0], 1024);
	std::unique_ptr<char[]> argvuq(new char[len + 1]);
	char *pStr = (argvuq.get());
	size_t lastChar = 0;
	wcstombs_s(&lastChar, pStr, len, argvW[0], len - 1);
	pStr[lastChar] = '\0';
	char **argv = &pStr;
	argc = 1;

	glutInit(&argc, argv);
	glutInitWindowSize(windowRect[0], windowRect[1]);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); //
	mainWnd = glutCreateWindow("CameraCalib");

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		std::wcout << L"Camera Calib" << glewGetErrorString(err) << std::endl;
		return false;
	}
	
	glutDisplayFunc(clbDisplay);
	glutKeyboardFunc(clbKeys);
	glutReshapeFunc(clbReshape);
	glutMouseFunc(clbMouse);
	glutCloseFunc(clbExitFunc);

	glEnable(GL_DEPTH_TEST);
	return true;
}
Example #6
0
std::wstring utils::path::join(const wchar_t * path, ...)
{
    va_list args;
    wchar_t *s = NULL;

    // Remove trailing slash, if there is one
    std::wstring joined_path = path;
    if (joined_path.compare(joined_path.size() - 1, 1, PATH_SEP) == 0)
        joined_path = joined_path.substr(0, joined_path.size() - 1);

    // Append each path in the varargs list
    va_start(args, path);

    for (s = va_arg(args, wchar_t *); s; s = va_arg(args, wchar_t *))
    {
        size_t path_len = wcsnlen(s, utils::path::MAX_LEN);
        if (path_len > 0)
        {
            if (wcsncmp(s, PATH_SEP, 1) != 0)
                joined_path += PATH_SEP;

            joined_path += s;
        }
    }

    va_end(args);
    
    return joined_path;
}
Example #7
0
static int __cdecl vwscan_fn (
        WINPUTFN inputfn,
        const char16_t *string,
        const char16_t *format,
        va_list arglist
        )
{
        miniFILE str;
        miniFILE *infile = &str;
        int retval;
        size_t count = wcsnlen(string, INT_MAX);

        _VALIDATE_RETURN( (string != NULL), EINVAL, EOF);
        _VALIDATE_RETURN( (format != NULL), EINVAL, EOF);

        infile->_flag = _IOREAD|_IOSTRG|_IOMYBUF;
        infile->_ptr = infile->_base = (char *) string;

        if(count>(INT_MAX/sizeof(char16_t)))
        {
            /* old-style functions allow any large value to mean unbounded */
            infile->_cnt = INT_MAX;
        }
        else
        {
            infile->_cnt = (int)count*sizeof(char16_t);
        }

        retval = (inputfn(infile, format, arglist));

        return(retval);
}
Example #8
0
int AtoW(const char *src, WCHAR *dst, int bufsize, int max_len)
{
	if (bufsize >= 1) {
		if (dst) {
			*dst = 0;
		}
		if (bufsize == 1) {
			return	0;
		}
	}

	int affect_len = bufsize ? bufsize - 1 : 0;
	int len = ::MultiByteToWideChar(CP_ACP, 0, src, max_len, dst, affect_len);

	if (dst && bufsize > 0 && max_len != 0) {
		if (len == 0) {
			if ((len = (int)wcsnlen(dst, affect_len)) == affect_len) {
				dst[len] = 0;
			}
		}
		else if (dst[len-1] == 0) {
			len--;
		}
		else if (dst[len]) {
			dst[len] = 0;
		}
	}

	return	len;
}
int MachineInstaller::PerformMachineInstallSetup()
{
	wchar_t packageName[512];

	if (!findPackageFromEmbeddedZip(packageName, sizeof(packageName))) {
		MessageBox(NULL, L"Corrupt installer", L"Cannot find package name for installer, is it created correctly?", MB_OK);
		return ERROR_INVALID_PARAMETER;
	}

	wchar_t machineInstallFolder[MAX_PATH];
	SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, machineInstallFolder);
	wcscat(machineInstallFolder, L"\\SquirrelMachineInstalls");

	// NB: This is the DACL for Program Files
	PSECURITY_DESCRIPTOR descriptor;
	ConvertStringSecurityDescriptorToSecurityDescriptor(
		L"D:PAI(A;;FA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;CIIO;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464)(A;;0x1301bf;;;SY)(A;OICIIO;GA;;;SY)(A;;0x1301bf;;;BA)(A;OICIIO;GA;;;BA)(A;;0x1200a9;;;BU)(A;OICIIO;GXGR;;;BU)(A;OICIIO;GA;;;CO)(A;;0x1200a9;;;AC)(A;OICIIO;GXGR;;;AC)",
		SDDL_REVISION_1,
		&descriptor, NULL);

	SECURITY_ATTRIBUTES attrs;
	attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
	attrs.bInheritHandle = false;
	attrs.lpSecurityDescriptor = descriptor;

	if (!CreateDirectory(machineInstallFolder, &attrs) && GetLastError() != ERROR_ALREADY_EXISTS) {
		LocalFree(descriptor);
		return GetLastError();
	}

	LocalFree(descriptor);

	wcscat(machineInstallFolder, L"\\");
	wcscat(machineInstallFolder, packageName);
	wcscat(machineInstallFolder, L".exe");

	wchar_t ourFile[MAX_PATH];
	HMODULE hMod = GetModuleHandle(NULL);
	GetModuleFileName(hMod, ourFile, _countof(ourFile));

	if (!CopyFile(ourFile, machineInstallFolder, false)) {
		return GetLastError();
	}

	HKEY runKey;
	DWORD dontcare;
	if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, &dontcare) != ERROR_SUCCESS) {
		return GetLastError();
	}

	wcscat_s(machineInstallFolder, L" --checkInstall");

	if (RegSetValueEx(runKey, packageName, 0, REG_SZ, (BYTE*)machineInstallFolder, (wcsnlen(machineInstallFolder, sizeof(machineInstallFolder)) + 1) * sizeof(wchar_t)) != ERROR_SUCCESS) {
		return GetLastError();
	}

	RegCloseKey(runKey);
	return 0;
}
Example #10
0
WCHAR *wcsdupNew(const WCHAR *_s, int max_len)
{
	int		len = int((max_len == -1) ? wcslen(_s) : wcsnlen(_s, max_len));
	WCHAR	*s = new WCHAR [len + 1];
	memcpy(s, _s, len * sizeof(WCHAR));
	s[len] = 0;
	return	s;
}
Example #11
0
int CompareFilesByName(_In_ PVOID pLeftFile, _In_ PVOID pRightFile)
{
    PFILEINFO pLeft = (PFILEINFO)pLeftFile;
    PFILEINFO pRight = (PFILEINFO)pRightFile;

    size_t count = wcsnlen(pLeft->szFilename, ARRAYSIZE(pLeft->szFilename));
    return _wcsnicmp(pLeft->szFilename, pRight->szFilename, count);
}
Example #12
0
//============================================================================
void ReadStringFromMsg(const wchar_t* curMsgPtr, wchar_t* destPtr, unsigned* length) {
    if (!(*length)) {
        size_t maxlen = wcsnlen(curMsgPtr, MAX_PATH - 1);   // Hacky sack
        (*length) = maxlen;
        destPtr[maxlen] = 0;    // Don't do this on fixed length, because there's no room for it
    }
    memcpy(destPtr, curMsgPtr, *length * sizeof(wchar_t));
}
void RefreshModelTree()
{	
	TVITEM item;	
	HWND hwndTree = GetControl(IDC_MODELS);

	TreeView_DeleteAllItems(hwndTree);
	
	// Loop over all of the registered targets (COS IDs) and add them to the view
	for (TargetIterator targetIter = g_targets.begin(); targetIter != g_targets.end(); targetIter++)		
	{
		item.mask = TVIF_TEXT | TVIF_IMAGE;
		item.cChildren = targetIter->cosIDs.size() > 0 ? 1 : 0;
		item.pszText = targetIter->model_filename;
		item.cchTextMax = (int)wcsnlen(item.pszText, sizeof(targetIter->model_filename)/sizeof(targetIter->model_filename[0]));
		item.iImage = 3;	// Invalid image ID to appear white

		TVINSERTSTRUCT	tvinsert;
		tvinsert.hParent = TVI_ROOT;
		tvinsert.item = item;
		tvinsert.hInsertAfter = TVI_LAST;
		HTREEITEM parent = TreeView_InsertItem(hwndTree, &tvinsert);

		for (TrackingIterator iter = targetIter->cosIDs.begin(); iter != targetIter->cosIDs.end(); iter++)
		{
			pxcCHAR buf[260] = {'\0'};

			item.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_PARAM;
			item.cChildren = 0;
			_snwprintf_s(buf, 260, L"ID: %2d    Name: %ws", iter->cosID, iter->friendlyName);		
			item.pszText = buf;
			item.cchTextMax = (int) wcsnlen(item.pszText,sizeof(buf)/sizeof(buf[0]));
			item.iImage = I_IMAGECALLBACK;
			item.lParam = (iter - targetIter->cosIDs.begin() << 8) | (targetIter - g_targets.begin());

			TVINSERTSTRUCT	tvinsert;
			tvinsert.hParent = parent;
			tvinsert.item = item;
			tvinsert.hInsertAfter = TVI_LAST;
			TreeView_InsertItem(hwndTree, &tvinsert);			
		}

		TreeView_Expand(hwndTree, parent, TVE_EXPAND);
	}
}
Example #14
0
bool File::Open(const wchar *Name, uint Mode) {
    wcsncpy(FileName, Name, wcsnlen(Name, 2048));
    if (part > 0) {
        shared_stream->next_stream_file();
    }

    part++;

    return true;
}
void SafeAppend(wchar_t* buffer, size_t bufferSize, size_t* length, wchar_t* text)
{
    // Append the new text if it fits into the buffer, and adjust the length.
    // Otherwise leave the buffer alone.
    size_t c = wcsnlen(text, UINT32_MAX);
    if (*length + c < bufferSize)
    {
        memcpy(buffer + *length, text, c * sizeof(buffer[0]));
        *length += c;
        buffer[*length] = '\0';
    }
}
Example #16
0
WCHAR *wcsdupNew(const WCHAR *_s, int max_len)
{
	int		len = int((max_len == -1) ? wcslen(_s) : wcsnlen(_s, max_len));
	WCHAR	*s = new WCHAR [len + 1];
	memcpy(s, _s, len * sizeof(WCHAR));
	s[len] = 0;

	if (len > 0) {
		if (IsSurrogateL(s[len-1])) { // surrogate includes IVS
			s[len-1] = 0;
		}
	}

	return	s;
}
Example #17
0
void WONCommon::WStringToString(const wchar_t* src, size_t n, string& dst)
{
	if (!src || !*src || !n)
		dst.erase();
	else
	{
		size_t aCopySize = wcsnlen(src, n);
		
		char* aBuf = new char[aCopySize + 1];
		WideToAscii(aBuf, src, aCopySize);
		aBuf[aCopySize] = 0;
		dst = aBuf;

		delete[] aBuf;
	}
}
Example #18
0
string
WONCommon::WStringToString(const wchar_t* theStr, size_t n)
{
	if (!theStr || !*theStr || !n)
		return string();

	size_t aCopySize = wcsnlen(theStr, n);
	
	char* aBuf = new char[aCopySize + 1];
	WideToAscii(aBuf, theStr, aCopySize);
	aBuf[aCopySize] = 0;
	string  aRet(aBuf);

	delete[] aBuf;
	return aRet;
}
Example #19
0
static void
test_wcsnlen(const wchar_t *s)
{
	wchar_t *s1;
	size_t size, len, bufsize;
	int i;

	size = wcslen(s) + 1;
	for (i = 0; i <= 1; i++) {
	    for (bufsize = 0; bufsize <= size + 10; bufsize++) {
		s1 = makebuf(bufsize * sizeof(wchar_t), i);
		wmemcpy(s1, s, bufsize);
		len = (size > bufsize) ? bufsize : size - 1;
		assert(wcsnlen(s1, bufsize) == len);
	    }
	}
}
Example #20
0
static void loadExeName(std::set<std::wstring, std::less<>>& set, LPCWSTR section, LPCWSTR path) {
	#define BUFFER_SIZE 4096
	wchar_t* buffer = new wchar_t[BUFFER_SIZE];
	size_t load = GetPrivateProfileSectionW(section, buffer, BUFFER_SIZE, path);
	wchar_t* p = buffer;
	while (load > 0) {
		size_t len = wcsnlen(p, load);
		if (len >= load) {
			break;
		}
		set.insert(CharLowerW(p));
		p += len + 1;
		load -= len + 1;
	}
	delete[] buffer;
	#undef BUFFER_SIZE
}
Example #21
0
HRESULT
LocalAllocString(LPWSTR* ppResult, LPCWSTR pString)
{
	SIZE_T cch;
	//SIZE_T maxlen = 1024;

    if (!ppResult || !pString)
        return E_INVALIDARG;

	cch = wcsnlen(pString, 1024) + 1;
    *ppResult = (LPWSTR)LocalAlloc(LPTR, cch * sizeof(WCHAR));

    if (!*ppResult)
        return E_OUTOFMEMORY;

	wcscpy_s(*ppResult, (int)cch, pString);

    return S_OK;
}
Example #22
0
static errno_t __cdecl
_int_wmktemp_s (wchar_t *d, size_t dn)
{
  size_t sz;
  if (!d || !dn)
    {
      _wmktemp (NULL);
      return EINVAL;
    }
  sz = wcsnlen (d, dn);
  if (sz >= dn || sz < 6)
    {
      d[0] = 0;
      _wmktemp (NULL);
      return EINVAL;
    }
  if (_wmktemp (d) != NULL)
    return 0;
  return errno;
}
Example #23
0
std::wstring CUtils::GetGameDirectory(const wchar_t* append)
{
	if (m_gameDirectory[0] == L'\x00')
	{
		GetModuleFileName(GetModuleHandle(NULL), m_gameDirectory, MAX_PATH);

		for (int i = wcsnlen(m_gameDirectory, MAX_PATH); i >= 0; i--)
		{
			if (m_gameDirectory[i] == L'\\')
			{
				m_gameDirectory[i] = L'\x00';
				break;
			}
		}
	}

	std::wstring path(m_gameDirectory);
	path.append(append);

	return path;
}
Example #24
0
static void loadFontSubstitutes(LPCWSTR path) {
	#define BUFFER_SIZE 4096
	wchar_t* buffer = new wchar_t[BUFFER_SIZE];
	size_t load = GetPrivateProfileSectionW(L"FontSubstitutes", buffer, BUFFER_SIZE, path);
	wchar_t* p = buffer;
	while (load > 0) {
		size_t len = wcsnlen(p, load);
		if (len >= load) {
			break;
		}
		wchar_t* p2 = wcschr(p, L'=');
		if (p2) {
			*p2++ = L'\0';
			FontSubstitutesMap[p] = p2;
		}
		p += len + 1;
		load -= len + 1;
	}
	delete[] buffer;
	#undef BUFFER_SIZE
}
Example #25
0
wchar_t *wcpcpy(wchar_t *dest, const wchar_t *src)
{
    static wcpcpy_t real_wcpcpy = NULL;
    size_t max_bytes, max_wchars, len;

    if (!real_wcpcpy)
	real_wcpcpy = (wcpcpy_t) getLibraryFunction("wcpcpy");

    if (_libsafe_exclude)
	return real_wcpcpy(dest, src);

    if ((max_bytes = _libsafe_stackVariableP(dest)) == 0) {
	LOG(5, "strcpy(<heap var> , <src>)\n");
	return real_wcpcpy(dest, src);
    }

    LOG(4, "wcpcpy(<stack var> , <src>) stack limit=%d)\n", max_bytes);
    /*
     * Note: we can't use the standard wcsncpy()!  From the wcsncpy(3) manual
     * pages: "If the length wcslen(src) is smaller than n, the remaining wide
     * characters in the array pointed to by dest are filled with  L'\0'
     * characters."  We do not want null written all over the 'dest', hence,
     * our own implementation.
     */
    max_wchars = max_bytes / sizeof(wchar_t);
    if ((len = wcsnlen(src, max_wchars)) == max_wchars) {
	/*
	 * If wcsnlen() returns max_wchars, it means that no L'\0' character was
	 * found in the first max_wchars wide characters.  So, this
	 * wide-character string won't fit in the stack frame.
	 */
	_libsafe_die("Overflow caused by wcpcpy()");
    }

    /*
     * Note that we can use wcpcpy() directly since there is no memcpy()
     * optimization as in the case of strcpy().
     */
    return real_wcpcpy(dest, src);
}
Example #26
0
static bool initialiseProgramDataFiles(HSP *sp, wchar_t *programDataDir)
{
	size_t dirLen = wcsnlen(programDataDir, MAX_PATH);
	size_t fnLen = dirLen+wcslen(HSP_DEFAULT_VMSTORE)+1;
	wchar_t *vmStoreFile = (wchar_t *)my_calloc(sizeof(wchar_t)*fnLen);
	wcscpy_s(vmStoreFile, fnLen, programDataDir);
	PathAppendW(vmStoreFile, HSP_DEFAULT_VMSTORE);
	sp->vmStoreFile = vmStoreFile;
	HANDLE fileHandle;
	if ((fileHandle = CreateFileW(vmStoreFile, 
								  GENERIC_READ | GENERIC_WRITE, 
								  FILE_SHARE_WRITE, NULL,
								  OPEN_ALWAYS, 
								  FILE_ATTRIBUTE_NORMAL, 
								  NULL)) == INVALID_HANDLE_VALUE) {
		myLog(LOG_ERR, "initialiseProgramDataFiles: cannot open VM store file %S\n", vmStoreFile);
		return false;
	} else {
		int cHandle = _open_osfhandle((long)fileHandle, _O_RDWR | _O_TEXT);
		sp->f_vmStore = _fdopen(cHandle, "r+t");
	}
	fnLen = dirLen+wcslen(HSP_DEFAULT_PORTSTORE)+1;
	wchar_t *portStoreFile = (wchar_t *)my_calloc(sizeof(wchar_t)*fnLen);
	wcscpy_s(portStoreFile, fnLen, programDataDir);
	PathAppendW(portStoreFile, HSP_DEFAULT_PORTSTORE);
	sp->portStoreFile = portStoreFile;
	if ((fileHandle = CreateFileW(portStoreFile, 
								  GENERIC_READ | GENERIC_WRITE,
								  FILE_SHARE_WRITE, NULL,
								  OPEN_ALWAYS, 
								  FILE_ATTRIBUTE_NORMAL, 
								  NULL)) == INVALID_HANDLE_VALUE) {
		myLog(LOG_ERR, "initialiseProgramDataFiles: cannot open VM store file %S\n", portStoreFile);
		return false;
	} else {
		int cHandle = _open_osfhandle((long)fileHandle, _O_RDWR | _O_TEXT);
		sp->f_portStore = _fdopen(cHandle, "r+t");
	}
	return true;
}
Example #27
0
static TACommandVerdict wcsnlen_cmd(TAThread thread, TAInputStream stream)
{
    wchar_t* ws;
    size_t n;
    size_t res;

    // Prepare
    ws = (wchar_t*)readPointer(&stream);
    n = readSize(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = wcsnlen(ws, n);

    END_TARGET_OPERATION(thread);

    // Response
    writeSize(thread, res);
    sendResponse(thread);

    return taDefaultVerdict;
}
CString CClipboardMonitorDlg::PasteClipboardString()
{
	CString result;
	if (IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard())
	{
		HANDLE hClipboard = GetClipboardData(CF_UNICODETEXT);
		if (hClipboard)
		{
			wchar_t* ptr = reinterpret_cast<wchar_t*>(GlobalLock(hClipboard)); 
			if (ptr != NULL) 
			{ 
				const int MAX_LEN = 1024;
				const int MIN_LEN = 10;
				size_t len = wcsnlen(ptr, MAX_LEN);
				if (MIN_LEN < len && len < MAX_LEN)
					result = ptr;

				GlobalUnlock(hClipboard); 
			} 
		}		
		CloseClipboard();
	}
	return result;
}
void
RegistryMonitor::run()
{
	DWORD dwReturn; 
	monitorRunning = true;
	int waitTime = REGISTRY_DEFAULT_WAIT_TIME;
	while(isMonitorRunning())
	{
		ZeroMemory(registryEventsBuffer, REGISTRY_EVENTS_BUFFER_SIZE);
		DeviceIoControl(hDriver,
			IOCTL_GET_REGISTRY_EVENTS, 
			0, 
			0, 
			registryEventsBuffer, 
			REGISTRY_EVENTS_BUFFER_SIZE, 
			&dwReturn, 
			NULL);
		/* Go through all the registry events received. Events are variable sized
		   so the starts of them are calculated by adding the lengths of the various
		   data stored in it */
		if(dwReturn >= sizeof(REGISTRY_EVENT))
		{
			UINT offset = 0;
			do {
				/* e->registryData contains the registry path first and then optionally
				   some data */
				PREGISTRY_EVENT e = (PREGISTRY_EVENT)(registryEventsBuffer + offset);
				BYTE* registryData = NULL;
				wchar_t* szRegistryPath = NULL;
				
				wstring registryEventName = getRegistryEventName(e->eventType);
				/* Get the registry string */
				szRegistryPath = (wchar_t*)malloc(e->registryPathLengthB);
				CopyMemory(szRegistryPath, e->registryData, e->registryPathLengthB);
				wstring registryPath = convertRegistryObjectNameToHiveName(szRegistryPath);
				wstring processPath = ProcessManager::getInstance()->getProcessPath((DWORD)e->processId);
				wchar_t processIdString[11];
				swprintf_s(processIdString, 11, L"%ld", e->processId);
				
				/* If there is data stored retrieve it */
				if(e->dataLengthB > 0)
				{
					registryData = (BYTE*)malloc(e->dataLengthB);
					CopyMemory(registryData, e->registryData+e->registryPathLengthB, e->dataLengthB);				
				}
				
				/* Is the event excluded */
				if(!Monitor::isEventAllowed(registryEventName,processPath,registryPath))
				{
					wchar_t szTempTime[256];
					convertTimefieldsToString(e->time, szTempTime, 256);
					wstring time = szTempTime;
					//Handle all the post-processing to format the data
					wchar_t szTemp[256];
					wstring other;
					size_t tmp_len;
					vector<wstring> extraData;
					//registry event extra.at(0) == PID
					extraData.push_back(processIdString);
					//registry event extra.at(1) == name of registry value
					if(e->valueNameLength > 0){
						extraData.push_back(e->valueName);
					}
					else{
						extraData.push_back(L"");
					}

					//registry event extra.at(2) == registry value type
					//registry event extra.at(3) == registry value data (if any)
					//MS description of data types:
					//http://support.microsoft.com/kb/256986
					switch(e->dataType){
						case REG_NONE:
							extraData.push_back(L"REG_NONE");
							extraData.push_back(L""); //This is so that the logger adds an extra blank value
							break;
						case REG_SZ:
							extraData.push_back(L"REG_SZ");
							if(registryData != NULL){
								extraData.push_back((wchar_t *)registryData);
							}
							else{
								extraData.push_back(L"");
							}
								break;
						case REG_EXPAND_SZ:
							extraData.push_back(L"REG_EXPAND_SZ");
							if(registryData != NULL){
								extraData.push_back((wchar_t *)registryData);
							}
							else{
								extraData.push_back(L"");
							}
							break;
						case REG_BINARY:
							extraData.push_back(L"REG_BINARY");
							if(registryData != NULL){
								for(DWORD n = 0; n < e->dataLengthB; n++){
									swprintf(szTemp, L"%x", registryData[n]);
									other.append(szTemp);
								}
								extraData.push_back(other);
							}
							else{
								extraData.push_back(L"");
							}
							break;
						case REG_DWORD:
							extraData.push_back(L"REG_DWORD");
							if(registryData != NULL){
								swprintf_s(szTemp, 256, L"%lx", ((DWORD *)registryData)[0]);
								extraData.push_back(szTemp);
							}
							else{
								extraData.push_back(L"");
							}
							break;
						//TODO: Untested
						case REG_DWORD_BIG_ENDIAN:
							extraData.push_back(L"REG_DWORD_BIG_ENDIAN");
							if(registryData != NULL){
								swprintf_s(szTemp, 256, L"%x%x%x%x", registryData[0],registryData[1],registryData[2],registryData[3]);
								extraData.push_back(szTemp);
							}
							else{
								extraData.push_back(L"");
							}
							break;
						//From MS: "A Unicode string naming a symbolic link."
						//TODO: Untested
						case REG_LINK:
							extraData.push_back(L"REG_LINK");
							if(registryData != NULL){
								extraData.push_back((wchar_t *)registryData);
							}
							else{
								extraData.push_back(L"");
							}
							break;
						//TODO: regedit won't let me make a string,empty string, string, but that 
						// doesn't mean something else might not be able to do it. Look into it as it would
						// break the while condition into ending early.
						case REG_MULTI_SZ:
							extraData.push_back(L"REG_MULTI_SZ");
							if(registryData != NULL){
								while(((wchar_t *)registryData)[0] != '\0' ){
									other.append((wchar_t *)registryData);
									other.append(L"-|-");
									tmp_len = wcsnlen((wchar_t *)registryData, 512); //This doesn't count the null char in the length
									registryData = (BYTE *)((wchar_t *)registryData + (tmp_len + 1));
								}
								extraData.push_back(other);
							}
							else{
								extraData.push_back(L"");
							}
							break;
						//TODO: Untested, "A series of nested arrays..."
						case REG_RESOURCE_LIST:
							extraData.push_back(L"REG_RESOURCE_LIST");
							if(registryData != NULL){
								extraData.push_back(L"FILL IN");
							}
							else{
								extraData.push_back(L"");
							}
							break;
						//TODO: Untested, "A series of nested arrays..."
						case REG_FULL_RESOURCE_DESCRIPTOR:
							extraData.push_back(L"REG_FULL_RESOURCE_DESCRIPTOR");
							if(registryData != NULL){
								extraData.push_back(L"FILL IN");
							}
							else{
								extraData.push_back(L"");
							}
							break;
						//TODO: Untested, "A series of nested arrays..."
						case REG_RESOURCE_REQUIREMENTS_LIST:
							extraData.push_back(L"REG_RESOURCE_REQUIREMENTS_LIST");
							if(registryData != NULL){
								extraData.push_back(L"FILL IN");
							}
							else{
								extraData.push_back(L"");
							}
							break;
						case REG_QWORD_LITTLE_ENDIAN:
							extraData.push_back(L"REG_QWORD");
							if(registryData != NULL){
								swprintf_s(szTemp, 256, L"%lx%lx", ((DWORD *)registryData)[0],((DWORD *)registryData)[1]);
								extraData.push_back(szTemp);
							}
							else{
								extraData.push_back(L"");
							}
							break;
						default:
							extraData.push_back(L"UNKNOWN TYPE!");
							if(registryData != NULL){
								swprintf_s(szTemp, 256, L"%ld", e->dataType);
								extraData.push_back(szTemp);
							}
							else{
								extraData.push_back(L"");
							}
							break;
					}
					signal_onRegistryEvent(registryEventName, time, processPath, registryPath, extraData);
				}
				if(registryData != NULL)
					free(registryData);
				if(szRegistryPath != NULL)
					free(szRegistryPath);
				offset += sizeof(REGISTRY_EVENT) + e->registryPathLengthB + e->dataLengthB;
			}while(offset < dwReturn);
			
			
		}

		if(dwReturn == (REGISTRY_EVENTS_BUFFER_SIZE))
		{
			waitTime = REGISTRY_BUFFER_FULL_WAIT_TIME;
		} else {
			waitTime = REGISTRY_DEFAULT_WAIT_TIME;
		}

		Sleep(waitTime);
	}
	SetEvent(hMonitorStoppedEvent);
}
Example #30
0
/**
 * Scrobbles a track. Also finds meta data, length and (possibly) album, for
 * the current track.
 */
int Scrobblify::Start(const std::wstring& artist,
                      const std::wstring& track) {
    // Handle currently playing track
    if (current_request_id_ > 0) {
        Stop();
    }

    // Lines are divided into fields terminated by 0x1
    const wchar_t kDelimiterChar = 0x1;
    const wchar_t kDelimiter[] = {kDelimiterChar, _T('\0')};
    const size_t kDelimiterLength = 1;
    const size_t kHashLength = 32;
    const size_t kLongHashLength = 40;

    // Search all the meta-data files available
    for (std::vector<std::wstring>::const_iterator it = metadata_paths_.begin();
            it != metadata_paths_.end();
            ++it) {
        // Go get some meta data
        FILE *metadata_file;

        if (_wfopen_s(&metadata_file, (*it).c_str(), _T("r")) != 0) {
            continue;
        }

        std::wifstream in(metadata_file);
        const size_t kMaxLineLength = 2048;
        wchar_t line[kMaxLineLength];

        // Skip first line (contains "21" for no apparent reason)
        in.getline(line, kMaxLineLength);

        // Skip if file is empty
        if (wcsnlen(line, 1) == 0) {
            in.close();
            continue;
        }

        // Find hash for artist
        wchar_t artist_hash[kHashLength];
        bool artist_hash_found = false;

        for (;
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {
            if (wcsncmp(artist.c_str(),
                        &line[kHashLength + kDelimiterLength],
                        artist.size()) == 0) {
                artist_hash_found = true;
                wcsncpy(artist_hash, line, kHashLength);
                break;
            }
        }

        if (!artist_hash_found) {
            in.close();
            continue; // Try next file
        }

        // Skip rest of artist section
        for (in.getline(line, kMaxLineLength);
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {}

        in.getline(line, kMaxLineLength); // Skip section separator
        std::wifstream::pos_type album_section_position = in.tellg();

        // Skip albums section -- move to next empty line
        for (;
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) { }

        // Parse songs section. Each song is formatted like
        //   hash        32 bytes
        //   track
        //   artists     ; split with 0x2
        //   long hash
        //   length
        //   ...
        int length = 0;
        bool track_found = false;
        wchar_t album_hash[kHashLength];

        for (in.getline(line, kMaxLineLength);
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {
            if (wcsncmp(track.c_str(),
                        &line[kHashLength + kDelimiterLength],
                        track.size()) == 0) {
                // Skip hash, separator, track, separator.
                wchar_t *p = &line[kHashLength + kDelimiterLength + track.size() +
                                   kDelimiterLength];

                // Match any of the artists
                bool artist_match_found = wcsncmp(artist_hash, p, kHashLength) == 0;

                for (p += kHashLength;
                        *p == 0x2;
                        p += kHashLength + kDelimiterLength) {
                    if (!artist_match_found && // Don't compare if artist has been found
                            wcsncmp(artist_hash, &p[1], kHashLength) == 0) {
                        artist_match_found = true;
                    }
                }

                if (!artist_match_found) {
                    continue;
                }

                p += kDelimiterLength + kLongHashLength + kDelimiterLength;

                // Read track length
                length = _wtoi(p);
                track_found = true;

                // Skip length
                p = wcschr(p, kDelimiterChar);
                p += kDelimiterLength;

                // Skip track number
                p = wcschr(p, kDelimiterChar);
                p += kDelimiterLength;

                // Get album hash
                wcsncpy(album_hash, p, kHashLength);
                break;
            }
        }

        if (!track_found || length <= 0) {
            in.close();
            continue;
        }

        // Get album
        in.seekg(album_section_position); // Seek back to the album section
        std::wstring album;

        for (in.getline(line, kMaxLineLength);
                wcsnlen(line, kMaxLineLength) > 0;
                in.getline(line, kMaxLineLength)) {
            if (wcsncmp(album_hash, line, kHashLength) == 0) {
                size_t album_length = wcscspn(&line[kHashLength + kDelimiterLength],
                                              kDelimiter);
                album.assign(line, kHashLength + kDelimiterLength, album_length);
                break;
            }
        }

        in.close();
        return current_request_id_ = scrob_submitter_.Start(
                                         ToUtf8(artist),
                                         ToUtf8(track),
                                         ToUtf8(album),
                                         "",
                                         length,
                                         scrobble_directory_);
    }

    // No meta-data found; fall back on a five minute track length
    // TODO(liesen): does this violate any AudioScrobbler rules?
    return current_request_id_ = scrob_submitter_.Start(
                                     ToUtf8(artist),
                                     ToUtf8(track),
                                     "",
                                     "",
                                     5 * 60, // five minutes -- more than most songs
                                     scrobble_directory_);
}