Example #1
0
bool Gpackage::write_file(const WCHAR *path, const BYTE *filename, const BYTE *uncompr, UINT uncompr_len)
{
    WCHAR wfilename[MAX_FILENAME_LEN * 3 + MAX_PATH];
    size_t path_len = wcsnlen_s(path, MAX_PATH);
    wcscpy_s(wfilename, MAX_PATH-1, path);
    wcscpy_s(wfilename + path_len, 2, L"\\");

    if (!ansi_shift_jis_to_utf16((CHAR*)filename, wfilename+path_len+1, MAX_FILENAME_LEN * 3))
        return false;

    WCHAR *sep = wcsrchr((WCHAR *)wfilename, L'\\');
    HANDLE un_file = INVALID_HANDLE_VALUE;
    if (sep != nullptr) {
        WCHAR temp_char = *sep;
        *sep = L'\0';
        create_directory_r(wfilename);
        *sep = temp_char;
    }
    un_file = CreateFileW(wfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);

    if (un_file == INVALID_HANDLE_VALUE)
        return false;

    DWORD number_of_bytes_written;
    if (!WriteFile(un_file, uncompr, uncompr_len, &number_of_bytes_written, NULL))
        return false;
    return true;
}
Example #2
0
static int
change_ext(wchar_t *dest, const wchar_t *src, const wchar_t *ext)
{
    size_t src_len = wcsnlen_s(src, MAXPATHLEN+1);
    size_t i = src_len;
    if (i >= MAXPATHLEN+1)
        Py_FatalError("buffer overflow in getpathp.c's reduce()");

    while (i > 0 && src[i] != '.' && !is_sep(src[i]))
        --i;

    if (i == 0) {
        dest[0] = '\0';
        return -1;
    }

    if (is_sep(src[i]))
        i = src_len;

    if (wcsncpy_s(dest, MAXPATHLEN+1, src, i) ||
        wcscat_s(dest, MAXPATHLEN+1, ext)) {
        dest[0] = '\0';
        return -1;
    }

    return 0;
}
Example #3
0
bool RestartAsNormal(const char* args)
{
	wchar_t name[255];
	GetModuleFileNameW(NULL, name, 255);

	wchar_t szWorkingDir[255];
	GetModuleFileNameW(NULL, szWorkingDir, 255);

	size_t exePathLen = wcsnlen_s(szWorkingDir, 255);
	for (size_t x=exePathLen; x>0; x--)
	{
		if (szWorkingDir[x] == L'\\')
			break;
		else
			szWorkingDir[x] = L'\0';
	}

	wchar_t wArgs[255];
	wArgs[0] = 0;

	if (args)
	{
		for (size_t x=0; x<strlen(args); x++)
			wArgs[x] = (wchar_t)args[x];

		wArgs[strlen(args)] = 0;
	}

	HRESULT res = CreateProcessWithExplorerIL(name, wArgs, szWorkingDir);
	return SUCCEEDED(res);
}
Example #4
0
static std::vector<std::wstring>
GetDosDeviceNames()
{
  std::vector<std::wstring> v;
  std::vector<wchar_t> buf;
  buf.resize(1024);
  DWORD rv = GetLogicalDriveStringsW(buf.size(), buf.data());
  if (rv == 0 || rv > buf.size()) {
    return v;
  }

  // buf will be a list of null terminated strings, with the last string
  // being 0 length.
  const wchar_t* p = buf.data();
  const wchar_t* end = &buf.back();
  size_t l;
  while (p < end && (l = wcsnlen_s(p, end - p)) > 0) {
    // The string is of the form "C:\". We need to strip off the trailing
    // backslash.
    std::wstring drive = std::wstring(p, p + l);
    if (drive.back() == '\\') {
      drive.erase(drive.end() - 1);
    }
    v.push_back(move(drive));
    p += l + 1;
  }
  return v;
}
int SensorListControl::CustomDrawText(HDC hdc, int rowIndex, int columnIndex, HFONT hFont, RECT& rect)
{
    WCHAR text[MaxTextLength] = {0};
    ListView_GetItemText(m_hWnd, rowIndex, columnIndex, text, _countof(text));

    SelectObject(hdc, hFont);

    return DrawTextW(hdc, text, (int)wcsnlen_s(text, MaxTextLength), &rect, DT_LEFT | DT_SINGLELINE | DT_NOPREFIX);
}
void RemoteDesktop::DesktopBackground::_RestoreWallpaperStyle(){
	HKEY hKey;

	if (::RegOpenKeyExW(HKEY_CURRENT_USER, L"Control Panel\\Desktop", 0, KEY_WRITE, &hKey) == ERROR_SUCCESS)
	{
		DWORD sz = wcsnlen_s(_Wallpaper_Style, ARRAYSIZE(_Wallpaper_Style));
		::RegSetValueExW(hKey, L"WallpaperStyle", 0, REG_SZ, (unsigned char*)_Wallpaper_Style, sz);
		::RegCloseKey(hKey);
	}
}
Example #7
0
/* gotlandmark only called by search_for_prefix, which ensures
   'prefix' is null terminated in bounds.  join() ensures
   'landmark' can not overflow prefix if too long.
*/
static int
gotlandmark(const wchar_t *landmark)
{
    int ok;
    Py_ssize_t n = wcsnlen_s(prefix, MAXPATHLEN);

    join(prefix, landmark);
    ok = ismodule(prefix, FALSE);
    prefix[n] = '\0';
    return ok;
}
Example #8
0
//
// Check if the developer set Flickr key
//
bool FlickrUploader::CheckForValidFlickrValues()
{
    if (wcsnlen_s(flickr_api_key, 32) == 0 || wcsnlen_s(flickr_secret, 16) == 0)
    {
        // Bring up message box to show warning
        ::TaskDialog(
            nullptr,
            nullptr,
            L"Developer Warning",
            L"IMPORTANT: To enable uploading to Flickr in this application, you'll need to provide your own values for these two static variables (flickr_api_key and flickr_secret).",
            L"View FlickerUploader.cpp for more information.",
            TDCBF_OK_BUTTON,
            TD_WARNING_ICON,
            nullptr);

        return false;
    }

    return true;
}
Example #9
0
/* assumes 'dir' null terminated in bounds.  Never writes
   beyond existing terminator.
*/
static void
reduce(wchar_t *dir)
{
    size_t i = wcsnlen_s(dir, MAXPATHLEN+1);
    if (i >= MAXPATHLEN+1)
        Py_FatalError("buffer overflow in getpathp.c's reduce()");

    while (i > 0 && !is_sep(dir[i]))
        --i;
    dir[i] = '\0';
}
Example #10
0
SizeF GDIPluseExt::GetBounds(CString strText,CString strFont,INT nfontsize)
{
	StringFormat strformat;
	GraphicsPath path;

#ifdef _UNICODE


	FontFamily  fontFamily(strFont);
	path.AddString(strText,strText.GetLength(), &fontFamily, 
		FontStyleRegular, 
		(REAL)nfontsize,
		PointF(0,0), 
		&strformat );

#else

	//字符转换
	int font_len = strFont.GetLength();
	WCHAR* pfont_w = new WCHAR[font_len];
	MultiByteToWideChar(CP_ACP,0,strFont.GetBuffer(),-1,pfont_w,font_len);
	strFont.ReleaseBuffer();
	//字符转换
	int text_len = strText.GetLength();
	WCHAR* ptext_w = new WCHAR[text_len];
	MultiByteToWideChar(CP_ACP,0,strText.GetBuffer(),-1,ptext_w,text_len);
	strText.ReleaseBuffer();


	FontFamily  fontFamily(pfont_w);

	Font font(&fontFamily, (REAL)nfontsize, FontStyleRegular, UnitPixel);


	path.AddString(ptext_w,wcsnlen_s(ptext_w,text_len), &fontFamily, 
		font.GetStyle(),
		font.GetSize(),
		PointF(0,0), 
		&strformat );


	DEL_P(ptext_w);
	DEL_P(pfont_w);
#endif

	RectF rcBound;
	// 获取边界范围
	path.GetBounds(&rcBound);
	TRACE("Round_Size:%d\r\n",rcBound.Width);

	// 返回文本的宽高
	return SizeF(rcBound.Width,rcBound.Height);
}
Example #11
0
ULONG
RspInitialize(
	IN PWSTR StoragePath	
	)
{
	ULONG Status;
	ULONG Length;
	SYSTEMTIME Time;
	WCHAR Buffer[MAX_PATH];

	Status = S_OK;
	RtlZeroMemory(&RspStorage, sizeof(RSP_STORAGE));
	RtlZeroMemory(&RspIndex, sizeof(RSP_INDEX));
	RtlZeroMemory(&RspView, sizeof(RSP_VIEW));

	InitializeListHead(&RspRecordList);
	InitializeListHead(&RspCallbackList);
	InitializeListHead(&RspProbeGroupList);
	InitializeListHead(&RspAddOnGroupList);

	RspHostThreadId = GetCurrentThreadId();
	
	if (WorkMode == CaptureMode) {

		PspGetFilePath(RspStoragePath, MAX_PATH - 1);
		StringCchCat(RspStoragePath, MAX_PATH - 1, L"\\log");

		if (CreateDirectory(RspStoragePath, NULL) != TRUE) {
			if (GetLastError() != ERROR_ALREADY_EXISTS) {
				return S_FALSE;
			}															
		}

		StringCchCopy(Buffer, MAX_PATH, RspStoragePath);
		Length = (ULONG)wcsnlen_s(Buffer, MAX_PATH);

		GetLocalTime(&Time);
		StringCchPrintf(Buffer + Length, MAX_PATH - Length, L"\\dprobe-%02d%02d%02d%02d%02d.dtl", 
						Time.wMonth, Time.wDay, Time.wHour, Time.wMinute, Time.wSecond);

		Status = RspCreateCache(Buffer);
		SspInitialize();

	} else {

		Status = RspLoadCache(StoragePath);
		SspInitialize();
		SspLoadStackTraceDatabase();
	}

	return Status;
}
BOOL StringReverseW(PWSTR pWideCharStr, DWORD cchLength)
{
	PWSTR pEndOfStr = pWideCharStr + wcsnlen_s(pWideCharStr, cchLength) - 1;
	wchar_t cCharT;

	while (pWideCharStr < pEndOfStr)
	{
		cCharT = *pWideCharStr;
		*pWideCharStr = *pEndOfStr;
		*pEndOfStr = cCharT;

		pWideCharStr++;
		pEndOfStr--;
	}

	return(TRUE);
}
Example #13
0
/* Assumes 'filename' MAXPATHLEN+1 bytes long -
   may extend 'filename' by one character.
*/
static int
ismodule(wchar_t *filename, int update_filename) /* Is module -- check for .pyc/.pyo too */
{
    size_t n;

    if (exists(filename))
        return 1;

    /* Check for the compiled version of prefix. */
    n = wcsnlen_s(filename, MAXPATHLEN+1);
    if (n < MAXPATHLEN) {
        int exist = 0;
        filename[n] = Py_OptimizeFlag ? L'o' : L'c';
        filename[n + 1] = L'\0';
        exist = exists(filename);
        if (!update_filename)
            filename[n] = L'\0';
        return exist;
    }
    return 0;
}
Example #14
0
bool GetClipboardAsString(wstring &str)
{
	bool gotIt = false;
	OpenClipboard(NULL);
	HANDLE clip = GetClipboardData(CF_UNICODETEXT);
	if(clip != NULL)
	{
		HANDLE h = GlobalLock(clip);
		if(h != NULL)
		{
			WCHAR const *c = (WCHAR *)clip;
			size_t length = wcsnlen_s(c, 4096);
			WCHAR *buffer = new WCHAR[length + 1];
			CopyMemory(buffer, c, sizeof(WCHAR) * length);
			buffer[length] = (WCHAR)0;
			GlobalUnlock(clip);
			str = buffer;
			gotIt = true;
		}
	}
	CloseClipboard();
	return gotIt;
}
Example #15
0
/* Is module -- check for .pyc too.
   Assumes 'filename' MAXPATHLEN+1 bytes long -
   may extend 'filename' by one character. */
