示例#1
0
文件: dirmod.c 项目: 50wu/gpdb
/*
 *	pgsymlink - uses Win32 junction points
 *
 *	For reference:	http://www.codeproject.com/KB/winsdk/junctionpoints.aspx
 */
int
pgsymlink(const char *oldpath, const char *newpath)
{
	HANDLE		dirhandle;
	DWORD		len;
	char		buffer[MAX_PATH * sizeof(WCHAR) + sizeof(REPARSE_JUNCTION_DATA_BUFFER)];
	char		nativeTarget[MAX_PATH];
	char	   *p = nativeTarget;
	REPARSE_JUNCTION_DATA_BUFFER *reparseBuf = (REPARSE_JUNCTION_DATA_BUFFER *) buffer;

	CreateDirectory(newpath, 0);
	dirhandle = CreateFile(newpath, GENERIC_READ | GENERIC_WRITE,
						   0, 0, OPEN_EXISTING,
			   FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0);

	if (dirhandle == INVALID_HANDLE_VALUE)
		return -1;

	/* make sure we have an unparsed native win32 path */
	if (memcmp("\\??\\", oldpath, 4))
		sprintf(nativeTarget, "\\??\\%s", oldpath);
	else
		strcpy(nativeTarget, oldpath);

	while ((p = strchr(p, '/')) != 0)
		*p++ = '\\';

	len = strlen(nativeTarget) * sizeof(WCHAR);
	reparseBuf->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
	reparseBuf->ReparseDataLength = len + 12;
	reparseBuf->Reserved = 0;
	reparseBuf->SubstituteNameOffset = 0;
	reparseBuf->SubstituteNameLength = len;
	reparseBuf->PrintNameOffset = len + sizeof(WCHAR);
	reparseBuf->PrintNameLength = 0;
	MultiByteToWideChar(CP_ACP, 0, nativeTarget, -1,
						reparseBuf->PathBuffer, MAX_PATH);

	/*
	 * FSCTL_SET_REPARSE_POINT is coded differently depending on SDK version;
	 * we use our own definition
	 */
	if (!DeviceIoControl(dirhandle,
	 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 41, METHOD_BUFFERED, FILE_ANY_ACCESS),
						 reparseBuf,
	reparseBuf->ReparseDataLength + REPARSE_JUNCTION_DATA_BUFFER_HEADER_SIZE,
						 0, 0, &len, 0))
	{
		LPSTR		msg;

		errno = 0;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
					  NULL, GetLastError(),
					  MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
					  (LPSTR) &msg, 0, NULL);
#ifndef FRONTEND
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not set junction for \"%s\": %s",
						nativeTarget, msg)));
#else
		fprintf(stderr, _("could not set junction for \"%s\": %s\n"),
				nativeTarget, msg);
#endif
		LocalFree(msg);

		CloseHandle(dirhandle);
		RemoveDirectory(newpath);
		return -1;
	}

	CloseHandle(dirhandle);

	return 0;
}
示例#2
0
void image::restoreImage() 
{
	openRestoreDrives();

	BYTE* buffer = new BYTE[bufferSize];
	LPDWORD bytesRead = new DWORD();
		
	*bytesRead = bufferSize;
	dCompress* comp; 
	comp= new dCompress();
	BYTE* outbuff;
	int outbuffersize;//  = 10000;
	int returnread = 0;
	int returnwrite = 0;
	char message[200];
	int tValue;

	long readSize = 0;
	long writeSize = 0;

	//DWORD *written = 0;
	while (*bytesRead != 0)
	{
		returnread = ReadFile(hFile[0],buffer,bufferSize,bytesRead,NULL);
		//cout << "return read: " << returnread << endl;
		//FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),0, message,200,NULL);
		//cout << "Message: " << message << endl;

		if (buffer [*bytesRead - 1] == (0xFF))
		{
			if ((buffer [*bytesRead -2] == (0xFE)) && (buffer [*bytesRead-3 ] == 0xFF))
			{
				SetFilePointer(hFile[0],-3,NULL,FILE_CURRENT);
				*bytesRead -= 3;			
			}	
			else
			{
				SetFilePointer(hFile[0],-1,NULL,FILE_CURRENT);
				*bytesRead -= 1;
			}		
		}
			
		if	(buffer [*bytesRead - 2] == (0xFF))
		{
			SetFilePointer(hFile[0],-2,NULL,FILE_CURRENT);
			*bytesRead -= 2;
		}
		
		comp-> uData(((BYTE*)buffer),*bytesRead, &outbuff, &outbuffersize); 
		cout << "ResoreImage, Initial: " << *bytesRead << " Final: " << outbuffersize << " ";

		readSize += *bytesRead;
		writeSize += outbuffersize;

		tValue = outbuffersize - 500;
		while (tValue > 0)
		{
			cout << "*";
			tValue -= 100;
		}

		cout << endl;

		 *bytesRead = outbuffersize; //this was here 
		//returnwrite = WriteFile(hFile[1],outbuff,outbuffersize,bytesRead,NULL);//this is the correct one
	    //returnwrite = WriteFile(hFile[1],buffer,bufferSize,bytesRead,NULL);//origial code
		//returnwrite = WriteFile(hFile[1],buffer,outbuffersize,bytesRead,NULL);//fails to read		
		 //cout << "Buffer size: " << outbuffersize << endl;
		cout <<"Read in : "<< *bytesRead<< endl;

/*			cout << "File: " << hFile[1] << endl
				 << "Buffer: \"" << outbuff << "\"" << endl
				 << "oBuffSize: " << outbuffersize << endl;
//				 << "bytesWritten: " << *bytesRead << endl;*/
		returnwrite = WriteFile(hFile[1],outbuff,outbuffersize,bytesRead,NULL);//this is correct!!
		cout <<"Read in after Write: "<< *bytesRead<< endl;
		cout << "return write: " << returnwrite << "  bytesRead: " << *bytesRead << endl;
		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),0, message,200,NULL);
		cout << "Error Message : " << message << endl;

		//if (false == returnwrite)
		//{
//			cout << "File: " << hFile[1] << endl
				// << "Buffer: \"" << outbuff << "\"" << endl
//				 << "oBuffSize: " << outbuffersize << endl
//				 << "bytesWritten: " << *bytesRead << endl;
		//}

		//dumpbyte(outbuff,10);
		//dumpbyte(outbuff+(outbuffersize-10),10);

		delete[] outbuff;

		//as long as bytesRead==sectorSize the commands
		//completed successfully
	}	
	delete bytesRead;
	delete [] buffer;

	cout << readSize << " bytes read from image file" << endl;
	cout << writeSize << " bytes written to drive" << endl;
	cout << "Compression: " << (readSize/(double)writeSize)*100 << "%" << endl;

	CloseHandle(hFile[0]); Inform ("Source File Closed   ");
	CloseHandle(hFile[1]); Inform ("Destination File Closed   ");
}
bool CCodeProcessor::TryBuild( const char *rootdir, const char *filename, unsigned char *buffer, int filelength )
{
//	vprintf( "trying build\n" );

	FILE *fp;
	fp = fopen( filename, "wb" );
	if ( !fp )
	{
		assert( 0 );
		return false;
	}

	fwrite( buffer, filelength, 1, fp );
	fclose( fp );

	// if build is successful, return true
	//
	//	return true;
	char commandline[ 512 ];
	char directory[ 512 ];

	sprintf( directory, rootdir );

	//	sprintf( commandline, "msdev engdll.dsw /MAKE \"quiver - Win32 GL Debug\" /OUT log.txt" );

	// Builds the default configuration
	sprintf( commandline, "\"C:\\Program Files\\Microsoft Visual Studio\\Common\\MSDev98\\Bin\\msdev.exe\" %s /MAKE \"%s\" /OUT log.txt", m_szDSP, m_szConfig );

	PROCESS_INFORMATION pi;
	memset( &pi, 0, sizeof( pi ) );

	STARTUPINFO si;
	memset( &si, 0, sizeof( si ) );
	si.cb = sizeof( si );

	if ( !CreateProcess( NULL, commandline, NULL, NULL, TRUE, 0, NULL, directory, &si, &pi ) )
	{
LPVOID lpMsgBuf;
FormatMessage( 
    FORMAT_MESSAGE_ALLOCATE_BUFFER | 
    FORMAT_MESSAGE_FROM_SYSTEM | 
    FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
    (LPTSTR) &lpMsgBuf,
    0,
    NULL 
);
// Process any inserts in lpMsgBuf.
// ...
// Display the string.
MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
// Free the buffer.
LocalFree( lpMsgBuf );
		return false;
	}

	// Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

	bool retval = false;
	DWORD exitCode = -1;
	if ( GetExitCodeProcess( pi.hProcess, &exitCode ) )
	{
		if ( !exitCode )
		{
			retval = true;
		}
	}
	
    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );

	return retval;
}
示例#4
0
bool UpdateXMLData(const Category cat, const char *redirect_url /*= 0*/, int recurse_count /*=0*/) {
	
	if(recurse_count > MAX_REDIRECT_RECURSE) {
		PUShowMessageT(TranslateT("Updater: Error getting data - too many redirects"), SM_WARNING);
		return false;
	}

	NETLIBHTTPREQUEST req = {0};
	NETLIBHTTPHEADER etag_hdr = {0};

	if(OldXMLDataExists(cat)) {
		// ensure backend not checked more than once every MIN_XMLDATA_AGE hours
		long age = OldXMLDataAge(cat);
		if(age >= 0 && age < MIN_XMLDATA_AGE)	{	// get it only if our file is at least 8 hours old
#ifdef DEBUG_HTTP_POPUPS
			char buff[512];
			sprintf(buff, "XML Data is recent (%d hours old) - not downloading, using local copy", age);
			PUShowMessage(buff, SM_NOTIFY);
#endif

			return LoadOldXMLData(cat, false);
		}

		// add ETag header for conditional get
		DBCONTACTGETSETTING cgs;
		DBVARIANT dbv;
		cgs.szModule = MODULE;
		char buff[256];
		strcpy(buff, "DataETag_");
		strcat(buff, category_files[cat]);
		cgs.szSetting = buff;
		cgs.pValue = &dbv;
		if(!CallService(MS_DB_CONTACT_GETSETTING, 0, (LPARAM)&cgs)) {
			req.headersCount = 1;
			req.headers = &etag_hdr;
			etag_hdr.szName = "If-None-Match";
			etag_hdr.szValue = _strdup(dbv.pszVal);
			DBFreeVariant(&dbv);
		}
	}

	req.cbSize = sizeof(req);
	req.requestType = REQUEST_GET;
	char URL[MAX_PATH];
	if(!redirect_url) {
		strcpy(URL, MIM_BACKEND_URL_PREFIX);
		strcat(URL, category_files[cat]);
		strcat(URL, ".bz2");
	} else {
		strcpy(URL, redirect_url);
	}
	req.szUrl = URL;
	req.flags = NLHRF_HTTP11;
	req.nlc = hNetlibHttp;

	if (CallService(MS_SYSTEM_GETVERSION, 0, 0) >= PLUGIN_MAKE_VERSION(0,9,0,5))
		req.flags |= NLHRF_PERSISTENT | NLHRF_REDIRECT;

	NETLIBHTTPREQUEST *resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)hNetlibUser, (LPARAM)&req);
	free(etag_hdr.szValue);

	if (!resp) 
	{
		hNetlibHttp = NULL;
		if (!Miranda_Terminated())
		{
			int err = GetLastError();
			if (err) 
			{
				TCHAR buff[512];
				int len = mir_sntprintf(buff, SIZEOF(buff), TranslateT("Failed to download XML data: "));
				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, err, 0, buff + len, 512 - len, 0);
				ShowError(buff);
				//MessageBox(0, buff + len, TranslateT("Updater: Error Downloading XML Data"), MB_OK | MB_ICONWARNING);
			} 
			else 
			{
				ShowError(TranslateT("Failed to download XML data - Response is NULL"));
				//MessageBox(0, TranslateT("Error downloading XML data...\nResponse is NULL"), TranslateT("Updater Error"), MB_OK | MB_ICONWARNING);
				NLog("Failed to download XML data - Response is NULL");
			}
		}
		return LoadOldXMLData(cat, false);
	} 
	else if (resp->resultCode == 304) { // 'Not Modified' response
		hNetlibHttp = resp->nlc;
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
		resp = 0;
#ifdef DEBUG_HTTP_POPUPS
		PUShowMessage("XML Data unchanged - using local copy", SM_NOTIFY);
#endif

		// mark data as current
		return LoadOldXMLData(cat, true);
	} else if(resp->resultCode >= 300 && resp->resultCode < 400) { // redirect response
		hNetlibHttp = resp->nlc;
		// get new location
		bool ret = false;
		for(int i = 0; i < resp->headersCount; i++) {
			//MessageBox(0, resp->headers[i].szValue, resp->headers[i].szName, MB_OK);
			if(strcmp(resp->headers[i].szName, "Location") == 0) {
				ret = UpdateXMLData(cat, resp->headers[i].szValue, recurse_count + 1);
				break;
			}
		}
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
		resp = 0;
		if(!ret) return LoadOldXMLData(cat, false);

		return ret;

	} else if(resp->resultCode != 200) {
		hNetlibHttp = resp->nlc;
		TCHAR buff[512];
		mir_sntprintf(buff, SIZEOF(buff), TranslateT("Failed to download XML data - Invalid response, code %d"), resp->resultCode);
		ShowError(buff);
		NLog(buff);
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
		resp = 0;
		return LoadOldXMLData(cat, false);
	}
		
	// resp->resultCode == 200
	hNetlibHttp = resp->nlc;

	if(!bz2_decompress_xml(resp->pData, resp->dataLength, &pData[cat], &dataLength[cat])) {
		ShowError(TranslateT("Failed to decompress XML data"));
		CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
		resp = 0;
		return LoadOldXMLData(cat, false);
	}

	// store date header and data for response 'Not Modified' (304) above
	for(int i = 0; i < resp->headersCount; i++) {
		//MessageBox(0, resp->headers[i].szValue, resp->headers[i].szName, MB_OK);
		if(strcmp(resp->headers[i].szName, "ETag") == 0) {
			//MessageBox(0, resp->headers[i].szValue, "Storing ETag", MB_OK);
			char buff[256];
			strcpy(buff, "DataETag_");
			strcat(buff, category_files[cat]);
			DBWriteContactSettingString(0, MODULE, buff, resp->headers[i].szValue);
		}
	}

	CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
	resp = 0;

	SaveXMLData(cat);

	doc[cat] = ezxml_parse_str((char*)pData[cat], strlen((char*)pData[cat]));
	if (!doc[cat]) return false;

	return true;
}
/////////////////////////////////////////////////////////////////////////////
//++
//
//  FormatError
//
//  Description:
//      Format an error.
//
//  Arguments:
//      rstrError   String in which to return the error message.
//      dwError     Error code to format.
//
//  Return Value:
//      None.
//
//--
/////////////////////////////////////////////////////////////////////////////
void
FormatError(
      CString & rstrErrorInout
    , DWORD     dwErrorIn
    )
{
    DWORD   cch;
    TCHAR   szError[ 512 ];

    //
    // Format the NT status code from CLUSAPI.  This is necessary
    // for the cases where cluster messages haven't been added to
    // the system message file yet.
    //

    cch = FormatMessage(
                      FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS
                    , ::GetModuleHandle( _T( "CLUSAPI.DLL" ) )
                    , dwErrorIn
                    , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
                    , szError
                    , RTL_NUMBER_OF( szError )
                    , 0
                    );
    if ( cch == 0 )
    {
        cch = FormatMessage(
                          FORMAT_MESSAGE_FROM_SYSTEM
                        , NULL
                        , dwErrorIn
                        , MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL )
                        , szError
                        , RTL_NUMBER_OF( szError )
                        , 0
                        );
        if ( cch == 0 )
        {
            //
            // Format the NT status code from NTDLL since this hasn't been
            // integrated into the system yet.
            //

            cch = FormatMessage(
                              FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS
                            , ::GetModuleHandle( _T( "NTDLL.DLL" ) )
                            , dwErrorIn
                            , MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)
                            , szError
                            , RTL_NUMBER_OF( szError )
                            , 0
                            );
        }  // if:  error formatting status code from system
    }  // if:  error formatting status code from ClusApi

    if ( cch > 0 )
    {
        rstrErrorInout = szError;
    }  // if:  no error
    else
    {
        TRACE( _T( "FormatError() - Error 0x%08.8x formatting string for error code 0x%08.8x\n" ), GetLastError(), dwErrorIn );
        rstrErrorInout.Format( _T( "Error 0x%08.8x" ), dwErrorIn );
    }  // else:  error formatting the message

}  //*** FormatError
static void Fatal(DWORD dw, wchar_t* message, ...) 
{
	void *lpDisplayBuf, *lpMsgBuf;
	
	if(dw == 0) {
		// If no return code was specified, we assume that the message
		// contains a function name that failed. In that case, we retrieve
		// the system error message for the last-error code
		dw = GetLastError();
		
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			dw,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(wchar_t*) &lpMsgBuf,
			0,
			NULL
		);

		// Allocate our buffer for the error message.
		lpDisplayBuf = (void*)LocalAlloc(
			LMEM_ZEROINIT,
			(lstrlenW((const wchar_t*)lpMsgBuf) + lstrlenW((const wchar_t*)message) + 47) * sizeof(wchar_t)
		);
		_snwprintf(
			(wchar_t*)lpDisplayBuf,
			LocalSize(lpDisplayBuf) / sizeof(wchar_t),
			L"FATAL: %s failed with error %d: %s",
			message,
			dw,
			lpMsgBuf
		);
	} else {
		// Otherwise, we assume that the error message is a format string.
		va_list args = NULL;
		
		// Allocate buffer for our resulting format string.
		lpMsgBuf = (void*)LocalAlloc(
			LMEM_ZEROINIT,
			(lstrlenW((const wchar_t*)message) + 8) * sizeof(wchar_t)
		);
		_snwprintf(
			(wchar_t*)lpMsgBuf,
			LocalSize(lpMsgBuf) / sizeof(wchar_t),
			L"FATAL: %s",
			message
		);
		
		// Might as well use the maximum allowed buffer, since there's no way I know of the
		// get the size of the resulting buff.
		lpDisplayBuf = (void*)LocalAlloc(LMEM_ZEROINIT, 4096 * sizeof(wchar_t));
		memset(lpDisplayBuf, 0, 4096 * sizeof(wchar_t));
		va_start(args, lpMsgBuf);
		_vsnwprintf(
			(wchar_t*)lpDisplayBuf,
			4096,
			lpMsgBuf,
			args
		);
		va_end(args);
	}
	MessageBoxW(NULL, (const wchar_t*)lpDisplayBuf, L"Fatal Error", MB_OK | MB_ICONERROR);
	LocalFree(lpMsgBuf);
	LocalFree(lpDisplayBuf);
	ExitProcess(dw); 
}
LRESULT CALLBACK
winMWExtWMWindowProc (HWND hwnd, UINT message,
                      WPARAM wParam, LPARAM lParam)
{
    WindowPtr		pWin = NULL;
    win32RootlessWindowPtr pRLWinPriv = NULL;
    ScreenPtr		pScreen = NULL;
    winPrivScreenPtr	pScreenPriv = NULL;
    winScreenInfo		*pScreenInfo = NULL;
    HWND			hwndScreen = NULL;
    POINT			ptMouse;
    static Bool		s_fTracking = FALSE;
    HDC			hdcUpdate;
    PAINTSTRUCT		ps;
    LPWINDOWPOS		pWinPos = NULL;
    RECT			rcClient;
    winWMMessageRec	wmMsg;
    Bool			fWMMsgInitialized = FALSE;

    /* Check if the Windows window property for our X window pointer is valid */
    if ((pRLWinPriv = (win32RootlessWindowPtr)GetProp (hwnd, WIN_WINDOW_PROP)) != NULL)
    {
        pWin = pRLWinPriv->pFrame->win;
        pScreen				= pWin->drawable.pScreen;
        if (pScreen) pScreenPriv		= winGetScreenPriv(pScreen);
        if (pScreenPriv) pScreenInfo	= pScreenPriv->pScreenInfo;
        if (pScreenPriv) hwndScreen	= pScreenPriv->hwndScreen;

        wmMsg.msg		= 0;
        wmMsg.hwndWindow	= hwnd;
        wmMsg.iWindow	= (Window)pWin->drawable.id;

        wmMsg.iX		= pRLWinPriv->pFrame->x;
        wmMsg.iY		= pRLWinPriv->pFrame->y;
        wmMsg.iWidth	= pRLWinPriv->pFrame->width;
        wmMsg.iHeight	= pRLWinPriv->pFrame->height;

        fWMMsgInitialized = TRUE;
#if CYGDEBUG
        winDebugWin32Message("winMWExtWMWindowProc", hwnd, message, wParam, lParam);

        winDebug ("\thWnd %08X\n", hwnd);
        winDebug ("\tpScreenPriv %08X\n", pScreenPriv);
        winDebug ("\tpScreenInfo %08X\n", pScreenInfo);
        winDebug ("\thwndScreen %08X\n", hwndScreen);
        winDebug ("winMWExtWMWindowProc (%08x) %08x %08x %08x\n",
                  pRLWinPriv, message, wParam, lParam);
#endif
    }
    /* Branch on message type */
    switch (message)
    {
    case WM_CREATE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_CREATE\n");
#endif
        /* */
        SetProp (hwnd,
                 WIN_WINDOW_PROP,
                 (HANDLE)((LPCREATESTRUCT) lParam)->lpCreateParams);
        return 0;

    case WM_CLOSE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_CLOSE %d\n", pRLWinPriv->fClose);
#endif
        /* Tell window-manager to close window */
        if (pRLWinPriv->fClose)
        {
            DestroyWindow (hwnd);
        }
        else
        {
            if (winIsInternalWMRunning(pScreenInfo))
            {
                /* Tell our Window Manager thread to kill the window */
                wmMsg.msg = WM_WM_KILL;
                if (fWMMsgInitialized)
                    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
            }
            winWindowsWMSendEvent(WindowsWMControllerNotify,
                                  WindowsWMControllerNotifyMask,
                                  1,
                                  WindowsWMCloseWindow,
                                  pWin->drawable.id,
                                  0, 0, 0, 0);
        }
        return 0;

    case WM_DESTROY:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_DESTROY\n");
#endif
        /* Free the shaodw DC; which allows the bitmap to be freed */
        DeleteDC (pRLWinPriv->hdcShadow);
        pRLWinPriv->hdcShadow = NULL;

        /* Free the shadow bitmap */
        DeleteObject (pRLWinPriv->hbmpShadow);
        pRLWinPriv->hbmpShadow = NULL;

        /* Free the screen DC */
        ReleaseDC (pRLWinPriv->hWnd, pRLWinPriv->hdcScreen);
        pRLWinPriv->hdcScreen = NULL;

        /* Free shadow buffer info header */
        free (pRLWinPriv->pbmihShadow);
        pRLWinPriv->pbmihShadow = NULL;

        pRLWinPriv->fResized = FALSE;
        pRLWinPriv->pfb = NULL;
        free (pRLWinPriv);
        RemoveProp (hwnd, WIN_WINDOW_PROP);
        break;

    case WM_MOUSEMOVE:
#if CYGMULTIWINDOW_DEBUG && 0
        winDebug ("winMWExtWMWindowProc - WM_MOUSEMOVE\n");
#endif
        /* Unpack the client area mouse coordinates */
        ptMouse.x = GET_X_LPARAM(lParam);
        ptMouse.y = GET_Y_LPARAM(lParam);

        /* Translate the client area mouse coordinates to screen coordinates */
        ClientToScreen (hwnd, &ptMouse);

        /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
        ptMouse.x -= GetSystemMetrics (SM_XVIRTUALSCREEN);
        ptMouse.y -= GetSystemMetrics (SM_YVIRTUALSCREEN);

        /* We can't do anything without privates */
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;

        /* Has the mouse pointer crossed screens? */
        if (pScreen != miPointerGetScreen(inputInfo.pointer))
            miPointerSetScreen (inputInfo.pointer, pScreenInfo->dwScreen,
                                ptMouse.x - pScreenInfo->dwXOffset,
                                ptMouse.y - pScreenInfo->dwYOffset);

        /* Are we tracking yet? */
        if (!s_fTracking)
        {
            TRACKMOUSEEVENT		tme;

            /* Setup data structure */
            ZeroMemory (&tme, sizeof (tme));
            tme.cbSize = sizeof (tme);
            tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hwnd;

            /* Call the tracking function */
            if (!(*g_fpTrackMouseEvent) (&tme))
                ErrorF ("winMWExtWMWindowProc - _TrackMouseEvent failed\n");

            /* Flag that we are tracking now */
            s_fTracking = TRUE;
        }

        /* Kill the timer used to poll mouse events */
        if (g_uipMousePollingTimerID != 0)
        {
            KillTimer (pScreenPriv->hwndScreen, WIN_POLLING_MOUSE_TIMER_ID);
            g_uipMousePollingTimerID = 0;
        }

        /* Deliver absolute cursor position to X Server */
        miPointerAbsoluteCursor (ptMouse.x - pScreenInfo->dwXOffset,
                                 ptMouse.y - pScreenInfo->dwYOffset,
                                 g_c32LastInputEventTime = GetTickCount ());
        return 0;

    case WM_NCMOUSEMOVE:
#if CYGMULTIWINDOW_DEBUG && 0
        winDebug ("winMWExtWMWindowProc - WM_NCMOUSEMOVE\n");
#endif
        /*
         * We break instead of returning 0 since we need to call
         * DefWindowProc to get the mouse cursor changes
         * and min/max/close button highlighting in Windows XP.
         * The Platform SDK says that you should return 0 if you
         * process this message, but it fails to mention that you
         * will give up any default functionality if you do return 0.
         */

        /* We can't do anything without privates */
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;

        /*
         * Timer to poll mouse events.  This is needed to make
         * programs like xeyes follow the mouse properly.
         */
        if (g_uipMousePollingTimerID == 0)
            g_uipMousePollingTimerID = SetTimer (pScreenPriv->hwndScreen,
                                                 WIN_POLLING_MOUSE_TIMER_ID,
                                                 MOUSE_POLLING_INTERVAL,
                                                 NULL);
        break;

    case WM_MOUSELEAVE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_MOUSELEAVE\n");
#endif
        /* Mouse has left our client area */

        /* Flag that we are no longer tracking */
        s_fTracking = FALSE;

        /*
         * Timer to poll mouse events.  This is needed to make
         * programs like xeyes follow the mouse properly.
         */
        if (g_uipMousePollingTimerID == 0)
            g_uipMousePollingTimerID = SetTimer (pScreenPriv->hwndScreen,
                                                 WIN_POLLING_MOUSE_TIMER_ID,
                                                 MOUSE_POLLING_INTERVAL,
                                                 NULL);
        return 0;

    case WM_LBUTTONDBLCLK:
    case WM_LBUTTONDOWN:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_LBUTTONDBLCLK\n");
#endif
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        SetCapture (hwnd);
        return winMouseButtonsHandle (pScreen, ButtonPress, Button1, wParam);

    case WM_LBUTTONUP:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_LBUTTONUP\n");
#endif
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        ReleaseCapture ();
        return winMouseButtonsHandle (pScreen, ButtonRelease, Button1, wParam);

    case WM_MBUTTONDBLCLK:
    case WM_MBUTTONDOWN:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_MBUTTONDBLCLK\n");
#endif
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        SetCapture (hwnd);
        return winMouseButtonsHandle (pScreen, ButtonPress, Button2, wParam);

    case WM_MBUTTONUP:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_MBUTTONUP\n");
#endif
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        ReleaseCapture ();
        return winMouseButtonsHandle (pScreen, ButtonRelease, Button2, wParam);

    case WM_RBUTTONDBLCLK:
    case WM_RBUTTONDOWN:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_RBUTTONDBLCLK\n");
#endif
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        SetCapture (hwnd);
        return winMouseButtonsHandle (pScreen, ButtonPress, Button3, wParam);

    case WM_RBUTTONUP:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_RBUTTONUP\n");
#endif
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        ReleaseCapture ();
        return winMouseButtonsHandle (pScreen, ButtonRelease, Button3, wParam);

    case WM_XBUTTONDBLCLK:
    case WM_XBUTTONDOWN:
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        SetCapture (hwnd);
        return winMouseButtonsHandle (pScreen, ButtonPress, HIWORD(wParam) + 5, wParam);
    case WM_XBUTTONUP:
        if (pScreenPriv == NULL || pScreenInfo->fIgnoreInput)
            break;
        ReleaseCapture ();
        return winMouseButtonsHandle (pScreen, ButtonRelease, HIWORD(wParam) + 5, wParam);

    case WM_MOUSEWHEEL:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_MOUSEWHEEL\n");
#endif

        /* Pass the message to the root window */
        SendMessage (hwndScreen, message, wParam, lParam);
        return 0;

    case WM_MOUSEACTIVATE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_MOUSEACTIVATE\n");
#endif
#if 1
        /* Check if this window needs to be made active when clicked */
        if (winIsInternalWMRunning(pScreenInfo) && pWin->overrideRedirect)
        {
#if CYGMULTIWINDOW_DEBUG
            winDebug ("winMWExtWMWindowProc - WM_MOUSEACTIVATE - "
                      "MA_NOACTIVATE\n");
#endif

            /* */
            return MA_NOACTIVATE;
        }
#endif
        if (!winIsInternalWMRunning(pScreenInfo) && !IsMouseActive (pWin))
            return MA_NOACTIVATE;

        break;

    case WM_KILLFOCUS:
        /* Pop any pressed keys since we are losing keyboard focus */
        winKeybdReleaseKeys ();
        return 0;

    case WM_SYSDEADCHAR:
    case WM_DEADCHAR:
        /*
         * NOTE: We do nothing with WM_*CHAR messages,
         * nor does the root window, so we can just toss these messages.
         */
        return 0;

    case WM_SYSKEYDOWN:
    case WM_KEYDOWN:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_*KEYDOWN\n");
#endif

        /*
         * Don't pass Alt-F4 key combo to root window,
         * let Windows translate to WM_CLOSE and close this top-level window.
         *
         * NOTE: We purposely don't check the fUseWinKillKey setting because
         * it should only apply to the key handling for the root window,
         * not for top-level window-manager windows.
         *
         * ALSO NOTE: We do pass Ctrl-Alt-Backspace to the root window
         * because that is a key combo that no X app should be expecting to
         * receive, since it has historically been used to shutdown the X server.
         * Passing Ctrl-Alt-Backspace to the root window preserves that
         * behavior, assuming that -unixkill has been passed as a parameter.
         */
        if (wParam == VK_F4 && (GetKeyState (VK_MENU) & 0x8000))
            break;

        /* Pass the message to the root window */
        SendMessage (hwndScreen, message, wParam, lParam);
        return 0;

    case WM_SYSKEYUP:
    case WM_KEYUP:

#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_*KEYUP\n");
#endif

        /* Pass the message to the root window */
        SendMessage (hwndScreen, message, wParam, lParam);
        return 0;

    case WM_HOTKEY:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_HOTKEY\n");
#endif

        /* Pass the message to the root window */
        SendMessage (hwndScreen, message, wParam, lParam);
        return 0;

    case WM_PAINT:

        /* BeginPaint gives us an hdc that clips to the invalidated region */
        hdcUpdate = BeginPaint (hwnd, &ps);

        /* Try to copy from the shadow buffer */
        if (!BitBlt (hdcUpdate,
                     ps.rcPaint.left, ps.rcPaint.top,
                     ps.rcPaint.right - ps.rcPaint.left,
                     ps.rcPaint.bottom - ps.rcPaint.top,
                     pRLWinPriv->hdcShadow,
                     ps.rcPaint.left, ps.rcPaint.top,
                     SRCCOPY))
        {
            LPVOID lpMsgBuf;

            /* Display a fancy error message */
            FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
                           FORMAT_MESSAGE_FROM_SYSTEM |
                           FORMAT_MESSAGE_IGNORE_INSERTS,
                           NULL,
                           GetLastError (),
                           MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                           (LPTSTR) &lpMsgBuf,
                           0, NULL);

            ErrorF ("winMWExtWMWindowProc - BitBlt failed: %s\n",
                    (LPSTR)lpMsgBuf);
            LocalFree (lpMsgBuf);
        }

        /* EndPaint frees the DC */
        EndPaint (hwnd, &ps);
        break;

    case WM_ACTIVATE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_ACTIVATE\n");
#endif
        if (LOWORD(wParam) != WA_INACTIVE)
        {
            if (winIsInternalWMRunning(pScreenInfo))
            {
#if 0
                /* Raise the window to the top in Z order */
                wmMsg.msg = WM_WM_RAISE;
                if (fWMMsgInitialized)
                    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
#endif
                /* Tell our Window Manager thread to activate the window */
                wmMsg.msg = WM_WM_ACTIVATE;
                if (fWMMsgInitialized)
                    if (!pWin || !pWin->overrideRedirect) /* for OOo menus */
                        winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
            }
            winWindowsWMSendEvent(WindowsWMControllerNotify,
                                  WindowsWMControllerNotifyMask,
                                  1,
                                  WindowsWMActivateWindow,
                                  pWin->drawable.id,
                                  0, 0,
                                  0, 0);
        }
        return 0;

#if 1
    case WM_WINDOWPOSCHANGING:
        pWinPos = (LPWINDOWPOS)lParam;
        if (!(pWinPos->flags & SWP_NOZORDER))
        {
            if (pRLWinPriv->fRestackingNow || pScreenPriv->fRestacking)
            {
#if CYGMULTIWINDOW_DEBUG
                winDebug ("Win %08x is now restacking.\n", (unsigned int)pRLWinPriv);
#endif
                break;
            }

            if (winIsInternalWMRunning(pScreenInfo) || IsRaiseOnClick (pWin))
            {
#if CYGMULTIWINDOW_DEBUG
                winDebug ("Win %08x has WINDOWSWM_RAISE_ON_CLICK.\n", (unsigned int)pRLWinPriv);
#endif
                break;
            }

#if CYGMULTIWINDOW_DEBUG
            winDebug ("Win %08x forbid to change z order (%08x).\n",
                      (unsigned int)pRLWinPriv, (unsigned int)pWinPos->hwndInsertAfter);
#endif
            pWinPos->flags |= SWP_NOZORDER;
        }
        break;
#endif

    case WM_MOVE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_MOVE - %d ms\n",
                  (unsigned int)GetTickCount ());
