Example #1
0
File: usUtils.cpp Project: 0r/MITK
void message_output(MsgType msgType, const char *buf)
{
  if (handler)
  {
    (*handler)(msgType, buf);
  }
  else
  {
    fprintf(stderr, "%s\n", buf);
    fflush(stderr);
  }

  if (msgType == ErrorMsg)
  {
  #if defined(_MSC_VER) && !defined(NDEBUG) && defined(_DEBUG) && defined(_CRT_ERROR)
    // get the current report mode
    int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
    _CrtSetReportMode(_CRT_ERROR, reportMode);
    int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, CppMicroServices_VERSION_STR, buf);
    if (ret == 0  && reportMode & _CRTDBG_MODE_WNDW)
      return; // ignore
    else if (ret == 1)
      _CrtDbgBreak();
  #endif

  #ifdef US_PLATFORM_POSIX
    abort(); // trap; generates core dump
  #else
    exit(1); // goodbye cruel world
  #endif
  }
}
Example #2
0
	Exec_stat exec(MCExecPoint& ep)
	{
#if defined(WIN32) && defined(_DEBUG)
		_CrtDbgBreak();
#endif
		return ES_NORMAL;
	}
Example #3
0
bool MkCheck::ExceptionForDebug(const wchar_t* expression, const wchar_t* message)
{
	MkStr msg;
	msg.Reserve(1024);
	msg += L"EXPRESSION : ";
	msg += expression;
	msg += L"\nMESSAGE : ";
	msg += message;

#if (MKDEF_CHECK_EXCEPTION_BREAK)
	int rlt = MessageBox(NULL, msg.GetPtr(), L"Oops!!! Break?", MB_YESNO);
	if (rlt == IDYES)
	{
		// break
		_CrtDbgBreak();
	}
	else if (rlt == IDNO)
#else
	int rlt = MessageBox(NULL, msg.GetPtr(), L"Oops!!!", MB_OK);
	if (rlt == IDOK)
#endif
	{
		// log 기록 후 진행
		MK_LOG_MGR.Msg(L"<Error> " + msg, true);
	}

	return true; // excute action
}
Example #4
0
void CLDebugBreak(){
	//can be used for debug breaking...
#if defined(_CLCOMPILER_MSVC) && defined(_DEBUG)
	_CrtDbgBreak();
#else
	int i=0; //a line to put breakpoint on
#endif
}
Example #5
0
void pwerror()
{
	PWSTR msg;
	ATLENSURE(FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, GetLastError(), 0, reinterpret_cast<PWSTR>(&msg), 0, nullptr));
	fputws(msg, stderr);
	_CrtDbgBreak();
	LocalFree(msg);
}
Example #6
0
void TriggerBreakpoint()
{
#ifdef _MSC_VER
    _CrtDbgBreak();
#elif defined(__GNUC__) && ((__i386__) || (__x86_64__))
    __asm__ __volatile__ ( "int $3\n\t" );
#else
    raise(SIGTRAP);
#endif
}
Example #7
0
void __cdecl xf_free
(
    void * _Memory
#ifdef TRACK_MEMORY_ALLOCATIONS
    , LPCSTR lpszFileName, int nLine
#endif
)
{
	if (!_Memory)
	{
		return; // Nothing to do
	}
	if (!ghHeap)
	{
		//_ASSERTE(ghHeap && _Memory);
		#ifdef _DEBUG
		_CrtDbgBreak();
		#endif
		return;
	}
#ifdef TRACK_MEMORY_ALLOCATIONS
	xf_mem_block* p = ((xf_mem_block*)_Memory)-1;

	if (p->bBlockUsed == TRUE)
	{
		int nCCcmp = memcmp(((LPBYTE)_Memory)+p->nBlockSize, "\xCC\xCC\xCC\xCC\xCC\xCC\xCC\xCC", 8);
		_ASSERTE(nCCcmp == 0);
		memset(_Memory, 0xFD, p->nBlockSize);
	}
	else
	{
		_ASSERTE(p->bBlockUsed == TRUE);
	}

	p->bBlockUsed = FALSE;
	msprintf(p->sCreatedFrom, countof(p->sCreatedFrom), "-- %s:%i", _PointToName(lpszFileName), nLine);
	_Memory = (void*)p;
#endif
	#ifdef _DEBUG
	size_t _Size1 = HeapSize(ghHeap, 0, _Memory);
	_ASSERTE(_Size1 > 0);
	#endif

	HeapFree(ghHeap, 0, _Memory);

	#ifdef FORCE_HEAP_CHECK
	xf_dump_chk();
	#endif
	//#ifdef _DEBUG
	//SIZE_T _Size2 = HeapSize(ghHeap, 0, _Memory);
	//if (_Size1 == _Size2) {
	//	_ASSERTE(_Size1 != _Size2);
	//}
	//#endif
}
Example #8
0
 void DebuggerBreak::engage() {
    if (_break) {
       try {
          _CrtDbgBreak();
       }
       catch (...) {
          // allow applications to run in debug mode without debugger
          _break = false;
       }
    }
 }