static int
ismodule(wchar_t *filename, int update_filename)
{
    size_t n;

    if (exists(filename)) {
        return 1;
    }

    /* Check for the compiled version of prefix. */
    n = wcsnlen_s(filename, MAXPATHLEN+1);
    if (n < MAXPATHLEN) {
        int exist = 0;
        filename[n] = L'c';
        filename[n + 1] = L'\0';
        exist = exists(filename);
        if (!update_filename) {
            filename[n] = L'\0';
        }
        return exist;
    }
    return 0;
}
Example #16
0
ESTATUS main_ApcWriteProcessMemoryInternal(
	HANDLE hProcess, 
	HANDLE hThread, 
	PVOID pvBaseAddress, 
	PVOID pvBuffer, 
	DWORD dwBufferSize
	)
{
	PWCHAR pwcPos = NULL;
	ESTATUS eReturn = ESTATUS_INVALID;
	PVOID pvTempBuffer = NULL;
	PVOID pvLocalBufferPointer = pvBuffer;
	PVOID pvRemoteBufferPointer = pvBaseAddress;
	DWORD dwBytesWritten = 0;

	while (pvLocalBufferPointer < (PUCHAR)pvBuffer + dwBufferSize)
	{
		DWORD cbTempBufferSize = 0;
				
		pwcPos = (PWCHAR)pvLocalBufferPointer + wcsnlen_s(
			(LPWSTR)pvLocalBufferPointer, 
			(dwBufferSize - dwBytesWritten) / sizeof(WCHAR)
			);
		if (0 == pwcPos)
		{
			goto lblCleanup;
		}
		if (pvLocalBufferPointer == pwcPos)
		{
			pvRemoteBufferPointer = (PUCHAR)pvRemoteBufferPointer + sizeof(UNICODE_NULL);
			pvLocalBufferPointer = (PUCHAR)pvLocalBufferPointer + sizeof(UNICODE_NULL);
			dwBytesWritten += sizeof(UNICODE_NULL);
			continue;
		}

		cbTempBufferSize = (PUCHAR)pwcPos - (PUCHAR)pvLocalBufferPointer;

		pvTempBuffer = HeapAlloc(
			GetProcessHeap(), 
			HEAP_ZERO_MEMORY, 
			cbTempBufferSize + sizeof(UNICODE_NULL)
			);
		if (NULL == pvTempBuffer)
		{
			goto lblCleanup;
		}

		memcpy(pvTempBuffer, pvLocalBufferPointer, cbTempBufferSize);

		eReturn = main_ApcWriteProcessMemoryNullTerminated(
			hProcess, 
			hThread, 
			pvRemoteBufferPointer, 
			pvTempBuffer, 
			cbTempBufferSize + sizeof(UNICODE_NULL)
			);
		if (ESTATUS_FAILED(eReturn))
		{
			goto lblCleanup;
		}
		pvRemoteBufferPointer = (PUCHAR)pvRemoteBufferPointer + cbTempBufferSize;
		pvLocalBufferPointer = (PUCHAR)pvLocalBufferPointer + cbTempBufferSize;
		dwBytesWritten += cbTempBufferSize;
		
		if (NULL != pvTempBuffer)
		{
			HeapFree(GetProcessHeap(), 0, pvTempBuffer);
			pvTempBuffer = NULL;

		}
	}

	eReturn = ESTATUS_SUCCESS;

lblCleanup:
	if (NULL != pvTempBuffer)
	{
		HeapFree(GetProcessHeap(), 0, pvTempBuffer);
		pvTempBuffer = NULL;
	}

	return eReturn;


}
RemoteDesktop::EventLog::EventLog(std::wstring name){
	Name = name;
	auto key_path(L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\" + name);

	HKEY key;

	DWORD last_error = RegCreateKeyEx(HKEY_LOCAL_MACHINE,
		key_path.c_str(),
		0,
		0,
		REG_OPTION_NON_VOLATILE,
		KEY_SET_VALUE,
		0,
		&key,
		0);
	if (ERROR_SUCCESS == last_error)
	{
		wchar_t szPath[MAX_PATH];
		bool ret = false;

		GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath));

		const DWORD types_supported = EVENTLOG_ERROR_TYPE |
			EVENTLOG_WARNING_TYPE |
			EVENTLOG_INFORMATION_TYPE;

		RegSetValueEx(key,
			L"EventMessageFile",
			0,
			REG_SZ,
			(BYTE*)szPath,
			wcsnlen_s(szPath, MAX_PATH) * 2);

		RegSetValueEx(key,
			L"CategoryMessageFile",
			0,
			REG_SZ,
			(BYTE*)szPath,
			wcsnlen_s(szPath, MAX_PATH) * 2);

		RegSetValueEx(key,
			L"ParameterMessageFile",
			0,
			REG_SZ,
			(BYTE*)szPath,
			wcsnlen_s(szPath, MAX_PATH) * 2);

		RegSetValueEx(key,
			L"TypesSupported",
			0,
			REG_DWORD,
			(LPBYTE)&types_supported,
			sizeof(types_supported));
		DWORD catcount = 3;
		RegSetValueEx(key,
			L"CategoryCount",
			0,
			REG_DWORD,
			(LPBYTE)&catcount,
			sizeof(catcount));
		RegCloseKey(key);
	}
	else
	{
		std::cerr << "Failed to install source: " << last_error << "\n";
	}

	_EventSource = RegisterEventSource(NULL, name.c_str());
}
Example #18
0
//Print errors to log file
bool __fastcall PrintError(
	const size_t ErrorType, 
	const wchar_t *Message, 
	const SSIZE_T ErrorCode, 
	const wchar_t *FileName, 
	const size_t Line)
{
//Print Error: Enable/Disable.
	if (!Parameter.PrintError || //PrintError parameter check
		Message == nullptr || CheckEmptyBuffer(Message, wcsnlen_s(Message, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t)) || //Message check
		FileName != nullptr && CheckEmptyBuffer(FileName, wcsnlen_s(FileName, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t))) //FileName check
			return false;

//Get current date and time.
	std::shared_ptr<tm> TimeStructure(new tm());
	memset(TimeStructure.get(), 0, sizeof(tm));
	auto TimeValues = time(nullptr);
#if defined(PLATFORM_WIN)
	if (localtime_s(TimeStructure.get(), &TimeValues) > 0)
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	if (localtime_r(&TimeValues, TimeStructure.get()) == nullptr)
#endif
		return false;

//Print Start Time at first printing.
	time_t InnerStartTime = 0;
	if (StartTime > 0)
	{
		InnerStartTime = StartTime;
		StartTime = 0;
	}

//Print to screen.
#if defined(PLATFORM_WIN)
	if (GlobalRunningStatus.Console)
#elif defined(PLATFORM_LINUX)
	if (!GlobalRunningStatus.Daemon)
#endif
	{
	//Print start time before print errors.
		if (InnerStartTime > 0)
		{
			std::shared_ptr<tm> TimeStructureTemp(new tm());
			memset(TimeStructureTemp.get(), 0, sizeof(tm));
		#if defined(PLATFORM_WIN)
			if (localtime_s(TimeStructureTemp.get(), &InnerStartTime) > 0)
		#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
			if (localtime_r(&InnerStartTime, TimeStructureTemp.get()) == nullptr)
		#endif
				return false;

			wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", TimeStructureTemp->tm_year + 1900, TimeStructureTemp->tm_mon + 1, TimeStructureTemp->tm_mday, TimeStructureTemp->tm_hour, TimeStructureTemp->tm_min, TimeStructureTemp->tm_sec);
		}

	//Print errors.
		switch (ErrorType)
		{
		//System Error
			case LOG_ERROR_SYSTEM:
			{
				if (ErrorCode == 0)
				{
					wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				}
				else {
				#if defined(PLATFORM_WIN)
				//About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx.
					if (ErrorCode == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
						wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
					else 
				#endif
						wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode);
				}
			}break;
		//Parameter Error
			case LOG_ERROR_PARAMETER:
			{
				wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Parameter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				if (FileName != nullptr)
				{
				//Delete double backslash.
					std::wstring sFileName(FileName);
					while (sFileName.find(L"\\\\") != std::wstring::npos)
						sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\"));

				//Write to file
					if (Line > 0)
						wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str());
					else 
						wprintf_s(L" in %ls", sFileName.c_str());
				}

			//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
				if (ErrorCode > 0)
					wprintf_s(L", error code is %d", (int)ErrorCode);

				wprintf_s(L".\n");
			}break;
		//IPFilter Error
			case LOG_ERROR_IPFILTER:
			{
				wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> IPFilter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				if (FileName != nullptr)
				{
				//Delete double backslash.
					std::wstring sFileName(FileName);
					while (sFileName.find(L"\\\\") != std::wstring::npos)
						sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\"));

				//Write to file
					if (Line > 0)
						wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str());
					else 
						wprintf_s(L" in %ls", sFileName.c_str());
				}

			//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
				if (ErrorCode > 0)
					wprintf_s(L", error code is %d", (int)ErrorCode);

				wprintf_s(L".\n");
			}break;
		//Hosts Error
			case LOG_ERROR_HOSTS:
			{
				wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Hosts Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				if (FileName != nullptr)
				{
				//Delete double backslash.
					std::wstring sFileName(FileName);
					while (sFileName.find(L"\\\\") != std::wstring::npos)
						sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\"));

				//Write to file
					if (Line > 0)
						wprintf_s(L" in line %d of %ls", (int)Line, sFileName.c_str());
					else 
						wprintf_s(L" in %ls", sFileName.c_str());
				}

			//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
				if (ErrorCode > 0)
					wprintf_s(L", error code is %d", (int)ErrorCode);

				wprintf_s(L".\n");
			}break;
		//Network Error
		//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
			case LOG_ERROR_NETWORK:
			{
				if (ErrorCode == 0)
					wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			#if defined(PLATFORM_WIN)
				else if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable.
					return true;
			#endif
				else 
					wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode);
			}break;
		//WinPcap Error
		#if defined(ENABLE_PCAP)
			case LOG_ERROR_PCAP:
			{
				wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Pcap Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			}break;
		#endif
		//DNSCurve Error
		#if defined(ENABLE_LIBSODIUM)
			case LOG_ERROR_DNSCURVE:
			{
			#if defined(PLATFORM_WIN)
				if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable.
					return true;
				else 
			#endif
					wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> DNSCurve Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			}break;
		#endif
		//Notice
			case LOG_MESSAGE_NOTICE:
			{
				wprintf_s(L"%d-%02d-%02d %02d:%02d:%02d -> Notice: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			}break;
			default:
			{
				return false;
			}
		}
	}