#endif
        if (g_fNoConfigureWindow) break;
#if 0
        /* Bail if Windows window is not actually moving */
        if (pRLWinPriv->dwX == (short) LOWORD(lParam)
                && pRLWinPriv->dwY == (short) HIWORD(lParam))
            break;

        /* Also bail if we're maximizing, we'll do the whole thing in WM_SIZE */
        {
            WINDOWPLACEMENT windPlace;
            windPlace.length = sizeof (WINDOWPLACEMENT);

            /* Get current window placement */
            GetWindowPlacement (hwnd, &windPlace);

            /* Bail if maximizing */
            if (windPlace.showCmd == SW_MAXIMIZE
                    || windPlace.showCmd == SW_SHOWMAXIMIZED)
                break;
        }
#endif

#if CYGMULTIWINDOW_DEBUG
        winDebug ("\t(%d, %d)\n", (short) LOWORD(lParam), (short) HIWORD(lParam));
#endif
        if (!pRLWinPriv->fMovingOrSizing)
        {
            if (winIsInternalWMRunning(pScreenInfo))
                winAdjustXWindow (pWin, hwnd);

            winMWExtWMMoveXWindow (pWin,
                                   (LOWORD(lParam) - wBorderWidth (pWin)
                                    - GetSystemMetrics (SM_XVIRTUALSCREEN)),
                                   (HIWORD(lParam) - wBorderWidth (pWin)
                                    - GetSystemMetrics (SM_YVIRTUALSCREEN)));
        }
        return 0;

    case WM_SHOWWINDOW:
#if CYGMULTIWINDOW_DEBUG || TRUE
        winDebug ("winMWExtWMWindowProc - WM_SHOWWINDOW - %d ms\n",
                  (unsigned int)GetTickCount ());
#endif
        /* Bail out if the window is being hidden */
        if (!wParam)
            return 0;

        if (!pScreenInfo->fInternalWM)//XXXX
            return 0;

        winMWExtWMUpdateWindowDecoration (pRLWinPriv, pScreenInfo);

        if (winIsInternalWMRunning(pScreenInfo))
        {
#if CYGMULTIWINDOW_DEBUG || TRUE
            winDebug ("\tMapWindow\n");
#endif
            /* Tell X to map the window */
            MapWindow (pWin, wClient(pWin));

            if (!pRLWinPriv->pFrame->win->overrideRedirect)
                /* Bring the Windows window to the foreground */
                SetForegroundWindow (hwnd);

            /* Setup the Window Manager message */
            wmMsg.msg = WM_WM_MAP;
            wmMsg.iWidth = pRLWinPriv->pFrame->width;
            wmMsg.iHeight = pRLWinPriv->pFrame->height;

            /* Tell our Window Manager thread to map the window */
            if (fWMMsgInitialized)
                winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
        }
        break;

    case WM_SIZING:
        /* Need to legalize the size according to WM_NORMAL_HINTS */
        /* for applications like xterm */
        return ValidateSizing (hwnd, pWin, wParam, lParam);

    case WM_WINDOWPOSCHANGED:
    {
        pWinPos = (LPWINDOWPOS) lParam;
#if CYGMULTIWINDOW_DEBUG
        winDebug("winMWExtWMWindowProc - WM_WINDOWPOSCHANGED\n");
        winDebug("\tflags: %s%s%s%s%s%s%s%s%s%s%s%s\n",
                 (pWinPos->flags & SWP_DRAWFRAME)?"SWP_DRAWFRAME ":"",
                 (pWinPos->flags & SWP_FRAMECHANGED)?"SWP_FRAMECHANGED ":"",
                 (pWinPos->flags & SWP_HIDEWINDOW)?"SWP_HIDEWINDOW ":"",
                 (pWinPos->flags & SWP_NOACTIVATE)?"SWP_NOACTIVATE ":"",
                 (pWinPos->flags & SWP_NOCOPYBITS)?"SWP_NOCOPYBITS ":"",
                 (pWinPos->flags & SWP_NOMOVE)?"SWP_NOMOVE ":"",
                 (pWinPos->flags & SWP_NOOWNERZORDER)?"SWP_NOOWNERZORDER ":"",
                 (pWinPos->flags & SWP_NOSIZE)?"SWP_NOSIZE ":"",
                 (pWinPos->flags & SWP_NOREDRAW)?"SWP_NOREDRAW ":"",
                 (pWinPos->flags & SWP_NOSENDCHANGING)?"SWP_NOSENDCHANGING ":"",
                 (pWinPos->flags & SWP_NOZORDER)?"SWP_NOZORDER ":"",
                 (pWinPos->flags & SWP_SHOWWINDOW)?"SWP_SHOWWINDOW ":"");
        winDebug("\tno_configure: %s\n", (g_fNoConfigureWindow?"Yes":"No"));
        winDebug("\textend: (%d, %d, %d, %d)\n",
                 pWinPos->x, pWinPos->y, pWinPos->cx, pWinPos->cy);

#endif
        if (pWinPos->flags & SWP_HIDEWINDOW) break;

        /* Reorder if window z order was changed */
        if ((pScreenPriv != NULL)
                && !(pWinPos->flags & SWP_NOZORDER)
                && !(pWinPos->flags & SWP_SHOWWINDOW)
                && winIsInternalWMRunning(pScreenInfo))
        {
#if CYGMULTIWINDOW_DEBUG
            winDebug ("\twindow z order was changed\n");
#endif
            if (pWinPos->hwndInsertAfter == HWND_TOP
                    ||pWinPos->hwndInsertAfter == HWND_TOPMOST
                    ||pWinPos->hwndInsertAfter == HWND_NOTOPMOST)
            {
#if CYGMULTIWINDOW_DEBUG
                winDebug ("\traise to top\n");
#endif
                /* Raise the window to the top in Z order */
                wmMsg.msg = WM_WM_RAISE;
                if (fWMMsgInitialized)
                    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
            }
#if 1
            else if (pWinPos->hwndInsertAfter == HWND_BOTTOM)
            {
            }
            else
            {
                /* Check if this window is top of X windows. */
                HWND hWndAbove = NULL;
                DWORD dwCurrentProcessID = GetCurrentProcessId ();
                DWORD dwWindowProcessID = 0;

                for (hWndAbove = pWinPos->hwndInsertAfter;
                        hWndAbove != NULL;
                        hWndAbove = GetNextWindow (hWndAbove, GW_HWNDPREV))
                {
                    /* Ignore other XWin process's window */
                    GetWindowThreadProcessId (hWndAbove, &dwWindowProcessID);

                    if ((dwWindowProcessID == dwCurrentProcessID)
                            && GetProp (hWndAbove, WIN_WINDOW_PROP)
                            && !IsWindowVisible (hWndAbove)
                            && !IsIconic (hWndAbove) ) /* ignore minimized windows */
                        break;
                }
                /* If this is top of X windows in Windows stack,
                   raise it in X stack. */
                if (hWndAbove == NULL)
                {
#if CYGMULTIWINDOW_DEBUG
                    winDebug ("\traise to top\n");
#endif
                    /* Raise the window to the top in Z order */
                    wmMsg.msg = WM_WM_RAISE;
                    if (fWMMsgInitialized)
                        winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
                }
            }
#endif
        }

        if (!(pWinPos->flags & SWP_NOSIZE)) {
            if (IsIconic(hwnd)) {
#if CYGMULTIWINDOW_DEBUG
                winDebug ("\tIconic -> MINIMIZED\n");
#endif
                if (winIsInternalWMRunning(pScreenInfo))
                {
                    /* Raise the window to the top in Z order */
                    wmMsg.msg = WM_WM_LOWER;
                    if (fWMMsgInitialized)
                        winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
                }
                winWindowsWMSendEvent(WindowsWMControllerNotify,
                                      WindowsWMControllerNotifyMask,
                                      1,
                                      WindowsWMMinimizeWindow,
                                      pWin->drawable.id,
                                      0, 0, 0, 0);
            } else if (IsZoomed(hwnd)) {
#if CYGMULTIWINDOW_DEBUG
                winDebug ("\tZoomed -> MAXIMIZED\n");
#endif
                winWindowsWMSendEvent(WindowsWMControllerNotify,
                                      WindowsWMControllerNotifyMask,
                                      1,
                                      WindowsWMMaximizeWindow,
                                      pWin->drawable.id,
                                      0, 0, 0, 0);
            } else {
#if CYGMULTIWINDOW_DEBUG
                winDebug ("\tnone -> RESTORED\n");
#endif
                winWindowsWMSendEvent(WindowsWMControllerNotify,
                                      WindowsWMControllerNotifyMask,
                                      1,
                                      WindowsWMRestoreWindow,
                                      pWin->drawable.id,
                                      0, 0, 0, 0);
            }
        }
        if (!g_fNoConfigureWindow ) {

            if (!pRLWinPriv->fMovingOrSizing
                    /*&& (pWinPos->flags & SWP_SHOWWINDOW)*/) {
                GetClientRect (hwnd, &rcClient);
                MapWindowPoints (hwnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);

                if (!(pWinPos->flags & SWP_NOMOVE)
                        &&!(pWinPos->flags & SWP_NOSIZE)) {
#if CYGMULTIWINDOW_DEBUG
                    winDebug ("\tmove & resize\n");
#endif
                    if (winIsInternalWMRunning(pScreenInfo))
                        winAdjustXWindow (pWin, hwnd);

                    winMWExtWMMoveResizeXWindow (pWin,
                                                 rcClient.left - wBorderWidth (pWin)
                                                 - GetSystemMetrics (SM_XVIRTUALSCREEN),
                                                 rcClient.top - wBorderWidth (pWin)
                                                 - GetSystemMetrics (SM_YVIRTUALSCREEN),
                                                 rcClient.right - rcClient.left
                                                 - wBorderWidth (pWin)*2,
                                                 rcClient.bottom - rcClient.top
                                                 - wBorderWidth (pWin)*2);
                } else if (!(pWinPos->flags & SWP_NOMOVE)) {
#if CYGMULTIWINDOW_DEBUG
                    winDebug ("\tmove\n");
#endif
                    if (winIsInternalWMRunning(pScreenInfo))
                        winAdjustXWindow (pWin, hwnd);

                    winMWExtWMMoveResizeXWindow (pWin,
                                                 rcClient.left - wBorderWidth (pWin)
                                                 - GetSystemMetrics (SM_XVIRTUALSCREEN),
                                                 rcClient.top - wBorderWidth (pWin)
                                                 - GetSystemMetrics (SM_YVIRTUALSCREEN),
                                                 rcClient.right - rcClient.left
                                                 - wBorderWidth (pWin)*2,
                                                 rcClient.bottom - rcClient.top
                                                 - wBorderWidth (pWin)*2);
                } else if (!(pWinPos->flags & SWP_NOMOVE)) {
#if CYGMULTIWINDOW_DEBUG
                    winDebug ("\tmove\n");
#endif
                    if (winIsInternalWMRunning(pScreenInfo))
                        winAdjustXWindow (pWin, hwnd);

                    winMWExtWMMoveXWindow (pWin,
                                           rcClient.left - wBorderWidth (pWin)
                                           - GetSystemMetrics (SM_XVIRTUALSCREEN),
                                           rcClient.top - wBorderWidth (pWin)
                                           - GetSystemMetrics (SM_YVIRTUALSCREEN));
                } else if (!(pWinPos->flags & SWP_NOSIZE)) {
#if CYGMULTIWINDOW_DEBUG
                    winDebug ("\tresize\n");
#endif
                    if (winIsInternalWMRunning(pScreenInfo))
                        winAdjustXWindow (pWin, hwnd);

                    winMWExtWMResizeXWindow (pWin,
                                             rcClient.right - rcClient.left
                                             - wBorderWidth (pWin)*2,
                                             rcClient.bottom - rcClient.top
                                             - wBorderWidth (pWin)*2);
                }
            }
        }
    }