Example #9
0
File: pal.c Project: mixtile/xskit
void xsAssert(const char *expression, const char *file, int line)
{
#ifdef _MSC_VER
#ifdef _DEBUG
	_CrtDbgReport(_CRT_ASSERT, file, line, NULL, expression);
#endif
	_CrtDbgBreak();
#else
	_assert(expression, file, line);
#endif
}
Example #10
0
		void LogManager::qtMessageHandler(QtMsgType type, const char *pMessage)
		{
#else
		void LogManager::qtMessageHandler(QtMsgType type, const QMessageLogContext &, const QString & pMessage)
		{
#endif
			Level level;
			switch (type)
			{
					case QtDebugMsg:
							level = Level::DEBUG_INT;
							break;
					case QtWarningMsg:
							level = Level::WARN_INT;
							break;
					case QtCriticalMsg:
							level = Level::ERROR_INT;
							break;
					case QtFatalMsg:
							level = Level::FATAL_INT;
							break;
					default:
							level = Level::TRACE_INT;
			}
			instance()->qtLogger()->log(level, pMessage);

			// Qt fatal behaviour copied from global.cpp qt_message_output()
			// begin {

			if ((type == QtFatalMsg) ||
					((type == QtWarningMsg) && (!qgetenv("QT_FATAL_WARNINGS").isNull())) )
			{
#if defined(Q_CC_MSVC) && defined(QT_DEBUG) && defined(_DEBUG) && defined(_CRT_ERROR)
					// get the current report mode
					int reportMode = _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
					_CrtSetReportMode(_CRT_ERROR, reportMode);
					int ret = _CrtDbgReport(_CRT_ERROR, __FILE__, __LINE__, QT_VERSION_STR, qPrintable(pMessage));
					if (ret == 0  && reportMode & _CRTDBG_MODE_WNDW)
							return; // ignore
					else if (ret == 1)
							_CrtDbgBreak();
#endif

#if defined(Q_OS_UNIX) && defined(QT_DEBUG)
					abort(); // trap; generates core dump
#else
					exit(1); // goodbye cruel world
#endif
			}

			// } end
	}
Example #11
0
int GuiMessageBox(HWND hConEmuWndRoot, LPCWSTR asText, LPCWSTR asTitle, int anBtns)
{
	int nResult = 0;
	
	if (hConEmuWndRoot)
	{
		HWND hConWnd = myGetConsoleWindow();
		CESERVER_REQ *pIn = (CESERVER_REQ*)malloc(sizeof(*pIn));
		ExecutePrepareCmd(pIn, CECMD_ASSERT, sizeof(CESERVER_REQ_HDR)+sizeof(MyAssertInfo));
		pIn->AssertInfo.nBtns = anBtns;
		_wcscpyn_c(pIn->AssertInfo.szTitle, countof(pIn->AssertInfo.szTitle), asTitle, countof(pIn->AssertInfo.szTitle)); //-V501
		_wcscpyn_c(pIn->AssertInfo.szDebugInfo, countof(pIn->AssertInfo.szDebugInfo), asText, countof(pIn->AssertInfo.szDebugInfo)); //-V501

		wchar_t szGuiPipeName[128];
		msprintf(szGuiPipeName, countof(szGuiPipeName), CEGUIPIPENAME, L".", (DWORD)hConEmuWndRoot); //-V205

		CESERVER_REQ* pOut = ExecuteCmd(szGuiPipeName, pIn, 1000, hConWnd);

		free(pIn);

		if (pOut)
		{
			if (pOut->hdr.cbSize > sizeof(CESERVER_REQ_HDR))
			{
				nResult = pOut->dwData[0];
			}
			ExecuteFreeResult(pOut);
		}
	}
	else
	{
		//_ASSERTE(hConEmuWndRoot!=NULL);
		// Избежать статической линковки к user32
		HMODULE hUser32 = GetModuleHandle(L"User32.dll");
		if (hUser32 == NULL)
			hUser32 = LoadLibrary(L"User32.dll");
		typedef int (WINAPI* MessageBoxW_T)(HWND, LPCWSTR, LPCWSTR, UINT);
		MessageBoxW_T _MessageBoxW = hUser32 ? (MessageBoxW_T)GetProcAddress(hUser32, "MessageBoxW") : NULL;
		if (_MessageBoxW)
		{
			nResult = _MessageBoxW(NULL, asText, asTitle, MB_SYSTEMMODAL|anBtns);
		}
		else
		{
			#ifdef _DEBUG
			_CrtDbgBreak();
			#endif
		}
	}

	return nResult;
}
Example #12
0
void writeLog(const TCHAR *logFileName, const TCHAR *log2write)
{	
	FILE* f = NULL;
	errno_t err = _tfopen_s(&f, logFileName, TEXT("a+"));
	if ( err != 0 ) {
		if ( IsDebuggerPresent( ) ) {
			_CrtDbgBreak( );
			}
		//TODO: log it somehow!
		return;
		}
	fwrite(log2write, sizeof(log2write[0]), lstrlen(log2write), f);
	fputc('\n', f);
	fflush(f);
	fclose(f);
}
Example #13
0
int NVDALogCrtReportHook(int reportType,const wchar_t *message,int *returnValue) {
	bool doDebugBreak=false;
	int level=LOGLEVEL_WARNING;
	if(reportType==_CRT_ERROR) {
		level=LOGLEVEL_ERROR;
		doDebugBreak=true;
	} else if(reportType==_CRT_ASSERT) {
		level=LOGLEVEL_CRITICAL;
		doDebugBreak=true;
	}
	logMessage(level,message);
	if(doDebugBreak&&IsDebuggerPresent()) {
		_CrtDbgBreak();
	}
	*returnValue=0;
	return true;
}
// ------------------------------------------------------------------
void msvc_debugger_listener::error(Dereferee::error_code code, va_list args)
{
	char text[513];
	vsprintf(text, error_messages[code], args);
	CxxTest::__cxxtest_assertmsg = text;

	if(debugging)
	{
		void** bt = platform->get_backtrace(NULL, NULL);
		int bufsize = vsnprintf(NULL, 0, error_messages[code], args) + 1;
		char* buffer = (char*)malloc(bufsize);
		vsnprintf(buffer, bufsize, error_messages[code], args);

		char function[DEREFEREE_MAX_FUNCTION_LEN];
		char filename[DEREFEREE_MAX_FILENAME_LEN];
		int line_number;

		void *addr = bt[4];

		bool success = platform->get_backtrace_frame_info(
			addr, function, filename, &line_number);

		platform->free_backtrace(bt);

#ifdef _DEBUG
		if(1 == _CrtDbgReport(_CRT_ERROR, filename,
			line_number, _pgmptr, buffer))
			_CrtDbgBreak();
#endif

		free(buffer);
	}

	// Can't use abort() here because it hard-kills the process on Windows,
	// rather than raising a signal that would be caught so execution could
	// continue with the next test case. Instead, cause an access violation
	// that will be caught by the structured exception handler.
	int* x = 0;
	*x = 0xBADBEEF;
}
Example #15
0
void MyAssertTrap()
{
	_CrtDbgBreak();
}
Example #16
0
int main()
{
	_CrtDbgBreak();
	return 0;
}
Example #17
0
// prefast (6262): This func uses lots of stack because we want to tolerate very large reports, and we can't use malloc here.
int __cdecl _VCrtDbgReportA(
    int nRptType,
    void * returnAddress,
    char const* szFile,
    int nLine,
    char const* szModule,
    char const* szFormat,
    va_list arglist
    )
{
    int retval=0;
    int handled=FALSE;

    char    szLineMessage[DBGRPT_MAX_MSG]{0};
    char    szOutMessage [DBGRPT_MAX_MSG]{0};
    wchar_t szOutMessage2[DBGRPT_MAX_MSG]{0};
    char    szUserMessage[DBGRPT_MAX_MSG]{0};

    if (nRptType < 0 || nRptType >= _CRT_ERRCNT)
        return -1;

    /*
     * handle the (hopefully rare) case of
     *
     * 1) ASSERT while already dealing with an ASSERT
     *      or
     * 2) two threads asserting at the same time
     */

    __try
    {
        if (_CRT_ASSERT == nRptType && _InterlockedIncrement(&_crtAssertBusy) > 0)
        {
            /* use only 'safe' functions -- must not assert in here! */

            _ERRCHECK(_itoa_s(nLine, szLineMessage, DBGRPT_MAX_MSG, 10));

            OutputDebugStringA("Second Chance Assertion Failed: File ");
            OutputDebugStringA(szFile ? szFile : "<file unknown>");
            OutputDebugStringA(", Line ");
            OutputDebugStringA(szLineMessage);
            OutputDebugStringA("\n");

            _CrtDbgBreak();
            retval=-1;
            __leave;
        }

        // Leave space for ASSERTINTRO1 and "\r\n"
        if (szFormat)
        {
            int szlen = 0;
            _ERRCHECK_SPRINTF(szlen = _vsnprintf_s(szUserMessage, DBGRPT_MAX_MSG,
                                                    DBGRPT_MAX_MSG - 2- max(sizeof(ASSERTINTRO1),sizeof(ASSERTINTRO2)),
                                                    szFormat, arglist));
            if (szlen < 0)
            {
                _ERRCHECK(strcpy_s(szUserMessage, DBGRPT_MAX_MSG, DBGRPT_TOOLONGMSG));
            }
        }

        if (_CRT_ASSERT == nRptType)
        {
            _ERRCHECK(strcpy_s(szLineMessage, DBGRPT_MAX_MSG, szFormat ? ASSERTINTRO1 : ASSERTINTRO2));
        }

        _ERRCHECK(strcat_s(szLineMessage, DBGRPT_MAX_MSG, szUserMessage));

        if (_CRT_ASSERT == nRptType)
        {
            if (_CrtDbgMode[nRptType] & _CRTDBG_MODE_FILE)
            {
                _ERRCHECK(strcat_s(szLineMessage, DBGRPT_MAX_MSG, "\r"));
            }

            _ERRCHECK(strcat_s(szLineMessage, DBGRPT_MAX_MSG, "\n"));
        }

        if (szFile)
        {
            int szlen = 0;
            _ERRCHECK_SPRINTF(szlen = _snprintf_s(szOutMessage, DBGRPT_MAX_MSG, DBGRPT_MAX_MSG - 1, "%s(%d) : %s",
                                                    szFile, nLine, szLineMessage));
            if (szlen < 0)
            {
                _ERRCHECK(strcpy_s(szOutMessage, DBGRPT_MAX_MSG, DBGRPT_TOOLONGMSG));
            }
        }
        else
        {
            _ERRCHECK(strcpy_s(szOutMessage, DBGRPT_MAX_MSG, szLineMessage));
        }

        {
            size_t ret = 0;
            errno_t e = 0;
            _ERRCHECK_EINVAL_ERANGE(e = mbstowcs_s(&ret, szOutMessage2, DBGRPT_MAX_MSG, szOutMessage, _TRUNCATE));
            if(e != 0)
            {
                _ERRCHECK(wcscpy_s(szOutMessage2, DBGRPT_MAX_MSG, _CRT_WIDE(DBGRPT_INVALIDMSG)));
            }
        }

        /* User hook may handle report.
            We have to check the ANSI Hook2 List & then the UNICODE Hook2 List.
            Then we have check any ANSI individual Hook set through
            SetReportHook */

        if (_pReportHookList || _pReportHookListW)
        {
            __crt_report_hook_node<char> *pnode=nullptr;
            __crt_report_hook_node<wchar_t> *pnodeW=nullptr;

            __acrt_lock(__acrt_debug_lock);
            __try
            {
                for (pnode = _pReportHookList; pnode; pnode = pnode->next)
                {
                    int hook_retval=0;
                    if (pnode->hook(nRptType, szOutMessage, &hook_retval))
                    {
                        handled=TRUE;
                        retval=hook_retval;
                        __leave;
                    }
                }

                for (pnodeW = _pReportHookListW; pnodeW; pnodeW = pnodeW->next)
                {
                    int hook_retval=0;
                    if (pnodeW->hook(nRptType, szOutMessage2, &hook_retval))
                    {
                        handled=TRUE;
                        retval=hook_retval;
                        __leave;
                    }
                }
            }
            __finally
            {
                __acrt_unlock(__acrt_debug_lock);
            }
        }

        if (handled)
            __leave;

        if (_pfnReportHook)
        {
            int hook_retval=0;
            if (_pfnReportHook(nRptType, szOutMessage, &hook_retval))
            {
                retval = hook_retval;
                __leave;
            }
        }

        if (_CrtDbgMode[nRptType] & _CRTDBG_MODE_FILE)
        {
            if (_CrtDbgFile[nRptType] != _CRTDBG_INVALID_HFILE)
            {
                DWORD bytes_written = 0;
                WriteFile(_CrtDbgFile[nRptType], szOutMessage, static_cast<DWORD>(strlen(szOutMessage)), &bytes_written, nullptr);
            }
        }

        if (_CrtDbgMode[nRptType] & _CRTDBG_MODE_DEBUG)
        {
            OutputDebugStringA(szOutMessage);
        }

        if (_CrtDbgMode[nRptType] & _CRTDBG_MODE_WNDW)
        {
            szLineMessage[0] = 0;
            if (nLine)
            {
                _ERRCHECK(_itoa_s(nLine, szLineMessage, DBGRPT_MAX_MSG, 10));
            }

            retval = __acrt_MessageWindowA(nRptType, returnAddress, szFile, (nLine ? szLineMessage : nullptr), szModule, szUserMessage);
        }
    }
    void exec_ctxt(MCExecContext &ctxt)
	{
#if defined(WIN32) && defined(_DEBUG)
		_CrtDbgBreak();
#endif;
	}
Example #19
0
void MyAssertTrap()
{
	HooksUnlocker;
	_CrtDbgBreak();
}
Example #20
0
void CMraProto::MraAvatarsThreadProc(LPVOID lpParameter)
{
	MRA_AVATARS_QUEUE *pmraaqAvatarsQueue = (MRA_AVATARS_QUEUE*)lpParameter;
	MRA_AVATARS_QUEUE_ITEM *pmraaqiAvatarsQueueItem;

	CMStringA szEmail, szServer;
	CMStringW wszFileName;
	BOOL bContinue, bKeepAlive, bUseKeepAliveConn, bFailed, bDownloadNew, bDefaultAvt;
	BYTE btBuff[BUFF_SIZE_RCV];
	DWORD dwResultCode, dwAvatarFormat, dwReceived, dwServerPort, dwErrorCode;
	size_t dwAvatarSizeServer;
	FILETIME ftLastModifiedTimeServer, ftLastModifiedTimeLocal;
	SYSTEMTIME stAvatarLastModifiedTimeLocal;
	HANDLE hConnection = NULL;
	NETLIBSELECT nls = { 0 };
	INTERNET_TIME itAvatarLastModifiedTimeServer;
	PROTO_AVATAR_INFORMATIONT pai;
	WCHAR szErrorText[2048];

	nls.cbSize = sizeof(nls);
	pai.cbSize = sizeof(pai);

	InterlockedIncrement((volatile LONG*)&pmraaqAvatarsQueue->lThreadsRunningCount);

	while (InterlockedExchangeAdd((volatile LONG*)&pmraaqAvatarsQueue->bIsRunning, 0)) {
		if (FifoMTItemPop(pmraaqAvatarsQueue, NULL, (LPVOID*)&pmraaqiAvatarsQueueItem) != NO_ERROR) { // waiting until service stop or new task
			NETLIB_CLOSEHANDLE(hConnection);
			WaitForSingleObjectEx(pmraaqAvatarsQueue->hThreadEvent, MRA_AVT_DEFAULT_QE_CHK_INTERVAL, FALSE);
			continue;
		}
		/* Try download. */
		bFailed = TRUE;
		bDownloadNew = FALSE;
		bDefaultAvt = FALSE;

		if (!DB_GetStringA(NULL, MRA_AVT_SECT_NAME, "Server", szServer))
			szServer = MRA_AVT_DEFAULT_SERVER;
		dwServerPort = db_get_dw(NULL, MRA_AVT_SECT_NAME, "ServerPort", MRA_AVT_DEFAULT_SERVER_PORT);
		bUseKeepAliveConn = db_get_b(NULL, MRA_AVT_SECT_NAME, "UseKeepAliveConn", MRA_AVT_DEFAULT_USE_KEEPALIVE_CONN);

		if (mraGetStringA(pmraaqiAvatarsQueueItem->hContact, "e-mail", szEmail)) {
			szEmail.MakeLower();

			int iStart = 0;
			CMStringA szUser = szEmail.Tokenize("@", iStart);
			CMStringA szDomain = szEmail.Tokenize("@", iStart);
			if (!szUser.IsEmpty() && !szDomain.IsEmpty()) {
				ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_CONNECTING, NULL, 0);
				if (hConnection == NULL)
					hConnection = MraAvatarsHttpConnect(pmraaqAvatarsQueue->hNetlibUser, szServer, dwServerPort);
				if (hConnection) {
					ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_CONNECTED, NULL, 0);
					ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_SENTREQUEST, NULL, 0);
					if (!MraAvatarsHttpTransaction(hConnection, REQUEST_HEAD, szUser, szDomain, szServer, MAHTRO_AVTMRIM, bUseKeepAliveConn, &dwResultCode, &bKeepAlive, &dwAvatarFormat, &dwAvatarSizeServer, &itAvatarLastModifiedTimeServer)) {
						switch (dwResultCode) {
						case 200:
							if (MraAvatarsGetContactTime(pmraaqiAvatarsQueueItem->hContact, "AvatarLastModifiedTime", &stAvatarLastModifiedTimeLocal)) {
								SystemTimeToFileTime(&itAvatarLastModifiedTimeServer.stTime, &ftLastModifiedTimeServer);
								SystemTimeToFileTime(&stAvatarLastModifiedTimeLocal, &ftLastModifiedTimeLocal);

								if ((*((DWORDLONG*)&ftLastModifiedTimeServer)) != (*((DWORDLONG*)&ftLastModifiedTimeLocal))) {// need check for update
									bDownloadNew = TRUE;
									//ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_STATUS, 0, 0);
								}
								else {// avatar is valid
									if (MraAvatarsGetFileName(pmraaqAvatarsQueue, pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat, wszFileName) == NO_ERROR) {
										if (IsFileExist(wszFileName))
											bFailed = FALSE;
										else
											bDownloadNew = TRUE;
									}
								}
							}
							else // need update
								bDownloadNew = TRUE;

							break;
						case 404:// return def avatar
							if (MraAvatarsGetFileName((HANDLE)pmraaqAvatarsQueue, NULL, PA_FORMAT_DEFAULT, wszFileName) == NO_ERROR) {
								if (IsFileExist(wszFileName)) {
									dwAvatarFormat = ProtoGetAvatarFormat(wszFileName);
									bFailed = FALSE;
								}
								else//loading default avatar
									bDownloadNew = TRUE;

								bDefaultAvt = TRUE;
							}
							break;

						default:
							mir_sntprintf(szErrorText, SIZEOF(szErrorText), TranslateT("Avatars: server return HTTP code: %lu"), dwResultCode);
							ShowFormattedErrorMessage(szErrorText, NO_ERROR);
							break;
						}
					}
					if (bUseKeepAliveConn == FALSE || bKeepAlive == FALSE) NETLIB_CLOSEHANDLE(hConnection);
				}

				if (bDownloadNew) {
					if (hConnection == NULL)
						hConnection = MraAvatarsHttpConnect(pmraaqAvatarsQueue->hNetlibUser, szServer, dwServerPort);

					if (hConnection) {
						ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_DATA, NULL, 0);
						if (MraAvatarsHttpTransaction(hConnection, REQUEST_GET, szUser, szDomain, szServer, MAHTRO_AVT, bUseKeepAliveConn, &dwResultCode, &bKeepAlive, &dwAvatarFormat, &dwAvatarSizeServer, &itAvatarLastModifiedTimeServer) == NO_ERROR && dwResultCode == 200) {
							if (bDefaultAvt)
								dwAvatarFormat = PA_FORMAT_DEFAULT;

							if (!MraAvatarsGetFileName(pmraaqAvatarsQueue, pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat, wszFileName)) {
								HANDLE hFile = CreateFile(wszFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
								if (hFile != INVALID_HANDLE_VALUE) {
									DWORD dwWritten = 0;
									bContinue = TRUE;
									nls.dwTimeout = (1000 * db_get_dw(NULL, MRA_AVT_SECT_NAME, "TimeOutReceive", MRA_AVT_DEFAULT_TIMEOUT_RECV));
									nls.hReadConns[0] = hConnection;

									while (bContinue) {
										switch (CallService(MS_NETLIB_SELECT, 0, (LPARAM)&nls)) {
										case SOCKET_ERROR:
										case 0:// Time out
											dwErrorCode = GetLastError();
											ShowFormattedErrorMessage(L"Avatars: error on receive file data", dwErrorCode);
											bContinue = FALSE;
											break;
										case 1:
											dwReceived = Netlib_Recv(hConnection, (LPSTR)&btBuff, SIZEOF(btBuff), 0);
											if (dwReceived == 0 || dwReceived == SOCKET_ERROR) {
												dwErrorCode = GetLastError();
												ShowFormattedErrorMessage(L"Avatars: error on receive file data", dwErrorCode);
												bContinue = FALSE;
											}
											else {
												if (WriteFile(hFile, (LPVOID)&btBuff, dwReceived, &dwReceived, NULL)) {
													dwWritten += dwReceived;
													if (dwWritten >= dwAvatarSizeServer)
														bContinue = FALSE;
												}
												else {
													dwErrorCode = GetLastError();
													ShowFormattedErrorMessage(L"Avatars: cant write file data, error", dwErrorCode);
													bContinue = FALSE;
												}
											}
											break;
										}
									}
									CloseHandle(hFile);
									bFailed = FALSE;
								}
								else {
									dwErrorCode = GetLastError();
									mir_sntprintf(szErrorText, SIZEOF(szErrorText), TranslateT("Avatars: can't open file %s, error"), wszFileName);
									ShowFormattedErrorMessage(szErrorText, dwErrorCode);
								}
							}
						}
						else _CrtDbgBreak();

						if (bUseKeepAliveConn == FALSE || bKeepAlive == FALSE)
							NETLIB_CLOSEHANDLE(hConnection);
					}
				}
			}
		}

		if (bFailed) {
			DeleteFile(wszFileName);
			pai.hContact = pmraaqiAvatarsQueueItem->hContact;
			pai.format = PA_FORMAT_UNKNOWN;
			pai.filename[0] = 0;
			ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_FAILED, (HANDLE)&pai, 0);
		}
		else {
			pai.hContact = pmraaqiAvatarsQueueItem->hContact;
			pai.format = dwAvatarFormat;
			if (db_get_b(NULL, MRA_AVT_SECT_NAME, "ReturnAbsolutePath", MRA_AVT_DEFAULT_RET_ABC_PATH))
				lstrcpyn(pai.filename, wszFileName, SIZEOF(pai.filename));
			else
				PathToRelativeT(wszFileName, pai.filename);

			if (bDefaultAvt) dwAvatarFormat = PA_FORMAT_DEFAULT;
			SetContactAvatarFormat(pmraaqiAvatarsQueueItem->hContact, dwAvatarFormat);
			MraAvatarsSetContactTime(pmraaqiAvatarsQueueItem->hContact, "AvatarLastModifiedTime", &itAvatarLastModifiedTimeServer.stTime);
			// write owner avatar file name to DB
			if (pmraaqiAvatarsQueueItem->hContact == NULL) // proto avatar
				CallService(MS_AV_REPORTMYAVATARCHANGED, (WPARAM)m_szModuleName, 0);

			ProtoBroadcastAck(pmraaqiAvatarsQueueItem->hContact, ACKTYPE_AVATAR, ACKRESULT_SUCCESS, (HANDLE)&pai, 0);
		}
		mir_free(pmraaqiAvatarsQueueItem);
	}

	InterlockedDecrement((volatile LONG*)&pmraaqAvatarsQueue->lThreadsRunningCount);
}
Example #21
0
DWORD CMraProto::MraMrimProxyConnect(HANDLE hMraMrimProxyData, HANDLE *phConnection)
{
	DWORD dwRetErrorCode;

	if (hMraMrimProxyData && phConnection) {
		BOOL bIsHTTPSProxyUsed, bContinue;
		BYTE lpbBufferRcv[BUFF_SIZE_RCV_MIN_FREE];
		DWORD dwBytesReceived, dwConnectReTryCount, dwCurConnectReTryCount;
		size_t dwRcvBuffSize = BUFF_SIZE_RCV_MIN_FREE, dwRcvBuffSizeUsed;
		NETLIBSELECT nls = {0};
		MRA_MRIMPROXY_DATA *pmmpd = (MRA_MRIMPROXY_DATA*)hMraMrimProxyData;
		NETLIBOPENCONNECTION nloc = {0};

		// адреса есть, значит инициаторы не мы
		if (pmmpd->malAddrList.dwAddrCount) {
			CMStringA szAddresses = MraAddrListGetToBuff(&pmmpd->malAddrList);
			MraProxyAck(PROXY_STATUS_OK, pmmpd->szEmail, pmmpd->dwIDRequest, pmmpd->dwDataType, pmmpd->lpszUserData, szAddresses, pmmpd->mguidSessionID);
		}
		// мы инициаторы
		else {
			pmmpd->hWaitHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
			if (pmmpd->szEmail)
			if (MraProxy(pmmpd->szEmail, pmmpd->dwIDRequest, pmmpd->dwDataType, pmmpd->lpszUserData, "", pmmpd->mguidSessionID))
				WaitForSingleObjectEx(pmmpd->hWaitHandle, INFINITE, FALSE);

			CloseHandle(pmmpd->hWaitHandle);
			pmmpd->hWaitHandle = NULL;
		}

		dwRetErrorCode = ERROR_NO_NETWORK;
		if (pmmpd->malAddrList.dwAddrCount) {
			pmmpd->hConnection = NULL;
			bIsHTTPSProxyUsed = IsHTTPSProxyUsed(m_hNetlibUser);
			dwConnectReTryCount = getDword("ConnectReTryCountMRIMProxy", MRA_DEFAULT_CONN_RETRY_COUNT_MRIMPROXY);
			nloc.cbSize = sizeof(nloc);
			nloc.flags = NLOCF_V2;
			nloc.timeout = ((MRA_TIMEOUT_DIRECT_CONN-1)/(pmmpd->malAddrList.dwAddrCount*dwConnectReTryCount));// -1 сек чтобы был запас
			if (nloc.timeout < MRA_TIMEOUT_CONN_MIN) nloc.timeout = MRA_TIMEOUT_CONN_MIN;
			if (nloc.timeout > MRA_TIMEOUT_CONN_MAX) nloc.timeout = MRA_TIMEOUT_CONN_MAX;

			// Set up the sockaddr structure
			for (size_t i = 0; i < pmmpd->malAddrList.dwAddrCount && dwRetErrorCode != NO_ERROR; i++) {
				// через https прокси только 443 порт
				if ((pmmpd->malAddrList.pMailAddress[i].dwPort == MRA_SERVER_PORT_HTTPS && bIsHTTPSProxyUsed) || bIsHTTPSProxyUsed == FALSE) {
					if (pmmpd->dwDataType == MRIM_PROXY_TYPE_FILES)
						ProtoBroadcastAck(MraHContactFromEmail(pmmpd->szEmail, FALSE, TRUE, NULL), ACKTYPE_FILE, ACKRESULT_CONNECTING, (HANDLE)pmmpd->dwIDRequest, 0);

					nloc.szHost = inet_ntoa((*((in_addr*)&pmmpd->malAddrList.pMailAddress[i].dwAddr)));
					nloc.wPort = (WORD)pmmpd->malAddrList.pMailAddress[i].dwPort;

					dwCurConnectReTryCount = dwConnectReTryCount;
					do {
						pmmpd->hConnection = (HANDLE)CallService(MS_NETLIB_OPENCONNECTION, (WPARAM)m_hNetlibUser, (LPARAM)&nloc);
					}
						while (--dwCurConnectReTryCount && pmmpd->hConnection == NULL);

					if (pmmpd->hConnection) {
						nls.cbSize = sizeof(nls);
						nls.dwTimeout = (MRA_TIMEOUT_DIRECT_CONN*1000*2);
						nls.hReadConns[0] = pmmpd->hConnection;
						bContinue = TRUE;
						dwRcvBuffSizeUsed = 0;

						if (pmmpd->dwDataType == MRIM_PROXY_TYPE_FILES)
							ProtoBroadcastAck(MraHContactFromEmail(pmmpd->szEmail, FALSE, TRUE, NULL), ACKTYPE_FILE, ACKRESULT_CONNECTED, (HANDLE)pmmpd->dwIDRequest, 0);
						MraSendPacket(nls.hReadConns[0], 0, MRIM_CS_PROXY_HELLO, &pmmpd->mguidSessionID, sizeof(MRA_GUID));

						while (bContinue) {
							switch (CallService(MS_NETLIB_SELECT, 0, (LPARAM)&nls)) {
							case SOCKET_ERROR:
							case 0:// Time out
								dwRetErrorCode = GetLastError();
								ShowFormattedErrorMessage(L"Disconnected, socket error", dwRetErrorCode);
								bContinue = FALSE;
								break;

							case 1:
								if (dwRcvBuffSizeUsed == BUFF_SIZE_RCV_MIN_FREE) { // bad packet
									bContinue = FALSE;
									_CrtDbgBreak();
								}
								else {
									dwBytesReceived = Netlib_Recv(nls.hReadConns[0], (LPSTR)(lpbBufferRcv + dwRcvBuffSizeUsed), (int)(dwRcvBuffSize - dwRcvBuffSizeUsed), 0);
									if (dwBytesReceived && dwBytesReceived != SOCKET_ERROR) { // connected
										dwRcvBuffSizeUsed += dwBytesReceived;
										if (dwRcvBuffSizeUsed >= sizeof(mrim_packet_header_t)) { // packet header received
											if (((mrim_packet_header_t*)lpbBufferRcv)->magic == CS_MAGIC) { // packet OK
												if ((dwRcvBuffSizeUsed-sizeof(mrim_packet_header_t)) >= ((mrim_packet_header_t*)lpbBufferRcv)->dlen) { // full packet received, may be more than one
													if (((mrim_packet_header_t*)lpbBufferRcv)->msg == MRIM_CS_PROXY_HELLO_ACK) // connect OK!
														dwRetErrorCode = NO_ERROR;
													else // bad/wrong
														_CrtDbgBreak();

													bContinue = FALSE;
												}
												else // not all packet received, continue receiving
													debugLogA("Not all packet received, continue receiving\n");
											}
											else  { // bad packet
												debugLogA("Bad packet\n");
												_ASSERT(false);
												bContinue = FALSE;
											}
										}
										else // packet too small, continue receiving
											debugLogA("Packet to small, continue receiving\n");
									}
									else { // disconnected
										dwRetErrorCode = GetLastError();
										ShowFormattedErrorMessage(L"Disconnected, socket read error", dwRetErrorCode);
										bContinue = FALSE;
									}
								}
								break;
							}// end switch
						}// end while
					}
					else dwRetErrorCode = GetLastError();
				}// filtered
			}// end for

			if (dwRetErrorCode != NO_ERROR) // кажется не туда подключились :)
				NETLIB_CLOSEHANDLE(pmmpd->hConnection);
		}
		*phConnection = pmmpd->hConnection;
	}
	else dwRetErrorCode = ERROR_INVALID_HANDLE;
	return dwRetErrorCode;
}
Example #22
0
// Override the default behavior for assertion failures to break into the
// debugger.
int __cdecl CrtDbgHook(int nReportType, char* szMsg, int* pnRet) {
  // Break into the debugger, and then report that the exception was handled.
  _CrtDbgBreak();
  return TRUE;
}