//Check whole file size.
	std::unique_lock<std::mutex> ErrLogMutex(ErrorLogLock);
#if defined(PLATFORM_WIN)
	std::shared_ptr<WIN32_FILE_ATTRIBUTE_DATA> File_WIN32_FILE_ATTRIBUTE_DATA(new WIN32_FILE_ATTRIBUTE_DATA());
	memset(File_WIN32_FILE_ATTRIBUTE_DATA.get(), 0, sizeof(WIN32_FILE_ATTRIBUTE_DATA));
	if (GetFileAttributesExW(GlobalRunningStatus.Path_ErrorLog->c_str(), GetFileExInfoStandard, File_WIN32_FILE_ATTRIBUTE_DATA.get()) != FALSE)
	{
		std::shared_ptr<LARGE_INTEGER> ErrorFileSize(new LARGE_INTEGER());
		memset(ErrorFileSize.get(), 0, sizeof(LARGE_INTEGER));
		ErrorFileSize->HighPart = File_WIN32_FILE_ATTRIBUTE_DATA->nFileSizeHigh;
		ErrorFileSize->LowPart = File_WIN32_FILE_ATTRIBUTE_DATA->nFileSizeLow;
		if (ErrorFileSize->QuadPart > 0 && (size_t)ErrorFileSize->QuadPart >= Parameter.LogMaxSize && 
			DeleteFileW(GlobalRunningStatus.Path_ErrorLog->c_str()) != 0)
				PrintError(LOG_ERROR_SYSTEM, L"Old Error Log file was deleted", 0, nullptr, 0);
	}

	File_WIN32_FILE_ATTRIBUTE_DATA.reset();
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	std::shared_ptr<struct stat> FileStat(new struct stat());
	memset(FileStat.get(), 0, sizeof(struct stat));
	if (stat(GlobalRunningStatus.sPath_ErrorLog->c_str(), FileStat.get()) == EXIT_SUCCESS && FileStat->st_size >= (off_t)Parameter.LogMaxSize && 
		remove(GlobalRunningStatus.sPath_ErrorLog->c_str()) == EXIT_SUCCESS)
			PrintError(LOG_ERROR_SYSTEM, L"Old Error Log file was deleted", 0, nullptr, 0);

	FileStat.reset();