#if CYGMULTIWINDOW_DEBUG
    winDebug ("winMWExtWMWindowProc - WM_WINDOWPOSCHANGED - done.\n");
#endif
    return 0;

    case WM_SIZE:
        /* see dix/window.c */
        /* FIXME: Maximize/Restore? */
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_SIZE - %d ms\n",
                  (unsigned int)GetTickCount ());
#endif
#if CYGMULTIWINDOW_DEBUG
        winDebug ("\t(%d, %d) %d\n", (short) LOWORD(lParam), (short) HIWORD(lParam), g_fNoConfigureWindow);
#endif
        if (g_fNoConfigureWindow) break;

        /* Branch on type of resizing occurring */
        switch (wParam)
        {
        case SIZE_MINIMIZED:
#if CYGMULTIWINDOW_DEBUG
            winDebug ("\tSIZE_MINIMIZED\n");
#endif
            if (winIsInternalWMRunning(pScreenInfo))
            {
                /* Raise the window to the top in Z order */
                wmMsg.msg = WM_WM_LOWER;
                if (fWMMsgInitialized)
                    winSendMessageToWM (pScreenPriv->pWMInfo, &wmMsg);
            }
            winWindowsWMSendEvent(WindowsWMControllerNotify,
                                  WindowsWMControllerNotifyMask,
                                  1,
                                  WindowsWMMinimizeWindow,
                                  pWin->drawable.id,
                                  0, 0,
                                  LOWORD(lParam), HIWORD(lParam));
            break;

        case SIZE_RESTORED:
#if CYGMULTIWINDOW_DEBUG
            winDebug ("\tSIZE_RESTORED\n");
#endif
            winWindowsWMSendEvent(WindowsWMControllerNotify,
                                  WindowsWMControllerNotifyMask,
                                  1,
                                  WindowsWMRestoreWindow,
                                  pWin->drawable.id,
                                  0, 0,
                                  LOWORD(lParam), HIWORD(lParam));
            break;

        case SIZE_MAXIMIZED:
#if CYGMULTIWINDOW_DEBUG
            winDebug ("\tSIZE_MAXIMIZED\n");
#endif
            winWindowsWMSendEvent(WindowsWMControllerNotify,
                                  WindowsWMControllerNotifyMask,
                                  1,
                                  WindowsWMMaximizeWindow,
                                  pWin->drawable.id,
                                  0, 0,
                                  LOWORD(lParam), HIWORD(lParam));
            break;
        }

        /* Perform the resize and notify the X client */
        if (!pRLWinPriv->fMovingOrSizing)
        {
            if (winIsInternalWMRunning(pScreenInfo))
                winAdjustXWindow (pWin, hwnd);

            winMWExtWMResizeXWindow (pWin,
                                     (short) LOWORD(lParam)
                                     - wBorderWidth (pWin)*2,
                                     (short) HIWORD(lParam)
                                     - wBorderWidth (pWin)*2);
        }
        break;

    case WM_ACTIVATEAPP:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_ACTIVATEAPP - %d ms\n",
                  (unsigned int)GetTickCount ());
#endif
        if (wParam)
        {
            if (winIsInternalWMRunning(pScreenInfo))
            {
            }
            else
            {
            }
            winWindowsWMSendEvent(WindowsWMActivationNotify,
                                  WindowsWMActivationNotifyMask,
                                  1,
                                  WindowsWMIsActive,
                                  pWin->drawable.id,
                                  0, 0,
                                  0, 0);
        }
        else
        {
            winWindowsWMSendEvent(WindowsWMActivationNotify,
                                  WindowsWMActivationNotifyMask,
                                  1,
                                  WindowsWMIsInactive,
                                  pWin->drawable.id,
                                  0, 0,
                                  0, 0);
        }
        break;

    case WM_SETCURSOR:
        if (LOWORD(lParam) == HTCLIENT)
        {
            if (!g_fSoftwareCursor) SetCursor (pScreenPriv->cursor.handle);
            return TRUE;
        }
        break;

    case WM_ENTERSIZEMOVE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_ENTERSIZEMOVE - %d ms\n",
                  (unsigned int)GetTickCount ());
#endif
        pRLWinPriv->fMovingOrSizing = TRUE;
        break;

    case WM_EXITSIZEMOVE:
#if CYGMULTIWINDOW_DEBUG
        winDebug ("winMWExtWMWindowProc - WM_EXITSIZEMOVE - %d ms\n",
                  (unsigned int)GetTickCount ());
#endif
        pRLWinPriv->fMovingOrSizing = FALSE;

        GetClientRect (hwnd, &rcClient);

        MapWindowPoints (hwnd, HWND_DESKTOP, (LPPOINT)&rcClient, 2);

        if (winIsInternalWMRunning(pScreenInfo))
            winAdjustXWindow (pWin, hwnd);

        winMWExtWMMoveResizeXWindow (pWin,
                                     rcClient.left - wBorderWidth (pWin)
                                     - GetSystemMetrics (SM_XVIRTUALSCREEN),
                                     rcClient.top - wBorderWidth (pWin)
                                     - GetSystemMetrics (SM_YVIRTUALSCREEN),
                                     rcClient.right - rcClient.left
                                     - wBorderWidth (pWin)*2,
                                     rcClient.bottom - rcClient.top
                                     - wBorderWidth (pWin)*2);
        break;

    case WM_MANAGE:
        ErrorF ("winMWExtWMWindowProc - WM_MANAGE\n");
        break;

    case WM_UNMANAGE:
        ErrorF ("winMWExtWMWindowProc - WM_UNMANAGE\n");
        break;

    default:
        break;
    }

    return DefWindowProc (hwnd, message, wParam, lParam);
}
示例#8
0
int ScriptController::Execute()
{
	PrepareEnvOptions(NULL);
	PrepareArgs();

	int iExitCode = 0;
	int pipein;

#ifdef CHILD_WATCHDOG
	bool bChildConfirmed = false;
	while (!bChildConfirmed && !m_bTerminated)
	{
#endif

#ifdef WIN32
	// build command line

	char* szCmdLine = NULL;
	if (m_szArgs)
	{
		char szCmdLineBuf[2048];
		int iUsedLen = 0;
		for (const char** szArgPtr = m_szArgs; *szArgPtr; szArgPtr++)
		{
			snprintf(szCmdLineBuf + iUsedLen, 2048 - iUsedLen, "\"%s\" ", *szArgPtr);
			iUsedLen += strlen(*szArgPtr) + 3;
		}
		szCmdLineBuf[iUsedLen < 2048 ? iUsedLen - 1 : 2048 - 1] = '\0';
		szCmdLine = szCmdLineBuf;
	}
	else
	{
		szCmdLine = m_szCmdLine;
	}
	
	// create pipes to write and read data
	HANDLE hReadPipe, hWritePipe;
	SECURITY_ATTRIBUTES SecurityAttributes;
	memset(&SecurityAttributes, 0, sizeof(SecurityAttributes));
	SecurityAttributes.nLength = sizeof(SecurityAttributes);
	SecurityAttributes.bInheritHandle = TRUE;

	CreatePipe(&hReadPipe, &hWritePipe, &SecurityAttributes, 0);

	SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0);

	STARTUPINFO StartupInfo;
	memset(&StartupInfo, 0, sizeof(StartupInfo));
	StartupInfo.cb = sizeof(StartupInfo);
	StartupInfo.dwFlags = STARTF_USESTDHANDLES;
	StartupInfo.hStdInput = 0;
	StartupInfo.hStdOutput = hWritePipe;
	StartupInfo.hStdError = hWritePipe;

	PROCESS_INFORMATION ProcessInfo;
	memset(&ProcessInfo, 0, sizeof(ProcessInfo));

	char* szEnvironmentStrings = m_environmentStrings.GetStrings();

	BOOL bOK = CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, szEnvironmentStrings, m_szWorkingDir, &StartupInfo, &ProcessInfo);
	if (!bOK)
	{
		DWORD dwErrCode = GetLastError();
		char szErrMsg[255];
		szErrMsg[255-1] = '\0';
		if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwErrCode, 0, szErrMsg, 255, NULL))
		{
			PrintMessage(Message::mkError, "Could not start %s: %s", m_szInfoName, szErrMsg);
		}
		else
		{
			PrintMessage(Message::mkError, "Could not start %s: error %i", m_szInfoName, dwErrCode);
		}
		if (!Util::FileExists(m_szScript))
		{
			PrintMessage(Message::mkError, "Could not find file %s", m_szScript);
		}
		free(szEnvironmentStrings);
		return -1;
	}

	free(szEnvironmentStrings);

	debug("Child Process-ID: %i", (int)ProcessInfo.dwProcessId);

	m_hProcess = ProcessInfo.hProcess;

	// close unused "write" end
	CloseHandle(hWritePipe);

	pipein = _open_osfhandle((intptr_t)hReadPipe, _O_RDONLY);

#else

	int p[2];
	int pipeout;

	// create the pipe
	if (pipe(p))
	{
		PrintMessage(Message::mkError, "Could not open pipe: errno %i", errno);
		return -1;
	}

	char** pEnvironmentStrings = m_environmentStrings.GetStrings();

	pipein = p[0];
	pipeout = p[1];

	debug("forking");
	pid_t pid = fork();

	if (pid == -1)
	{
		PrintMessage(Message::mkError, "Could not start %s: errno %i", m_szInfoName, errno);
		free(pEnvironmentStrings);
		return -1;
	}
	else if (pid == 0)
	{
		// here goes the second instance

		// create new process group (see Terminate() where it is used)
		setsid();
			
		// close up the "read" end
		close(pipein);
      			
		// make the pipeout to be the same as stdout and stderr
		dup2(pipeout, 1);
		dup2(pipeout, 2);
		
		close(pipeout);

#ifdef CHILD_WATCHDOG
		fwrite("\n", 1, 1, stdout);
		fflush(stdout);
#endif

		chdir(m_szWorkingDir);
		environ = pEnvironmentStrings;
		execvp(m_szScript, (char* const*)m_szArgs);

		if (errno == EACCES)
		{
			fprintf(stdout, "[WARNING] Fixing permissions for %s\n", m_szScript);
			fflush(stdout);
			Util::FixExecPermission(m_szScript);
			execvp(m_szScript, (char* const*)m_szArgs);
		}

		// NOTE: the text "[ERROR] Could not start " is checked later,
		// by changing adjust the dependent code below.
		fprintf(stdout, "[ERROR] Could not start %s: %s", m_szScript, strerror(errno));
		fflush(stdout);
		_exit(254);
	}

	// continue the first instance
	debug("forked");
	debug("Child Process-ID: %i", (int)pid);

	free(pEnvironmentStrings);

	m_hProcess = pid;

	// close unused "write" end
	close(pipeout);
#endif

	// open the read end
	m_pReadpipe = fdopen(pipein, "r");
	if (!m_pReadpipe)
	{
		PrintMessage(Message::mkError, "Could not open pipe to %s", m_szInfoName);
		return -1;
	}
	
#ifdef CHILD_WATCHDOG
	debug("Creating child watchdog");
	ChildWatchDog* pWatchDog = new ChildWatchDog();
	pWatchDog->SetAutoDestroy(false);
	pWatchDog->SetProcessID(pid);
	pWatchDog->Start();
#endif
	
	char* buf = (char*)malloc(10240);

	debug("Entering pipe-loop");
	bool bFirstLine = true;
	bool bStartError = false;
	while (!m_bTerminated && !m_bDetached && !feof(m_pReadpipe))
	{
		if (ReadLine(buf, 10240, m_pReadpipe) && m_pReadpipe)
		{
#ifdef CHILD_WATCHDOG
			if (!bChildConfirmed)
			{
				bChildConfirmed = true;
				pWatchDog->Stop();
				debug("Child confirmed");
				continue;
			}
#endif
			if (bFirstLine && !strncmp(buf, "[ERROR] Could not start ", 24))
			{
				bStartError = true;
			}
			ProcessOutput(buf);
			bFirstLine = false;
		}
	}
	debug("Exited pipe-loop");

#ifdef CHILD_WATCHDOG
	debug("Destroying WatchDog");
	if (!bChildConfirmed)
	{
		pWatchDog->Stop();
	}
	while (pWatchDog->IsRunning())
	{
		usleep(5 * 1000);
	}
	delete pWatchDog;
#endif
	
	free(buf);
	if (m_pReadpipe)
	{
		fclose(m_pReadpipe);
	}

	if (m_bTerminated)
	{
		warn("Interrupted %s", m_szInfoName);
	}

	iExitCode = 0;

	if (!m_bTerminated && !m_bDetached)
	{
#ifdef WIN32
	WaitForSingleObject(m_hProcess, INFINITE);
	DWORD dExitCode = 0;
	GetExitCodeProcess(m_hProcess, &dExitCode);
	iExitCode = dExitCode;
#else
	int iStatus = 0;
	waitpid(m_hProcess, &iStatus, 0);
	if (WIFEXITED(iStatus))
	{
		iExitCode = WEXITSTATUS(iStatus);
		if (iExitCode == 254 && bStartError)
		{
			iExitCode = -1;
		}
	}
#endif
	}
	
#ifdef CHILD_WATCHDOG
	}	// while (!bChildConfirmed && !m_bTerminated)
#endif
	
	debug("Exit code %i", iExitCode);

	return iExitCode;
}
示例#9
0
void SocketLayer::SetSocketOptions( SOCKET listenSocket)
{
	int sock_opt = 1;
	// // On Vista, can get WSAEACCESS (10013)
	/*
	if ( setsockopt( listenSocket, SOL_SOCKET, SO_REUSEADDR, ( char * ) & sock_opt, sizeof ( sock_opt ) ) == -1 )
	{
	#if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG) && !defined(X360)
	DWORD dwIOError = GetLastError();
	LPVOID messageBuffer;
	FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
	NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
	( LPTSTR ) & messageBuffer, 0, NULL );
	// something has gone wrong here...
	RAKNET_DEBUG_PRINTF( "setsockopt(SO_REUSEADDR) failed:Error code - %d\n%s", dwIOError, messageBuffer );
	//Free the buffer.
	LocalFree( messageBuffer );
	#endif
	}
	*/

	// This doubles the max throughput rate
	sock_opt=1024*256;
	setsockopt(listenSocket, SOL_SOCKET, SO_RCVBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) );

	// Immediate hard close. Don't linger the socket, or recreating the socket quickly on Vista fails.
	sock_opt=0;
	setsockopt(listenSocket, SOL_SOCKET, SO_LINGER, ( char * ) & sock_opt, sizeof ( sock_opt ) );

#if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3)
	// This doesn't make much difference: 10% maybe
	// Not supported on console 2
	sock_opt=1024*16;
	setsockopt(listenSocket, SOL_SOCKET, SO_SNDBUF, ( char * ) & sock_opt, sizeof ( sock_opt ) );
#endif

	/*
	#ifdef _WIN32
		unsigned long nonblocking = 1;
		ioctlsocket( listenSocket, FIONBIO, &nonblocking );
	#elif defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)
                                                                                                            
	#else
		fcntl( listenSocket, F_SETFL, O_NONBLOCK );
	#endif
	*/

	// Set broadcast capable
	sock_opt=1;
	if ( setsockopt( listenSocket, SOL_SOCKET, SO_BROADCAST, ( char * ) & sock_opt, sizeof( sock_opt ) ) == -1 )
		{
#if defined(_WIN32) && defined(_DEBUG)
		DWORD dwIOError = GetLastError();
		// On Vista, can get WSAEACCESS (10013)
		// See http://support.microsoft.com/kb/819124
		// http://blogs.msdn.com/wndp/archive/2007/03/19/winsock-so-exclusiveaddruse-on-vista.aspx
		// http://msdn.microsoft.com/en-us/library/ms740621(VS.85).aspx
#if !defined(_XBOX) && !defined(X360)
		LPVOID messageBuffer;
		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
			( LPTSTR ) & messageBuffer, 0, NULL );
		// something has gone wrong here...
		RAKNET_DEBUG_PRINTF( "setsockopt(SO_BROADCAST) failed:Error code - %d\n%s", dwIOError, messageBuffer );
		//Free the buffer.
		LocalFree( messageBuffer );
#endif
#endif

		}
}
LRESULT CALLBACK
winTopLevelWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    POINT ptMouse;
    HDC hdcUpdate;
    PAINTSTRUCT ps;
    WindowPtr pWin = NULL;
    winPrivWinPtr pWinPriv = NULL;
    ScreenPtr s_pScreen = NULL;
    winPrivScreenPtr s_pScreenPriv = NULL;
    winScreenInfo *s_pScreenInfo = NULL;
    HWND hwndScreen = NULL;
    DrawablePtr pDraw = NULL;
    winWMMessageRec wmMsg;
    Bool fWMMsgInitialized = FALSE;
    static Bool s_fTracking = FALSE;
    Bool needRestack = FALSE;
    LRESULT ret;
    static Bool	hasEnteredSizeMove = FALSE;

    winDebugWin32Message("winTopLevelWindowProc", hwnd, message, wParam,
                         lParam);

    /* Check if the Windows window property for our X window pointer is valid */
    if ((pWin = GetProp(hwnd, WIN_WINDOW_PROP)) != NULL) {
        /* Our X window pointer is valid */

        /* Get pointers to the drawable and the screen */
        pDraw = &pWin->drawable;
        s_pScreen = pWin->drawable.pScreen;

        /* Get a pointer to our window privates */
        pWinPriv = winGetWindowPriv(pWin);

        /* Get pointers to our screen privates and screen info */
        s_pScreenPriv = pWinPriv->pScreenPriv;
        s_pScreenInfo = s_pScreenPriv->pScreenInfo;

        /* Get the handle for our screen-sized window */
        hwndScreen = s_pScreenPriv->hwndScreen;

        /* */
        wmMsg.msg = 0;
        wmMsg.hwndWindow = hwnd;
        wmMsg.iWindow = (Window) GetProp(hwnd, WIN_WID_PROP);

        wmMsg.iX = pDraw->x;
        wmMsg.iY = pDraw->y;
        wmMsg.iWidth = pDraw->width;
        wmMsg.iHeight = pDraw->height;

        fWMMsgInitialized = TRUE;

    }
#ifdef _DEBUG
    else if (message!=WM_CREATE)
    {
        winDebug("Warning: message 0x%x received when WIN_WINDOW_PROP NULL\n",message);
    }
#endif

    /* Branch on message type */
    switch (message) {
    case WM_CREATE:

        /* */
        SetProp(hwnd,
                WIN_WINDOW_PROP,
                (HANDLE) ((LPCREATESTRUCT) lParam)->lpCreateParams);

        /* */
        SetProp(hwnd,
                WIN_WID_PROP,
                (HANDLE) winGetWindowID(((LPCREATESTRUCT) lParam)->
                                        lpCreateParams));

        /*
         * Make X windows' Z orders sync with Windows windows because
         * there can be AlwaysOnTop windows overlapped on the window
         * currently being created.
         */
        winReorderWindowsMultiWindow();

        /* Fix a 'round title bar corner background should be transparent not black' problem when first painted */
        {
            RECT rWindow;
            HRGN hRgnWindow;

            GetWindowRect(hwnd, &rWindow);
            hRgnWindow = CreateRectRgnIndirect(&rWindow);
            SetWindowRgn(hwnd, hRgnWindow, TRUE);
        }

        SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)VCXSRV_SIGNATURE);

        return 0;

    case WM_INIT_SYS_MENU:
        /*
         * Add whatever the setup file wants to for this window
         */
        SetupSysMenu((unsigned long) hwnd);
        return 0;

    case WM_SYSCOMMAND:
        /*
         * Any window menu items go through here
         */
        if (HandleCustomWM_COMMAND((unsigned long) hwnd, LOWORD(wParam))) {
            /* Don't pass customized menus to DefWindowProc */
            return 0;
        }
        if (wParam == SC_RESTORE || wParam == SC_MAXIMIZE) {
            WINDOWPLACEMENT wndpl;

            wndpl.length = sizeof(wndpl);
            if (GetWindowPlacement(hwnd, &wndpl) &&
                    wndpl.showCmd == SW_SHOWMINIMIZED)
                needRestack = TRUE;
        }
        break;

    case WM_INITMENU:
        /* Checks/Unchecks any menu items before they are displayed */
        HandleCustomWM_INITMENU((unsigned long) hwnd, wParam);
        break;

    case WM_ERASEBKGND:
        /*
         * Pretend that we did erase the background but we don't care,
         * since we repaint the entire region anyhow
         * This avoids some flickering when resizing.
         */
        return TRUE;

    case WM_PAINT:
        /* Only paint if our window handle is valid */
        if (hwndScreen == NULL)
            break;

        /* BeginPaint gives us an hdc that clips to the invalidated region */
        hdcUpdate = BeginPaint(hwnd, &ps);
        /* Avoid the BitBlt's if the PAINTSTRUCT is bogus */
        if (ps.rcPaint.right == 0 && ps.rcPaint.bottom == 0 &&
                ps.rcPaint.left == 0 && ps.rcPaint.top == 0) {
            EndPaint(hwnd, &ps);
            return 0;
        }

