コード例 #1
0
ファイル: nlsupport.c プロジェクト: CaoMomo/core
static rtl_Locale * _parse_locale( const char * locale )
{
    static sal_Unicode c_locale[2] = { (sal_Unicode) 'C', 0 };

    /* check if locale contains a valid string */
    if( locale )
    {
        size_t len = strlen( locale );

        if( len >= 2 )
        {
            rtl_uString * pLanguage = NULL;
            rtl_uString * pCountry  = NULL;
            rtl_uString * pVariant  = NULL;

            size_t offset = 2;

            rtl_Locale * ret;

            /* language is a two or three letter code */
            if( (len > 3 && '_' == locale[3]) || (len == 3 && '_' != locale[2]) )
                offset = 3;

            /* convert language code to unicode */
            rtl_string2UString( &pLanguage, locale, offset, RTL_TEXTENCODING_ASCII_US, OSTRING_TO_OUSTRING_CVTFLAGS );
            OSL_ASSERT(pLanguage != NULL);

            /* convert country code to unicode */
            if( len >= offset+3 && '_' == locale[offset] )
            {
                rtl_string2UString( &pCountry, locale + offset + 1, 2, RTL_TEXTENCODING_ASCII_US, OSTRING_TO_OUSTRING_CVTFLAGS );
                OSL_ASSERT(pCountry != NULL);
                offset += 3;
            }

            /* convert variant code to unicode - do not rely on "." as delimiter */
            if( len > offset ) {
                rtl_string2UString( &pVariant, locale + offset, len - offset, RTL_TEXTENCODING_ASCII_US, OSTRING_TO_OUSTRING_CVTFLAGS );
                OSL_ASSERT(pVariant != NULL);
            }

            ret =  rtl_locale_register( pLanguage->buffer, pCountry ? pCountry->buffer : c_locale + 1, pVariant ? pVariant->buffer : c_locale + 1 );

            if (pVariant) rtl_uString_release(pVariant);
            if (pCountry) rtl_uString_release(pCountry);
            if (pLanguage) rtl_uString_release(pLanguage);

            return ret;
        }
        else
            return rtl_locale_register( c_locale, c_locale + 1, c_locale + 1 );
    }

    return NULL;
}
コード例 #2
0
ファイル: pipe.c プロジェクト: CaoMomo/core
sal_Int32 SAL_CALL osl_sendPipe(oslPipe pPipe,
                       const void* pBuffer,
                       sal_Int32 BytesToSend)
{
    DWORD nBytes;
    OVERLAPPED   os;

    OSL_ASSERT(pPipe);

    memset(&os, 0, sizeof(OVERLAPPED));
    os.hEvent = pPipe->m_WriteEvent;
    ResetEvent(pPipe->m_WriteEvent);

    if (! WriteFile(pPipe->m_File, pBuffer, BytesToSend, &nBytes, &os) &&
        ((GetLastError() != ERROR_IO_PENDING) ||
          ! GetOverlappedResult(pPipe->m_File, &os, &nBytes, TRUE)))
    {
          if (GetLastError() == ERROR_PIPE_NOT_CONNECTED)
            nBytes = 0;
        else
            nBytes = (DWORD) -1;

         pPipe->m_Error = osl_Pipe_E_ConnectionAbort;
    }

    return (nBytes);
}
コード例 #3
0
static void osl_gen_random_name_impl_(rtl_uString** rand_name)
{
    static uint64_t value;

    char     buffer[RAND_NAME_LENGTH];
    struct   timeval tv;
    uint64_t v;
    int      i;

    gettimeofday(&tv, NULL);

    value += ((uint64_t)tv.tv_usec << 16) ^ tv.tv_sec ^ getpid();

    v = value;

    for (i = 0; i < RAND_NAME_LENGTH; i++)
    {
        buffer[i] = LETTERS[v % COUNT_OF_LETTERS];
        v        /= COUNT_OF_LETTERS;
    }

    rtl_string2UString(
            rand_name,
            buffer,
            RAND_NAME_LENGTH,
            RTL_TEXTENCODING_ASCII_US,
            OSTRING_TO_OUSTRING_CVTFLAGS);
    OSL_ASSERT(*rand_name != NULL);
}
コード例 #4
0
ファイル: time.c プロジェクト: CaoMomo/core
sal_Bool SAL_CALL osl_getSystemTime(TimeValue* pTimeVal)
{
    SYSTEMTIME SystemTime;
    FILETIME   CurTime, OffTime;
    __int64    Value;

    OSL_ASSERT(pTimeVal != 0);

    GetSystemTime(&SystemTime);
    SystemTimeToFileTime(&SystemTime, &CurTime);

    SystemTime.wYear         = 1970;
    SystemTime.wMonth        = 1;
    SystemTime.wDayOfWeek    = 0;
    SystemTime.wDay          = 1;
    SystemTime.wHour         = 0;
    SystemTime.wMinute       = 0;
    SystemTime.wSecond       = 0;
    SystemTime.wMilliseconds = 0;

    SystemTimeToFileTime(&SystemTime, &OffTime);

    Value = *((__int64 *)&CurTime) - *((__int64 *)&OffTime);

    pTimeVal->Seconds  = (unsigned long) (Value / 10000000L);
    pTimeVal->Nanosec  = (unsigned long)((Value % 10000000L) * 100);

    return (sal_True);
}
コード例 #5
0
ファイル: pipe.c プロジェクト: Echo360/LibreOffice-core
sal_Int32 SAL_CALL osl_sendPipe(oslPipe pPipe,
                       const void* pBuffer,
                       sal_Int32 BytesToSend)
{
    int nRet=0;

    OSL_ASSERT(pPipe);

    if ( pPipe == 0 )
    {
        OSL_TRACE("osl_sendPipe : Invalid socket");
        errno=EINVAL;
        return -1;
    }

    nRet = send(pPipe->m_Socket,
                  (sal_Char*)pBuffer,
                  BytesToSend, 0);

    if ( nRet <= 0 )
    {
        OSL_TRACE("osl_sendPipe failed : %i '%s'",nRet,strerror(errno));
    }

     return nRet;
}
コード例 #6
0
ファイル: pipe.c プロジェクト: Echo360/LibreOffice-core
sal_Int32 SAL_CALL osl_writePipe( oslPipe pPipe, const void *pBuffer , sal_Int32 n )
{
    /* loop until all desired bytes were send or an error occurred */
    sal_Int32 BytesSend= 0;
    sal_Int32 BytesToSend= n;

    OSL_ASSERT(pPipe);
    while (BytesToSend > 0)
    {
        sal_Int32 RetVal;

        RetVal= osl_sendPipe(pPipe, pBuffer, BytesToSend);

        /* error occurred? */
        if(RetVal <= 0)
        {
            break;
        }

        BytesToSend -= RetVal;
        BytesSend += RetVal;
        pBuffer= (sal_Char*)pBuffer + RetVal;
    }

    return BytesSend;
}
コード例 #7
0
ファイル: pipe.c プロジェクト: CaoMomo/core
sal_Int32 SAL_CALL osl_receivePipe(oslPipe pPipe,
                        void* pBuffer,
                        sal_Int32 BytesToRead)
{
    DWORD nBytes;
    OVERLAPPED   os;

    OSL_ASSERT(pPipe);

    memset(&os, 0, sizeof(OVERLAPPED));
    os.hEvent = pPipe->m_ReadEvent;

    ResetEvent(pPipe->m_ReadEvent);

    if (! ReadFile(pPipe->m_File, pBuffer, BytesToRead, &nBytes, &os) &&
        ((GetLastError() != ERROR_IO_PENDING) ||
         ! GetOverlappedResult(pPipe->m_File, &os, &nBytes, TRUE)))
    {
        DWORD lastError = GetLastError();

        if (lastError == ERROR_MORE_DATA)
            nBytes = BytesToRead;
          else
          {
              if (lastError == ERROR_PIPE_NOT_CONNECTED)
                nBytes = 0;
            else
                nBytes = (DWORD) -1;

             pPipe->m_Error = osl_Pipe_E_ConnectionAbort;
        }
    }

    return (nBytes);
}
コード例 #8
0
ファイル: process.c プロジェクト: beppec56/openoffice
oslProcessError SAL_CALL osl_searchPath_impl(const sal_Char* pszName, const sal_Char* pszPath,
			       sal_Char Separator, sal_Char *pszBuffer, sal_uInt32 Max)
{
	sal_Char path[PATH_MAX + 1];
	sal_Char *pchr;

    path[0] = '\0';
    
	OSL_ASSERT(pszName != NULL);

	if ( pszName == 0 )
	{
		return osl_Process_E_NotFound;
	}

	if (pszPath == NULL)
		pszPath = "PATH";

	if (Separator == '\0')
		Separator = ':';


	if ( (pchr = getenv(pszPath)) != 0 )
	{
		sal_Char *pstr;

		while (*pchr != '\0')
		{
			pstr = path;

			while ((*pchr != '\0') && (*pchr != Separator))
				*pstr++ = *pchr++;

			if ((pstr > path) && ((*(pstr - 1) != '/')))
				*pstr++ = '/';

			*pstr = '\0';

			strcat(path, pszName);

			if (access(path, 0) == 0)
			{
                char szRealPathBuf[PATH_MAX] = "";
                
				if( NULL == realpath(path, szRealPathBuf) || (strlen(szRealPathBuf) >= (sal_uInt32)Max))
					return osl_Process_E_Unknown;

				strcpy(pszBuffer, path);

				return osl_Process_E_None;
			}

			if (*pchr == Separator)
				pchr++;
		}
	}

	return osl_Process_E_NotFound;
}
コード例 #9
0
ファイル: security.c プロジェクト: beppec56/openoffice
sal_Bool SAL_CALL osl_getHomeDir(oslSecurity Security, rtl_uString **pustrDirectory)
{
	rtl_uString	*ustrSysDir = NULL;
	sal_Bool	bSuccess = sal_False;

    if (Security != NULL)
	{
		oslSecurityImpl *pSecImpl = (oslSecurityImpl*)Security;

		if (pSecImpl->m_pNetResource != NULL)
		{
			rtl_uString_newFromStr( &ustrSysDir, pSecImpl->m_pNetResource->lpRemoteName);

			bSuccess = (sal_Bool)(osl_File_E_None == osl_getFileURLFromSystemPath( ustrSysDir, pustrDirectory ));
		}
		else
		{
#if 0
			if (pSecImpl->m_hToken)
			{
				DWORD  nInfoBuffer = 512;
				UCHAR* pInfoBuffer = malloc(nInfoBuffer);

				while (!GetTokenInformation(pSecImpl->m_hToken, TokenUser,
	           							    pInfoBuffer, nInfoBuffer, &nInfoBuffer))
				{
					if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
						pInfoBuffer = realloc(pInfoBuffer, nInfoBuffer);
					else
					{
						free(pInfoBuffer);
						pInfoBuffer = NULL;
						break;
					}
				}

				/* not implemented */
				OSL_ASSERT(sal_False);

				if (pInfoBuffer)
				{
					/* if (EqualSid() ... */

				}
			}
			else
#endif

				bSuccess = (sal_Bool)(GetSpecialFolder(&ustrSysDir, CSIDL_PERSONAL) && 
				                     (osl_File_E_None == osl_getFileURLFromSystemPath(ustrSysDir, pustrDirectory)));
		}
	}

	if ( ustrSysDir )
		rtl_uString_release( ustrSysDir );

	return bSuccess;
}
コード例 #10
0
ファイル: security.c プロジェクト: beppec56/openoffice
oslSecurityError SAL_CALL osl_loginUser( rtl_uString *strUserName, rtl_uString *strPasswd, oslSecurity *pSecurity )
{
	oslSecurityError ret;

	if (!isWNT())
	{
		*pSecurity = osl_getCurrentSecurity();
		ret = osl_Security_E_None;
	}
	else
	{
		sal_Unicode*	strUser;
		sal_Unicode*	strDomain = _wcsdup(rtl_uString_getStr(strUserName));
		HANDLE	hUserToken;		
        
        #if OSL_DEBUG_LEVEL > 0		    
		    LUID luid;
		#endif
		
		if (NULL != (strUser = wcschr(strDomain, L'/')))
			*strUser++ = L'\0';
		else
		{
			strUser   = strDomain;
			strDomain = NULL;
		}

		// this process must have the right: 'act as a part of operatingsystem'				
		OSL_ASSERT(LookupPrivilegeValue(NULL, SE_TCB_NAME, &luid));

		if (LogonUserW(strUser, strDomain ? strDomain : L"", rtl_uString_getStr(strPasswd),
					  LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
		 			  &hUserToken))
		{
			oslSecurityImpl* pSecImpl = malloc(sizeof(oslSecurityImpl));

			pSecImpl->m_pNetResource = NULL;
			pSecImpl->m_hToken = hUserToken;
			pSecImpl->m_hProfile = NULL;
			wcscpy(pSecImpl->m_User, strUser);

			*pSecurity = (oslSecurity)pSecImpl;
			ret = osl_Security_E_None;
		}
		else
			ret = osl_Security_E_UserUnknown;

		if (strDomain)
			free(strDomain);
		else
			free(strUser);
	}

	return ret;
}
コード例 #11
0
ファイル: string.c プロジェクト: beppec56/openoffice
sal_Int32 SAL_CALL rtl_str_valueOfDouble(sal_Char * pStr, double d)
{
    rtl_String * pResult = NULL;
    sal_Int32 nLen;
    rtl_math_doubleToString(
        &pResult, 0, 0, d, rtl_math_StringFormat_G,
        RTL_STR_MAX_VALUEOFDOUBLE - RTL_CONSTASCII_LENGTH("-x.E-xxx"), '.', 0,
        0, sal_True);
    nLen = pResult->length;
    OSL_ASSERT(nLen < RTL_STR_MAX_VALUEOFDOUBLE);
    rtl_copyMemory(pStr, pResult->buffer, (nLen + 1) * sizeof(sal_Char));
    rtl_string_release(pResult);
    return nLen;
}
コード例 #12
0
ファイル: pipe.c プロジェクト: beppec56/openoffice
sal_Int32 SAL_CALL osl_receivePipe(oslPipe pPipe,
						void* pBuffer,
						sal_Int32 BytesToRead)
{
    DWORD nBytes;

	OSL_ASSERT(pPipe);

	/* if we have a system pipe use it */
	if ( IS_NT /*pPipe->m_File != INVALID_HANDLE_VALUE*/)
	{
		OVERLAPPED   os;
		rtl_zeroMemory(&os,sizeof(OVERLAPPED));
		os.hEvent = pPipe->m_ReadEvent;

		ResetEvent(pPipe->m_ReadEvent);
			
		if (! ReadFile(pPipe->m_File, pBuffer, BytesToRead, &nBytes, &os) &&
			((GetLastError() != ERROR_IO_PENDING) ||
			 ! GetOverlappedResult(pPipe->m_File, &os, &nBytes, TRUE)))
		{
			DWORD lastError = GetLastError();

			if (lastError == ERROR_MORE_DATA)
				nBytes = BytesToRead;
	  		else 
	  		{
	  			if (lastError == ERROR_PIPE_NOT_CONNECTED)
					nBytes = 0;
				else			
					nBytes = (DWORD) -1;

			 	pPipe->m_Error = osl_Pipe_E_ConnectionAbort;
			}
		}
	}			
	else
	{
		BOOL fSuccess = ReadSimplePipe( pPipe->m_File, pBuffer, BytesToRead, &nBytes, TRUE );

		if ( !fSuccess )
		{
			nBytes = 0;
		 	pPipe->m_Error = osl_Pipe_E_ConnectionAbort;
		}

	}

	return (nBytes);    
}
コード例 #13
0
ファイル: time.c プロジェクト: NadithM/core
sal_Bool SAL_CALL osl_getSystemTime(TimeValue* pTimeVal)
{
    SYSTEMTIME SystemTime;
    FILETIME   CurTime, OffTime;
    __int64    Value;

    typedef VOID (WINAPI *GetSystemTimePreciseAsFileTime_PROC)(LPFILETIME);

    static HMODULE hModule = NULL;
    static GetSystemTimePreciseAsFileTime_PROC pGetSystemTimePreciseAsFileTime = NULL;

    OSL_ASSERT(pTimeVal != 0);

    if ( !hModule )
    {
        hModule = GetModuleHandleA( "Kernel32.dll" );
        if ( hModule )
            pGetSystemTimePreciseAsFileTime = (GetSystemTimePreciseAsFileTime_PROC)
                GetProcAddress(hModule, "GetSystemTimePreciseAsFileTime");
    }

    // use ~1 microsecond resolution if available
    if (pGetSystemTimePreciseAsFileTime)
        pGetSystemTimePreciseAsFileTime(&CurTime);
    else
    {
        GetSystemTime(&SystemTime);
        SystemTimeToFileTime(&SystemTime, &CurTime);
    }

    SystemTime.wYear         = 1970;
    SystemTime.wMonth        = 1;
    SystemTime.wDayOfWeek    = 0;
    SystemTime.wDay          = 1;
    SystemTime.wHour         = 0;
    SystemTime.wMinute       = 0;
    SystemTime.wSecond       = 0;
    SystemTime.wMilliseconds = 0;

    SystemTimeToFileTime(&SystemTime, &OffTime);

    Value = *((__int64 *)&CurTime) - *((__int64 *)&OffTime);

    pTimeVal->Seconds  = (unsigned long) (Value / 10000000L);
    pTimeVal->Nanosec  = (unsigned long)((Value % 10000000L) * 100);

    return sal_True;
}
コード例 #14
0
ファイル: security.c プロジェクト: NadithM/core
sal_Bool SAL_CALL osl_getConfigDir(oslSecurity Security, rtl_uString **pustrDirectory)
{
    sal_Bool    bSuccess = sal_False;

    if (Security != NULL)
    {
        oslSecurityImpl *pSecImpl = (oslSecurityImpl*)Security;

        if (pSecImpl->m_pNetResource != NULL)
        {
            rtl_uString *ustrSysDir = NULL;

            rtl_uString_newFromStr( &ustrSysDir, pSecImpl->m_pNetResource->lpRemoteName);
            bSuccess = (sal_Bool)(osl_File_E_None == osl_getFileURLFromSystemPath( ustrSysDir, pustrDirectory));

            if ( ustrSysDir )
                rtl_uString_release( ustrSysDir );
        }
        else
        {
            if (pSecImpl->m_hToken)
            {
                /* not implemented */
                OSL_ASSERT(sal_False);
            }
            else
            {
                rtl_uString *ustrFile = NULL;
                sal_Unicode sFile[_MAX_PATH];

                if ( !GetSpecialFolder( &ustrFile, CSIDL_APPDATA) )
                {
                    OSL_VERIFY(GetWindowsDirectoryW(sFile, _MAX_DIR) > 0);

                    rtl_uString_newFromStr( &ustrFile, sFile);
                }

                bSuccess = (sal_Bool)(osl_File_E_None == osl_getFileURLFromSystemPath(ustrFile, pustrDirectory));

                if ( ustrFile )
                    rtl_uString_release( ustrFile );
            }
        }
    }

    return bSuccess;
}
コード例 #15
0
ファイル: process.c プロジェクト: beppec56/openoffice
void SAL_CALL osl_freeProcessHandle(oslProcess Process)
{
    if (Process != NULL)
	{
		oslProcessImpl *pChild, *pPrev = NULL;

		OSL_ASSERT(ChildListMutex != NULL);

		if ( ChildListMutex == 0 )
		{
			return;
		}

		osl_acquireMutex(ChildListMutex);

		pChild = ChildList;

		/* remove process from child list */
		while (pChild != NULL)
		{
			if (pChild == (oslProcessImpl*)Process)
			{
				if (pPrev != NULL)
					pPrev->m_pnext = pChild->m_pnext;
				else
					ChildList = pChild->m_pnext;

				break;
			}

			pPrev  = pChild;
			pChild = pChild->m_pnext;
		}

		osl_releaseMutex(ChildListMutex);

		osl_destroyCondition(((oslProcessImpl*)Process)->m_terminated);

		free(Process);
	}
}
コード例 #16
0
ファイル: pipe.c プロジェクト: beppec56/openoffice
sal_Int32 SAL_CALL osl_sendPipe(oslPipe pPipe,
					   const void* pBuffer,
					   sal_Int32 BytesToSend)
{
    DWORD nBytes;
	OSL_ASSERT(pPipe);

	if (IS_NT/*pPipe->m_File != INVALID_HANDLE_VALUE*/)
	{
		OVERLAPPED   os;
		rtl_zeroMemory(&os, sizeof(OVERLAPPED));
		os.hEvent = pPipe->m_WriteEvent;
		ResetEvent(pPipe->m_WriteEvent);

		if (! WriteFile(pPipe->m_File, pBuffer, BytesToSend, &nBytes, &os) &&
			((GetLastError() != ERROR_IO_PENDING) ||
			  ! GetOverlappedResult(pPipe->m_File, &os, &nBytes, TRUE)))
		{
		  	if (GetLastError() == ERROR_PIPE_NOT_CONNECTED)
				nBytes = 0;
			else			
				nBytes = (DWORD) -1;

		 	pPipe->m_Error = osl_Pipe_E_ConnectionAbort;
		}
	}			
	else
	{
		BOOL fSuccess = WriteSimplePipe( pPipe->m_File, pBuffer, BytesToSend, &nBytes, TRUE );

		if ( !fSuccess )
		{
			nBytes = 0;
		 	pPipe->m_Error = osl_Pipe_E_ConnectionAbort;
		}
	}
			
	return (nBytes);
}
コード例 #17
0
ファイル: strtmpl.c プロジェクト: beppec56/openoffice
static IMPL_RTL_STRCODE* IMPL_RTL_STRINGNAME( ImplNewCopy )( IMPL_RTL_STRINGDATA** ppThis,
                                                             IMPL_RTL_STRINGDATA* pStr,
                                                             sal_Int32 nCount )
{
    IMPL_RTL_STRCODE*       pDest;
    const IMPL_RTL_STRCODE* pSrc;
    IMPL_RTL_STRINGDATA*    pData = IMPL_RTL_STRINGNAME( ImplAlloc )( pStr->length );
    OSL_ASSERT(pData != NULL);

    pDest   = pData->buffer;
    pSrc    = pStr->buffer;
    while ( nCount > 0 )
    {
        *pDest = *pSrc;
        pDest++;
        pSrc++;
        nCount--;
    }

    *ppThis = pData;
    return pDest;
}
コード例 #18
0
ファイル: nlsupport.c プロジェクト: CaoMomo/core
void _imp_getProcessLocale( rtl_Locale ** ppLocale )
{
    WCHAR langCode[ELP_LANGUAGE_FIELD_LENGTH];
    WCHAR ctryCode[ELP_COUNTRY_FIELD_LENGTH];
    LCID  localeId;

    OSL_ASSERT( ppLocale );

    /* get the LCID to retrieve information from */
    localeId = GetUserDefaultLCID();

    /* call GetLocaleInfo to retrieve the iso codes */
    if( GetLocaleInfo( localeId, LOCALE_SISO639LANGNAME , langCode, ELP_LANGUAGE_FIELD_LENGTH )  &&
        GetLocaleInfo( localeId, LOCALE_SISO3166CTRYNAME , ctryCode, ELP_COUNTRY_FIELD_LENGTH ) )
    {
        *ppLocale = rtl_locale_register( langCode, ctryCode, L"" );
    }
    else
    {
        *ppLocale = rtl_locale_register( L"C", L"", L"" );
    }
}
コード例 #19
0
oslFileError SAL_CALL osl_getTempDirURL( rtl_uString** pustrTempDir )
{
    oslFileError error;
    /* described in environ(7) */
    const char *pValue = getenv( "TMPDIR" );
    rtl_uString *ustrTempPath = NULL;

    if ( !pValue )
        pValue = getenv( "TEMP" );

    if ( !pValue )
        pValue = getenv( "TMP" );

    if ( !pValue )
        pValue = "/tmp";

    rtl_string2UString( &ustrTempPath, pValue, strlen( pValue ), osl_getThreadTextEncoding(), OSTRING_TO_OUSTRING_CVTFLAGS );
    OSL_ASSERT(ustrTempPath != NULL);
    error = osl_getFileURLFromSystemPath( ustrTempPath, pustrTempDir );
    rtl_uString_release( ustrTempPath );

    return error;
}
コード例 #20
0
ファイル: pipe.c プロジェクト: Echo360/LibreOffice-core
sal_Int32 SAL_CALL osl_readPipe( oslPipe pPipe, void *pBuffer , sal_Int32 n )
{
    /* loop until all desired bytes were read or an error occurred */
    sal_Int32 BytesRead= 0;
    sal_Int32 BytesToRead= n;

    OSL_ASSERT( pPipe );
    while (BytesToRead > 0)
    {
        sal_Int32 RetVal;
        RetVal= osl_receivePipe(pPipe, pBuffer, BytesToRead);

        /* error occurred? */
        if(RetVal <= 0)
        {
            break;
        }

        BytesToRead -= RetVal;
        BytesRead += RetVal;
        pBuffer= (sal_Char*)pBuffer + RetVal;
    }
    return BytesRead;
}
コード例 #21
0
ファイル: security.c プロジェクト: NadithM/core
static sal_Bool GetSpecialFolder(rtl_uString **strPath, int nFolder)
{
    sal_Bool bRet = sal_False;
    HINSTANCE hLibrary;
    sal_Char PathA[_MAX_PATH];
    sal_Unicode PathW[_MAX_PATH];

    if ((hLibrary = LoadLibrary("shell32.dll")) != NULL)
    {
        BOOL (WINAPI *pSHGetSpecialFolderPathA)(HWND, LPSTR, int, BOOL);
        BOOL (WINAPI *pSHGetSpecialFolderPathW)(HWND, LPWSTR, int, BOOL);

        pSHGetSpecialFolderPathA = (BOOL (WINAPI *)(HWND, LPSTR, int, BOOL))GetProcAddress(hLibrary, "SHGetSpecialFolderPathA");
        pSHGetSpecialFolderPathW = (BOOL (WINAPI *)(HWND, LPWSTR, int, BOOL))GetProcAddress(hLibrary, "SHGetSpecialFolderPathW");

        if (pSHGetSpecialFolderPathA)
        {
            if (pSHGetSpecialFolderPathA(GetActiveWindow(), PathA, nFolder, TRUE))
            {
                rtl_string2UString( strPath, PathA, (sal_Int32) strlen(PathA), osl_getThreadTextEncoding(), OUSTRING_TO_OSTRING_CVTFLAGS);
                OSL_ASSERT(*strPath != NULL);
                bRet = sal_True;
            }
        }
        else if (pSHGetSpecialFolderPathW)
        {
            if (pSHGetSpecialFolderPathW(GetActiveWindow(), PathW, nFolder, TRUE))
            {
                rtl_uString_newFromStr( strPath, PathW);
                bRet = sal_True;
            }
        }
        else
        {
            HRESULT (WINAPI *pSHGetSpecialFolderLocation)(HWND, int, LPITEMIDLIST *) = (HRESULT (WINAPI *)(HWND, int, LPITEMIDLIST *))GetProcAddress(hLibrary, "SHGetSpecialFolderLocation");
            BOOL (WINAPI *pSHGetPathFromIDListA)(LPCITEMIDLIST, LPSTR) = (BOOL (WINAPI *)(LPCITEMIDLIST, LPSTR))GetProcAddress(hLibrary, "SHGetPathFromIDListA");
            BOOL (WINAPI *pSHGetPathFromIDListW)(LPCITEMIDLIST, LPWSTR) = (BOOL (WINAPI *)(LPCITEMIDLIST, LPWSTR))GetProcAddress(hLibrary, "SHGetPathFromIDListW");
             HRESULT (WINAPI *pSHGetMalloc)(LPMALLOC *) = (HRESULT (WINAPI *)(LPMALLOC *))GetProcAddress(hLibrary, "SHGetMalloc");

            if (pSHGetSpecialFolderLocation && (pSHGetPathFromIDListA || pSHGetPathFromIDListW ) && pSHGetMalloc )
            {
                   LPITEMIDLIST pidl;
                LPMALLOC pMalloc;
                   HRESULT  hr;

                   hr = pSHGetSpecialFolderLocation(GetActiveWindow(), nFolder, &pidl);

                /* Get SHGetSpecialFolderLocation fails if directory does not exists. */
                /* If it fails we try to create the directory and redo the call */
                if (! SUCCEEDED(hr))
                {
                    HKEY hRegKey;

                    if (RegOpenKey(HKEY_CURRENT_USER,
                                   "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
                                   &hRegKey) == ERROR_SUCCESS)
                    {
                        LONG lRet;
                        DWORD lSize = SAL_N_ELEMENTS(PathA);
                        DWORD Type = REG_SZ;

                        switch (nFolder)
                        {
                            case CSIDL_APPDATA:
                                lRet = RegQueryValueEx(hRegKey, "AppData", NULL, &Type, (LPBYTE)PathA, &lSize);
                                  break;

                            case CSIDL_PERSONAL:
                                lRet = RegQueryValueEx(hRegKey, "Personal", NULL, &Type, (LPBYTE)PathA, &lSize);
                                break;

                            default:
                                lRet = -1l;
                        }

                        if ((lRet == ERROR_SUCCESS) && (Type == REG_SZ))
                        {
                            if (_access(PathA, 0) < 0)
                                CreateDirectory(PathA, NULL);

                               hr = pSHGetSpecialFolderLocation(GetActiveWindow(), nFolder, &pidl);
                        }

                        RegCloseKey(hRegKey);
                    }
                }

                if (SUCCEEDED(hr))
                {
                    if (pSHGetPathFromIDListW && pSHGetPathFromIDListW(pidl, PathW))
                       {
                        /* if directory does not exist, create it */
                        if (_waccess(PathW, 0) < 0)
                            CreateDirectoryW(PathW, NULL);

                        rtl_uString_newFromStr( strPath, PathW);
                        bRet = sal_True;
                       }
                    else if (pSHGetPathFromIDListA && pSHGetPathFromIDListA(pidl, PathA))
                    {
                        /* if directory does not exist, create it */
                        if (_access(PathA, 0) < 0)
                            CreateDirectoryA(PathA, NULL);

                        rtl_string2UString( strPath, PathA, (sal_Int32) strlen(PathA), osl_getThreadTextEncoding(), OUSTRING_TO_OSTRING_CVTFLAGS);
                        OSL_ASSERT(*strPath != NULL);
                        bRet = sal_True;
                    }
                   }

                   if (SUCCEEDED(pSHGetMalloc(&pMalloc)))
                {
                       pMalloc->lpVtbl->Free(pMalloc, pidl);
                    pMalloc->lpVtbl->Release(pMalloc);
                }
            }
        }
    }

    FreeLibrary(hLibrary);

    return bRet;
}
コード例 #22
0
ファイル: string.c プロジェクト: beppec56/openoffice
sal_Bool SAL_CALL rtl_impl_convertUStringToString(rtl_String ** pTarget,
                                                  sal_Unicode const * pSource,
                                                  sal_Int32 nLength,
                                                  rtl_TextEncoding nEncoding,
                                                  sal_uInt32 nFlags,
                                                  sal_Bool bCheckErrors)
{
    OSL_ASSERT(pTarget != NULL
               && (pSource != NULL || nLength == 0)
               && nLength >= 0
               && rtl_isOctetTextEncoding(nEncoding));

    if ( !nLength )
        rtl_string_new( pTarget );
    else
    {
        rtl_String*                 pTemp;
        rtl_UnicodeToTextConverter  hConverter;
        sal_uInt32                  nInfo;
        sal_Size                    nSrcChars;
        sal_Size                    nDestBytes;
        sal_Size                    nNewLen;
        sal_Size                    nNotConvertedChars;
        sal_Size                    nMaxCharLen;

        /* Optimization for UTF-8 - we try to calculate the exact length */
        /* For all other encoding we try an good estimation */
        if ( nEncoding == RTL_TEXTENCODING_UTF8 )
        {
            nNewLen = rtl_ImplGetFastUTF8ByteLen( pSource, nLength );
            /* Includes the string only ASCII, then we could copy
               the buffer faster */
            if ( nNewLen == (sal_Size)nLength )
            {
                IMPL_RTL_STRCODE* pBuffer;
                if ( *pTarget )
                    IMPL_RTL_STRINGNAME( release )( *pTarget );
                *pTarget = IMPL_RTL_STRINGNAME( ImplAlloc )( nLength );
                OSL_ASSERT(*pTarget != NULL);
                pBuffer = (*pTarget)->buffer;
                do
                {
                    /* Check ASCII range */
                    OSL_ENSURE( *pSource <= 127,
                                "rtl_uString2String() - UTF8 test is encoding is wrong" );

                    *pBuffer = (IMPL_RTL_STRCODE)(unsigned char)*pSource;
                    pBuffer++;
                    pSource++;
                    nLength--;
                }
                while ( nLength );
                return sal_True;
            }

            nMaxCharLen = 4;
        }
        else
        {
            rtl_TextEncodingInfo aTextEncInfo;
            aTextEncInfo.StructSize = sizeof( aTextEncInfo );
            if ( !rtl_getTextEncodingInfo( nEncoding, &aTextEncInfo ) )
            {
                aTextEncInfo.AverageCharSize    = 1;
                aTextEncInfo.MaximumCharSize    = 8;
            }

            nNewLen = nLength*aTextEncInfo.AverageCharSize;
            nMaxCharLen = aTextEncInfo.MaximumCharSize;
        }

        nFlags |= RTL_UNICODETOTEXT_FLAGS_FLUSH;
        hConverter = rtl_createUnicodeToTextConverter( nEncoding );

        for (;;)
        {
            pTemp = IMPL_RTL_STRINGNAME( ImplAlloc )( nNewLen );
            OSL_ASSERT(pTemp != NULL);
            nDestBytes = rtl_convertUnicodeToText( hConverter, 0,
                                                   pSource, nLength,
                                                   pTemp->buffer, nNewLen,
                                                   nFlags,
                                                   &nInfo, &nSrcChars );
            if (bCheckErrors && (nInfo & RTL_UNICODETOTEXT_INFO_ERROR) != 0)
            {
                rtl_freeMemory(pTemp);
                rtl_destroyUnicodeToTextConverter(hConverter);
                return sal_False;
            }

            if ((nInfo & RTL_UNICODETOTEXT_INFO_DESTBUFFERTOSMALL) == 0)
                break;

            /* Buffer not big enough, try again with enough space */
            rtl_freeMemory( pTemp );

            /* Try with the max. count of characters with
               additional overhead for replacing functionality */
            nNotConvertedChars = nLength-nSrcChars;
            nNewLen = nDestBytes+(nNotConvertedChars*nMaxCharLen)+nNotConvertedChars+4;
        }

        /* Set the buffer to the correct size or is there to
           much overhead, reallocate to the correct size */
        if ( nNewLen > nDestBytes+8 )
        {
            rtl_String* pTemp2 = IMPL_RTL_STRINGNAME( ImplAlloc )( nDestBytes );
            OSL_ASSERT(pTemp2 != NULL);
            rtl_str_ImplCopy( pTemp2->buffer, pTemp->buffer, nDestBytes );
            rtl_freeMemory( pTemp );
            pTemp = pTemp2;
        }
        else
        {
            pTemp->length = nDestBytes;
            pTemp->buffer[nDestBytes] = 0;
        }

        rtl_destroyUnicodeToTextConverter( hConverter );
        if ( *pTarget )
            IMPL_RTL_STRINGNAME( release )( *pTarget );
        *pTarget = pTemp;

        /* Results the conversion in an empty buffer -
           create an empty string */
        if ( pTemp && !nDestBytes )
            rtl_string_new( pTarget );
    }
    return sal_True;
}
コード例 #23
0
ファイル: pipe.c プロジェクト: beppec56/openoffice
oslPipe SAL_CALL osl_acceptPipe(oslPipe pPipe)
{
	oslPipe  pAcceptedPipe = NULL;
	
	HANDLE		 Event;
    OVERLAPPED   os;

	OSL_ASSERT(pPipe);

	if (IS_NT)
	{
		DWORD nBytesTransfered;
		rtl_uString* path = NULL;
		rtl_uString* temp = NULL;

		OSL_ASSERT (pPipe->m_File != INVALID_HANDLE_VALUE);

		Event = pPipe->m_AcceptEvent;
		rtl_zeroMemory(&os, sizeof(OVERLAPPED));
		os.hEvent = pPipe->m_AcceptEvent;
		ResetEvent(pPipe->m_AcceptEvent);

		if ( !ConnectNamedPipe(pPipe->m_File, &os))
		{
			switch ( GetLastError() )
			{
			case ERROR_PIPE_CONNECTED:	// Client already connected to pipe
			case ERROR_NO_DATA:			// Client was connected but has already closed pipe end
										// should only appear in nonblocking mode but in fact does
										// in blocking asynchronous mode.
				break;
			case ERROR_PIPE_LISTENING:	// Only for nonblocking mode but see ERROR_NO_DATA
			case ERROR_IO_PENDING:		// This is normal if not client is connected yet
			case ERROR_MORE_DATA:		// Should not happen
				// blocking call to accept
				if( !GetOverlappedResult( pPipe->m_File, &os, &nBytesTransfered, TRUE ) )
				{
					// Possible error could be that between ConnectNamedPipe and GetOverlappedResult a connect
					// took place.

					switch ( GetLastError() )
					{
					case ERROR_PIPE_CONNECTED:	// Pipe was already connected
					case ERROR_NO_DATA:			// Pipe was connected but client has already closed -> ver fast client ;-)
						break;					// Everything's fine !!!
					default:
						// Something went wrong
						return 0;
					}
				}
				break;
			default:					// All other error say that somethings going wrong.
				return 0;
			}
		}

		
		pAcceptedPipe = __osl_createPipeImpl();
		OSL_ASSERT(pAcceptedPipe);

		osl_incrementInterlockedCount(&(pAcceptedPipe->m_Reference));
		rtl_uString_assign(&pAcceptedPipe->m_Name, pPipe->m_Name);
		pAcceptedPipe->m_File = pPipe->m_File;

		rtl_uString_newFromAscii(&temp, PIPESYSTEM);
		rtl_uString_newConcat(&path, temp, pPipe->m_Name);
		rtl_uString_release(temp);

		// prepare for next accept
		pPipe->m_File = 
        	CreateNamedPipeW(path->buffer, 
				PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
				PIPE_WAIT | PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
				PIPE_UNLIMITED_INSTANCES,
				4096, 4096,
				NMPWAIT_WAIT_FOREVER, 
				pAcceptedPipe->m_Security);
		rtl_uString_release( path );
	}
	else /* Win9x */
	{
		pAcceptedPipe = __osl_createPipeImpl();
		OSL_ASSERT(pAcceptedPipe);

		osl_incrementInterlockedCount(&(pAcceptedPipe->m_Reference));
		rtl_uString_assign(&pAcceptedPipe->m_Name, pPipe->m_Name);
		pAcceptedPipe->m_File = pPipe->m_File;

		pAcceptedPipe->m_File = AcceptSimplePipeConnection( pPipe->m_File );
	}

	return pAcceptedPipe;
}
コード例 #24
0
ファイル: nlsupport.c プロジェクト: CaoMomo/core
rtl_TextEncoding osl_getTextEncodingFromLocale( rtl_Locale * pLocale )
{
    const _pair *language=0;

    char  locale_buf[64] = "";
    char  codeset_buf[64];

    char *ctype_locale = 0;
    char *codeset      = 0;

    /* default to process locale if pLocale == NULL */
    if( NULL == pLocale )
        osl_getProcessLocale( &pLocale );

    /* convert rtl_Locale to locale string */
    _compose_locale( pLocale, locale_buf, 64 );

    /* basic thread safeness */
    pthread_mutex_lock( &aLocalMutex );

    /* remember the charset as indicated by the LC_CTYPE locale */
    ctype_locale = setlocale( LC_CTYPE, NULL );

    /* set the desired LC_CTYPE locale */
    if( NULL == setlocale( LC_CTYPE, locale_buf ) )
    {
        pthread_mutex_unlock(&aLocalMutex);
        return RTL_TEXTENCODING_DONTKNOW;
    }

    /* get the charset as indicated by the LC_CTYPE locale */
#if defined(NETBSD) && !defined(CODESET)
    codeset = NULL;
#else
    codeset = nl_langinfo( CODESET );
#endif

    if ( codeset != NULL )
    {
        /* get codeset into mt save memory */
        strncpy( codeset_buf, codeset, sizeof(codeset_buf) );
        codeset_buf[sizeof(codeset_buf) - 1] = 0;
        codeset = codeset_buf;
    }

    /* restore the original value of locale */
    if ( ctype_locale != NULL )
        setlocale( LC_CTYPE, ctype_locale );

    pthread_mutex_unlock( &aLocalMutex );

    /* search the codeset in our language list */
    if ( codeset != NULL )
    {
        language = _pair_search (codeset, _nl_language_list, SAL_N_ELEMENTS( _nl_language_list ) );
    }

    OSL_ASSERT( language && ( RTL_TEXTENCODING_DONTKNOW != language->value ) );

    /* a matching item in our list provides a mapping from codeset to
     * rtl-codeset */
    if ( language != NULL )
        return language->value;

    return RTL_TEXTENCODING_DONTKNOW;
}
コード例 #25
0
ファイル: pipe.c プロジェクト: Echo360/LibreOffice-core
oslPipe SAL_CALL osl_acceptPipe(oslPipe pPipe)
{
    int     s, flags;
    oslPipe pAcceptedPipe;

    OSL_ASSERT(pPipe);
    if ( pPipe == 0 )
    {
        return NULL;
    }

    OSL_ASSERT(strlen(pPipe->m_Name) > 0);

#if defined(LINUX)
    pPipe->m_bIsAccepting = sal_True;
#endif

    s = accept(pPipe->m_Socket, NULL, NULL);

#if defined(LINUX)
    pPipe->m_bIsAccepting = sal_False;
#endif

    if (s < 0)
    {
        OSL_TRACE("osl_acceptPipe : accept error '%s'", strerror(errno));
        return NULL;
    }

#if defined(LINUX)
    if ( pPipe->m_bIsInShutdown  )
    {
        close(s);
        return NULL;
    }
#endif /* LINUX */
    else
    {
        /* alloc memory */
        pAcceptedPipe = __osl_createPipeImpl();

        OSL_ASSERT(pAcceptedPipe);
        if(pAcceptedPipe==NULL)
        {
            close(s);
            return NULL;
        }

        /* set close-on-exec flag */
        if (!((flags = fcntl(s, F_GETFD, 0)) < 0))
        {
            flags |= FD_CLOEXEC;
            if (fcntl(s, F_SETFD, flags) < 0)
            {
                OSL_TRACE("osl_acceptPipe: error changing socket flags. "
                          "Errno: %d; %s",errno,strerror(errno));
            }
        }

        pAcceptedPipe->m_Socket = s;
    }

    return pAcceptedPipe;
}
コード例 #26
0
ファイル: jpegc.c プロジェクト: beppec56/openoffice
void ReadJPEG( void* pJPEGReader, void* pIStm, long* pLines )
{
	struct jpeg_decompress_struct	cinfo;
	struct my_error_mgr				jerr;
    struct JPEGCreateBitmapParam    aCreateBitmapParam;
	HPBYTE							pDIB;
	HPBYTE							pTmp;
    long                            nWidth;
    long                            nHeight;
    long                            nAlignedWidth;
    JSAMPLE * range_limit;
    HPBYTE pScanLineBuffer = NULL;
    long nScanLineBufferComponents = 0;
    // declare bDecompCreated volatile because of gcc
    // warning: variable 'bDecompCreated' might be clobbered by `longjmp' or `vfork'
	volatile long					bDecompCreated = 0;

	/* Falls der Stream nicht ausreicht (IO_PENDING)
	 wird ueber ein longjmp in der Schleife nach Exit
	 gesprungen, wir geben dann die Anzahl
	 der bisher bearbeiteten Scanlines zurueck*/
	if ( setjmp( jerr.setjmp_buffer ) )
		goto Exit;

	cinfo.err = jpeg_std_error( &jerr.pub );
	jerr.pub.error_exit = my_error_exit;
	jerr.pub.output_message = my_output_message;

	jpeg_create_decompress( &cinfo );
	bDecompCreated = 1;
        jpeg_svstream_src( &cinfo, pIStm );
	jpeg_read_header( &cinfo, sal_True );

	cinfo.scale_num = 1;
	cinfo.scale_denom = 1;
	cinfo.output_gamma = 1.0;
	cinfo.raw_data_out = sal_False;
	cinfo.quantize_colors = sal_False;
	if ( cinfo.jpeg_color_space == JCS_YCbCr )
	    cinfo.out_color_space = JCS_RGB;
	else if ( cinfo.jpeg_color_space == JCS_YCCK )
	    cinfo.out_color_space = JCS_CMYK;

	OSL_ASSERT(cinfo.out_color_space == JCS_CMYK || cinfo.out_color_space == JCS_GRAYSCALE || cinfo.out_color_space == JCS_RGB);

    /* change scale for preview import */
    if( nPreviewWidth || nPreviewHeight )
    {
		if( nPreviewWidth == 0 ) {
			nPreviewWidth = ( cinfo.image_width*nPreviewHeight )/cinfo.image_height;
			if( nPreviewWidth <= 0 )
				nPreviewWidth = 1;
		} else if( nPreviewHeight == 0 ) {
			nPreviewHeight = ( cinfo.image_height*nPreviewWidth )/cinfo.image_width;
			if( nPreviewHeight <= 0 )
				nPreviewHeight = 1;
		}

        for( cinfo.scale_denom = 1; cinfo.scale_denom < 8; cinfo.scale_denom *= 2 )
        {
            if( cinfo.image_width < nPreviewWidth * cinfo.scale_denom )
                break;
            if( cinfo.image_height < nPreviewHeight * cinfo.scale_denom )
                break;
        }

        if( cinfo.scale_denom > 1 )
        {
            cinfo.dct_method            = JDCT_FASTEST;
            cinfo.do_fancy_upsampling   = sal_False;
            cinfo.do_block_smoothing    = sal_False;
        }
    }

	jpeg_start_decompress( &cinfo );

	nWidth = cinfo.output_width;
	nHeight = cinfo.output_height;
	aCreateBitmapParam.nWidth = nWidth;
	aCreateBitmapParam.nHeight = nHeight;

    aCreateBitmapParam.density_unit = cinfo.density_unit;
    aCreateBitmapParam.X_density = cinfo.X_density;
    aCreateBitmapParam.Y_density = cinfo.Y_density;
    aCreateBitmapParam.bGray = cinfo.output_components == 1;
	pDIB = CreateBitmap( pJPEGReader, &aCreateBitmapParam );
    nAlignedWidth = aCreateBitmapParam.nAlignedWidth;
    range_limit=cinfo.sample_range_limit;

	if ( cinfo.out_color_space == JCS_CMYK )
	{
    		nScanLineBufferComponents = cinfo.output_width * 4;
		pScanLineBuffer = rtl_allocateMemory( nScanLineBufferComponents );
	}

	if( pDIB )
	{
		if( aCreateBitmapParam.bTopDown )
			pTmp = pDIB;
		else
		{
			pTmp = pDIB + ( nHeight - 1 ) * nAlignedWidth;
			nAlignedWidth = -nAlignedWidth;
		}

		for ( *pLines = 0; *pLines < nHeight; (*pLines)++ )
		{
		    if (pScanLineBuffer!=NULL) { // in other words cinfo.out_color_space == JCS_CMYK
			int i;
			int j;
			jpeg_read_scanlines( &cinfo, (JSAMPARRAY) &pScanLineBuffer, 1 );
			// convert CMYK to RGB
			for( i=0, j=0; i < nScanLineBufferComponents; i+=4, j+=3 )
			{
			    int c_=255-pScanLineBuffer[i+0];
			    int m_=255-pScanLineBuffer[i+1];
			    int y_=255-pScanLineBuffer[i+2];
			    int k_=255-pScanLineBuffer[i+3];
			    pTmp[j+0]=range_limit[ 255L - ( c_ + k_ ) ];
			    pTmp[j+1]=range_limit[ 255L - ( m_ + k_ ) ];
			    pTmp[j+2]=range_limit[ 255L - ( y_ + k_ ) ];
			}
		    } else {
			jpeg_read_scanlines( &cinfo, (JSAMPARRAY) &pTmp, 1 );
		    }
		    /* PENDING ??? */
		    if ( cinfo.err->msg_code == 113 )
			break;
		    
		    pTmp += nAlignedWidth;
		}
	}

    if ( pDIB )
    {
        jpeg_finish_decompress( &cinfo );
    }
    else
    {
        jpeg_abort_decompress( &cinfo );
    }

	if (pScanLineBuffer!=NULL) {
	    rtl_freeMemory( pScanLineBuffer );
	    pScanLineBuffer=NULL;
	}

Exit:

	if( bDecompCreated )
		jpeg_destroy_decompress( &cinfo );
}
コード例 #27
0
ファイル: process.c プロジェクト: beppec56/openoffice
static void ChildStatusProc(void *pData)
{
	pid_t pid = -1;
	int   status = 0;
	int   channel[2];
	ProcessData  data;
	ProcessData *pdata;
	int		stdOutput[2] = { -1, -1 }, stdInput[2] = { -1, -1 }, stdError[2] = { -1, -1 };

	pdata = (ProcessData *)pData;

	/* make a copy of our data, because forking will only copy
	   our local stack of the thread, so the process data will not be accessible
	   in our child process */
	memcpy(&data, pData, sizeof(data));

    if (socketpair(AF_UNIX, SOCK_STREAM, 0, channel) == -1)
        status = errno;

    fcntl(channel[0], F_SETFD, FD_CLOEXEC);
    fcntl(channel[1], F_SETFD, FD_CLOEXEC);

	/* Create redirected IO pipes */
	if ( status == 0 && data.m_pInputWrite )
		if (pipe( stdInput ) == -1)
		    status = errno;

	if ( status == 0 && data.m_pOutputRead )
		if (pipe( stdOutput ) == -1)
		    status = errno;

	if ( status == 0 && data.m_pErrorRead )
		if (pipe( stdError ) == -1)
		    status = errno;

    if ( (status == 0) && ((pid = fork()) == 0) )
    {
		/* Child */
        int chstatus = 0;
        sal_Int32 nWrote;

	    if (channel[0] != -1) close(channel[0]);

		if ((data.m_uid != (uid_t)-1) && ((data.m_uid != getuid()) || (data.m_gid != getgid())))
		{
			OSL_ASSERT(geteuid() == 0);		/* must be root */

			if (! INIT_GROUPS(data.m_name, data.m_gid) || (setuid(data.m_uid) != 0))
				OSL_TRACE("Failed to change uid and guid, errno=%d (%s)\n", errno, strerror(errno));
#if defined(LINUX) || defined (FREEBSD)
			unsetenv("HOME");
#else
			putenv("HOME=");
#endif
		}

  		if (data.m_pszDir)
  			chstatus = chdir(data.m_pszDir);

   	    if (chstatus == 0 && ((data.m_uid == (uid_t)-1) || ((data.m_uid == getuid()) && (data.m_gid == getgid()))))
		{
            int i;
			for (i = 0; data.m_pszEnv[i] != NULL; i++)
            {
                if (strchr(data.m_pszEnv[i], '=') == NULL)
                {
                    unsetenv(data.m_pszEnv[i]); /*TODO: check error return*/
                }
                else
                {
                    putenv(data.m_pszEnv[i]); /*TODO: check error return*/
                }
            }

            OSL_TRACE("ChildStatusProc : starting '%s'",data.m_pszArgs[0]);
     
			/* Connect std IO to pipe ends */

			/* Write end of stdInput not used in child process */
			if (stdInput[1] != -1) close( stdInput[1] );

			/* Read end of stdOutput not used in child process */
			if (stdOutput[0] != -1) close( stdOutput[0] );

			/* Read end of stdError not used in child process */
			if (stdError[0] != -1) close( stdError[0] );

			/* Redirect pipe ends to std IO */

			if ( stdInput[0] != STDIN_FILENO )
			{
				dup2( stdInput[0], STDIN_FILENO );
				if (stdInput[0] != -1) close( stdInput[0] );
			}

			if ( stdOutput[1] != STDOUT_FILENO )
			{
				dup2( stdOutput[1], STDOUT_FILENO );
				if (stdOutput[1] != -1) close( stdOutput[1] );
			}

			if ( stdError[1] != STDERR_FILENO )
			{
				dup2( stdError[1], STDERR_FILENO );
				if (stdError[1] != -1) close( stdError[1] );
			}

	    	pid=execv(data.m_pszArgs[0], (sal_Char **)data.m_pszArgs);

		}

        OSL_TRACE("Failed to exec, errno=%d (%s)\n", errno, strerror(errno));

        OSL_TRACE("ChildStatusProc : starting '%s' failed",data.m_pszArgs[0]);
        
		/* if we reach here, something went wrong */
        nWrote = write(channel[1], &errno, sizeof(errno));
		if (nWrote != sizeof(errno))
            OSL_TRACE("sendFdPipe : sending failed (%s)",strerror(errno));

	    if (channel[1] != -1) close(channel[1]);

		_exit(255);
    }
    else
    {   /* Parent  */
        int i = -1;
		if (channel[1] != -1) close(channel[1]);

		/* Close unused pipe ends */
		if (stdInput[0] != -1) close( stdInput[0] );
		if (stdOutput[1] != -1) close( stdOutput[1] );
		if (stdError[1] != -1) close( stdError[1] );

		if (pid > 0)
		{
			while (((i = read(channel[0], &status, sizeof(status))) < 0))
			{
				if (errno != EINTR)
					break;
			}
		}

		if (channel[0] != -1) close(channel[0]);

		if ((pid > 0) && (i == 0))
		{
			pid_t	child_pid;
			osl_acquireMutex(ChildListMutex);

			pdata->m_pProcImpl->m_pid = pid;
			pdata->m_pProcImpl->m_pnext = ChildList;
			ChildList = pdata->m_pProcImpl;

			/* Store used pipe ends in data structure */

			if ( pdata->m_pInputWrite )
				*(pdata->m_pInputWrite) = osl_createFileHandleFromFD( stdInput[1] );
				
			if ( pdata->m_pOutputRead )
				*(pdata->m_pOutputRead) = osl_createFileHandleFromFD( stdOutput[0] );
				
			if ( pdata->m_pErrorRead )
				*(pdata->m_pErrorRead) = osl_createFileHandleFromFD( stdError[0] );

			osl_releaseMutex(ChildListMutex);

			osl_setCondition(pdata->m_started);
            
			do
			{
				child_pid = waitpid(pid, &status, 0);
			} while ( 0 > child_pid && EINTR == errno );

			if ( child_pid < 0)
			{
				OSL_TRACE("Failed to wait for child process, errno=%d (%s)\n", errno, strerror(errno));

				/* 
				We got an other error than EINTR. Anyway we have to wake up the
				waiting thread under any circumstances */

				child_pid = pid;
			}

			
			if ( child_pid > 0 )
			{
				oslProcessImpl* pChild;

				osl_acquireMutex(ChildListMutex);

				pChild = ChildList;

				/* check if it is one of our child processes */
				while (pChild != NULL)
				{
					if (pChild->m_pid == child_pid)
					{
						if (WIFEXITED(status))
							pChild->m_status = WEXITSTATUS(status);
						else
							pChild->m_status = -1;

						osl_setCondition(pChild->m_terminated);
					}

					pChild = pChild->m_pnext;
				}

				osl_releaseMutex(ChildListMutex);
			}
		}
		else
		{
            OSL_TRACE("ChildStatusProc : starting '%s' failed",data.m_pszArgs[0]);            
			OSL_TRACE("Failed to launch child process, child reports errno=%d (%s)\n", status, strerror(status));

			/* Close pipe ends */
			if ( pdata->m_pInputWrite )
				*pdata->m_pInputWrite = NULL;

			if ( pdata->m_pOutputRead )
				*pdata->m_pOutputRead = NULL;

			if ( pdata->m_pErrorRead )
				*pdata->m_pErrorRead = NULL;

			if (stdInput[1] != -1) close( stdInput[1] );
			if (stdOutput[0] != -1) close( stdOutput[0] );
			if (stdError[0] != -1) close( stdError[0] );

            //if pid > 0 then a process was created, even if it later failed
            //e.g. bash searching for a command to execute, and we still
            //need to clean it up to avoid "defunct" processes
            if (pid > 0)
            {
                pid_t child_pid;
                do
                {
                    child_pid = waitpid(pid, &status, 0);
                } while ( 0 > child_pid && EINTR == errno );
            }

			/* notify (and unblock) parent thread */
			osl_setCondition(pdata->m_started);
		}
	}
}
コード例 #28
0
ファイル: process.c プロジェクト: beppec56/openoffice
oslProcessError SAL_CALL osl_joinProcessWithTimeout(oslProcess Process, const TimeValue* pTimeout)
{
	oslProcessImpl* pChild    = ChildList;
	oslProcessError osl_error = osl_Process_E_None;
		
    OSL_PRECOND(Process, "osl_joinProcess: Invalid parameter");
    OSL_ASSERT(ChildListMutex);
    
    if (NULL == Process || 0 == ChildListMutex)
        return osl_Process_E_Unknown;
            	 	
	osl_acquireMutex(ChildListMutex);
	
	/* check if process is a child of ours */
	while (pChild != NULL)
	{
		if (pChild == (oslProcessImpl*)Process)
			break;

		pChild = pChild->m_pnext;
	}

	osl_releaseMutex(ChildListMutex);
        
	if (pChild != NULL)
	{
		oslConditionResult cond_res = osl_waitCondition(pChild->m_terminated, pTimeout);
		
		if (osl_cond_result_timeout == cond_res)
		    osl_error = osl_Process_E_TimedOut;
		else if (osl_cond_result_ok != cond_res)
		    osl_error = osl_Process_E_Unknown;		    
	}
	else /* alien process; StatusThread will not be able
	   		to set the condition terminated */
	{
		pid_t pid = ((oslProcessImpl*)Process)->m_pid;
		
		if (pTimeout)
		{
			int timeout = 0;
			struct timeval tend;		
				
			gettimeofday(&tend, NULL);									
			
			tend.tv_sec += pTimeout->Seconds;			
												
			while (!is_process_dead(pid) && ((timeout = is_timeout(&tend)) == 0))
				sleep(1);
				
			if (timeout)
				osl_error = osl_Process_E_TimedOut;
		}
		else /* infinite */
		{
			while (!is_process_dead(pid))
				sleep(1);
		}				
	}
	return osl_error;	
}
コード例 #29
0
ファイル: process.c プロジェクト: beppec56/openoffice
oslProcessError SAL_CALL osl_psz_executeProcess(sal_Char *pszImageName,
                                                sal_Char *pszArguments[],
                                                oslProcessOption Options,
                                                oslSecurity Security,
                                                sal_Char *pszDirectory,
                                                sal_Char *pszEnvironments[],
                                                oslProcess *pProcess,
												oslFileHandle	*pInputWrite,
												oslFileHandle	*pOutputRead,
												oslFileHandle	*pErrorRead
												)
{
    int     i;
	sal_Char    path[PATH_MAX + 1];
	ProcessData Data;
	oslThread hThread;

    path[0] = '\0';
    
    memset(&Data,0,sizeof(ProcessData));
	Data.m_pInputWrite = pInputWrite;
	Data.m_pOutputRead = pOutputRead;
	Data.m_pErrorRead = pErrorRead;

	if (pszImageName == NULL)
		pszImageName = pszArguments[0];

	OSL_ASSERT(pszImageName != NULL);

	if ( pszImageName == 0 )
	{
		return osl_Process_E_NotFound;
	}

	if ((Options & osl_Process_SEARCHPATH) &&
		(osl_searchPath_impl(pszImageName, NULL, '\0', path, sizeof(path)) == osl_Process_E_None))
		pszImageName = path;

	Data.m_pszArgs[0] = strdup(pszImageName);
	Data.m_pszArgs[1] = 0;

    if ( pszArguments != 0 )
    {
        for (i = 0; ((i + 2) < MAX_ARGS) && (pszArguments[i] != NULL); i++)
            Data.m_pszArgs[i+1] = strdup(pszArguments[i]);
        Data.m_pszArgs[i+2] = NULL;
    }

	Data.m_options = Options;
	Data.m_pszDir  = (pszDirectory != NULL) ? strdup(pszDirectory) : NULL;

	if (pszEnvironments != NULL)
	{
		for (i = 0; ((i + 1) < MAX_ENVS) &&  (pszEnvironments[i] != NULL); i++)
			Data.m_pszEnv[i] = strdup(pszEnvironments[i]);
	 	Data.m_pszEnv[i+1] = NULL;
	}
	else
	 	Data.m_pszEnv[0] = NULL;

	if (Security != NULL)
	{
	    Data.m_uid  = ((oslSecurityImpl*)Security)->m_pPasswd.pw_uid;
	    Data.m_gid  = ((oslSecurityImpl*)Security)->m_pPasswd.pw_gid;
		Data.m_name = ((oslSecurityImpl*)Security)->m_pPasswd.pw_name;
	}
	else
		Data.m_uid = (uid_t)-1;

	Data.m_pProcImpl = (oslProcessImpl*) malloc(sizeof(oslProcessImpl));
	Data.m_pProcImpl->m_pid = 0;
	Data.m_pProcImpl->m_terminated = osl_createCondition();
	Data.m_pProcImpl->m_pnext = NULL;

	if (ChildListMutex == NULL)
		ChildListMutex = osl_createMutex();

	Data.m_started = osl_createCondition();

	hThread = osl_createThread(ChildStatusProc, &Data);

	osl_waitCondition(Data.m_started, NULL);
    osl_destroyCondition(Data.m_started);

    for (i = 0; Data.m_pszArgs[i] != NULL; i++)
		  free((void *)Data.m_pszArgs[i]);

    for (i = 0; Data.m_pszEnv[i] != NULL; i++)
		  free((void *)Data.m_pszEnv[i]);

    if ( Data.m_pszDir != 0 )
    {
		free((void *)Data.m_pszDir);
    }

	osl_destroyThread(hThread);

	if (Data.m_pProcImpl->m_pid != 0)
	{
		*pProcess = Data.m_pProcImpl;

	 	if (Options & osl_Process_WAIT)
			osl_joinProcess(*pProcess);

		return osl_Process_E_None;
    }

	osl_destroyCondition(Data.m_pProcImpl->m_terminated);
	free(Data.m_pProcImpl);

	return osl_Process_E_Unknown;
}
コード例 #30
0
ファイル: t_cipher.c プロジェクト: CaoMomo/core
int SAL_CALL main (void)
{
    rtlCipher cipher;

    /* ECB */
    cipher = rtl_cipher_create (rtl_Cipher_AlgorithmBF, rtl_Cipher_ModeECB);
    OSL_ASSERT(cipher != 0);
    if (cipher != 0)
    {
        rtlCipherError result;
        sal_uInt8      ecb_in[40], ecb_out[40];
        sal_uInt32     length = strlen(cbc_data) + 1;

        result = rtl_cipher_init (
            cipher, rtl_Cipher_DirectionBoth,
            cbc_key, sizeof(cbc_key), NULL, 0);
        OSL_ASSERT(result == rtl_Cipher_E_None);

        memset (ecb_out, 0, sizeof(ecb_out));
        result = rtl_cipher_encode (
            cipher, cbc_data, length, ecb_out, sizeof(ecb_out));
        OSL_ASSERT(result == rtl_Cipher_E_None);
        OSL_ASSERT(memcmp (ecb_out, ecb_ok, sizeof(ecb_ok)) == 0);

        memset (ecb_in,  0, sizeof(ecb_in));
        result = rtl_cipher_decode (
            cipher, ecb_out, length, ecb_in, sizeof(ecb_in));
        OSL_ASSERT(result == rtl_Cipher_E_None);
        OSL_ASSERT(memcmp (ecb_in, cbc_data, length) == 0);

        rtl_cipher_destroy (cipher);
    }

    /* CBC */
    cipher = rtl_cipher_create (rtl_Cipher_AlgorithmBF, rtl_Cipher_ModeCBC);
    OSL_ASSERT(cipher != 0);
    if (cipher != 0)
    {
        rtlCipherError result;
        sal_uInt8      cbc_in[40], cbc_out[40];
        sal_uInt32     length = strlen(cbc_data) + 1;

        result = rtl_cipher_init (
            cipher, rtl_Cipher_DirectionEncode,
            cbc_key, sizeof(cbc_key), cbc_iv, sizeof(cbc_iv));
        OSL_ASSERT(result == rtl_Cipher_E_None);

        memset (cbc_out, 0, sizeof(cbc_out));
        result = rtl_cipher_encode (
            cipher, cbc_data, length, cbc_out, sizeof(cbc_out));
        OSL_ASSERT(result == rtl_Cipher_E_None);
        OSL_ASSERT(memcmp (cbc_out, cbc_ok, sizeof(cbc_ok)) == 0);

        result = rtl_cipher_init (
            cipher, rtl_Cipher_DirectionDecode,
            cbc_key, sizeof(cbc_key), cbc_iv, sizeof(cbc_iv));
        OSL_ASSERT(result == rtl_Cipher_E_None);

        memset (cbc_in,  0, sizeof(cbc_in));
        result = rtl_cipher_decode (
            cipher, cbc_out, length, cbc_in, sizeof(cbc_in));
        OSL_ASSERT(result == rtl_Cipher_E_None);
        OSL_ASSERT(memcmp (cbc_in, cbc_data, length) == 0);

        rtl_cipher_destroy (cipher);
     }

    /* CFB */
    cipher = rtl_cipher_create (rtl_Cipher_AlgorithmBF, rtl_Cipher_ModeStream);
    OSL_ASSERT(cipher != 0);
    if (cipher != 0)
    {
        rtlCipherError result;
        sal_uInt8      cfb_in[40], cfb_out[40];
        sal_uInt32     length = strlen(cbc_data) + 1;

        result = rtl_cipher_init (
            cipher, rtl_Cipher_DirectionEncode,
            cbc_key, sizeof(cbc_key), cbc_iv, sizeof(cbc_iv));
        OSL_ASSERT(result == rtl_Cipher_E_None);

        memset (cfb_out, 0, sizeof(cfb_out));
        result = rtl_cipher_encode (
            cipher, cbc_data, length, cfb_out, sizeof(cfb_out));
        OSL_ASSERT(result == rtl_Cipher_E_None);
        OSL_ASSERT(memcmp (cfb_out, cfb_ok, sizeof(cfb_ok)) == 0);

        result = rtl_cipher_init (
            cipher, rtl_Cipher_DirectionDecode,
            cbc_key, sizeof(cbc_key), cbc_iv, sizeof(cbc_iv));
        OSL_ASSERT(result == rtl_Cipher_E_None);

        memset (cfb_in,  0, sizeof(cfb_in));
        result = rtl_cipher_decode (
            cipher, cfb_out, length, cfb_in, sizeof(cfb_in));
        OSL_ASSERT(result == rtl_Cipher_E_None);
        OSL_ASSERT(memcmp (cfb_in, cbc_data, length) == 0);

        rtl_cipher_destroy (cipher);
    }

    /* ARCFOUR */
    cipher = rtl_cipher_create (rtl_Cipher_AlgorithmARCFOUR, rtl_Cipher_ModeStream);
    OSL_ASSERT(cipher != 0);
    if (cipher != 0)
    {
        rtlCipherError result;
        sal_uInt8      arcfour_out[40];
        sal_Size       length;
        int            i, n;

        n = SAL_N_ELEMENTS(arcfour_data_len);
        for (i = 0; i < n; i++)
        {
            length = arcfour_data_len[i];

            result = rtl_cipher_init (
                cipher, rtl_Cipher_DirectionBoth,
                &(arcfour_key[i][1]), arcfour_key[i][0], 0, 0);
            OSL_ASSERT(result == rtl_Cipher_E_None);

            memset (arcfour_out, 0, sizeof(arcfour_out));
            result = rtl_cipher_encode (
                cipher, &(arcfour_data[i][0]), length,
                arcfour_out, sizeof(arcfour_out));
            OSL_ASSERT(result == rtl_Cipher_E_None);
            OSL_ASSERT(memcmp (arcfour_out, arcfour_ok[i], length) == 0);
        }

        n = arcfour_data_len[3];
        for (i = 1; i < n; i++)
        {
            length = i;

            result = rtl_cipher_init (
                cipher, rtl_Cipher_DirectionBoth,
                &(arcfour_key[3][1]), arcfour_key[3][0], 0, 0);
            OSL_ASSERT(result == rtl_Cipher_E_None);

            memset (arcfour_out, 0, sizeof(arcfour_out));
            result = rtl_cipher_encode (
                cipher, &(arcfour_data[3][0]), length,
                arcfour_out, sizeof(arcfour_out));
            OSL_ASSERT(result == rtl_Cipher_E_None);
            OSL_ASSERT(memcmp (arcfour_out, arcfour_ok[3], length) == 0);
            OSL_ASSERT(arcfour_out[length] == 0);
        }

        n = arcfour_data_len[3];
        for (i = 1; i < n; i++)
        {
            length = i;

            result = rtl_cipher_init (
                cipher, rtl_Cipher_DirectionBoth,
                &(arcfour_key[3][1]), arcfour_key[3][0], 0, 0);
            OSL_ASSERT(result == rtl_Cipher_E_None);

            memset (arcfour_out, 0, sizeof(arcfour_out));
            result = rtl_cipher_encode (
                cipher, &(arcfour_data[3][0]), length,
                &(arcfour_out[0]), sizeof(arcfour_out));
            OSL_ASSERT(result == rtl_Cipher_E_None);

            result = rtl_cipher_encode (
                cipher, &(arcfour_data[3][length]), n - length,
                &(arcfour_out[length]), sizeof(arcfour_out) - length);
            OSL_ASSERT(result == rtl_Cipher_E_None);

            OSL_ASSERT(memcmp (arcfour_out, arcfour_ok[3], length) == 0);
        }

        rtl_cipher_destroy (cipher);
    }

    /* Done */
    return 0;
}