#endif

//Main print
#if defined(PLATFORM_WIN)
	FILE *Output = nullptr;
	if (_wfopen_s(&Output, GlobalRunningStatus.Path_ErrorLog->c_str(), L"a,ccs=UTF-8") == EXIT_SUCCESS && Output != nullptr)
#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
	auto Output = fopen(GlobalRunningStatus.sPath_ErrorLog->c_str(), "a");
	if (Output != nullptr)
#endif
	{
	//Print start time before print errors.
		if (InnerStartTime > 0)
		{
			std::shared_ptr<tm> TimeStructureTemp(new tm());
			memset(TimeStructureTemp.get(), 0, sizeof(tm));
			
		#if defined(PLATFORM_WIN)
			if (localtime_s(TimeStructureTemp.get(), &InnerStartTime) > 0)
		#elif (defined(PLATFORM_LINUX) || defined(PLATFORM_MACX))
			if (localtime_r(&InnerStartTime, TimeStructureTemp.get()) == nullptr)
		#endif
			{
				fclose(Output);
				return false;
			}

			fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Log opened at this moment.\n", TimeStructureTemp->tm_year + 1900, TimeStructureTemp->tm_mon + 1, TimeStructureTemp->tm_mday, TimeStructureTemp->tm_hour, TimeStructureTemp->tm_min, TimeStructureTemp->tm_sec);
		}

	//Print errors.
		switch (ErrorType)
		{
		//System Error
			case LOG_ERROR_SYSTEM:
			{
				if (ErrorCode == 0)
				{
					fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				}
				else {
				#if defined(PLATFORM_WIN)
				//About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx.
					if (ErrorCode == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
						fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
					else 
				#endif
						fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> System Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode);
				}
			}break;
		//Parameter Error
			case LOG_ERROR_PARAMETER:
			{
				fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Parameter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				if (FileName != nullptr)
				{
				//Delete double backslash.
					std::wstring sFileName(FileName);
					while (sFileName.find(L"\\\\") != std::wstring::npos)
						sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\"));

				//Write to file
					if (Line > 0)
						fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str());
					else 
						fwprintf_s(Output, L" in %ls", sFileName.c_str());
				}

			//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
				if (ErrorCode > 0)
					fwprintf_s(Output, L", error code is %d", (int)ErrorCode);

				fwprintf_s(Output, L".\n");
			}break;
		//IPFilter Error
			case LOG_ERROR_IPFILTER:
			{
				fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> IPFilter Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				if (FileName != nullptr)
				{
				//Delete double backslash.
					std::wstring sFileName(FileName);
					while (sFileName.find(L"\\\\") != std::wstring::npos)
						sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\"));

				//Write to file
					if (Line > 0)
						fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str());
					else 
						fwprintf_s(Output, L" in %ls", sFileName.c_str());
				}

			//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
				if (ErrorCode > 0)
					fwprintf_s(Output, L", error code is %d", (int)ErrorCode);

				fwprintf_s(Output, L".\n");
			}break;
		//Hosts Error
			case LOG_ERROR_HOSTS:
			{
				fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Hosts Error: %ls", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
				if (FileName != nullptr)
				{
				//Delete double backslash.
					std::wstring sFileName(FileName);
					while (sFileName.find(L"\\\\") != std::wstring::npos)
						sFileName.erase(sFileName.find(L"\\\\"), wcslen(L"\\"));

				//Write to file
					if (Line > 0)
						fwprintf_s(Output, L" in line %d of %ls", (int)Line, sFileName.c_str());
					else 
						fwprintf_s(Output, L" in %ls", sFileName.c_str());
				}

			//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
				if (ErrorCode > 0)
					fwprintf_s(Output, L", error code is %d", (int)ErrorCode);

				fwprintf_s(Output, L".\n");
			}break;
		//Network Error
		//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
			case LOG_ERROR_NETWORK:
			{
				if (ErrorCode == 0)
					fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			#if defined(PLATFORM_WIN)
				else if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable.
					break;
			#endif
				else 
					fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Network Error: %ls, error code is %d.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message, (int)ErrorCode);
			}break;
		//WinPcap Error
		#if defined(ENABLE_PCAP)
			case LOG_ERROR_PCAP:
			{
				fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> WinPcap Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			}break;
		#endif
		//DNSCurve Error
		#if defined(ENABLE_LIBSODIUM)
			case LOG_ERROR_DNSCURVE:
			{
			#if defined(PLATFORM_WIN)
				if (ErrorCode == WSAENETUNREACH) //Block error messages when network is unreachable.
					break;
				else 
			#endif
					fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> DNSCurve Error: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			}break;
		#endif
		//Notice
			case LOG_MESSAGE_NOTICE:
			{
				fwprintf_s(Output, L"%d-%02d-%02d %02d:%02d:%02d -> Notice: %ls.\n", TimeStructure->tm_year + 1900, TimeStructure->tm_mon + 1, TimeStructure->tm_mday, TimeStructure->tm_hour, TimeStructure->tm_min, TimeStructure->tm_sec, Message);
			}break;
			default:
			{
				fclose(Output);
				return false;
			}
		}

	//Close file.
		fclose(Output);
		return true;
	}

	return false;
}
Example #19
0
//Print errors to log file
bool __fastcall PrintError(
	_In_ const size_t ErrorType, 
	_In_ const wchar_t *Message, 
	_In_opt_ const SSIZE_T ErrorCode, 
	_In_opt_ const wchar_t *FileName, 
	_In_opt_ const size_t Line)
{
//Print Error: Enable/Disable, parameter check, message check and file name check
	if (!Parameter.PrintError || //PrintError 
		Message == nullptr || CheckEmptyBuffer(Message, wcsnlen_s(Message, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t)) || 
		FileName != nullptr && CheckEmptyBuffer(FileName, wcsnlen_s(FileName, ORIGINAL_PACKET_MAXSIZE) * sizeof(wchar_t)))
			return false;

//Convert file name.
	std::wstring FileNameString, ErrorMessage;
	if (FileName != nullptr)
	{
		FileNameString.append(L" in ");

	//Add line number.
		if (Line > 0)
			FileNameString.append(L"line %d of ");

	//Delete double backslash.
		FileNameString.append(FileName);
		while (FileNameString.find(L"\\\\") != std::wstring::npos)
			FileNameString.erase(FileNameString.find(L"\\\\"), wcslen(L"\\"));
	}

//Add log error type.
	switch (ErrorType)
	{
	//Message Notice
		case LOG_MESSAGE_NOTICE:
		{
			ErrorMessage.append(L"Notice: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	//System Error
	//About System Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx.
		case LOG_ERROR_SYSTEM:
		{
			ErrorMessage.append(L"System Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
		#if defined(PLATFORM_WIN)
			else if (ErrorCode == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
				ErrorMessage.append(L", ERROR_FAILED_SERVICE_CONTROLLER_CONNECT(The service process could not connect to the service controller).\n");
		#endif
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	//Parameter Error
		case LOG_ERROR_PARAMETER:
		{
			ErrorMessage.append(L"Parameter Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	//IPFilter Error
	//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
		case LOG_ERROR_IPFILTER:
		{
			ErrorMessage.append(L"IPFilter Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	//Hosts Error
	//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
		case LOG_ERROR_HOSTS:
		{
			ErrorMessage.append(L"Hosts Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	//Network Error
	//About Windows Sockets Error Codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx.
		case LOG_ERROR_NETWORK:
		{
			ErrorMessage.append(L"Network Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
		#if defined(PLATFORM_WIN)
			else if (ErrorCode == WSAENETUNREACH || //Block error messages when getting Network Unreachable error.
				ErrorCode == WSAEHOSTUNREACH) //Block error messages when getting Host Unreachable error.
					return true;
		#endif
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	//WinPcap Error
	#if defined(ENABLE_PCAP)
		case LOG_ERROR_PCAP:
		{
			ErrorMessage.append(L"Pcap Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

/* There are no any error codes to be reported in LOG_ERROR_PCAP.
		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
*/
			ErrorMessage.append(L"\n");
		}break;
	#endif
	//DNSCurve Error
	#if defined(ENABLE_LIBSODIUM)
		case LOG_ERROR_DNSCURVE:
		{
			ErrorMessage.append(L"DNSCurve Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	#endif
	//SOCKS Error
		case LOG_ERROR_SOCKS:
		{
			ErrorMessage.append(L"SOCKS Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
	//HTTP Error
		case LOG_ERROR_HTTP:
		{
			ErrorMessage.append(L"HTTP Error: ");
			ErrorMessage.append(Message);

		//Copy file name and its line number to error log.
			if (!FileNameString.empty())
				ErrorMessage.append(FileNameString);

		//Add error code.
			if (ErrorCode == 0)
				ErrorMessage.append(L".\n");
			else 
				ErrorMessage.append(L", error code is %d.\n");
		}break;
		default:
		{
			return false;
		}
	}

//Print error log.
	return PrintScreenAndWriteFile(ErrorMessage, ErrorCode, Line);
}
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine)
{
	PROCESS_INFORMATION pi = { 0 };
	STARTUPINFO si = { 0 };
	CResource zipResource;
	wchar_t targetDir[MAX_PATH];
	wchar_t logFile[MAX_PATH];
	std::vector<CString> to_delete;

	ExpandEnvironmentStrings(L"%LocalAppData%\\SquirrelTemp", targetDir, _countof(targetDir));
	if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
		goto failedExtract;
	}

	swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir);

	if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
		goto failedExtract;
	}

	DWORD dwSize = zipResource.GetSize();
	if (dwSize < 0x100) {
		goto failedExtract;
	}

	BYTE* pData = (BYTE*)zipResource.Lock();
	HZIP zipFile = OpenZip(pData, dwSize, NULL);
	SetUnzipBaseDir(zipFile, targetDir);

	// NB: This library is kind of a disaster
	ZRESULT zr;
	int index = 0;
	do {
		ZIPENTRY zentry;
		wchar_t targetFile[MAX_PATH];

		zr = GetZipItem(zipFile, index, &zentry);
		if (zr != ZR_OK && zr != ZR_MORE) {
			break;
		}

		// NB: UnzipItem won't overwrite data, we need to do it ourselves
		swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name);
		DeleteFile(targetFile);

		if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break;
		to_delete.push_back(CString(targetFile));
		index++;
	} while (zr == ZR_MORE || zr == ZR_OK);

	CloseZip(zipFile);
	zipResource.Release();

	// nfi if the zip extract actually worked, check for Update.exe
	wchar_t updateExePath[MAX_PATH];
	swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe");

	if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) {
		goto failedExtract;
	}

	// Run Update.exe
	si.cb = sizeof(STARTUPINFO);
	si.wShowWindow = SW_SHOW;
	si.dwFlags = STARTF_USESHOWWINDOW;

	if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) {
		lpCommandLine = L"--install .";
	}

	wchar_t cmd[MAX_PATH];
	swprintf_s(cmd, L"%s %s", updateExePath, lpCommandLine);

	if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) {
		goto failedExtract;
	}

	WaitForSingleObject(pi.hProcess, INFINITE);

	DWORD dwExitCode;
	if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) {
		dwExitCode = (DWORD)-1;
	}

	if (dwExitCode != 0) {
		DisplayErrorMessage(CString(
			L"There was an error while installing the application. " 
			L"Check the setup log for more information and contact the author."), logFile);
	}

	for (unsigned int i = 0; i < to_delete.size(); i++) {
		DeleteFile(to_delete[i]);
	}

	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	return (int) dwExitCode;

failedExtract:
	DisplayErrorMessage(CString(L"Failed to extract installer"), NULL);
	return (int) dwExitCode;
}
Example #21
0
BOOL GDIPluseExt::DrawBoardsText(Graphics&  gp,PointF startpf,CString strText,CString strFont,INT nfontsize,Color textcolor,Color boardscolor)
{

	gp.SetSmoothingMode(SmoothingModeAntiAlias);
	gp.SetInterpolationMode(InterpolationModeHighQualityBicubic);

#ifdef _UNICODE

	StringFormat strformat;
	FontFamily  fontFamily(strFont);
	GraphicsPath path;
	path.AddString(strText,strText.GetLength(), &fontFamily, 
		FontStyleRegular, 
		(REAL)nfontsize,
		startpf, 
		&strformat );
	for(int i=1; i < 4; ++i)
	{
		Pen pen(boardscolor, (REAL)i);
		pen.SetLineJoin(LineJoinRound);
		gp.DrawPath(&pen, &path);
	}
	SolidBrush  textBrush(textcolor); 
	gp.FillPath(&textBrush, &path);
#else

	//字符转换
	int font_len = strFont.GetLength();
	WCHAR* pfont_w = new WCHAR[font_len];
	MultiByteToWideChar(CP_ACP,0,strFont.GetBuffer(),-1,pfont_w,font_len);
	strFont.ReleaseBuffer();
	//字符转换
	int text_len = strText.GetLength();
	WCHAR* ptext_w = new WCHAR[text_len];
	MultiByteToWideChar(CP_ACP,0,strText.GetBuffer(),-1,ptext_w,text_len);
	strText.ReleaseBuffer();


	FontFamily  fontFamily(pfont_w);

	Font font(&fontFamily, (REAL)nfontsize, FontStyleRegular, UnitPixel);

	GraphicsPath path;
	StringFormat strformat;

	path.AddString(ptext_w,wcsnlen_s(ptext_w,text_len), &fontFamily, 
		font.GetStyle(),
		font.GetSize(),
		startpf, 
		&strformat );

	for(int i=1; i < 4; ++i)
	{
		Pen pen(boardscolor,(REAL)i);
		pen.SetLineJoin(LineJoinRound);
		gp.DrawPath(&pen, &path);
	}

	SolidBrush  textBrush(textcolor); 
	gp.FillPath(&textBrush, &path);
	
	DEL_P(ptext_w);
	DEL_P(pfont_w);
#endif
	return TRUE;
}
Example #22
0
void TestMove_s( void )
{

    wchar_t    buf[128];
    wchar_t    s2[] = L"VALUE";
    wchar_t    str[] = L"VALUE";

    wchar_t    src1[100] = L"hello";
    wchar_t    src2[7] = L"goodbye";
    wchar_t    dst1[6], dst2[5], dst3[5];

    wchar_t    sc1[100] = L"good";
    wchar_t    sc2[6] = L"hello";
    wchar_t    sc3[6] = L"hello";
    wchar_t    sc4[7] = L"abc";
    wchar_t    sc5[1000] = L"bye";

    int     violations = NumViolations;

    /*   wcstok_s */
    static wchar_t     str1[] = L"?a???b,,,#c";
    static wchar_t     str2[] = L"\t \t";
    static wchar_t     str3[] = L"?a???b,,,#c";
    wchar_t            *t, *ptr1, *ptr2, *ptr3;
    rsize_t         max1 = ARRAYCOUNT( str1 );
    rsize_t         max2 = ARRAYCOUNT( str2 );
    rsize_t         max3 = ARRAYCOUNT( str3 );


    /***********************************************************************/
    /*  set constraint-handler                                             */
    /***********************************************************************/

    set_constraint_handler_s( my_constraint_handler );

    /***********************************************************************/
    /*  memcpy_s                                                           */
    /***********************************************************************/
//  printf( "Test memcpys      (%s).\n", ProgramName );

    /* Test the "good" case */
    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, 0 ) == 0 );
    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, 1 + wcslen( s2 ) ) == 0 );
    VERIFY( wmemcpy_s( buf, wcslen( s2 ) + 2, s2, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wmemcpy_s( buf, 3, s2, wcslen( s2 ) ) != 0 );
    VERIFY( buf[0] == L'\0' );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( NULL, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), NULL, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, sizeof( buf ) / sizeof( buf[0] )+ 1 ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), buf + 1, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    VERIFY( wmemcpy_s( buf, ARRAYCOUNT( buf ), s2, ~0 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif

    /***********************************************************************/
    /*  memmove_s                                                          */
    /***********************************************************************/
//  printf( "Test memmove      (%s).\n", ProgramName );

    /* Test the "good" cases */
    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, 0 ) == 0 );
    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), buf + 1, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wmemmove_s( buf, 1 + wcslen( s2 ), s2, 1 + wcslen( s2 ) ) == 0 );

    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wmemmove_s( buf, 3, s2, wcslen( s2 ) ) != 0 );
    VERIFY( buf[0] == L'\0' );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( NULL, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), NULL, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, ARRAYCOUNT( buf ) + 1 ) != 0 );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    VERIFY( wmemmove_s( buf, ~0, s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wmemmove_s( buf, ARRAYCOUNT( buf ), s2, ~0 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif

    /***********************************************************************/
    /*  wcscpy_s                                                           */
    /***********************************************************************/
//  printf( "Test memcpy       (%s).\n", ProgramName );

    /* Test the "good" cases */
    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), s2 ) == 0 );
    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), s2 ) == 0 );
    VERIFY( wcscpy_s( buf, wcslen( s2 ) + 1, s2 ) == 0 );


    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wcscpy_s( buf, 3, s2 ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( buf[0] == L'\0' );

    VERIFY( wcscpy_s( NULL, ARRAYCOUNT( buf ), s2 ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), NULL ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscpy_s( buf, 5, s2 ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscpy_s( buf, ARRAYCOUNT( buf ), buf + 1 ) != 0 );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    VERIFY( wcscpy_s( buf, ~0, s2 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif

    /***********************************************************************/
    /*  wcscat_s                                                           */
    /***********************************************************************/
//  printf( "Test wcscat       (%s).\n", ProgramName );
    wcscpy( sc1,src1 );
    VERIFY( wcscmp( sc1,src1 ) == 0 );
    VERIFY( wcscat_s( sc1, 100, sc5 ) == 0 );
    VERIFY( wcscmp( sc1, L"hellobye") == 0 );

    VERIFY( wcscat_s( sc2, 6, L"" ) == 0 );

    VERIFY( wcscat_s( sc3, 6, L"X" ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( sc3[0] == L'\0');

    VERIFY( wcscat_s(sc4, 7, L"defghijklmn") != 0);
    VERIFY( NumViolations == ++violations );

    VERIFY( wcscmp(sc4, L"" ) == 0);


    /***********************************************************************/
    /*  wcsnlen_s                                                          */
    /***********************************************************************/

//  printf( "Test wcsnlen      (%s).\n", ProgramName );
    /* Test the "good" case */
    VERIFY( wcsnlen_s( str, ARRAYCOUNT( str ) ) == wcslen( str ) );
    VERIFY( wcsnlen_s( str, 4 ) == 4 );
    VERIFY( wcsnlen_s( str, 0 ) == 0 );
    VERIFY( wcsnlen_s( NULL, 1000 ) == 0 );

    /* Test various failing cases */

    /* No runtime-constraint violations to test */

    VERIFY( NumViolations == violations );

    /***********************************************************************/
    /*  wcsncpy_s                                                          */
    /***********************************************************************/

//  printf( "Test wcsncpy      (%s).\n", ProgramName );
    /* Test the "good" case */
    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), s2, 0 ) == 0 );
    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) == 0 );
    VERIFY( wcsncpy_s( buf, wcslen( s2 ) + 1, s2, wcslen( s2 ) ) == 0 );

    VERIFY( wcslen( buf ) == wcslen( L"VALUE" ) );
    VERIFY( wcscmp( buf, L"VALUE" ) == 0 );
    VERIFY( NumViolations == violations );

    VERIFY( wcsncpy_s( dst1, 6, src1, 100 ) == 0 );
    VERIFY( wcscmp( dst1, src1 ) == 0 );

    VERIFY( wcsncpy_s( dst3, 5, src2, 4 ) == 0 );

    /* Test various failing cases */
    /* Test runtime-constraint violations */
    VERIFY( wcsncpy_s( buf, 3, s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( buf[0] == '\0' );

    VERIFY( wcsncpy_s( NULL, ARRAYCOUNT( buf ), s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), NULL, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), buf + 1, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( dst2, 5, src2, 7 ) != 0 );
    VERIFY( NumViolations == ++violations );


#if RSIZE_MAX != SIZE_MAX
    VERIFY( wcsncpy_s( buf, ~0, s2, wcslen( s2 ) ) != 0 );
    VERIFY( NumViolations == ++violations );

    VERIFY( wcsncpy_s( buf, ARRAYCOUNT( buf ), s2, ~0 ) != 0 );
    VERIFY( NumViolations == ++violations );
#endif


    /***********************************************************************/
    /*  wcsncat_s                                                          */
    /***********************************************************************/

//  printf( "Test wcsncat      (%s).\n", ProgramName );
    wcscpy( sc1, L"good" );
    wcscpy( sc2, L"hello" );
    wcscpy( sc3, L"hello" );
    wcscpy( sc4, L"abc" );
    VERIFY( wcsncat_s( sc1, 100, sc5, 1000 ) == 0);
    VERIFY( wcscmp( sc1, L"goodbye" ) == 0 );

    VERIFY( wcsncat_s( sc2, 6, L"", 1 ) == 0 );

    VERIFY( wcsncat_s( sc4, 7, L"defghijklmn", 3 ) == 0 );
    VERIFY( wcscmp( sc4, L"abcdef" ) == 0 );

    /* Test runtime-constraint violations */
    VERIFY( wcsncat_s( sc3, 6, L"XXX", 3 ) != 0 );
    VERIFY( NumViolations == ++violations );
    VERIFY( sc3[0] == L'\0');

    /***********************************************************************/
    /*  wcstok_s                                                           */
    /***********************************************************************/

//  printf( "Test wcstok       (%s).\n", ProgramName );
    VERIFY( (t = wcstok_s( str1, &max1, L"?", &ptr1 )) != NULL );    /* points to the token "a" */
    VERIFY( wcscmp( t, L"a" ) == 0 );

    VERIFY( (t = wcstok_s( NULL, &max1, L",", &ptr1 )) != NULL );    /* points to the token "??b" */
    VERIFY( wcscmp( t, L"??b" ) == 0 );

    VERIFY( NULL == wcstok_s( str2, &max2, L" \t", &ptr2 ) );        /* null pointer */
    VERIFY( NumViolations == violations );

    VERIFY( (t = wcstok_s( NULL, &max1, L"#,", &ptr1 )) != NULL  );  /* points to the token "c" */
    VERIFY( wcscmp( t, L"c" ) == 0 );
    VERIFY( ptr1 != NULL );
    VERIFY( NumViolations == violations );

    VERIFY( NULL == wcstok_s( NULL, &max1, L"#,", &ptr1 ) );  /* at the end */

    wcscpy( str1, str3 );
    max1 = ARRAYCOUNT( str1 );
    VERIFY( NULL == wcstok_s( str1, &max1, str3, &ptr3 ) );         /* only delimiter chars */

//  printf( "Test wcstok rtc   (%s).\n", ProgramName );
    /* Test runtime-constraint violations */
    ptr1 = NULL;
    VERIFY( NULL == wcstok_s( NULL, &max1, L"?", &ptr1 ) );          /* null pointer */
    VERIFY( NumViolations == ++violations );

    VERIFY( NULL == wcstok_s( str3, NULL, L"?", &ptr1 ) );
    VERIFY( NumViolations == ++violations );

    VERIFY( NULL == wcstok_s( str3, &max3, NULL, &ptr1 ) );
    VERIFY( NumViolations == ++violations );

    VERIFY( NULL == wcstok_s( str3, &max3, L"?", NULL ) );
    VERIFY( NumViolations == ++violations );

    ptr3 = NULL;
    VERIFY( NULL == wcstok_s( NULL, &max3, L"?", &ptr3 ) );
    VERIFY( NumViolations == ++violations );

#if RSIZE_MAX != SIZE_MAX
    max1 = ~0;
    VERIFY( NULL == wcstok_s( str3, &max1, L"?", &ptr1 ) );
    VERIFY( NumViolations == ++violations );
#endif
}
int CUpdateRunner::ExtractUpdaterAndRun(wchar_t* lpCommandLine, bool useFallbackDir)
{
	PROCESS_INFORMATION pi = { 0 };
	STARTUPINFO si = { 0 };
	CResource zipResource;
	wchar_t targetDir[MAX_PATH];
	wchar_t logFile[MAX_PATH];
	std::vector<CString> to_delete;

	if (!useFallbackDir) {
		SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, targetDir);
	} else {
		wchar_t username[512];
		wchar_t uid[128];
		wchar_t appDataDir[MAX_PATH];
		ULONG unameSize = _countof(username);

		SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, appDataDir);
		GetUserName(username, &unameSize);
		DWORD lastError = GetLastError();

		_swprintf_c(targetDir, _countof(targetDir), L"%s\\%s", appDataDir, username);

		if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
			wchar_t err[4096];
			_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);
			DisplayErrorMessage(CString(err), NULL);

			return -1;
		}
	}

	wcscat_s(targetDir, _countof(targetDir), L"\\SquirrelTemp");

	if (!CreateDirectory(targetDir, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) {
		wchar_t err[4096];
		_swprintf_c(err, _countof(err), L"Unable to write to %s - IT policies may be restricting access to this folder", targetDir);

		if (useFallbackDir) {
			DisplayErrorMessage(CString(err), NULL);
		}

		goto failedExtract;
	}

	swprintf_s(logFile, L"%s\\SquirrelSetup.log", targetDir);

	if (!zipResource.Load(L"DATA", IDR_UPDATE_ZIP)) {
		goto failedExtract;
	}

	DWORD dwSize = zipResource.GetSize();
	if (dwSize < 0x100) {
		goto failedExtract;
	}

	BYTE* pData = (BYTE*)zipResource.Lock();
	HZIP zipFile = OpenZip(pData, dwSize, NULL);
	SetUnzipBaseDir(zipFile, targetDir);

	// NB: This library is kind of a disaster
	ZRESULT zr;
	int index = 0;
	do {
		ZIPENTRY zentry;
		wchar_t targetFile[MAX_PATH];

		zr = GetZipItem(zipFile, index, &zentry);
		if (zr != ZR_OK && zr != ZR_MORE) {
			break;
		}

		// NB: UnzipItem won't overwrite data, we need to do it ourselves
		swprintf_s(targetFile, L"%s\\%s", targetDir, zentry.name);
		DeleteFile(targetFile);

		if (UnzipItem(zipFile, index, zentry.name) != ZR_OK) break;
		to_delete.push_back(CString(targetFile));
		index++;
	} while (zr == ZR_MORE || zr == ZR_OK);

	CloseZip(zipFile);
	zipResource.Release();

	// nfi if the zip extract actually worked, check for Update.exe
	wchar_t updateExePath[MAX_PATH];
	swprintf_s(updateExePath, L"%s\\%s", targetDir, L"Update.exe");

	if (GetFileAttributes(updateExePath) == INVALID_FILE_ATTRIBUTES) {
		goto failedExtract;
	}

	// Run Update.exe
	si.cb = sizeof(STARTUPINFO);
	si.wShowWindow = SW_SHOW;
	si.dwFlags = STARTF_USESHOWWINDOW;

	if (!lpCommandLine || wcsnlen_s(lpCommandLine, MAX_PATH) < 1) {
		lpCommandLine = L"";
	}

	wchar_t cmd[MAX_PATH];
	swprintf_s(cmd, L"\"%s\" --install . %s", updateExePath, lpCommandLine);

	if (!CreateProcess(NULL, cmd, NULL, NULL, false, 0, NULL, targetDir, &si, &pi)) {
		goto failedExtract;
	}

	WaitForSingleObject(pi.hProcess, INFINITE);

	DWORD dwExitCode;
	if (!GetExitCodeProcess(pi.hProcess, &dwExitCode)) {
		dwExitCode = (DWORD)-1;
	}

	if (dwExitCode != 0) {
		DisplayErrorMessage(CString(
			L"There was an error while installing the application. " 
			L"Check the setup log for more information and contact the author."), logFile);
	}

	for (unsigned int i = 0; i < to_delete.size(); i++) {
		DeleteFile(to_delete[i]);
	}

	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	return (int) dwExitCode;

failedExtract:
	if (!useFallbackDir) {
		// Take another pass at it, using C:\ProgramData instead
		return ExtractUpdaterAndRun(lpCommandLine, true);
	}

	DisplayErrorMessage(CString(L"Failed to extract installer"), NULL);
	return (int) dwExitCode;
}