#ifdef XWIN_GLX_WINDOWS
        if (pWinPriv->fWglUsed) {
            /*
               For regions which are being drawn by GL, the shadow framebuffer doesn't have the
               correct bits, so don't bitblt from the shadow framebuffer

               XXX: For now, just leave it alone, but ideally we want to send an expose event to
               the window so it really redraws the affected region...
             */
            ValidateRect(hwnd, &(ps.rcPaint));
        }
        else
#endif
            /* Try to copy from the shadow buffer */
            if (!BitBlt(hdcUpdate,
                        ps.rcPaint.left, ps.rcPaint.top,
                        ps.rcPaint.right - ps.rcPaint.left,
                        ps.rcPaint.bottom - ps.rcPaint.top,
                        s_pScreenPriv->hdcShadow,
                        ps.rcPaint.left + pWin->drawable.x,
                        ps.rcPaint.top + pWin->drawable.y, SRCCOPY)) {
                LPVOID lpMsgBuf;

                /* Display a fancy error message */
                FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                              FORMAT_MESSAGE_FROM_SYSTEM |
                              FORMAT_MESSAGE_IGNORE_INSERTS,
                              NULL,
                              GetLastError(),
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                              (LPTSTR) &lpMsgBuf, 0, NULL);

                ErrorF("winTopLevelWindowProc - BitBlt failed: %s\n",
                       (LPSTR) lpMsgBuf);
                LocalFree(lpMsgBuf);
            }

        /* EndPaint frees the DC */
        EndPaint(hwnd, &ps);
        return 0;

    case WM_MOUSEMOVE:
        /* Unpack the client area mouse coordinates */
        ptMouse.x = GET_X_LPARAM(lParam);
        ptMouse.y = GET_Y_LPARAM(lParam);

        /* Translate the client area mouse coordinates to screen coordinates */
        ClientToScreen(hwnd, &ptMouse);

        /* Screen Coords from (-X, -Y) -> Root Window (0, 0) */
        ptMouse.x -= GetSystemMetrics(SM_XVIRTUALSCREEN);
        ptMouse.y -= GetSystemMetrics(SM_YVIRTUALSCREEN);

        /* We can't do anything without privates */
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;

        /* Has the mouse pointer crossed screens? */
        if (s_pScreen != miPointerGetScreen(g_pwinPointer))
            miPointerSetScreen(g_pwinPointer, s_pScreenInfo->dwScreen,
                               ptMouse.x - s_pScreenInfo->dwXOffset,
                               ptMouse.y - s_pScreenInfo->dwYOffset);

        /* Are we tracking yet? */
        if (!s_fTracking) {
            TRACKMOUSEEVENT tme;

            /* Setup data structure */
            ZeroMemory(&tme, sizeof(tme));
            tme.cbSize = sizeof(tme);
            tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hwnd;

            /* Call the tracking function */
            if (!TrackMouseEvent(&tme))
                ErrorF("winTopLevelWindowProc - TrackMouseEvent failed\n");

            /* Flag that we are tracking now */
            s_fTracking = TRUE;
        }

        /* Hide or show the Windows mouse cursor */
        if (g_fSoftwareCursor && g_fCursor) {
            /* Hide Windows cursor */
            g_fCursor = FALSE;
            ShowCursor(FALSE);
        }

        /* Kill the timer used to poll mouse events */
        if (g_uipMousePollingTimerID != 0) {
            KillTimer(s_pScreenPriv->hwndScreen, WIN_POLLING_MOUSE_TIMER_ID);
            g_uipMousePollingTimerID = 0;
        }

        /* Deliver absolute cursor position to X Server */
        winEnqueueMotion(ptMouse.x - s_pScreenInfo->dwXOffset,
                         ptMouse.y - s_pScreenInfo->dwYOffset);

        return 0;

    case WM_NCMOUSEMOVE:
        /*
         * We break instead of returning 0 since we need to call
         * DefWindowProc to get the mouse cursor changes
         * and min/max/close button highlighting in Windows XP.
         * The Platform SDK says that you should return 0 if you
         * process this message, but it fails to mention that you
         * will give up any default functionality if you do return 0.
         */

        /* We can't do anything without privates */
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;

        /* Non-client mouse movement, show Windows cursor */
        if (g_fSoftwareCursor && !g_fCursor) {
            g_fCursor = TRUE;
            ShowCursor(TRUE);
        }

        winStartMousePolling(s_pScreenPriv);

        break;

    case WM_MOUSELEAVE:
        /* We can't do anything without privates */
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        /* Mouse has left our client area */

        /* Flag that we are no longer tracking */
        s_fTracking = FALSE;

        /* Show the mouse cursor, if necessary */
        if (g_fSoftwareCursor && !g_fCursor) {
            g_fCursor = TRUE;
            ShowCursor(TRUE);
        }

        winStartMousePolling(s_pScreenPriv);

        return 0;

    case WM_LBUTTONDBLCLK:
    case WM_LBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[0] = TRUE;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, Button1, wParam);

    case WM_LBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[0] = FALSE;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease, Button1, wParam);

    case WM_MBUTTONDBLCLK:
    case WM_MBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[1] = TRUE;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, Button2, wParam);

    case WM_MBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[1] = FALSE;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease, Button2, wParam);

    case WM_RBUTTONDBLCLK:
    case WM_RBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[2] = TRUE;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, Button3, wParam);

    case WM_RBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        g_fButton[2] = FALSE;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease, Button3, wParam);

    case WM_XBUTTONDBLCLK:
    case WM_XBUTTONDOWN:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        SetCapture(hwnd);
        return winMouseButtonsHandle(s_pScreen, ButtonPress, HIWORD(wParam) + 5,
                                     wParam);

    case WM_XBUTTONUP:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;
        ReleaseCapture();
        winStartMousePolling(s_pScreenPriv);
        return winMouseButtonsHandle(s_pScreen, ButtonRelease,
                                     HIWORD(wParam) + 5, wParam);

    case WM_MOUSEWHEEL:
        if (SendMessage
                (hwnd, WM_NCHITTEST, 0,
                 MAKELONG(GET_X_LPARAM(lParam),
                          GET_Y_LPARAM(lParam))) == HTCLIENT) {
            /* Pass the message to the root window */
            SendMessage(hwndScreen, message, wParam, lParam);
            return 0;
        }
        else
            break;

    case WM_SETFOCUS:
        if (s_pScreenPriv == NULL || s_pScreenInfo->fIgnoreInput)
            break;

        {
            /* Get the parent window for transient handling */
            HWND hParent = GetParent(hwnd);

            if (hParent && IsIconic(hParent))
                ShowWindow(hParent, SW_RESTORE);
        }

        winRestoreModeKeyStates();

        /* Add the keyboard hook if possible */
        if (g_fKeyboardHookLL)
            g_fKeyboardHookLL = winInstallKeyboardHookLL();
        return 0;

    case WM_KILLFOCUS:
        /* Pop any pressed keys since we are losing keyboard focus */
        winKeybdReleaseKeys();

        /* Remove our keyboard hook if it is installed */
        winRemoveKeyboardHookLL();

        /* Revert the X focus as well, but only if the Windows focus is going to another window */
        if (!wParam && pWin)
            DeleteWindowFromAnyEvents(pWin, FALSE);

        return 0;

    case WM_SYSDEADCHAR:
    case WM_DEADCHAR:
        /*
         * NOTE: We do nothing with WM_*CHAR messages,
         * nor does the root window, so we can just toss these messages.
         */
        return 0;

    case WM_SYSKEYDOWN:
    case WM_KEYDOWN:

        /*
         * Don't pass Alt-F4 key combo to root window,
         * let Windows translate to WM_CLOSE and close this top-level window.
         *
         * NOTE: We purposely don't check the fUseWinKillKey setting because
         * it should only apply to the key handling for the root window,
         * not for top-level window-manager windows.
         *
         * ALSO NOTE: We do pass Ctrl-Alt-Backspace to the root window
         * because that is a key combo that no X app should be expecting to
         * receive, since it has historically been used to shutdown the X server.
         * Passing Ctrl-Alt-Backspace to the root window preserves that
         * behavior, assuming that -unixkill has been passed as a parameter.
         */
        if (wParam == VK_F4 && (GetKeyState(VK_MENU) & 0x8000))
            break;

#ifdef WINDBG
        if (wParam == VK_ESCAPE) {
            /* Place for debug: put any tests and dumps here */
            WINDOWPLACEMENT windPlace;
            RECT rc;
            LPRECT pRect;

            windPlace.length = sizeof(WINDOWPLACEMENT);
            GetWindowPlacement(hwnd, &windPlace);
            pRect = &windPlace.rcNormalPosition;
            winDebug ("\nCYGWINDOWING Dump:\n"
                      "\tdrawable: (%hd, %hd) - %hdx%hd\n", pDraw->x,
                      pDraw->y, pDraw->width, pDraw->height);
            winDebug ("\twindPlace: (%ld, %ld) - %ldx%ld\n", pRect->left,
                      pRect->top, pRect->right - pRect->left,
                      pRect->bottom - pRect->top);
            if (GetClientRect(hwnd, &rc)) {
                pRect = &rc;
                winDebug ("\tClientRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
                          pRect->top, pRect->right - pRect->left,
                          pRect->bottom - pRect->top);
            }
            if (GetWindowRect(hwnd, &rc)) {
                pRect = &rc;
                winDebug ("\tWindowRect: (%ld, %ld) - %ldx%ld\n", pRect->left,
                          pRect->top, pRect->right - pRect->left,
                          pRect->bottom - pRect->top);
            }
            winDebug ("\n");
        }
#endif

        /* Pass the message to the root window */
        return winWindowProc(hwndScreen, message, wParam, lParam);

    case WM_SYSKEYUP:
    case WM_KEYUP:

        /* Pass the message to the root window */
        return winWindowProc(hwndScreen, message, wParam, lParam);

    case WM_HOTKEY:

        /* Pass the message to the root window */
        SendMessage(hwndScreen, message, wParam, lParam);
        return 0;

    case WM_ACTIVATE:

        /* Pass the message to the root window */
        SendMessage(hwndScreen, message, wParam, lParam);

        if (LOWORD(wParam) != WA_INACTIVE) {
            /* Raise the window to the top in Z order */
            /* ago: Activate does not mean putting it to front! */
            /*
               wmMsg.msg = WM_WM_RAISE;
               if (fWMMsgInitialized)
               winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
             */

            /* Tell our Window Manager thread to activate the window */
            wmMsg.msg = WM_WM_ACTIVATE;
            if (fWMMsgInitialized && pWin->realized && !pWin->overrideRedirect /* for OOo menus */)
                winSendMessageToWM (s_pScreenPriv->pWMInfo, &wmMsg);
        }
        /* Prevent the mouse wheel from stalling when another window is minimized */
        if (HIWORD(wParam) == 0 && LOWORD(wParam) == WA_ACTIVE &&
                (HWND) lParam != NULL && (HWND) lParam != (HWND) GetParent(hwnd))
            SetFocus(hwnd);
        return 0;

    case WM_ACTIVATEAPP:
        /*
         * This message is also sent to the root window
         * so we do nothing for individual multiwindow windows
         */
        break;

    case WM_CLOSE:
        /* Removep AppUserModelID property */
        winSetAppUserModelID(hwnd, NULL);
        /* Branch on if the window was killed in X already */
        if (pWinPriv->fXKilled) {
            /* Window was killed, go ahead and destroy the window */
            DestroyWindow(hwnd);
        }
        else {
            /* Tell our Window Manager thread to kill the window */
            wmMsg.msg = WM_WM_KILL;
            if (fWMMsgInitialized)
                winSendMessageToWM(s_pScreenPriv->pWMInfo, &wmMsg);
        }
        return 0;

    case WM_DESTROY:

        /* Branch on if the window was killed in X already */
        if (pWinPriv && !pWinPriv->fXKilled) {
            winDebug ("winTopLevelWindowProc - WM_DESTROY - WM_WM_KILL\n");

            /* Tell our Window Manager thread to kill the window */
            wmMsg.msg = WM_WM_KILL;
            if (fWMMsgInitialized)
                winSendMessageToWM(s_pScreenPriv->pWMInfo, &wmMsg);
        }

        RemoveProp(hwnd, WIN_WINDOW_PROP);
        RemoveProp(hwnd, WIN_WID_PROP);
        RemoveProp(hwnd, WIN_NEEDMANAGE_PROP);

        break;

    case WM_MOVE:
        /* Adjust the X Window to the moved Windows window */
        if (!hasEnteredSizeMove) winAdjustXWindow (pWin, hwnd);
        /* else: Wait for WM_EXITSIZEMOVE */
        return 0;

    case WM_SHOWWINDOW:
        /* Bail out if the window is being hidden */
        if (!wParam)
            return 0;

        /* */
        if (!pWin->overrideRedirect) {
            HWND zstyle = HWND_NOTOPMOST;

            /* Flag that this window needs to be made active when clicked */
            SetProp(hwnd, WIN_NEEDMANAGE_PROP, (HANDLE) 1);

            /* Set the transient style flags */
            if (GetParent(hwnd))
                SetWindowLongPtr(hwnd, GWL_STYLE,
                                 WS_POPUP | WS_OVERLAPPED | WS_SYSMENU |
                                 WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
            /* Set the window standard style flags */
            else
                SetWindowLongPtr(hwnd, GWL_STYLE,
                                 (WS_POPUP | WS_OVERLAPPEDWINDOW |
                                  WS_CLIPCHILDREN | WS_CLIPSIBLINGS)
                                 & ~WS_CAPTION & ~WS_SIZEBOX);

            winUpdateWindowPosition(hwnd, &zstyle);

            {
                WinXWMHints hints;

                if (winMultiWindowGetWMHints(pWin, &hints)) {
                    /*
                       Give the window focus, unless it has an InputHint
                       which is FALSE (this is used by e.g. glean to
                       avoid every test window grabbing the focus)
                     */
                    if (!((hints.flags & InputHint) && (!hints.input))) {
                        SetForegroundWindow(hwnd);
                    }
                }
            }
            wmMsg.msg = WM_WM_MAP3;
        }
        else {                  /* It is an overridden window so make it top of Z stack */

            HWND forHwnd = GetForegroundWindow();
            winDebug ("overridden window is shown\n");
            if (forHwnd != NULL) {
                if (GetWindowLongPtr(forHwnd, GWLP_USERDATA) & (LONG_PTR)
                        VCXSRV_SIGNATURE) {
                    if (GetWindowLongPtr(forHwnd, GWL_EXSTYLE) & WS_EX_TOPMOST)
                        SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
                                     SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                    else
                        SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
                                     SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                }
            }
            wmMsg.msg = WM_WM_MAP2;
        }

        /* Tell our Window Manager thread to map the window */
        if (fWMMsgInitialized)
            winSendMessageToWM(s_pScreenPriv->pWMInfo, &wmMsg);

        winStartMousePolling(s_pScreenPriv);

        return 0;

    case WM_SIZING:
        /* Need to legalize the size according to WM_NORMAL_HINTS */
        /* for applications like xterm */
        return ValidateSizing(hwnd, pWin, wParam, lParam);

    case WM_WINDOWPOSCHANGING:
    {
        /*
          When window is moved or resized, force it to be redrawn, so that
          any OpenGL content is re-drawn correctly, rather than copying bits
          (which seem to be wrong, either because we are copying the wrong
          window in the window heirarchy, or because we don't have the bits
          drawn by OpenGL at all)

          XXX: really this should check if any child has fWglUsed set, but
          that might be expensive to check....
         */
        if (g_fNativeGl)
        {
            LPWINDOWPOS pWinPos = (LPWINDOWPOS)lParam;
            pWinPos->flags |= SWP_NOCOPYBITS;
        }
    }
    break;

    case WM_WINDOWPOSCHANGED:
    {
        LPWINDOWPOS pWinPos = (LPWINDOWPOS) lParam;

        if (!(pWinPos->flags & SWP_NOZORDER)) {
#if CYGWINDOWING_DEBUG
            winDebug("\twindow z order was changed\n");
#endif
            if (pWinPos->hwndInsertAfter == HWND_TOP
                    || pWinPos->hwndInsertAfter == HWND_TOPMOST
                    || pWinPos->hwndInsertAfter == HWND_NOTOPMOST) {
#if CYGWINDOWING_DEBUG
                winDebug("\traise to top\n");
#endif
                /* Raise the window to the top in Z order */
                winRaiseWindow(pWin);
            }
            else if (pWinPos->hwndInsertAfter == HWND_BOTTOM) {
            }
            else {
                /* Check if this window is top of X windows. */
                HWND hWndAbove = NULL;
                DWORD dwCurrentProcessID = GetCurrentProcessId();
                DWORD dwWindowProcessID = 0;

                for (hWndAbove = pWinPos->hwndInsertAfter;
                        hWndAbove != NULL;
                        hWndAbove = GetNextWindow(hWndAbove, GW_HWNDPREV)) {
                    /* Ignore other XWin process's window */
                    GetWindowThreadProcessId(hWndAbove, &dwWindowProcessID);

                    if ((dwWindowProcessID == dwCurrentProcessID)
                            && GetProp(hWndAbove, WIN_WINDOW_PROP)
                            && !IsWindowVisible(hWndAbove)
                            && !IsIconic(hWndAbove))        /* ignore minimized windows */
                        break;
                }
                /* If this is top of X windows in Windows stack,
                   raise it in X stack. */
                if (hWndAbove == NULL) {
#if CYGWINDOWING_DEBUG
                    winDebug("\traise to top\n");
#endif
                    winRaiseWindow(pWin);
                }
            }
        }
    }
        /*
         * Pass the message to DefWindowProc to let the function
         * break down WM_WINDOWPOSCHANGED to WM_MOVE and WM_SIZE.
         */
    break;

    case WM_ENTERSIZEMOVE:
        hasEnteredSizeMove = TRUE;
        return 0;

    case WM_EXITSIZEMOVE:
        /* Adjust the X Window to the moved Windows window */
        hasEnteredSizeMove = FALSE;
        winAdjustXWindow (pWin, hwnd);
        return 0;

    case WM_SIZE:
        /* see dix/window.c */
#ifdef WINDBG
    {
        char buf[64];

        switch (wParam) {
        case SIZE_MINIMIZED:
            strcpy(buf, "SIZE_MINIMIZED");
            break;
        case SIZE_MAXIMIZED:
            strcpy(buf, "SIZE_MAXIMIZED");
            break;
        case SIZE_RESTORED:
            strcpy(buf, "SIZE_RESTORED");
            break;
        default:
            strcpy(buf, "UNKNOWN_FLAG");
        }
        winDebug ("winTopLevelWindowProc - WM_SIZE to %dx%d (%s) - %d ms\n",
                  (int) LOWORD(lParam), (int) HIWORD(lParam), buf,
                  (int) (GetTickCount()));
    }
#endif
    if (!hasEnteredSizeMove)
    {
        /* Adjust the X Window to the moved Windows window */
        winAdjustXWindow (pWin, hwnd);
        if (wParam == SIZE_MINIMIZED) winReorderWindowsMultiWindow();
    }
        /* else: wait for WM_EXITSIZEMOVE */
        return 0; /* end of WM_SIZE handler */

    case WM_STYLECHANGED:
        /* when the style changes, adjust the window size so the client area remains the same */
    {
        LONG x,y;
        DrawablePtr pDraw = &pWin->drawable;
        x =  pDraw->x - wBorderWidth(pWin);
        y = pDraw->y - wBorderWidth(pWin);
        winPositionWindowMultiWindow(pWin, x, y);
    }
    return 0;

    case WM_MOUSEACTIVATE:

        /* Check if this window needs to be made active when clicked */
        if (!GetProp(pWinPriv->hWnd, WIN_NEEDMANAGE_PROP)) {
            winDebug ("winTopLevelWindowProc - WM_MOUSEACTIVATE - "
                      "MA_NOACTIVATE\n");

            /* */
            return MA_NOACTIVATE;
        }
        break;

    case WM_SETCURSOR:
        if (LOWORD(lParam) == HTCLIENT) {
            if (!g_fSoftwareCursor)
                SetCursor(s_pScreenPriv->cursor.handle);
            return TRUE;
        }
        break;

    default:
        break;
    }

    ret = DefWindowProc(hwnd, message, wParam, lParam);
    /*
     * If the window was minized we get the stack change before the window is restored
     * and so it gets lost. Ensure there stacking order is correct.
     */
    if (needRestack)
        winReorderWindowsMultiWindow();
    return ret;
}
示例#11
0
VOID
DisplayErrorMsg(
    LONG msgId,
    ...
    )
/*++

Routine Description:

    This routine displays the error message correspnding to
    the error indicated by msgId.

Arguments:

    msgId - the errorId. This is either the Win32 status code or the message ID.

Return Value:

    None

--*/
{
    
    va_list args;
    LPWSTR lpMsgBuf;

    va_start( args, msgId );
    
    if (FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
        NULL,
        MSG_ERROR,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        NULL
        ))
    {
        wprintf( L"%ws", lpMsgBuf );
        LocalFree( lpMsgBuf );
    }

    if (FormatMessage(
        (msgId >= MSG_FIRST_MESSAGE_ID ? FORMAT_MESSAGE_FROM_HMODULE :
                                        FORMAT_MESSAGE_FROM_SYSTEM)
         | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        msgId,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        &args
        ))
    {
        wprintf( L" %ws \n", (LPSTR)lpMsgBuf );
        LocalFree( lpMsgBuf );
    } else {
        if (NtDllHandle == INVALID_HANDLE_VALUE) {
            NtDllHandle = GetModuleHandle( L"NTDLL" );
        }
        
        if (FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
            (LPVOID)NtDllHandle,
            msgId,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
            (LPWSTR) &lpMsgBuf,
            0,
            &args))
        {
            wprintf( L" %ws \n", (LPSTR)lpMsgBuf );
            LocalFree( lpMsgBuf );
        } else {
            wprintf( L"Unable to format message for id %x - %x\n", msgId, GetLastError( ));
        }
    }
    
    va_end( args );
}
示例#12
0
void win_socket::get_error_text(char* buf, size_t buf_size)
{
    char* msg; 
    char  msgbuf[64];

    switch(errcode) { 
      case ok:
        msg = "ok";
        break;
      case not_opened:
        msg = "socket not opened";
        break;
      case bad_address: 
        msg = "bad address";
        break;
      case connection_failed: 
        msg = "exceed limit of attempts of connection to server";
        break;
      case broken_pipe:
        msg = "connection is broken";
        break; 
      case invalid_access_mode:
        msg = "invalid access mode";
        break;
      default: 
#ifndef PHAR_LAP
        {
          int   len;
#if defined(_WINCE) || defined(UNICODE)
          wchar_t cnvBuf[CNV_BUF_SIZE];
          FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                        NULL,
                        errcode,
                        0,
                        cnvBuf,
                        CNV_BUF_SIZE-1,
                        NULL);
          cnvBuf[CNV_BUF_SIZE-1] = '\0';
          len = wcstombs(buf, cnvBuf, buf_size);
#else
          len = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
                              NULL,
                              errcode,
                              0,
                              buf,
                              (DWORD)buf_size-1,
                              NULL);
#endif
          if (len == 0) { 
              sprintf(msgbuf, "unknown error code %u", errcode);
              msg = msgbuf;
          } else { 
              return;
          }
        }
#else
        sprintf(msgbuf, "System error code: %u", errcode);
        msg = msgbuf;
#endif
    }
    strncpy(buf, msg, buf_size-1);
    buf[buf_size-1] = '\0';
}
SQLRETURN GETOBJREF(SRVR_CALL_CONTEXT *srvrCallContext)
{
	DWORD			dwTimeout = 0;
	DWORD			curTimeout = 0;
	_timeb			time_start;
	_timeb			time_curr;

	SQLRETURN		rc = SQL_SUCCESS;
	CEE_status		sts;
	short			noOfRetries = 0;
	CConnect		*pConnection;
	VERSION_def		version;
	bool			bloop = true;
	int				dwSleep;

	odbcas_ASSvc_GetObjRefHdl_exc_ exception_ = {0,0,0};
	IDL_OBJECT_def		srvrObjRef;
	DIALOGUE_ID_def 	dialogueId = 0;
	SQL_IDENTIFIER_def	dataSource;
    USER_SID_def 		userSid = {0,0};;
    VERSION_LIST_def 	versionList = {0,0};
	long				isoMapping = 0;
	IDL_long			srvrNodeId = -1;
	IDL_long 		    srvrProcessId = -1;
	long long			timestamp = 0;

	IDL_OBJECT_def fwsrvrObjRef;
	char* pTCP;
	char* pIpAddress;
	char* pPortNumber;
	char* pObjectName;
	IDL_OBJECT_def objRef;
	char* pCheckComma;
	char* pCheck;
	char* srvrSegName=NULL;
	int   getObjRefRetryCnt = 0;

	pConnection = (CConnect *)srvrCallContext->sqlHandle;

	dwTimeout = srvrCallContext->u.connectParams.loginTimeout;
	
	if(dwTimeout != 0)
	{
		dwSleep = (dwTimeout / 3) * 1000;
		dwSleep = dwSleep > 5000 ? 5000 : dwSleep;
		dwSleep = dwSleep < 1000 ? 1000 : dwSleep;
	}
	else
		dwSleep = 5000;


	_ftime(&time_start);

TryAgain:

	pConnection->clearError();
		
	sts = odbcas_ASSvc_GetObjRefHdl_(NULL,
								srvrCallContext,
								srvrCallContext->u.connectParams.inContext,
								srvrCallContext->u.connectParams.userDesc,
								CORE_SRVR,
								getObjRefRetryCnt,
								&exception_,
				 				srvrObjRef,
								&dialogueId,
				 				dataSource,
								&userSid,
								&versionList,
								&isoMapping,
								&srvrNodeId,
								&srvrProcessId,
								&timestamp);

	if (sts != CEE_SUCCESS)
	{
		if (sts == CEE_INTERNALFAIL)
			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_EXCEPTION_MSG,0,"ASSOCIATION SERVICE",
				NULL,SQL_ROW_NUMBER_UNKNOWN,SQL_COLUMN_NUMBER_UNKNOWN,2,"Internal Error","GETOBJREF");
		else if (sts == TIMEOUT_EXCEPTION)
			pConnection->setDiagRec(DRIVER_ERROR, IDS_S1_T00, 0, FORMAT_ERROR((long)pConnection->m_asTCPIPSystem));
		else if ((sts == COMM_LINK_FAIL_EXCEPTION) || (sts == TRANSPORT_ERROR))
			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_ASSOC_SRVR_NOT_AVAILABLE,0, FORMAT_ERROR("ASSOCIATION SERVICE",(long)pConnection->m_asTCPIPSystem),
				NULL,SQL_ROW_NUMBER_UNKNOWN,SQL_COLUMN_NUMBER_UNKNOWN,1,"");
		else
			pConnection->setDiagRec(DRIVER_ERROR, IDS_ASSOC_SRVR_NOT_AVAILABLE, sts, FORMAT_ERROR((long)pConnection->m_asTCPIPSystem), 
				NULL, SQL_ROW_NUMBER_UNKNOWN, SQL_COLUMN_NUMBER_UNKNOWN, 1,LAST_ERROR_TO_TEXT());

		if(versionList._buffer != NULL)
			delete versionList._buffer;
		return SQL_ERROR;
	}
	
	/* Starts CCF */
	pConnection->setExceptionErrors(exception_.exception_nr, exception_.exception_detail);

	switch (exception_.exception_nr)
	{
	case CEE_SUCCESS:
		if (srvrObjRef[0] == 0)
		{
			pConnection->setExceptionErrors(odbcas_ASSvc_GetObjRefHdl_ASParamError_exn_,0);
			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_PROGRAM_ERROR, exception_.exception_nr,
					"Invalid Object Reference");
			break;
		}

		pConnection->m_srvrTCPIPSystem->setSwap(pConnection->m_asTCPIPSystem->swap());
		pConnection->setRetSrvrObjRef(srvrObjRef);
		strcpy(fwsrvrObjRef, srvrObjRef);

		strcpy(objRef, srvrObjRef);

		if ((pTCP = strtok(objRef, ":")) != NULL)
		{
			pCheckComma = strchr( srvrObjRef, ',' );
			if (pCheckComma != NULL)
			{
//
// New object ref tcp:\neo0001.$z123,1.2.3.4/18650:ObjectName
//
				pCheck = strtok(NULL,",");
				if (pCheck != NULL)
				{
					if ((pIpAddress = strtok(NULL, "/"))  != NULL)
					{
						if ((pPortNumber = strtok(NULL, ":")) != NULL)
						{
							if ((pObjectName = strtok(NULL, ":")) != NULL)
							{
								sprintf( fwsrvrObjRef, "%s:%s/%s:%s", pTCP,pIpAddress,pPortNumber,pObjectName);
							}
						}
					}
					srvrSegName = strtok(pCheck, ".");
				}
			}
			else
			{
//
// Old object ref tcp:\neo0001.$z123/18650:ObjectName
//
				strcpy(objRef, srvrObjRef);
				pCheck = objRef + 5;
				if ((pIpAddress = strtok(pCheck, ".")) != NULL)
				{
					strtok(NULL, "/");
					if ((pPortNumber = strtok(NULL, ":")) != NULL)
					{
						if ((pObjectName = strtok(NULL, ":")) != NULL)
						{
							sprintf( fwsrvrObjRef, "tcp:%s/%s:%s", pIpAddress,pPortNumber,pObjectName);
						}
					}
					srvrSegName = pIpAddress;
				}
			}
		}
		pConnection->setGetObjRefHdlOutput(fwsrvrObjRef, dialogueId, dataSource, &userSid, &versionList, srvrNodeId, srvrProcessId, timestamp);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASParamError_exn_ :
	// Added check to see if No CPUs or Invalid CPU list are set for MXCS server to start then return 
	// error back to client as param error then parse the error in client to return proper error message.
		pCheck = strstr(exception_.u.ASParamError.ErrorText, "CPU" );
		if (pCheck == NULL)
			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_PROGRAM_ERROR, exception_.exception_nr,
				exception_.u.ASParamError.ErrorText);
		else
			pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_NO_SRVR_AVAILABLE, 0,
				exception_.u.ASNotAvailable.ErrorText);
		break;	
	case odbcas_ASSvc_GetObjRefHdl_LogonUserFailure_exn_ :
		PVOID lpMsgBuf;
		FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
				NULL,
				exception_.u.LogonUserFailure.errorCode,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // Default language
				(LPTSTR) &lpMsgBuf,
				0,
				NULL);
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_UNABLE_TO_LOGON,
			exception_.u.LogonUserFailure.errorCode,
			 (char *)lpMsgBuf);
		LocalFree(lpMsgBuf);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASNotAvailable_exn_ :
		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_ASSOC_SRVR_NOT_AVAILABLE, 0,
			exception_.u.ASNotAvailable.ErrorText);
		break;
	case odbcas_ASSvc_GetObjRefHdl_DSNotAvailable_exn_:
		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_DS_NOT_AVAILABLE,0L,	
			exception_.u.DSNotAvailable.ErrorText);
		break;
	case odbcas_ASSvc_GetObjRefHdl_PortNotAvailable_exn_:
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_PORT_NOT_AVAILABLE);
		break;
	case odbcas_ASSvc_GetObjRefHdl_InvalidUser_exn_:
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_28_000);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASTimeout_exn_ :
		pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_S1_T00);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASNoSrvrHdl_exn_ :
		pConnection->setDiagRec(ASSOC_SERVER_ERROR,IDS_NO_SRVR_AVAILABLE, 0,
			exception_.u.ASNotAvailable.ErrorText);
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASTryAgain_exn_ :
	case -27:
		break;
	case -29:
		break;
	default:
		pConnection->setDiagRec(exception_.exception_nr, GET_OBJECT_REF_PROCNAME,
				pConnection->getSrvrIdentity());
		break;
	}	/* Ends CCF */

	
	switch (pConnection->getExceptionNr())
	{
	case CEE_SUCCESS:
		pConnection->getVersion(&version, NSK_ODBCAS_COMPONENT);
		if (version.componentId != NSK_ODBCAS_COMPONENT ||
			version.majorVersion != NSK_VERSION_MAJOR_1 ||
			version.minorVersion != NSK_VERSION_MINOR_0 )
		{
			char tmp[100];
			IDL_short majorVersion = version.majorVersion;
			IDL_short minorVersion = version.minorVersion;
			majorVersion = (majorVersion > 0)? majorVersion - 1: majorVersion;
			sprintf(tmp,"Incorrect AS version: %d.%d, expected: %d.%d",majorVersion,minorVersion,NSK_VERSION_MAJOR_1 - 1,NSK_VERSION_MINOR_0);
			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_S1_000, 0, tmp,NULL, 0, 0, 1, tmp);
			rc = SQL_ERROR;
		}
		break;
	case odbcas_ASSvc_GetObjRefHdl_ASTryAgain_exn_:
		_ftime(&time_curr);
		curTimeout = (long)(time_curr.time - time_start.time);

		if ((dwTimeout != 0) && (dwTimeout <= curTimeout))
		{
			pConnection->setDiagRec(ASSOC_SERVER_ERROR, IDS_S1_T00);
			rc = SQL_ERROR;
			break;
		}
		else
		{
			if(dwTimeout != 0)
				srvrCallContext->u.connectParams.loginTimeout = dwTimeout - curTimeout;

			Sleep(dwSleep); 
			getObjRefRetryCnt++;
			goto TryAgain;
		}
		break;
	default:
		rc = SQL_ERROR;
		break;
	}

	/*
	 * CleanUp
	 */ 

	if(versionList._buffer != NULL)
		delete versionList._buffer;

	return rc;
}
示例#14
0
文件: w_perror.c 项目: mingpen/OpenNT
int WSA_perror(
char *yourmsg,
int lerrno)
{
    char perr[MAX_MSGTABLE+1];
    unsigned msglen;
    unsigned usMsgNum;

    switch (lerrno) {
        case WSAENAMETOOLONG:
            usMsgNum = IDS_WSAENAMETOOLONG;
            break;
        case WSASYSNOTREADY:
            usMsgNum = IDS_WSASYSNOTREADY;
            break;
        case WSAVERNOTSUPPORTED:
            usMsgNum = IDS_WSAVERNOTSUPPORTED;
            break;
        case WSAESHUTDOWN:
            usMsgNum = IDS_WSAESHUTDOWN;
            break;
        case WSAEINTR:
            usMsgNum = IDS_WSAEINTR;
            break;
        case WSAHOST_NOT_FOUND:
            usMsgNum = IDS_WSAHOST_NOT_FOUND;
            break;
        case WSATRY_AGAIN:
            usMsgNum = IDS_WSATRY_AGAIN;
            break;
        case WSANO_RECOVERY:
            usMsgNum = IDS_WSANO_RECOVERY;
            break;
        case WSANO_DATA:
            usMsgNum = IDS_WSANO_DATA;
            break;
        case WSAEBADF:
            usMsgNum = IDS_WSAEBADF;
            break;
        case WSAEWOULDBLOCK:
            usMsgNum = IDS_WSAEWOULDBLOCK;
            break;
        case WSAEINPROGRESS:
            usMsgNum = IDS_WSAEINPROGRESS;
            break;
        case WSAEALREADY:
            usMsgNum = IDS_WSAEALREADY;
            break;
        case WSAEFAULT:
            usMsgNum = IDS_WSAEFAULT;
            break;
        case WSAEDESTADDRREQ:
            usMsgNum = IDS_WSAEDESTADDRREQ;
            break;
        case WSAEMSGSIZE:
            usMsgNum = IDS_WSAEMSGSIZE;
            break;
        case WSAEPFNOSUPPORT:
            usMsgNum = IDS_WSAEPFNOSUPPORT;
            break;
        case WSAENOTEMPTY:
            usMsgNum = IDS_WSAENOTEMPTY;
            break;
        case WSAEPROCLIM:
            usMsgNum = IDS_WSAEPROCLIM;
            break;
        case WSAEUSERS:
            usMsgNum = IDS_WSAEUSERS;
            break;
        case WSAEDQUOT:
            usMsgNum = IDS_WSAEDQUOT;
            break;
        case WSAESTALE:
            usMsgNum = IDS_WSAESTALE;
            break;
        case WSAEINVAL:
            usMsgNum = IDS_WSAEINVAL;
            break;
        case WSAEMFILE:
            usMsgNum = IDS_WSAEMFILE;
            break;
        case WSAELOOP:
            usMsgNum = IDS_WSAELOOP;
            break;
        case WSAEREMOTE:
            usMsgNum = IDS_WSAEREMOTE;
            break;
        case WSAENOTSOCK:
            usMsgNum = IDS_WSAENOTSOCK;
            break;
        case WSAEADDRNOTAVAIL:
            usMsgNum = IDS_WSAEADDRNOTAVAIL;
            break;
        case WSAEADDRINUSE:
            usMsgNum = IDS_WSAEADDRINUSE;
            break;
        case WSAEAFNOSUPPORT:
            usMsgNum = IDS_WSAEAFNOSUPPORT;
            break;
        case WSAESOCKTNOSUPPORT:
            usMsgNum = IDS_WSAESOCKTNOSUPPORT;
            break;
        case WSAEPROTONOSUPPORT:
            usMsgNum = IDS_WSAEPROTONOSUPPORT;
            break;
        case WSAENOBUFS:
            usMsgNum = IDS_WSAENOBUFS;
            break;
        case WSAETIMEDOUT:
            usMsgNum = IDS_WSAETIMEDOUT;
            break;
        case WSAEISCONN:
            usMsgNum = IDS_WSAEISCONN;
            break;
        case WSAENOTCONN:
            usMsgNum = IDS_WSAENOTCONN;
            break;
        case WSAENOPROTOOPT:
            usMsgNum = IDS_WSAENOPROTOOPT;
            break;
        case WSAECONNRESET:
            usMsgNum = IDS_WSAECONNRESET;
            break;
        case WSAECONNABORTED:
            usMsgNum = IDS_WSAECONNABORTED;
            break;
        case WSAENETDOWN:
            usMsgNum = IDS_WSAENETDOWN;
            break;
        case WSAENETRESET:
            usMsgNum = IDS_WSAENETRESET;
            break;
        case WSAECONNREFUSED:
            usMsgNum = IDS_WSAECONNREFUSED;
            break;
        case WSAEHOSTDOWN:
            usMsgNum = IDS_WSAEHOSTDOWN;
            break;
        case WSAEHOSTUNREACH:
            usMsgNum = IDS_WSAEHOSTUNREACH;
            break;
        case WSAEPROTOTYPE:
            usMsgNum = IDS_WSAEPROTOTYPE;
            break;
        case WSAEOPNOTSUPP:
            usMsgNum = IDS_WSAEOPNOTSUPP;
            break;
        case WSAENETUNREACH:
            usMsgNum = IDS_WSAENETUNREACH;
            break;
        case WSAETOOMANYREFS:
            usMsgNum = IDS_WSAETOOMANYREFS;
            break;
        default:
            return(0);
    }

    if (!(msglen = FormatMessage(
               FORMAT_MESSAGE_FROM_HMODULE,
               (LPVOID)SockModuleHandle,
               usMsgNum,
               0L,
               perr,
               MAX_MSGTABLE,
               NULL))) {
        return(0);
    }

    fprintf(stderr, "-> %s:%s\n", yourmsg, perr);
    return(1);
}
示例#15
0
int main(int argc, char *argv[])
{
    char *filepath, *cmd;
    char fn[SIZE];
    int i;
    int fd, fd_start, fd_end, fd_ret, fd_stdout, fd_stderr;
    time_t now;

#ifdef _WINDOWS
    char full_cmd[SIZE];
    TCHAR w_cmd[SIZE];
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    DWORD ret;
    LPVOID lpMsgBuf;
    char msg[SIZE];
#else
    pid_t pid;
    int ret;
#endif

    if (argc != 3) {
        fprintf(stderr, "%s output_filepath command\n", argv[0]);
        return -1;
    }
    filepath = argv[1];
    cmd = argv[2];
    ret = 127;

    fd = -1;
    fd_start = -1;
    fd_end = -1;
    fd_ret = -1;
    fd_stdout = -1;
    fd_stderr = -1;
    i = 0;
    while (ext[i] != NULL) {
        sprintf(fn, "%s.%s", filepath, ext[i]);
        fd = open(fn, O_WRONLY | O_BINARY | O_TRUNC);
        if (fd < 0) {
            fprintf(stderr, "%s: %s\n", fn, strerror(errno));
            return -1;
        }
        if (i == 0)
            fd_start = fd;
        else if (i == 1)
            fd_end = fd;
        else if (i == 2)
            fd_ret = fd;
        else if (i == 3)
            fd_stdout = fd;
        else if (i == 4)
            fd_stderr = fd;
        else
            close(fd);
        i++;
    }

    fflush(stdout);
    fflush(stderr);
    dup2(fd_stdout, 1);
    dup2(fd_stderr, 2);

    now = time(NULL);
    if (write(fd_start, &now, sizeof(now)) < 0)
        fprintf(stderr, "fd_start: %s\n", strerror(errno));
    close(fd_start);

#ifdef _WINDOWS
    ZeroMemory(full_cmd, sizeof(full_cmd));
    ZeroMemory(w_cmd, sizeof(w_cmd));
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));
    SetLastError(NO_ERROR);

    sprintf(full_cmd, "cmd /q /k \"%s\" & exit !errorlevel!", cmd);
    MultiByteToWideChar(CP_OEMCP, MB_PRECOMPOSED, full_cmd,
                        strlen(full_cmd), w_cmd, sizeof(w_cmd));

    if (0 == CreateProcess(NULL,        /* no module name (use command line) */
                           w_cmd,       /* name of app to launch */
                           NULL,        /* default process security attributes */
                           NULL,        /* default thread security attributes */
                           TRUE,        /* do not inherit handles from the parent */
                           0,   /* normal priority */
                           NULL,        /* use the same environment as the parent */
                           NULL,        /* launch in the current directory */
                           &si, /* startup information */
                           &pi  /* process information stored upon return */
        )) {
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                      FORMAT_MESSAGE_FROM_SYSTEM |
                      FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(),
                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                      (LPTSTR) & lpMsgBuf, 0, NULL);
        WideCharToMultiByte(CP_ACP, 0, (LPTSTR) lpMsgBuf, -1, msg, SIZE,
                            NULL, NULL);
        fprintf(stderr, "failed to create process for [%s]: %s", cmd, msg);
        LocalFree(lpMsgBuf);
    } else {
        WaitForSingleObject(pi.hProcess, INFINITE);
        GetExitCodeProcess(pi.hProcess, &ret);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
    }
#else
    pid = fork();
    if (pid < 0)
        fprintf(stderr, "fork: %s\n", strerror(errno));
    if (pid == 0) {
        execl("/bin/sh", "sh", "-c", cmd, NULL);
        fprintf(stderr, "%s :%s\n", cmd, strerror(errno));
        exit(ret);
    }

    if (pid > 0)
        waitpid(pid, &ret, WUNTRACED);
#endif
    now = time(NULL);
    if (write(fd_end, &now, sizeof(now)) < 0)
        fprintf(stderr, "fd_end: %s\n", strerror(errno));
    close(fd_end);

    if (write(fd_ret, &ret, sizeof(ret)) < 0)
        fprintf(stderr, "fd_ret: %s\n", strerror(errno));
    close(fd_ret);

    close(fd_stdout);
    close(fd_stderr);
    return 0;
}
示例#16
0
SOCKET SocketLayer::CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress, unsigned int sleepOn10048 )
{
	(void) blockingSocket;

	int ret;
	SOCKET listenSocket;
	sockaddr_in listenerSocketAddress;
	// Listen on our designated Port#
	listenerSocketAddress.sin_port = htons( port );
#if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)
	listenSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_VDP );
#else
	listenSocket = socket( AF_INET, SOCK_DGRAM, 0 );
#endif

	if ( listenSocket == (SOCKET) -1 )
	{
#if defined(_WIN32) && !defined(_XBOX) && defined(_DEBUG)
		DWORD dwIOError = GetLastError();
		LPVOID messageBuffer;
		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
			( LPTSTR ) & messageBuffer, 0, NULL );
		// something has gone wrong here...
		RAKNET_DEBUG_PRINTF( "socket(...) failed:Error code - %d\n%s", dwIOError, messageBuffer );
		//Free the buffer.
		LocalFree( messageBuffer );
#endif

		return (SOCKET) -1;
	}

	SetSocketOptions(listenSocket);

	// Fill in the rest of the address structure
	listenerSocketAddress.sin_family = AF_INET;

	if (forceHostAddress && forceHostAddress[0])
	{
//		printf("Force binding %s:%i\n", forceHostAddress, port);
		listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress );
	}
	else
	{
//		printf("Binding any on port %i\n", port);
		listenerSocketAddress.sin_addr.s_addr = INADDR_ANY;
	}

	// bind our name to the socket
	ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) );

	if ( ret <= -1 )
	{
#if defined(_WIN32) && !defined(_XBOX) && !defined(X360)
		DWORD dwIOError = GetLastError();
		if (dwIOError==10048)
		{
			if (sleepOn10048==0)
				return (SOCKET) -1;
			// Vista has a bug where it returns WSAEADDRINUSE (10048) if you create, shutdown, then rebind the socket port unless you wait a while first.
			// Wait, then rebind
			RakSleep(100);

			closesocket(listenSocket);
			listenerSocketAddress.sin_port = htons( port );
			listenSocket = socket( AF_INET, SOCK_DGRAM, 0 );
			if ( listenSocket == (SOCKET) -1 )
				return false;
			SetSocketOptions(listenSocket);

			// Fill in the rest of the address structure
			listenerSocketAddress.sin_family = AF_INET;
			if (forceHostAddress && forceHostAddress[0])
				listenerSocketAddress.sin_addr.s_addr = inet_addr( forceHostAddress );
			else
				listenerSocketAddress.sin_addr.s_addr = INADDR_ANY;

			// bind our name to the socket
			ret = bind( listenSocket, ( struct sockaddr * ) & listenerSocketAddress, sizeof( listenerSocketAddress ) );

			if ( ret >= 0 )
				return listenSocket;
		}
		dwIOError = GetLastError();
		LPVOID messageBuffer;
		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
			( LPTSTR ) & messageBuffer, 0, NULL );
		// something has gone wrong here...
		RAKNET_DEBUG_PRINTF( "bind(...) failed:Error code - %d\n%s", (unsigned int) dwIOError, (char*) messageBuffer );
		//Free the buffer.
		LocalFree( messageBuffer );
#elif (defined(__GNUC__)  || defined(__GCCXML__) || defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)) && !defined(__WIN32)
		switch (ret)
		{
		case EBADF:
			RAKNET_DEBUG_PRINTF("bind(): sockfd is not a valid descriptor.\n"); break;
#if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3)
		case ENOTSOCK:
			RAKNET_DEBUG_PRINTF("bind(): Argument is a descriptor for a file, not a socket.\n"); break;
#endif
		case EINVAL:
			RAKNET_DEBUG_PRINTF("bind(): The addrlen is wrong, or the socket was not in the AF_UNIX family.\n"); break;
		case EROFS:
			RAKNET_DEBUG_PRINTF("bind(): The socket inode would reside on a read-only file system.\n"); break;
		case EFAULT:
			RAKNET_DEBUG_PRINTF("bind(): my_addr points outside the user's accessible address space.\n"); break;
		case ENAMETOOLONG:
			RAKNET_DEBUG_PRINTF("bind(): my_addr is too long.\n"); break;
		case ENOENT:
			RAKNET_DEBUG_PRINTF("bind(): The file does not exist.\n"); break;
		case ENOMEM:
			RAKNET_DEBUG_PRINTF("bind(): Insufficient kernel memory was available.\n"); break;
		case ENOTDIR:
			RAKNET_DEBUG_PRINTF("bind(): A component of the path prefix is not a directory.\n"); break;
		case EACCES:
			RAKNET_DEBUG_PRINTF("bind(): Search permission is denied on a component of the path prefix.\n"); break;
#if !defined(_PS3) && !defined(__PS3__) && !defined(SN_TARGET_PS3)
		case ELOOP:
			RAKNET_DEBUG_PRINTF("bind(): Too many symbolic links were encountered in resolving my_addr.\n"); break;
#endif
		default:
			RAKNET_DEBUG_PRINTF("Unknown bind() error %i.\n", ret); break;
		}
#endif

		return (SOCKET) -1;
	}

	return listenSocket;
}
示例#17
0
文件: s_perror.c 项目: mingpen/OpenNT
void
s_perror(
char *yourmsg,
int lerrno)
{
    char perr[MAX_MSGTABLE+1];
    unsigned msglen;
    unsigned usMsgNum;

    switch (lerrno) {
//        case EZERO:
//            perr = "Error 0";
//            break;
        case EPERM:
        usMsgNum = IDS_EPERM ;
            break;
        case ENOENT:
        usMsgNum = IDS_ENOENT ;
            break;
        case ESRCH:
        usMsgNum = IDS_ESRCH ;
            break;
        case EINTR:
        usMsgNum = IDS_EINTR ;
            break;
        case EIO:
        usMsgNum = IDS_EIO ;
            break;
        case ENXIO:
        usMsgNum = IDS_ENXIO ;
            break;
        case E2BIG:
        usMsgNum = IDS_E2BIG ;
            break;
        case ENOEXEC:
        usMsgNum = IDS_ENOEXEC ;
            break;
        case EBADF:
        usMsgNum = IDS_EBADF ;
            break;
        case ECHILD:
        usMsgNum = IDS_ECHILD ;
            break;
        case EAGAIN:
        usMsgNum = IDS_EAGAIN ;
            break;
        case ENOMEM:
        usMsgNum = IDS_ENOMEM ;
            break;
        case EACCES:
        usMsgNum = IDS_EACCES ;
            break;
        case EFAULT:
        usMsgNum = IDS_EFAULT ;
            break;
//        case ENOTBLK:
//        perr = "Block device required";
//            break;
        case EBUSY:
        usMsgNum = IDS_EBUSY ;
            break;
        case EEXIST:
        usMsgNum = IDS_EEXIST ;
            break;
        case EXDEV:
        usMsgNum = IDS_EXDEV ;
            break;
        case ENODEV:
        usMsgNum = IDS_ENODEV ;
            break;
        case ENOTDIR:
        usMsgNum = IDS_ENOTDIR ;
            break;
        case EISDIR:
        usMsgNum = IDS_EISDIR ;
            break;
        case EINVAL:
        usMsgNum = IDS_EINVAL ;
            break;
        case ENFILE:
        usMsgNum = IDS_ENFILE ;
            break;
        case EMFILE:
        usMsgNum = IDS_EMFILE ;
            break;
        case ENOTTY:
        usMsgNum = IDS_EMFILE ;
            break;
//        case ETXTBSY:
//        perr = "Text file busy";
//            break;
        case EFBIG:
        usMsgNum = IDS_EFBIG ;
            break;
        case ENOSPC:
        usMsgNum = IDS_ENOSPC ;
            break;
        case ESPIPE:
        usMsgNum = IDS_ESPIPE ;
            break;
        case EROFS:
        usMsgNum = IDS_EROFS ;
            break;
        case EMLINK:
        usMsgNum = IDS_EMLINK ;
            break;
        case EPIPE:
        usMsgNum = IDS_EPIPE ;
            break;
        case EDOM:
        usMsgNum = IDS_EDOM ;
            break;
        case ERANGE:
        usMsgNum = IDS_ERANGE ;
            break;
//        case EUCLEAN:
//        perr = "File system not clean";
//            break;
        case EDEADLK:
        usMsgNum = IDS_EDEADLK ;
            break;
        case ENOMSG:
        usMsgNum = IDS_ENOMSG ;
            break;
        case EIDRM:
        usMsgNum = IDS_EIDRM ;
            break;
        case ECHRNG:
        usMsgNum = IDS_ECHRNG ;
            break;
        case EL2NSYNC:
        usMsgNum = IDS_EL2NSYNC ;
            break;
        case EL3HLT:
        usMsgNum = IDS_EL3HLT ;
            break;
        case EL3RST:
        usMsgNum = IDS_EL3RST ;
            break;
        case ELNRNG:
        usMsgNum = IDS_ELNRNG ;
            break;
        case EUNATCH:
        usMsgNum = IDS_EUNATCH ;
            break;
        case ENOCSI:
        usMsgNum = IDS_ENOCSI ;
            break;
        case EL2HLT:
        usMsgNum = IDS_EL2HLT ;
            break;
        case EBADE:
        usMsgNum = IDS_EBADE ;
            break;
        case EBADR:
        usMsgNum = IDS_EBADR ;
            break;
        case EXFULL:
        usMsgNum = IDS_EXFULL ;
            break;
        case ENOANO:
        usMsgNum = IDS_ENOANO ;
            break;
        case EBADRQC:
        usMsgNum = IDS_EBADRQC ;
            break;
        case EBADSLT:
        usMsgNum = IDS_EBADSLT ;
            break;
        case EBFONT:
        usMsgNum = IDS_EBFONT ;
            break;
        case ENOSTR:
        usMsgNum = IDS_ENOSTR ;
            break;
        case ENODATA:
        usMsgNum = IDS_ENODATA ;
            break;
        case ETIME:
        usMsgNum = IDS_ETIME ;
            break;
        case ENOSR:
        usMsgNum = IDS_ENOSR ;
            break;
        case ENONET:
        usMsgNum = IDS_ENONET ;
            break;
        case ENOPKG:
        usMsgNum = IDS_ENOPKG ;
            break;
        case EREMOTE:
        usMsgNum = IDS_EREMOTE ;
            break;
        case ENOLINK:
        usMsgNum = IDS_ENOLINK ;
            break;
        case EADV:
        usMsgNum = IDS_EADV ;
            break;
        case ESRMNT:
        usMsgNum = IDS_ESRMNT ;
            break;
        case ECOMM:
        usMsgNum = IDS_ECOMM ;
            break;
        case EPROTO:
        usMsgNum = IDS_EPROTO ;
            break;
        case EMULTIHOP:
        usMsgNum = IDS_EMULTIHOP ;
            break;
        case ELBIN:
        usMsgNum = IDS_ELBIN ;
            break;
        case EDOTDOT:
        usMsgNum = IDS_EDOTDOT ;
            break;
        case EBADMSG:
        usMsgNum = IDS_EBADMSG ;
            break;
        case ENOTUNIQ:
        usMsgNum = IDS_ENOTUNIQ ;
            break;
        case EREMCHG:
        usMsgNum = IDS_EREMCHG ;
            break;
        case ELIBACC:
        usMsgNum = IDS_ELIBACC;
            break;
        case ELIBBAD:
        usMsgNum = IDS_ELIBBAD ;
            break;
        case ELIBSCN:
        usMsgNum = IDS_ELIBSCN ;
            break;
        case ELIBMAX:
        usMsgNum = IDS_ELIBMAX ;
            break;
        case ELIBEXEC:
        usMsgNum = IDS_ELIBEXEC ;
            break;
        case ENOTSOCK:
        usMsgNum = IDS_ENOTSOCK ;
            break;
        case EADDRNOTAVAIL:
        usMsgNum = IDS_EADDRNOTAVAIL ;
            break;
        case EADDRINUSE:
        usMsgNum = IDS_EADDRINUSE ;
            break;
        case EAFNOSUPPORT:
        usMsgNum = IDS_EAFNOSUPPORT ;
            break;
        case ESOCKTNOSUPPORT:
        usMsgNum = IDS_ESOCKTNOSUPPORT ;
            break;
        case EPROTONOSUPPORT:
        usMsgNum = IDS_EPROTONOSUPPORT ;
            break;
        case ENOBUFS:
        usMsgNum = IDS_ENOBUFS ;
            break;
        case ETIMEDOUT:
        usMsgNum = IDS_ETIMEDOUT ;
            break;
        case EISCONN:
        usMsgNum = IDS_EISCONN ;
            break;
        case ENOTCONN:
        usMsgNum = IDS_ENOTCONN ;
            break;
        case ENOPROTOOPT:
        usMsgNum = IDS_ENOPROTOOPT ;
            break;
        case ECONNRESET:
        usMsgNum = IDS_ECONNRESET ;
            break;
        case ECONNABORT:
        usMsgNum = IDS_ECONNABORT ;
            break;
        case ENETDOWN:
        usMsgNum = IDS_ENETDOWN ;
            break;
        case ECONNREFUSED:
        usMsgNum = IDS_ECONNREFUSED ;
            break;
        case EHOSTUNREACH:
        usMsgNum = IDS_EHOSTUNREACH ;
            break;
        case EPROTOTYPE:
        usMsgNum = IDS_EPROTOTYPE ;
            break;
        case EOPNOTSUPP:
        usMsgNum = IDS_EOPNOTSUPP ;
            break;
        case ESUBNET:
        usMsgNum = IDS_ESUBNET ;
            break;
        case ENETNOLNK:
        usMsgNum = IDS_ENETNOLNK ;
            break;
        case EBADIOCTL:
        usMsgNum = IDS_EBADIOCTL ;
            break;
        case ERESOURCE:
        usMsgNum = IDS_ERESOURCE ;
            break;
        case EPROTUNR:
        usMsgNum = IDS_EPROTUNR ;
            break;
        case EPORTUNR:
        usMsgNum = IDS_EPORTUNR ;
            break;
        case ENETUNR:
        usMsgNum = IDS_ENETUNR ;
            break;
        case EPACKET:
        usMsgNum = IDS_EPACKET ;
            break;
        case ETYPEREG:
        usMsgNum = IDS_ETYPEREG ;
            break;
        case ENOTINIT:
        usMsgNum = IDS_ENOTINIT ;
            break;
        default:
            if (WSA_perror(yourmsg, lerrno)) {
                return;
            }
        usMsgNum = IDS_UNKNOWN ;
            break;
    }

    if (!(msglen = FormatMessage(
               FORMAT_MESSAGE_FROM_HMODULE,
               (LPVOID)SockModuleHandle,
               usMsgNum,
               0L,
               perr,
               MAX_MSGTABLE,
               NULL))) {
    return;
    }

    fprintf(stderr, "> %s:%s\n", yourmsg, perr);
    return;
}
示例#18
0
int SocketLayer::RecvFrom( const SOCKET s, RakPeer *rakPeer, int *errorCode, RakNetSmartPtr<RakNetSocket> rakNetSocket, unsigned short remotePortRakNetWasStartedOn_PS3 )
{
	int len=0;
#if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)
	char dataAndVoice[ MAXIMUM_MTU_SIZE*2 ];
	char *data=&dataAndVoice[sizeof(unsigned short)]; // 2 bytes in
#else
	char data[ MAXIMUM_MTU_SIZE ];
#endif

	if (slo)
	{
		SystemAddress sender;
		len = slo->RakNetRecvFrom(s,rakPeer,data,&sender,true);
		if (len>0)
		{
			ProcessNetworkPacket( sender, data, len, rakPeer, rakNetSocket, RakNet::GetTimeUS() );
			return 1;
		}
	}

	if ( s == (SOCKET) -1 )
	{
		*errorCode = -1;
		return -1;
	}

#if defined (_WIN32) || !defined(MSG_DONTWAIT)
	const int flag=0;
#else
	const int flag=MSG_DONTWAIT;
#endif

	sockaddr_in sa;
	socklen_t len2;
	unsigned short portnum=0;
	if (remotePortRakNetWasStartedOn_PS3!=0)
	{
#if defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)
                                                                                                                                                                                                                                                                           
#endif
	}
	else
	{
		len2 = sizeof( sa );
		sa.sin_family = AF_INET;
		sa.sin_port=0;

#if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)

		/*
		DWORD zero=0;
		WSABUF wsaBuf;
		DWORD lenDword=0;
		wsaBuf.buf=dataAndVoice;
		wsaBuf.len=sizeof(dataAndVoice);
		int result = WSARecvFrom( s, 
			&wsaBuf,
			1,
			&lenDword,
			&zero,
			( sockaddr* ) & sa, ( socklen_t* ) & len2,
			0,0	);
		len=lenDword;
		*/

		len = recvfrom( s, dataAndVoice, sizeof(dataAndVoice), flag, ( sockaddr* ) & sa, ( socklen_t* ) & len2 );
		if (len>2)
		{
			// Skip first two bytes
			len-=2;
		}
#else
		len = recvfrom( s, data, MAXIMUM_MTU_SIZE, flag, ( sockaddr* ) & sa, ( socklen_t* ) & len2 );
#endif

		portnum = ntohs( sa.sin_port );
	}

	if ( len == 0 )
	{
#ifdef _DEBUG
		RAKNET_DEBUG_PRINTF( "Error: recvfrom returned 0 on a connectionless blocking call\non port %i.  This is a bug with Zone Alarm.  Please turn off Zone Alarm.\n", portnum );
		RakAssert( 0 );
#endif

		// 4/13/09 Changed from returning -1 to 0, to prevent attackers from sending 0 byte messages to shutdown the server
		*errorCode = 0;
		return 0;
	}

	if ( len > 0 )
	{
		ProcessNetworkPacket( SystemAddress(sa.sin_addr.s_addr, portnum), data, len, rakPeer, rakNetSocket, RakNet::GetTimeUS() );

		return 1;
	}
	else
	{
		*errorCode = 0;


#if defined(_WIN32) && defined(_DEBUG)

		DWORD dwIOError = WSAGetLastError();

		if ( dwIOError == WSAEWOULDBLOCK )
		{
			return SOCKET_ERROR;
		}
		if ( dwIOError == WSAECONNRESET )
		{
#if defined(_DEBUG)
//			RAKNET_DEBUG_PRINTF( "A previous send operation resulted in an ICMP Port Unreachable message.\n" );
#endif


			unsigned short portnum=0;
			ProcessPortUnreachable(sa.sin_addr.s_addr, portnum, rakPeer);
			// *errorCode = dwIOError;
			return -1;
		}
		else
		{
#if defined(_DEBUG) && !defined(_XBOX) && !defined(X360)
			if ( dwIOError != WSAEINTR && dwIOError != WSAETIMEDOUT)
			{
				LPVOID messageBuffer;
				FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
					NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
					( LPTSTR ) & messageBuffer, 0, NULL );
				// something has gone wrong here...
				RAKNET_DEBUG_PRINTF( "recvfrom failed:Error code - %d\n%s", dwIOError, messageBuffer );

				//Free the buffer.
				LocalFree( messageBuffer );
			}
#endif
		}
#endif
	}

	return 0; // no data
}
示例#19
0
void Error (const char *error, ...)
{
  va_list argptr;
  char	text[4096];

  va_start (argptr,error);
  vsprintf (text, error,argptr);
  va_end (argptr);

  strcat( text, "\n" );

#if defined (__linux__) || defined (__APPLE__)
  if (errno != 0)
  {
    strcat( text, "errno: " );
    strcat( text, strerror (errno));
    strcat( text, "\n");
  }
#endif

#ifdef WIN32
  if (GetLastError() != 0)
  {
    LPVOID lpMsgBuf;
    FormatMessage( 
      FORMAT_MESSAGE_ALLOCATE_BUFFER | 
      FORMAT_MESSAGE_FROM_SYSTEM | 
      FORMAT_MESSAGE_IGNORE_INSERTS,
      0,
      GetLastError(),
      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
      (LPTSTR) &lpMsgBuf,
      0,
      0 
      );
    strcat( text, "GetLastError: " );
    /*
    Gtk will only crunch 0<=char<=127
    this is a bit hackish, but I didn't find useful functions in win32 API for this
    http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516
    */
    TCHAR *scan, *next = (TCHAR*)lpMsgBuf;
    do
    {
      scan = next;
      text[strlen(text)+1] = '\0';
      if ((scan[0] >= 0) && (scan[0] <= 127))
        text[strlen(text)] = char(scan[0]);
      else
        text[strlen(text)] = '?';
      next = CharNext(scan);
    } while (next != scan);
    strcat( text, "\n");
    LocalFree( lpMsgBuf );
  }
#endif

#if 0
  // we need to have a current context to call glError()
  if (g_glwindow_globals.d_glBase != 0)
  {
    // glGetError .. can record several errors, clears after calling
    //++timo TODO: be able to deal with several errors if necessary, for now I'm just warning about pending error messages
    // NOTE: forget that, most boards don't seem to follow the OpenGL standard
    GLenum iGLError = glGetError();
    if (iGLError != GL_NO_ERROR)
    {
      // use our own gluErrorString
      strcat( text, "gluErrorString: " );
      strcat( text, (char*)gluErrorString( iGLError ) );
      strcat( text, "\n" );
    }
  }
#endif

  strcat (text, "An unrecoverable error has occured.\n");

  ERROR_MESSAGE(text);

  // force close logging if necessary
	Sys_LogFile(false);

  _exit (1);
}
示例#20
0
int SocketLayer::SendTo( SOCKET s, const char *data, int length, unsigned int binaryAddress, unsigned short port, unsigned short remotePortRakNetWasStartedOn_PS3 )
{
	RakAssert(length<=MAXIMUM_MTU_SIZE-UDP_HEADER_SIZE);
	RakAssert(port!=0);
	if (slo)
	{
		SystemAddress sa(binaryAddress,port);
		return slo->RakNetSendTo(s,data,length,sa);
	}

	if ( s == (SOCKET) -1 )
	{
		return -1;
	}

	int len=0;

	if (remotePortRakNetWasStartedOn_PS3!=0)
	{
		len = SendTo_PS3Lobby(s,data,length,binaryAddress,port, remotePortRakNetWasStartedOn_PS3);
	}
	else
	{

#if (defined(_XBOX) || defined(_X360)) && defined(RAKNET_USE_VDP)
		len = SendTo_360(s,data,length,0,0,binaryAddress,port);
#else
		len = SendTo_PC(s,data,length,binaryAddress,port);
#endif
	}

	if ( len != -1 )
		return 0;

#if defined(_WIN32) && !defined(_WIN32_WCE)

	DWORD dwIOError = WSAGetLastError();

	if ( dwIOError == WSAECONNRESET )
	{
#if defined(_DEBUG)
		RAKNET_DEBUG_PRINTF( "A previous send operation resulted in an ICMP Port Unreachable message.\n" );
#endif

	}
	else if ( dwIOError != WSAEWOULDBLOCK && dwIOError != WSAEADDRNOTAVAIL)
	{
#if defined(_WIN32) && !defined(_XBOX) && !defined(X360) && defined(_DEBUG)
		LPVOID messageBuffer;
		FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL, dwIOError, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),  // Default language
			( LPTSTR ) & messageBuffer, 0, NULL );
		// something has gone wrong here...
		RAKNET_DEBUG_PRINTF( "sendto failed:Error code - %d\n%s", dwIOError, messageBuffer );

		//Free the buffer.
		LocalFree( messageBuffer );
#endif

	}

	return dwIOError;
#endif

	return 1; // error
}
示例#21
0
    /*
     * Write error message to Event Log, console or pop-up window
     *
     * If useGetLastError is 1, the last error returned from GetLastError()
     * is appended to pszMessage, separated by a ": ".
     *
     * eventLogType:                 MessageBox equivalent:
     * 
     * EVENTLOG_INFORMATION_TYPE     MB_ICONASTERISK
     * EVENTLOG_WARNING_TYPE         MB_ICONEXCLAMATION
     * EVENTLOG_ERROR_TYPE           MB_ICONSTOP
     * 
     */
VOID
ProcessError (WORD eventLogType, LPCTSTR pszMessage, int useGetLastError, int quiet)
{
  LPTSTR pErrorMsgTemp = NULL;
  HANDLE hEventSource = NULL;
  TCHAR pszMessageFull[MAX_STR_SIZE]; /* Combined pszMessage and GetLastError */

  /*
   * If useGetLastError enabled, generate text from GetLastError() and append to
   * pszMessageFull
   */
  if (useGetLastError) {
  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
		 FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),
		 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) & pErrorMsgTemp, 0, NULL);

    _snprintf (pszMessageFull, sizeof(pszMessageFull), "%s: %s", pszMessage, pErrorMsgTemp);
    if (pErrorMsgTemp) {
      LocalFree (pErrorMsgTemp);
      pErrorMsgTemp = NULL;
    }
  }
  else {
    _snprintf (pszMessageFull, sizeof(pszMessageFull), "%s", pszMessage);
  }
  
  hEventSource = RegisterEventSource (NULL, app_name);
  if (hEventSource != NULL) {
    pErrorMsgTemp = pszMessageFull;
    
    if (ReportEvent (hEventSource, 
          eventLogType, 
          0,
          DISPLAY_MSG,	/* To Just output the text to event log */
          NULL, 
          1, 
          0, 
          &pErrorMsgTemp, 
          NULL)) {
    }
    else {
      FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
          FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError (),
          MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
          (LPTSTR) & pErrorMsgTemp, 0, NULL);
      
      fprintf(stderr,"Could NOT lot to Event Log.  Error returned from ReportEvent(): %s\n",pErrorMsgTemp);
      if (pErrorMsgTemp) {
        LocalFree (pErrorMsgTemp);
        pErrorMsgTemp = NULL;
      }
    }
    DeregisterEventSource (hEventSource);
    }

      if (quiet) {
    fprintf(stderr,"%s\n",pszMessageFull);
      }
      else {
    switch (eventLogType) {
      case EVENTLOG_INFORMATION_TYPE:
        MessageBox (NULL, pszMessageFull, app_name, MB_ICONASTERISK);
        break;
      case EVENTLOG_WARNING_TYPE:
        MessageBox (NULL, pszMessageFull, app_name, MB_ICONEXCLAMATION);
        break;
      case EVENTLOG_ERROR_TYPE:
        MessageBox (NULL, pszMessageFull, app_name, MB_ICONSTOP);
        break;
      default:
        MessageBox (NULL, pszMessageFull, app_name, EVENTLOG_WARNING_TYPE);
        break;
      }
    }
  
  LocalFree (pErrorMsgTemp);  
}
示例#22
0
/**
 outTitle should be set before the call
 */
static void createErrorMessage(
    const char*         expression,
    const std::string&  message,
    const char*         filename,
    int                 lineNumber,
    std::string&        outTitle,
    std::string&        outMessage) {

    std::string le = "";
    const char* newline = "\n";

    #ifdef G3D_WIN32
        newline = "\r\n";

        // The last error value.  (Which is preserved across the call).
        DWORD lastErr = GetLastError();
    
        // The decoded message from FormatMessage
        LPTSTR formatMsg = NULL;

        if (NULL == formatMsg) {
            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                          FORMAT_MESSAGE_IGNORE_INSERTS |
                          FORMAT_MESSAGE_FROM_SYSTEM,
                            NULL,
                            lastErr,
                            0,
                            (LPTSTR)&formatMsg,
                            0,
                            NULL);
        }

        // Make sure the message got translated into something.
        LPTSTR realLastErr;
        if (NULL != formatMsg) {
            realLastErr = formatMsg;
        } else {
            realLastErr = _T("Last error code does not exist.");
        }

		if (lastErr != 0) {
	        le = G3D::format("Last Error (0x%08X): %s\r\n\r\n", lastErr, (LPCSTR)realLastErr);
		}

        // Get rid of the allocated memory from FormatMessage.
        if (NULL != formatMsg) {
            LocalFree((LPVOID)formatMsg);
        }

        char modulePath[MAX_PATH];
        GetModuleFileNameA(NULL, modulePath, MAX_PATH);

        const char* moduleName = strrchr(modulePath, '\\');
        outTitle = outTitle + string(" - ") + string(moduleName ? (moduleName + 1) : modulePath);

    #endif

    // Build the message.
    outMessage =
        G3D::format("%s%s%sExpression: %s%s%s:%d%s%s%s", 
                 message.c_str(), newline, newline, expression, newline, 
                 filename, lineNumber, newline, newline, le.c_str());
}
示例#23
0
bool _al_show_native_file_dialog(ALLEGRO_DISPLAY *display,
   ALLEGRO_NATIVE_DIALOG *fd)
{
   OPENFILENAME ofn;
   ALLEGRO_DISPLAY_WIN *win_display;
   int flags = 0;
   bool ret;
   char buf[4096] = "";
   ALLEGRO_USTR *filter_string = NULL;

   win_display = (ALLEGRO_DISPLAY_WIN *)display;

   if (fd->flags & ALLEGRO_FILECHOOSER_FOLDER) {
      return select_folder(win_display, fd);
   }

   /* Selecting a file. */
   memset(&ofn, 0, sizeof(OPENFILENAME));
   ofn.lStructSize = sizeof(OPENFILENAME);
   ofn.hwndOwner = (win_display) ? win_display->window : NULL;

   /* Create filter string. */
   if (fd->fc_patterns) {
      filter_string = create_filter_string(fd->fc_patterns);
      ofn.lpstrFilter = al_cstr(filter_string);
   }
   else {
      /* List all files by default. */
      ofn.lpstrFilter = "All Files\0*.*\0\0";
   }

   ofn.lpstrFile = buf;
   ofn.nMaxFile = sizeof(buf);

   if (fd->fc_initial_path) {
      ofn.lpstrInitialDir =
         al_path_cstr(fd->fc_initial_path, ALLEGRO_NATIVE_PATH_SEP);
   }

   if (fd->title)
      ofn.lpstrTitle = al_cstr(fd->title);

   flags |= OFN_NOCHANGEDIR | OFN_EXPLORER;
   if (fd->flags & ALLEGRO_FILECHOOSER_SAVE) {
      flags |= OFN_OVERWRITEPROMPT;
   }
   else {
      flags |= (fd->flags & ALLEGRO_FILECHOOSER_FILE_MUST_EXIST) ? OFN_FILEMUSTEXIST : 0;
   }
   flags |= (fd->flags & ALLEGRO_FILECHOOSER_MULTIPLE) ? OFN_ALLOWMULTISELECT : 0;
   flags |= (fd->flags & ALLEGRO_FILECHOOSER_SHOW_HIDDEN) ? 0x10000000 : 0; // NOTE: 0x10000000 is FORCESHOWHIDDEN
   ofn.Flags = flags;

   if (flags & OFN_OVERWRITEPROMPT) {
      ret = GetSaveFileName(&ofn);
   }
   else {
      ret = GetOpenFileName(&ofn);
   }

   al_ustr_free(filter_string);

   if (!ret) {
      DWORD err = GetLastError();
      if (err != ERROR_SUCCESS) {
         char buf[1000];
         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, buf, sizeof(buf), NULL);
         ALLEGRO_ERROR("al_show_native_file_dialog failed: %s\n", buf);
      }
      return false;
   }

   if (flags & OFN_ALLOWMULTISELECT) {
      int i;
      /* Count number of file names in buf. */
      fd->fc_path_count = 0;
      i = skip_nul_terminated_string(buf);
      while (1) {
         if (buf[i] == '\0') {
            fd->fc_path_count++;
            if (buf[i+1] == '\0')
               break;
         }
         i++;
      }
   }
   else {
      fd->fc_path_count = 1;
   }

   if (fd->fc_path_count == 1) {
      fd->fc_paths = al_malloc(sizeof(void *));
      fd->fc_paths[0] = al_create_path(buf);
   }
   else {
      int i, p;
      /* If multiple files were selected, the first string in buf is the
       * directory name, followed by each of the file names terminated by NUL.
       */
      fd->fc_paths = al_malloc(fd->fc_path_count * sizeof(void *));
      i = skip_nul_terminated_string(buf);
      for (p = 0; p < (int)fd->fc_path_count; p++) {
         fd->fc_paths[p] = al_create_path_for_directory(buf);
         al_set_path_filename(fd->fc_paths[p], buf+i);
         i += skip_nul_terminated_string(buf+i);
      }
   }

   return true;
}
示例#24
0
文件: client_common.c 项目: No9/uftp
/**
 * Run the postreceive script on list of received files
 */
void run_postreceive_multi(struct group_list_t *group, char *const *files,
                           int count)
{
    char **params;
    char gid_str[10];
    char gid_param[] = "-I";
    int i;

    if (!strcmp(postreceive, "")) {
        return;
    }

    params = safe_calloc(count + 4, sizeof(char *));

    snprintf(gid_str, sizeof(gid_str), "%08X", group->group_id);

    params[0] = postreceive;
    params[1] = gid_param;
    params[2] = gid_str;
    for (i = 0; i < count; i++) {
        params[i+3] = files[i];
    }
    params[count+4-1] = NULL;

    if (log_level >= 2) {
        cglog2(group, "Running postreceive: %s", postreceive);
        for (i = 1; i < count + 3; i++) {
            sclog2(" %s", params[i]);
        }
        slog2("");
    }

#ifdef WINDOWS
    {
        char cmdline[0x8000];  // Windows max command line length
        char cmdexe[MAXPATHNAME];
        int too_long, rval, is_cmd;

        strcpy(cmdline, "");
        if ((!strncmp(&postreceive[strlen(postreceive)-4], ".cmd", 4)) ||
                (!strncmp(&postreceive[strlen(postreceive)-4], ".bat", 4))) {
            is_cmd = 1;
            if (!GetEnvironmentVariable("SystemRoot", cmdexe, sizeof(cmdexe))) {
                char errbuf[300];
                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
                              0, errbuf, sizeof(errbuf), NULL);
                glog0(group, "Error getting sysroot: (%d) %s",
                             GetLastError(), errbuf);
                free(params);
                return;
            }
            strcat(cmdexe, "\\system32\\cmd.exe");
            strcat(cmdline, "/c \"");
        } else {
            is_cmd = 0;
        }
        for (too_long = 0, i = 0; i < count + 3; i++) {
            int size = 0x8000 - strlen(cmdline);
            if (size <= (int)strlen(params[i]) + 4) {
                too_long = 1;
                break;
            }
            // Quote everything except -I {group_id}
            if (i == 1 || i == 2) {
                strcat(cmdline, params[i]);
                strcat(cmdline," ");
            } else {
                strcat(cmdline, "\"");
                strcat(cmdline, params[i]);
                strcat(cmdline,"\" ");
            }
        }
        if (is_cmd) {
            strcat(cmdline, "\"");
        }

        if (!too_long) {
            STARTUPINFO startup_info;
            PROCESS_INFORMATION proc_info;

            GetStartupInfo(&startup_info);
            rval = CreateProcess(is_cmd ? cmdexe : postreceive, cmdline,
                NULL, NULL, 0, CREATE_NO_WINDOW, NULL, NULL,
                &startup_info, &proc_info);
            if (!rval) {
                char errbuf[300];
                FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
                              0, errbuf, sizeof(errbuf), NULL);
                glog0(group, "Error running script: (%d) %s",
                             GetLastError(), errbuf);
            }
        }
    }
#else
    {
        pid_t pid;
        if ((pid = fork()) == -1) {
            gsyserror(group, "fork failed");
        } else if (pid == 0) {
            close(listener);
            close(1);
            close(2);
            execv(postreceive, params);
            gsyserror(group, "exec failed");
            exit(1);
        }
    }
#endif

    free(params);
}
示例#25
0
// 0 if it can't get the resource, 1 if it can
// -1 if fail
int vrpn_Semaphore::condP()
{
    int iRetVal = 1;
#ifdef sgi
    if (fUsingLock) {
        // don't spin at all
        iRetVal = uscsetlock(l, 0);
        if (iRetVal <= 0) {
            perror("vrpn_Semaphore::condP: uscsetlock:");
            return -1;
        }
    }
    else {
        iRetVal = uscpsema(ps);
        if (iRetVal <= 0) {
            perror("vrpn_Semaphore::condP: uscpsema:");
            return -1;
        }
    }
#elif defined(_WIN32)
    switch (WaitForSingleObject(hSemaphore, 0)) {
    case WAIT_OBJECT_0:
        // got the resource
        break;
    case WAIT_TIMEOUT:
        // resource not free
        iRetVal = 0;
        break;
    case WAIT_ABANDONED:
        ALL_ASSERT(0, "vrpn_Semaphore::condP: thread holding resource died");
        return -1;
        break;
    case WAIT_FAILED:
        // get error info from windows (from FormatMessage help page)
        LPVOID lpMsgBuf;

        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
            GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            // Default language
            (LPTSTR)&lpMsgBuf, 0, NULL);
        fprintf(stderr,
            "Semaphore::condP: error waiting for resource, "
            "WIN32 WaitForSingleObject call caused the following error: %s",
            (LPTSTR)lpMsgBuf);
        // Free the buffer.
        LocalFree(lpMsgBuf);
        return -1;
        break;
    default:
        ALL_ASSERT(0, "vrpn_Semaphore::p: unknown return code");
        return -1;
    }
#else
    // Posix by default
    iRetVal = sem_trywait(semaphore);
    if (iRetVal == 0) {
        iRetVal = 1;
    }
    else if (errno == EAGAIN) {
        iRetVal = 0;
    }
    else {
        perror("vrpn_Semaphore::condP: ");
        iRetVal = -1;
    }
#endif
    return iRetVal;
}
示例#26
0
文件: client_common.c 项目: No9/uftp
/**
 * For the current file in a group, move the existing file to
 * the appropriate backup directory, if it exists.
 * In the event of a failure, delete the original file
 */
void move_to_backup(struct group_list_t *group)
{
    stat_struct statbuf;
    char backup_file[MAXBACKUPPATHNAME], *trim_name;
    int len;

    if (lstat_func(group->fileinfo.filepath, &statbuf) == -1) {
        return;
    }

    if (backupcnt == 0) {
        clear_path(group->fileinfo.filepath, group);
        return;
    }

#ifdef WINDOWS
    if ((group->fileinfo.filepath[1] == ':') &&
            (group->fileinfo.filepath[2] == '\\')) {
        trim_name = &group->fileinfo.filepath[3];
    } else {
        trim_name = group->fileinfo.filepath;
    }
#else
    trim_name = group->fileinfo.filepath;
#endif
    len = snprintf(backup_file, sizeof(backup_file), "%s%c%s%c%s%c%s",
                   backupdir[group->fileinfo.destdiridx], PATH_SEP,
                   group->start_date, PATH_SEP,
                   group->start_time, PATH_SEP, trim_name);
    if (len >= sizeof(backup_file)) {
        glog0(group, "Max pathname length exceeded for backup file, deleting",
                     group->fileinfo.filepath);
        clear_path(group->fileinfo.filepath, group);
        return;
    }
    clear_path(backup_file, group);
    if (!create_path_to_file(group, backup_file)) {
        glog0(group, "Error creating path to backup file");
        clear_path(group->fileinfo.filepath, group);
    }
#ifdef WINDOWS
    if (!MoveFile(group->fileinfo.filepath, backup_file)) {
        char errbuf[300];
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL,
                GetLastError(), 0, errbuf, sizeof(errbuf), NULL);
        glog0(group, "Couldn't rename from %s to %s, deleting: (%d): %s",
                group->fileinfo.filepath, backup_file, GetLastError(), errbuf);
        clear_path(group->fileinfo.filepath, group);
    } else {
        glog2(group, "Backed up existing file to %s", backup_file);
    }
#else
    if (rename(group->fileinfo.filepath, backup_file) == -1) {
        gsyserror(group, "Couldn't rename from %s to %s, deleting",
                         group->fileinfo.filepath, backup_file);
        clear_path(group->fileinfo.filepath, group);
    } else {
        glog2(group, "Backed up existing file to %s", backup_file);
    }
#endif
}
示例#27
0
//__________________________________________________________________________________
int main (int argc, char* argv[])
{
	mainArgCount = argc - 1;
	
	
	#ifdef	__HYPHYMPI__
		  int 		   rank, 
		  			   size;
		  			   			   			 
		  MPI_Init	   (&argc, &argv);
		  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
		  MPI_Comm_size(MPI_COMM_WORLD, &size);
		  
		  setParameter  (mpiNodeID,    (_Parameter)rank);
		  setParameter	(mpiNodeCount, (_Parameter)size);
		  _hy_mpi_node_rank = rank;
		  
		  if (rank == 0)
		  {
			  mpiNodesThatCantSwitch.Populate (size,1,0);		  	
			/* {
				  char hostname[256];
				  gethostname(hostname, sizeof(hostname));
				  printf("PID %d on %s ready for attach\n", getpid(), hostname);
				  fflush(stdout);
				  //getchar ();
			  }	*/	
#endif
	
	
	//for (long k=0; k<NSIG; k++)
	//{
	//	signal(k, &hyphyBreak);
	//}
	
	#ifdef	__HYPHYMPI__
		  }
	#endif
	
	char 	curWd[4096],
		    dirSlash = GetPlatformDirectoryChar ();
	getcwd (curWd,4096);

	_String baseDir (curWd), 
			argFile;
		

	baseDir=baseDir & dirSlash;
	pathNames&& &baseDir;
	
	baseDirectory = baseDir;
	baseArgDir	  = baseDirectory;
	
	_ExecutionList ex;
			
#ifdef _OPENMP
	systemCPUCount = omp_get_max_threads();
#endif
	
#ifdef _MINGW32_MEGA_
	{
		char pid[16];
		snprintf (pid,16,"%u", GetCurrentProcessId());
		
		_String pipeName = _String("\\\\.\\pipe\\MEGAPipe") & pid;
		printf ("Pipe name = %s\n", pipeName.sData);
		if ((_HY_MEGA_Pipe = CreateFile(pipeName.sData, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)
		{
			char* lpMsgBuf;
			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER | 
				FORMAT_MESSAGE_FROM_SYSTEM |
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				GetLastError(),
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				(LPTSTR) &lpMsgBuf,
				0, NULL );
			FlagError (_String("Failed to create a pipe named '") & pipeName & "' to send data from HyPhy to MEGA. Error: "&lpMsgBuf);
		}
	}
#endif	
	
	for (long i=1; i<argc;i++)
	{
		_String thisArg (argv[i]);
		if (thisArg.sData[0]=='-')
		{
			ProcessConfigStr (thisArg);
		}
		else
			if (thisArg.beginswith ("BASEPATH="))
			{
				baseArgDir = thisArg.Cut(9,-1);
				if (baseArgDir.sLength)
				{
					if (baseArgDir.sData[baseArgDir.sLength-1]!=dirSlash)
						baseArgDir = baseArgDir&dirSlash;
						
					baseDirectory = baseArgDir;
				}
			}
			else
				if (thisArg.beginswith ("USEPATH="))
				{
					baseDir 			= thisArg.Cut(8,-1);
					errorFileName 		= baseDir & errorFileName;
					messageFileName 	= baseDir & messageFileName;
					pathNames.Delete 	(0);
					pathNames&& 		&baseDir;
				}
				else
					#ifdef __MP__
					if (thisArg.beginswith ("CPU="))
					{
						_String cpus = thisArg.Cut(4,-1);
						systemCPUCount = cpus.toNum();
						if (systemCPUCount<1)
							systemCPUCount = 1;
						pthread_setconcurrency (systemCPUCount+1);
					}
					else
					#endif
				argFile = thisArg;
	}
	
  	GlobalStartup();

	if (calculatorMode)
	{
		printf ("\nHYPHY is running in calculator mode. Type 'exit' when you are finished.\n");
		while (ExpressionCalculator()) ;
		return 0;
	}
	
	if (pipeMode)
	{
		_String bfIn (stdin);
		_ExecutionList exIn (bfIn);
		exIn.Execute();
		GlobalShutdown();
		return 0;
	}
	
	// try to read the preferences
	_String		prefFile (curWd);
	prefFile = prefFile & '/' & prefFileName;
	FILE	 * testPrefFile = fopen (prefFile.sData,"r");
	if (!testPrefFile)
	{
		prefFile = baseArgDir & prefFileName;
		testPrefFile = fopen (prefFile.sData,"r");
	}
	if (testPrefFile)
	{		
		fclose(testPrefFile);
		ReadBatchFile (prefFile,ex);
		ex.Execute();
		ex.Clear();
	}
	//printf ("Node %d before mpiParallelOptimizer\n", rank);
	#ifdef __HYPHYMPI__
		if (rank>0)
		{
			//if (mpiParallelOptimizer || mpiPartitionOptimizer)
			//	mpiOptimizerLoop (rank, size);
			//else
			mpiNormalLoop (rank, size, baseDir);
			/*argFile = "SHUTDOWN_CONFIRM";
			MPISendString (argFile, senderID);*/
		}
		else
		{
	#endif
	if (!argFile.sLength)
	{	
		long selection = -2;
		if (!updateMode)
			selection = DisplayListOfChoices();

		if (selection == -1)
		{			
			dialogPrompt = "Batch file to run:";
			_String fStr (ReturnDialogInput (true));
			if (logInputMode)
			{
				_String tts = loggedFileEntry&fStr;
				loggedUserInputs && & tts;
			}
			
			PushFilePath (fStr);
			ReadBatchFile (fStr,ex);
		}
		else
		{
			_String templ;

			if (selection >= 0)
			    templ = baseArgDir &"TemplateBatchFiles" & dirSlash;
			else
			  	templ = baseArgDir & "TemplateBatchFiles" & dirSlash & "WebUpdate.bf";				
			
			if (selection >= 0)
				templ= templ&*(_String*)(*(_List*)availableTemplateFiles(selection))(2);

			PushFilePath (templ);
			ReadBatchFile (templ,ex);
		}
	}
	else
	{
#ifndef __MINGW32__
		if (argFile.sData[0] != '/')
			argFile		  = baseDirectory & argFile;
#else
		if (argFile.sData[1] != ':') // not an absolute path 
			argFile		  = baseDirectory & argFile;		
#endif
		PushFilePath  (argFile);
		ReadBatchFile (argFile,ex);
	}
	
	ex.Execute();
	
	if (usePostProcessors && (!updateMode))
	{
		ReadInPostFiles();
		printf ("\n\n**********Continue with result processing (y/n)?");
		_String c_str (StringFromConsole());
	
		if (logInputMode)
			loggedUserInputs && & c_str;

		if (c_str.getChar(0) !='n' && c_str.getChar(0)!='N' )
		{
			long choice = DisplayListOfPostChoices();
			while (choice != -1)
			{
				_ExecutionList postEx;
				argFile = *(_String*)(*(_List*)availablePostProcessors(choice-1))(1);
				PushFilePath (argFile);
				ReadBatchFile (argFile, postEx);
				postEx.Execute();	
				PopFilePath ();
				printf ("\n\n**********Continue with result processing (y/n)?");

				c_str = StringFromConsole();
				if (logInputMode)
					loggedUserInputs && & c_str;

				if (c_str.getChar(0)=='n' || c_str.getChar(0)=='N' ) 
					break;
				
				choice = DisplayListOfPostChoices();				
			}
		}
	}
	#ifdef __HYPHYMPI__
	}
	ReportWarning				(_String ("Node ") & (long)rank & " is shutting down\n");
	#endif
	
	
#ifdef _MINGW32_MEGA_
	if (_HY_MEGA_Pipe != INVALID_HANDLE_VALUE)
		CloseHandle (_HY_MEGA_Pipe);
#endif
	
	PurgeAll					(true);
	GlobalShutdown				();
	
	#ifdef __HYPHYMPI__
		if (rank == 0)
			printf ("\n\n");			
	#endif
	
}
示例#28
0
static int logg_internal(const enum loglevel level,
                         const char *file,
                         const char *func,
                         const unsigned int line,
                         int log_errno,
                         const char *fmt,
                         va_list args
                        )
{
	struct big_buff *logg_buff;
	int ret_val, old_errno, retry_cnt;

	old_errno  = errno;

	/* get our tls-print buf */
	if(!(logg_buff = logg_get_buf()))
	{
		/*
		 * hmmm, something went wrong, lets see, if we can get the message to
		 * the user by other means
		 */
		return do_vlogging(level, fmt, args);
	}

	/* add time, if wanted, to buffer */
	if(server.settings.logging.add_date_time)
		logg_buff->pos += add_time_to_buffer(buffer_start(*logg_buff), buffer_remaining(*logg_buff));

	/* put out the "extra" stuff, if there */
	if(file)
	{
		retry_cnt = 0;
		prefetch(strlpcpy);
		prefetch(file);
		prefetch(func);
		/*
		 * calling snprintf for 2 * strcpy + an itoa is "nice"
		 * but goes round the full stdio bloat:
		 * snprintf->vsnprintf->vfprintf-> myriads of funcs to print
		 */
		do
		{
			char *sptr, *stmp, *rstart;
			size_t remaining;

			stmp = sptr = buffer_start(*logg_buff);
			remaining = buffer_remaining(*logg_buff);
			rstart = strlpcpy(sptr, file, remaining);
			remaining -= rstart - sptr;
			if(unlikely(remaining < 7))
				goto realloc;
			sptr = rstart;

			*sptr++ = ':';
			remaining--;
			rstart = strlpcpy(sptr, func, remaining);
			remaining -= rstart - sptr;
			if(unlikely(remaining < 18)) /* make sure we have enough space */
				goto realloc;
			sptr = rstart;

			*sptr++ = '(';
			*sptr++ = ')';
			*sptr++ = '@';
			remaining -= 3;
			rstart = put_dec_trunc(sptr, line); /* 99,999 lines should be... */
			strreverse(sptr, rstart - 1);
			remaining -= rstart - sptr;
			if(unlikely(remaining < 2))
				goto realloc;
			sptr = rstart;
			*sptr++ = ':';
			*sptr++ = ' ';
			logg_buff->pos += sptr - stmp;
			break;
realloc:
			/* now we are in a slow path, no need to hurry */
			{
				struct big_buff *tmp_buff;
				size_t len = strlen(file) + strlen(func) + 6 + 30 + strlen(fmt) * 3;
				len = ROUND_ALIGN(len * 2, 2048) + logg_buff->capacity;
				tmp_buff = realloc(logg_buff, sizeof(*logg_buff) + len);
				if(tmp_buff) {
					logg_buff = tmp_buff;
					logg_buff->limit = logg_buff->capacity = len;
				} else
					break;
				retry_cnt++;
			}
		} while(retry_cnt < 4);
	}

	ret_val = 0; retry_cnt = 0;
	/* format the message in tls */
	do
	{
		size_t len = logg_buff->capacity;
		va_list tmp_valist;
		if(ret_val < 0)
		{
			len *= 2;
			if(++retry_cnt > 4) {
				ret_val = 0;
				break;
			}
		}
		else if((size_t)ret_val > buffer_remaining(*logg_buff))
			len = ROUND_ALIGN((size_t)ret_val * 2, 1024); /* align to a k */
		if(unlikely(len != logg_buff->capacity))
		{
			struct big_buff *tmp_buf = realloc(logg_buff, sizeof(*logg_buff) + len);
			if(tmp_buf) {
				logg_buff = tmp_buf;
				logg_buff->limit = logg_buff->capacity = len;
			} else {
				ret_val = buffer_remaining(*logg_buff);
				break;
			}
		}
		/* put msg printed out in buffer */
		va_copy(tmp_valist, args);
		ret_val = my_vsnprintf(buffer_start(*logg_buff), buffer_remaining(*logg_buff), fmt, tmp_valist);
		va_end(tmp_valist);
		/* error? repeat */
	} while(unlikely(ret_val < 0 || (size_t)ret_val > buffer_remaining(*logg_buff)));
	logg_buff->pos += (size_t)ret_val;

	/* add errno string if wanted */
	if(log_errno)
	{
		if(buffer_remaining(*logg_buff) < STRERROR_R_SIZE + 4)
		{
			size_t len = logg_buff->capacity * 2;
			struct big_buff *tmp_buff = realloc(logg_buff, sizeof(*logg_buff) + len);
			if(!tmp_buff)
				goto no_errno;
			logg_buff = tmp_buff;
			logg_buff->limit = logg_buff->capacity += len;
		}
		*buffer_start(*logg_buff) = ':'; logg_buff->pos++;
		*buffer_start(*logg_buff) = ' '; logg_buff->pos++;
		{
#if defined STRERROR_R_CHAR_P || defined HAVE_MTSAFE_STRERROR || WIN32 || !(defined HAVE_STRERROR_R || HAVE_DECL_STRERROR_R-0 > 0)
			size_t err_str_len;
# ifdef WIN32
			const char *s = buffer_start(*logg_buff);
			if(!(err_str_len = FormatMessage(
				FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */
				0, /* pointer to other source */
				old_errno, /* msg id */
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* language */
				buffer_start(*logg_buff), /* buffer */
				buffer_remaining(*logg_buff)-1, /* size */
				0 /* va_args */
			))) {
				s = "Unknown system error";
				err_str_len = strlen(s) < buffer_remaining(*logg_buff)-2 ?
				              strlen(s) : buffer_remaining(*logg_buff)-2;
			}
# else
#  ifdef STRERROR_R_CHAR_P
			/*
			 * the f***ing GNU-Version of strerror_r wich returns
			 * a char * to the buffer....
			 * This sucks especially in conjunction with strnlen,
			 * wich needs a #define __GNU_SOURCE, but conflicts
			 * with this...
			 */
			const char *s = strerror_r(old_errno, buffer_start(*logg_buff), buffer_remaining(*logg_buff)-2);
#  else
			/*
			 * Ol Solaris seems to have a static msgtable, so
			 * strerror is threadsafe and we don't have a
			 * _r version
			 */
			/*
			 * we also simply fall into here if strerror is not thread
			 * safe, but we have nothing else.
			 * Since what should we do in this case... _sys_errlist
			 * is a bsd extentions.
			 */
			const char *s = strerror(old_errno);
#  endif
			if(s)
				err_str_len = strnlen(s, buffer_remaining(*logg_buff)-2);
			else {
				s = "Unknown system error";
				err_str_len = strlen(s) < (buffer_remaining(*logg_buff)-2) ?
				              strlen(s) : buffer_remaining(*logg_buff)-2;
			}
# endif

			if(s != buffer_start(*logg_buff))
				my_memcpy(buffer_start(*logg_buff), s, err_str_len);
			logg_buff->pos += err_str_len;
#else
			if(!strerror_r(old_errno, buffer_start(*logg_buff), buffer_remaining(*logg_buff)))
//			if(!strerror_s(buffer_start(*logg_buff), buffer_remaining(*logg_buff), old_errno))
				logg_buff->pos += strnlen(buffer_start(*logg_buff), buffer_remaining(*logg_buff));
			else
			{
				size_t err_l;
				const char *bs;
				if(EINVAL == errno) {
					err_l = str_size("Unknown errno value!");
					bs = "Unknown errno value!";
				} else if(ERANGE == errno) {
					err_l = str_size("errno msg to long for buffer!");
					bs = "errno msg to long for buffer!";
				} else {
					err_l = str_size("failure while retrieving errno msg!");
					bs = "failure while retrieving errno msg!";
				}
				err_l = (buffer_remaining(*logg_buff)-2) >= err_l ? err_l : (buffer_remaining(*logg_buff)-2);
				my_memcpy(buffer_start(*logg_buff), bs, err_l);
				logg_buff->pos += err_l;
			}
#endif
		}
		*buffer_start(*logg_buff) = '\n'; logg_buff->pos++;
		*buffer_start(*logg_buff) = '\0';
	}
no_errno:

	/* output that stuff */
	buffer_flip(*logg_buff);
	ret_val = do_logging(level, buffer_start(*logg_buff), buffer_remaining(*logg_buff));
	logg_ret_buf(logg_buff);
	return ret_val;
}
示例#29
0
/*
========================
Sys_Exec

if waitMsec is INFINITE, completely block until the process exits
If waitMsec is -1, don't wait for the process to exit
Other waitMsec values will allow the workFn to be called at those intervals.
========================
*/
bool Sys_Exec(	const char * appPath, const char * workingPath, const char * args, 
	execProcessWorkFunction_t workFn, execOutputFunction_t outputFn, const int waitMS,
	unsigned int & exitCode ) {
		exitCode = 0;
		SECURITY_ATTRIBUTES secAttr;
		secAttr.nLength = sizeof( SECURITY_ATTRIBUTES );
		secAttr.bInheritHandle = TRUE;
		secAttr.lpSecurityDescriptor = NULL;

		HANDLE hStdOutRead;
		HANDLE hStdOutWrite;
		CreatePipe( &hStdOutRead, &hStdOutWrite, &secAttr, 0 );
		SetHandleInformation( hStdOutRead, HANDLE_FLAG_INHERIT, 0 );

		HANDLE hStdInRead;
		HANDLE hStdInWrite;
		CreatePipe( &hStdInRead, &hStdInWrite, &secAttr, 0 );
		SetHandleInformation( hStdInWrite, HANDLE_FLAG_INHERIT, 0 );										

		STARTUPINFO si;
		memset( &si, 0, sizeof( si ) );
		si.cb = sizeof( si );
		si.hStdError = hStdOutWrite;
		si.hStdOutput = hStdOutWrite;
		si.hStdInput = hStdInRead;
		si.wShowWindow = FALSE;
		si.dwFlags |= STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

		PROCESS_INFORMATION pi;
		memset ( &pi, 0, sizeof( pi ) );

		if ( outputFn != NULL ) {
			outputFn( va( "^2Executing Process: ^7%s\n^2working path: ^7%s\n^2args: ^7%s\n", appPath, workingPath, args ) );
		} else {
			outputFn = ExecOutputFn;
		}

		// we duplicate args here so we can concatenate the exe name and args into a single command line
		const char * imageName = appPath;
		char * cmdLine = NULL;
		{
			// if we have any args, we need to copy them to a new buffer because CreateProcess modifies
			// the command line buffer.
			if ( args != NULL ) {
				if ( appPath != NULL ) {
					int len = idStr::Length( args ) + idStr::Length( appPath ) + 1 /* for space */ + 1 /* for NULL terminator */ + 2 /* app quotes */;
					cmdLine = (char*)Mem_Alloc( len, TAG_TEMP );
					// note that we're putting quotes around the appPath here because when AAS2.exe gets an app path with spaces
					// in the path "w:/zion/build/win32/Debug with Inlines/AAS2.exe" it gets more than one arg for the app name,
					// which it most certainly should not, so I am assuming this is a side effect of using CreateProcess.
					idStr::snPrintf( cmdLine, len, "\"%s\" %s", appPath, args );
				} else {
					int len = idStr::Length( args ) + 1;
					cmdLine = (char*)Mem_Alloc( len, TAG_TEMP );
					idStr::Copynz( cmdLine, args, len );
				}
				// the image name should always be NULL if we have command line arguments because it is already
				// prefixed to the command line.
				imageName = NULL;
			}
		}

		BOOL result = CreateProcess( imageName, (LPSTR)cmdLine, NULL, NULL, TRUE, 0, NULL, workingPath, &si, &pi );

		if ( result == FALSE ) {
			TCHAR szBuf[1024]; 
			LPVOID lpMsgBuf;
			DWORD dw = GetLastError(); 

			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER | 
				FORMAT_MESSAGE_FROM_SYSTEM,
				NULL,
				dw,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				(LPTSTR) &lpMsgBuf,
				0, NULL );

			wsprintf( szBuf, "%d: %s", dw, lpMsgBuf );
			if ( outputFn != NULL ) {
				outputFn( szBuf );
			}
			LocalFree( lpMsgBuf );
			if ( cmdLine != NULL ) {
				Mem_Free( cmdLine );
			}
			return false;
		} else if ( waitMS >= 0 ) {	// if waitMS == -1, don't wait for process to exit
			DWORD ec = 0;
			DWORD wait = 0;
			char buffer[ 4096 ];
			for ( ; ; ) {
				wait = WaitForSingleObject( pi.hProcess, waitMS );
				GetExitCodeProcess( pi.hProcess, &ec );

				DWORD bytesRead = 0;
				DWORD bytesAvail = 0;
				DWORD bytesLeft = 0;
				BOOL ok = PeekNamedPipe( hStdOutRead, NULL, 0, NULL, &bytesAvail, &bytesLeft );
				if ( ok && bytesAvail != 0 ) {
					ok = ReadFile( hStdOutRead, buffer, sizeof( buffer ) - 3, &bytesRead, NULL );
					if ( ok && bytesRead > 0 ) {
						buffer[ bytesRead ] = '\0';
						if ( outputFn != NULL ) {
							int length = 0;
							for ( int i = 0; buffer[i] != '\0'; i++ ) {
								if ( buffer[i] != '\r' ) {
									buffer[length++] = buffer[i];
								}
							}
							buffer[length++] = '\0';
							outputFn( buffer );
						}
					}
				}

				if ( ec != STILL_ACTIVE ) {
					exitCode = ec;
					break;
				}

				if ( workFn != NULL ) {
					if ( !workFn() ) {
						TerminateProcess( pi.hProcess, 0 );
						break;
					}
				}
			}
		}

		// this assumes that windows duplicates the command line string into the created process's
		// environment space.
		if ( cmdLine != NULL ) {
			Mem_Free( cmdLine );
		}

		CloseHandle( pi.hProcess );
		CloseHandle( pi.hThread );
		CloseHandle( hStdOutRead );
		CloseHandle( hStdOutWrite );
		CloseHandle( hStdInRead );
		CloseHandle( hStdInWrite );
		return true;
}
示例#30
0
/***
 * Dialog callback for the controls property page.
 * We need to make a separate Controller object for this HWND.
 *
 * @param pWindow Handle of our window
 */
BOOL ControlPrefsPage::DlgProc(HWND pWindow, UINT pMsgId, WPARAM pWParam, LPARAM pLParam)
{
	Config *cfg = Config::GetInstance();

	InputEventController* const controller = app->GetController();

	BOOL lReturnValue = FALSE;
	switch (pMsgId) {
		// Catch environment modification events
		case WM_INITDIALOG:
			// add available maps to the drop-down box
			{
				std::vector<std::string> mapnames = controller->GetAvailableMaps();
				HWND hList = GetDlgItem(pWindow, IDC_MAP_SELECT);
				
				// add all the maps except console-keys
				for(size_t i = 0; i < mapnames.size(); i++) {
					if(mapnames.at(i) == "console-keys")
						continue; // don't add this one
					int item = SendMessage(hList, CB_ADDSTRING, 0, (LPARAM) mapnames.at(i).c_str());
				}

				// select first player map (or first map)
				std::string mapname = _("Player");
				mapname += " 1";
				int select = SendMessage(hList, CB_FINDSTRINGEXACT, -1, (LPARAM) mapname.c_str());
				SendMessage(hList, CB_SETCURSEL, (select == CB_ERR) ? 0 : select, 0); // set current item

				// now fake the message that we just changed the selection
				// (this is why there is no break at the end of this case)
				pWParam = IDC_MAP_SELECT;

				// initialize columns in ListView box
				LVCOLUMNW keycol;
				memset(&keycol, 0, sizeof(keycol));
				keycol.mask = LVCF_WIDTH | LVCF_TEXT;
				keycol.cx = 400; // 400px
				keycol.pszText = (LPWSTR) _("Action");

				LVCOLUMNW bindcol;
				memset(&bindcol, 0, sizeof(bindcol));
				bindcol.mask = LVCF_WIDTH | LVCF_TEXT;
				bindcol.cx = 135; // 135px
				bindcol.pszText = (LPWSTR) _("Binding");

				HWND listview = GetDlgItem(pWindow, IDC_CONTROL_BINDING);
				SendMessageW(listview, LVM_INSERTCOLUMN, 0, (LPARAM) &keycol);
				SendMessageW(listview, LVM_INSERTCOLUMN, 1, (LPARAM) &bindcol);

				pressAnyKeyDialog = NULL;
			}

		case WM_COMMAND:
			{
				switch(LOWORD(pWParam)) {
					// The user changed the map selection
					case IDC_MAP_SELECT:
						UpdateBindingLabels(pWindow);
						break;

					case IDC_CHANGE_BINDING:
						{
							char buffer[200];
							HWND combobox = GetDlgItem(pWindow, IDC_MAP_SELECT);
							SendMessage(combobox, WM_GETTEXT, 200, (LPARAM) &buffer);
							std::string mapname = buffer;

							// we need to populate the ListView with actions
							HWND hList = GetDlgItem(pWindow, IDC_CONTROL_BINDING);
							InputEventController::ActionMap map = controller->GetActionMap(mapname);

							// order bindings by defined ordering in ControlAction::listOrder
							std::map<int, int> orderMap;
							for(InputEventController::ActionMap::iterator it = map.begin(); it != map.end(); it++)
								orderMap[it->second->getListOrder()] = it->first;
							
							// user wants to change assigned binding
							int selectedIndex = SendMessage(hList, LVM_GETSELECTIONMARK, 0, 0);
							if(selectedIndex == -1)
								break; // apparently nothing is selected

							setControlHash = orderMap[selectedIndex];
							setControlMap = mapname;

							if(pressAnyKeyDialog == NULL) {
								WNDCLASSW lWinClass;

								lWinClass.style = CS_DBLCLKS;
								lWinClass.lpfnWndProc = PressKeyDialogFunc;
								lWinClass.cbClsExtra = 0;
								lWinClass.cbWndExtra = 0;
								lWinClass.hInstance = GetInstanceHandle();
								lWinClass.hIcon = NULL;
								lWinClass.hCursor = LoadCursor(NULL, IDC_ARROW);
								lWinClass.hbrBackground = (HBRUSH) COLOR_APPWORKSPACE + 1;
								lWinClass.lpszMenuName = NULL;
								lWinClass.lpszClassName = L"IDD_PRESS_ANY_KEY";

								lReturnValue = RegisterClassW(&lWinClass);

								// set HWND for when we get called back
								preferencesDialog = pWindow;

								RECT size = {0};
								GetWindowRect(app->GetWindowHandle(), &size);
								SetCursorPos(size.left + 110, size.top + 80); // move to center of new window

								pressAnyKeyDialog = CreateWindowW(
									L"IDD_PRESS_ANY_KEY",
									PACKAGE_NAME_L,
									(WS_POPUPWINDOW | WS_VISIBLE),
									size.left + 30,
									size.top + 30,
									160,
									100,
									app->GetWindowHandle(),
									NULL,
									GetInstanceHandle(),
									this);

								if(pressAnyKeyDialog == NULL) { // report error if necessary
									DWORD err = GetLastError();
									LPVOID errMsg;
					
									FormatMessage(
										FORMAT_MESSAGE_ALLOCATE_BUFFER |
										FORMAT_MESSAGE_FROM_SYSTEM,
										NULL,
										err,
										MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
										(LPTSTR) &errMsg,
										0, NULL);
									MessageBox(NULL, (const char*) errMsg, "AIEEE", MB_ICONERROR | MB_APPLMODAL | MB_OK);
									LocalFree(errMsg);
								}
							} else {
								// put focus back to already existing window
								EnableWindow(pWindow, false);
								EnableWindow(pressAnyKeyDialog, true);
							}
						}
						break;
				}
			}
			break;

		case WM_NOTIFY:
			switch (((NMHDR FAR *) pLParam)->code) {
				case PSN_APPLY:
					pressAnyKeyDialog = NULL;

					// reload controller
					app->ReloadController();

					cfg->Save();
					break;

				case PSN_RESET:
					pressAnyKeyDialog = NULL;
					break;

				case PSN_KILLACTIVE:
					// for receipt of PSN_APPLY
					SetWindowLong(pWindow, DWL_MSGRESULT, FALSE);
					break;
			}
	}

	return lReturnValue;
}