示例#1
0
文件: string.c 项目: Sunmonds/wine
static void test_StrCpyW(void)
{
  WCHAR szSrc[256];
  WCHAR szBuff[256];
  const StrFormatSizeResult* result = StrFormatSize_results;


  while(result->value)
  {
    MultiByteToWideChar(0,0,result->byte_size_64,-1,szSrc,sizeof(szSrc)/sizeof(WCHAR));

    StrCpyW(szBuff, szSrc);
    ok(!StrCmpW(szSrc, szBuff), "Copied string %s wrong\n", result->byte_size_64);
    result++;
  }
}
示例#2
0
void xhn::wpath_node::search(const wchar_t* path)
{
	path_name = path;
	transform(path_name.begin(), path_name.end(), path_name.begin(), FWCharFormat());
    wstring search_path = path_name;
#if defined(_WIN32) || defined(_WIN64)
	if (search_path.size() && search_path[search_path.size() - 1] != L'\\') {
		search_path += L'\\';
	}
#elif defined(__APPLE__)
    if (search_path.size() && search_path[search_path.size() - 1] != L'/') {
		search_path += L'/';
	}
#else
#    error
#endif
#if defined(_WIN32) || defined(_WIN64)
	wstring tmp = search_path +  L"*";

	struct _wfinddata_t fd;
	long h = _wfindfirst(tmp.c_str(), &fd);
	int ret = 0;
	while (h != -1L && !ret)
	{
		if (StrCmpW(fd.name, L".") != 0 && StrCmpW(fd.name, L"..") != 0)
		{
			wpath_node_ptr child;
#ifdef USE_SMART_PTR
            child = VNEW wpath_node;
#else
            child = GC_ALLOC(wpath_node);
#endif
			child->search((search_path + fd.name).c_str());
			if (fd.attrib == 0x10) {
			    child->is_folder = true;
			}
			child->next = children;
			children = child;
		}
		ret = _wfindnext(h, &fd);
	}
	_findclose(h);
#elif defined(__APPLE__)
    Utf8 utf8(search_path.c_str());
    vector<string> subFolders;
    vector<string> paths;
    GetPaths(((string)utf8).c_str(), subFolders, paths);
    {
        vector<string>::iterator iter = subFolders.begin();
        vector<string>::iterator end = subFolders.end();
        for (; iter != end; iter++) {
            string& subFolder = *iter;
            Unicode uc16(subFolder.c_str());
            wpath_node_ptr child;
#ifdef USE_SMART_PTR
            child = VNEW wpath_node;
#else
            child = GC_ALLOC(wpath_node);
#endif
            child->search(((wstring)uc16).c_str());
            child->is_folder = true;
            child->next = children;
			children = child;
        }
    }
    {
        vector<string>::iterator iter = paths.begin();
        vector<string>::iterator end = paths.end();
        for (; iter != end; iter++) {
            string& path = *iter;
            Unicode uc16(path.c_str());
            wpath_node_ptr child;
#ifdef USE_SMART_PTR
            child = VNEW wpath_node;
#else
            child = GC_ALLOC(wpath_node);
#endif
            child->path_name = uc16;
            child->is_folder = false;
            child->next = children;
			children = child;
        }
    }
#else
#    error
#endif
}
示例#3
0
long Cx_CfgRecord::SubmitRecord()
{
    if (m_arrValue.empty())
        return 0;

    std::vector<FieldValue> arrValue(m_arrValue);
    std::wostringstream sql, ssField, ssValues;

    m_arrValue.clear();

    if (m_bAdd)
    {
        ASSERT(DbFunc::IsDBName(m_wstrSQL.c_str()));

        sql << L"INSERT INTO " << m_wstrSQL << L" (";
        ssValues << L") VALUES (";
    }
    else
    {
        ASSERT(StrStrIW(m_wstrSQL.c_str(), L"SELECT ") == m_wstrSQL.c_str());

        const wchar_t* pszFrom = StrStrIW(m_wstrSQL.c_str(), L"FROM ");
        ASSERT_MESSAGE(pszFrom != NULL, "The SQL command must contains 'FROM' keyword.");

        std::wstring table(DbFunc::GetLevel1Name(pszFrom + 5));
        sql << L"UPDATE " << table;
        ssValues << L" SET ";
    }

    std::vector<FieldValue>::iterator it = arrValue.begin();
    for (long i = 0; it != arrValue.end(); ++it, ++i)
    {
        std::wstring wstrField(it->first);
        std::wstring wstrValue(it->second);
        ASSERT(!wstrValue.empty());

        if (StrCmpW(L"@NEWID", wstrValue.c_str()) == 0)
        {
            ASSERT(m_bAdd);

            m_wstrKeyField = wstrField;
            m_nKeyNewID = 0;
            if (!m_pDB->GetRecordNewID(m_nKeyNewID, m_wstrSQL, wstrField))
            {
                return 0;
            }

            wchar_t szNum[35];
            _ltow_s(m_nKeyNewID, szNum, _countof(szNum), 10);
            wstrValue = szNum;
        }
        else if (L'@' == wstrValue[0])
        {
            wstrValue = GetSQLFunc(wstrValue.c_str() + 1, m_pDB->GetSQLParser());
        }

        if (i > 0)
        {
            ssField << L",";
            ssValues << L",";
        }
        if (m_bAdd)
        {
            ssField << wstrField;
            ssValues << wstrValue;
        }
        else
        {
            ssValues << wstrField << L"=" << wstrValue;
        }
    }

    if (m_bAdd)
    {
        sql << ssField.str() << ssValues.str() << L") ";
    }
    else
    {
        sql << ssValues.str();

        const wchar_t* pszWhere = StrStrIW(m_wstrSQL.c_str(), L" WHERE");
        if (pszWhere != NULL)
        {
            sql << pszWhere;
        }
    }

    bool bRet = false;
    long nAffected = 0;

    try
    {
        bRet = (m_pDB->ExecuteSQL(sql.str().c_str(), __FILE__, __LINE__) != NULL);
        nAffected = m_pDB->GetRecordsAffected();
    }
    CATCH_DB_STR_ERROR;

    return nAffected;
}
示例#4
0
//////////////////////////////////////////////////////////
//
// HandleDuplicateLaunching
//
// Handle duplicate launching, or running from mtasa:// URI ?
//
//////////////////////////////////////////////////////////
void HandleDuplicateLaunching( void )
{
    LPSTR lpCmdLine = GetCommandLine();

    int iRecheckTimeLimit = 2000;
    while ( ! CreateSingleInstanceMutex () )
    {
        if ( strcmp ( lpCmdLine, "" ) != 0 )
        {
            HWND hwMTAWindow = FindWindow( NULL, "MTA: San Andreas" );
#ifdef MTA_DEBUG
            if( hwMTAWindow == NULL )
                hwMTAWindow = FindWindow( NULL, "MTA: San Andreas [DEBUG]" );
#endif
            if( hwMTAWindow != NULL )
            {
                LPWSTR szCommandLine = GetCommandLineW ();
                int numArgs;
                LPWSTR* aCommandLineArgs = CommandLineToArgvW ( szCommandLine, &numArgs );
                for ( int i = 0; i < numArgs; ++i )
                {
                    if ( StrCmpW ( aCommandLineArgs[i], L"-c" ) == 0 && numArgs > i )
                    {
                        WString wideConnectInfo = aCommandLineArgs[i + 1];
                        SString strConnectInfo = ToUTF8 ( wideConnectInfo );

                        COPYDATASTRUCT cdStruct;
                        cdStruct.cbData = strConnectInfo.length () + 1;
                        cdStruct.lpData = const_cast<char *> ( strConnectInfo.c_str () );
                        cdStruct.dwData = URI_CONNECT;

                        SendMessage( hwMTAWindow, WM_COPYDATA, NULL, (LPARAM)&cdStruct );
                        break;
                    }
                }

                
            }
            else
            {
                if ( iRecheckTimeLimit > 0 )
                {
                    // Sleep a little bit and check the mutex again
                    Sleep ( 500 );
                    iRecheckTimeLimit -= 500;
                    continue;
                }
                SString strMessage;
                strMessage += _(    "Trouble restarting MTA:SA\n\n"
                                    "If the problem persists, open Task Manager and\n"
                                    "stop the 'gta_sa.exe' and 'Multi Theft Auto.exe' processes\n\n\n"
                                    "Try to launch MTA:SA again?" );
                if ( MessageBoxUTF8( 0, strMessage, _("Error")+_E("CL04"), MB_ICONWARNING | MB_YESNO | MB_TOPMOST  ) == IDYES ) // Trouble restarting MTA:SA
                {
                    TerminateGTAIfRunning ();
                    TerminateOtherMTAIfRunning ();
                    ShellExecuteNonBlocking( "open", PathJoin ( GetMTASAPath (), MTA_EXE_NAME ), lpCmdLine );
                }
                return ExitProcess( EXIT_ERROR );
            }
        }
        else
        {
            if ( !IsGTARunning () && !IsOtherMTARunning () )
            {
                MessageBoxUTF8 ( 0, _("Another instance of MTA is already running.\n\nIf this problem persists, please restart your computer"), _("Error")+_E("CL05"), MB_ICONERROR | MB_TOPMOST  );
            }
            else
            if ( MessageBoxUTF8( 0, _("Another instance of MTA is already running.\n\nDo you want to terminate it?"), _("Error")+_E("CL06"), MB_ICONQUESTION | MB_YESNO | MB_TOPMOST  ) == IDYES )
            {
                TerminateGTAIfRunning ();
                TerminateOtherMTAIfRunning ();
                ShellExecuteNonBlocking( "open", PathJoin ( GetMTASAPath (), MTA_EXE_NAME ), lpCmdLine );
            }
        }
        return ExitProcess( EXIT_ERROR );
    }
}
示例#5
0
static DWORD Dde_OnExecute(HCONV hconv, HSZ hszTopic, HDDEDATA hdata)
{
    WCHAR szTopic[MAX_PATH];
    WCHAR szCommand[MAX_PATH];
    WCHAR *pszCommand;

    DdeQueryStringW(dwDDEInst, hszTopic, szTopic, _countof(szTopic), CP_WINUNICODE);

    pszCommand = (WCHAR*) DdeAccessData(hdata, NULL);
    if (!pszCommand)
        return DDE_FNOTPROCESSED;

    StringCchCopyW(szCommand, _countof(szCommand), pszCommand);

    DdeUnaccessData(hdata);

    TRACE("Dde_OnExecute: hconv=%p, topic=%S, command=%S\n", hconv, szTopic, pszCommand);

    /*
    [ViewFolder("%l", %I, %S)]    -- Open a folder in standard mode
    [ExploreFolder("%l", %I, %S)] -- Open a folder in "explore" mode (file tree is shown to the left by default)
    [FindFolder("%l", %I)]        -- Open a folder in "find" mode (search panel is shown to the left by default)
    [ShellFile("%1","%1",%S)]     -- Execute the contents of the specified .SCF file

    Approximate grammar (Upper names define rules, <lower> names define terminals, single-quotes are literals):

        Rules
            Command = ('[' Function ']') | Function
            Function = <identifier> '(' Parameters ')'
            Parameters = (<quoted-string> (',' <idlist> (',' <number>)?)?)?

        Terminals
            <identifier> =  [a-zA-Z]+
            <quoted-string> = \"([^\"]|\\.)\"
            <idlist> = \:[0-9]+\:[0-9]+
            <number> = [0-9]+
    */

    WCHAR Command[MAX_PATH] = L"";
    WCHAR Path[MAX_PATH] = L"";
    LPITEMIDLIST IdList = NULL;
    INT UnknownParameter = 0;

    // Simplified parsing (assumes the command will not be TOO broken):

    PWSTR cmd = szCommand;
    //    1. if starts with [, skip first char
    if (*cmd == L'[')
        cmd++;

    if (*cmd == L']')
    {
        ERR("Empty command. Nothing to run.\n");
        return DDE_FNOTPROCESSED;
    }

    // Read until first (, and take text before ( as command name
    {
        PWSTR cmdEnd = StrChrW(cmd, L'(');

        if (!cmdEnd)
        {
            ERR("Could not find '('. Invalid command.\n");
            return DDE_FNOTPROCESSED;
        }

        *cmdEnd = 0;

        StringCchCopy(Command, _countof(Command), cmd);

        cmd = cmdEnd + 1;
    }

    // Read first param after (, expecting quoted string
    if (*cmd != L')')
    {
        // Copy unescaped string
        PWSTR dst = Path;
        BOOL isQuote = FALSE;

        PWSTR arg = cmd;

        while (*arg && (isQuote || *arg != L','))
        {
            if (*arg == L'"')
            {
                isQuote = !isQuote;
                if (isQuote && arg != cmd) // do not copy the " at the beginning of the string
                {
                    *(dst++) = L'"';
                }
            }
            else
            {
                *(dst++) = *arg;
            }

            arg++;
        }

        cmd = arg + 1;

        while (*cmd == L' ')
            cmd++;
    }

    // Read second param, expecting an idlist in shared memory
    if (*cmd != L')')
    {
        if (*cmd != ':')
        {
            ERR("Expected ':'. Invalid command.\n");
            return DDE_FNOTPROCESSED;
        }

        PWSTR idlistEnd = StrChrW(cmd, L',');

        if (!idlistEnd)
            idlistEnd = StrChrW(cmd, L')');

        if (!idlistEnd)
        {
            ERR("Expected ',' or ')'. Invalid command.\n");
            return DDE_FNOTPROCESSED;
        }

        IdList = _ILReadFromSharedMemory(cmd);

        cmd = idlistEnd + 1;
    }

    // Read third param, expecting an integer
    if (*cmd != L')')
    {
        UnknownParameter = StrToIntW(cmd);
    }

    TRACE("Parse end: cmd=%S, S=%d, pidl=%p, path=%S\n", Command, UnknownParameter, IdList, Path);

    // Find handler in list
    for (int i = 0; i < HandlerListLength; i++)
    {
        DDECommandHandler & handler = HandlerList[i];
        if (StrCmpW(handler.Command, Command) == 0)
        {
            return handler.Handler(Command, Path, IdList, UnknownParameter);
        }
    }

    // No handler found
    ERR("Unknown command %S\n", Command);
    return DDE_FNOTPROCESSED;
}
示例#6
0
文件: keys-win.c 项目: gnutls/gnutls
/*-
 * _gnutls_privkey_import_system:
 * @pkey: The private key
 * @url: The URL of the key
 *
 * This function will import the given private key to the abstract
 * #gnutls_privkey_t type. 
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.4.0
 *
 -*/
int _gnutls_privkey_import_system_url(gnutls_privkey_t pkey, const char *url)
{
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
    return gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);
#else
	uint8_t id[MAX_WID_SIZE];
	HCERTSTORE store = NULL;
	size_t id_size;
	const CERT_CONTEXT *cert = NULL;
	CRYPT_HASH_BLOB blob;
	CRYPT_KEY_PROV_INFO *kpi = NULL;
	NCRYPT_KEY_HANDLE nc = NULL;
	HCRYPTPROV hCryptProv = NULL;
	NCRYPT_PROV_HANDLE sctx = NULL;
	DWORD kpi_size;
	SECURITY_STATUS r;
	int ret, enc_too = 0;
	WCHAR algo_str[64];
	DWORD algo_str_size = 0;
	priv_st *priv;
	DWORD i, dwErrCode = 0;

	if (ncrypt_init == 0)
		return gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);

	if (url == NULL)
		return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);

	priv = gnutls_calloc(1, sizeof(*priv));
	if (priv == NULL)
		return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);

	id_size = sizeof(id);
	ret = get_id(url, id, &id_size, 0);
	if (ret < 0)
		return gnutls_assert_val(ret);

	blob.cbData = id_size;
	blob.pbData = id;

	store = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER, L"MY");
	if (store == NULL) {
		gnutls_assert();
		ret = GNUTLS_E_FILE_ERROR;
		goto cleanup;
	}

	cert = CertFindCertificateInStore(store,
					  X509_ASN_ENCODING,
					  0,
					  CERT_FIND_KEY_IDENTIFIER,
					  &blob, NULL);

	if (cert == NULL) {
		char buf[64];
		_gnutls_debug_log("cannot find ID: %s from %s\n",
				  _gnutls_bin2hex(id, id_size,
						  buf, sizeof(buf), NULL), url);
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	kpi_size = 0;
	r = CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
					      NULL, &kpi_size);
	if (r == 0) {
		_gnutls_debug_log("error in getting context: %d from %s\n",
				  (int)GetLastError(), url);
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	kpi = gnutls_malloc(kpi_size);
	if (kpi == NULL) {
		gnutls_assert();
		ret = GNUTLS_E_MEMORY_ERROR;
		goto cleanup;
	}

	r = CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
					      kpi, &kpi_size);
	if (r == 0) {
		_gnutls_debug_log("error in getting context: %d from %s\n",
				  (int)GetLastError(), url);
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	r = pNCryptOpenStorageProvider(&sctx, kpi->pwszProvName, 0);
	if (!FAILED(r)) {	/* if this works carry on with CNG */

		r = pNCryptOpenKey(sctx, &nc, kpi->pwszContainerName, 0, 0);
		if (FAILED(r)) {
			ret =
			    gnutls_assert_val
			    (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
			goto cleanup;
		}

		r = pNCryptGetProperty(nc, NCRYPT_ALGORITHM_PROPERTY,
				       (BYTE *) algo_str, sizeof(algo_str),
				       &algo_str_size, 0);
		if (FAILED(r)) {
			ret =
			    gnutls_assert_val
			    (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
			goto cleanup;
		}

		if (StrCmpW(algo_str, BCRYPT_RSA_ALGORITHM) == 0) {
			priv->pk = GNUTLS_PK_RSA;
			priv->sign_algo = GNUTLS_SIGN_RSA_SHA256;
			enc_too = 1;
		} else if (StrCmpW(algo_str, BCRYPT_DSA_ALGORITHM) == 0) {
			priv->pk = GNUTLS_PK_DSA;
			priv->sign_algo = GNUTLS_SIGN_DSA_SHA1;
		} else if (StrCmpW(algo_str, BCRYPT_ECDSA_P256_ALGORITHM) == 0) {
			priv->pk = GNUTLS_PK_EC;
			priv->sign_algo = GNUTLS_SIGN_ECDSA_SHA256;
		} else if (StrCmpW(algo_str, BCRYPT_ECDSA_P384_ALGORITHM) == 0) {
			priv->pk = GNUTLS_PK_EC;
			priv->sign_algo = GNUTLS_SIGN_ECDSA_SHA384;
		} else if (StrCmpW(algo_str, BCRYPT_ECDSA_P521_ALGORITHM) == 0) {
			priv->pk = GNUTLS_PK_EC;
			priv->sign_algo = GNUTLS_SIGN_ECDSA_SHA512;
		} else {
			_gnutls_debug_log("unknown key algorithm: %ls\n",
					  algo_str);
			ret = gnutls_assert_val(GNUTLS_E_UNKNOWN_PK_ALGORITHM);
			goto cleanup;
		}
		priv->nc = nc;

		ret = gnutls_privkey_import_ext3(pkey, priv, cng_sign,
						 (enc_too !=
						  0) ? cng_decrypt : NULL,
						 cng_deinit, cng_info, 0);
		if (ret < 0) {
			gnutls_assert();
			goto cleanup;
		}
	} else {
		/* this should be CAPI */
		_gnutls_debug_log
		    ("error in opening CNG keystore: %x from %ls\n", (int)r,
		     kpi->pwszProvName);

		if (CryptAcquireContextW(&hCryptProv,
					 kpi->pwszContainerName,
					 kpi->pwszProvName,
					 kpi->dwProvType, kpi->dwFlags)) {
			for (i = 0; i < kpi->cProvParam; i++)
				if (!CryptSetProvParam(hCryptProv,
						       kpi->rgProvParam[i].
						       dwParam,
						       kpi->rgProvParam[i].
						       pbData,
						       kpi->rgProvParam[i].
						       dwFlags)) {
					dwErrCode = GetLastError();
					break;
				};
		} else {
			dwErrCode = GetLastError();
		}

		if (ERROR_SUCCESS != dwErrCode) {
			_gnutls_debug_log
			    ("error in getting cryptprov: %d from %s\n",
			     (int)GetLastError(), url);
			ret =
			    gnutls_assert_val
			    (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
			goto cleanup;
		}

		{
			BYTE buf[100 + sizeof(PROV_ENUMALGS_EX) * 2];
			PROV_ENUMALGS_EX *pAlgo = (PROV_ENUMALGS_EX *) buf;
			DWORD len = sizeof(buf);

			if (CryptGetProvParam
			    (hCryptProv, PP_ENUMALGS_EX, buf, &len,
			     CRYPT_FIRST)) {
				DWORD hash = 0;
				do {
					switch (pAlgo->aiAlgid) {
					case CALG_RSA_SIGN:
						priv->pk = GNUTLS_PK_RSA;
						enc_too = 1;
						break;
					case CALG_DSS_SIGN:
						priv->pk =
						    priv->pk ==
						    GNUTLS_PK_RSA ?
						    GNUTLS_PK_RSA :
						    GNUTLS_PK_DSA;
						break;
					case CALG_SHA1:
						hash = 1;
						break;
					case CALG_SHA_256:
						hash = 256;
						break;
					default:
						break;
					}

					len = sizeof(buf);	// reset the buffer size
				} while (CryptGetProvParam
					 (hCryptProv, PP_ENUMALGS_EX, buf, &len,
					  CRYPT_NEXT));

				if (priv->pk == GNUTLS_PK_DSA)
					priv->sign_algo = GNUTLS_SIGN_DSA_SHA1;
				else
					priv->sign_algo =
					    (hash >
					     1) ? GNUTLS_SIGN_RSA_SHA256 :
					    GNUTLS_SIGN_RSA_SHA1;
			}
		}

		priv->hCryptProv = hCryptProv;
		priv->dwKeySpec = kpi->dwKeySpec;

		ret = gnutls_privkey_import_ext3(pkey, priv, capi_sign,
						 (enc_too !=
						  0) ? capi_decrypt : NULL,
						 capi_deinit, capi_info, 0);
		if (ret < 0) {
			gnutls_assert();
			goto cleanup;
		}
	}
	ret = 0;
 cleanup:
	if (ret < 0) {
		if (nc != 0)
			pNCryptFreeObject(nc);
		if (hCryptProv != 0)
			CryptReleaseContext(hCryptProv, 0);
		gnutls_free(priv);
	}
	if (sctx != 0)
		pNCryptFreeObject(sctx);

	gnutls_free(kpi);

	if (cert != 0)
		CertFreeCertificateContext(cert);

	CertCloseStore(store, 0);
	return ret;
#endif
}
示例#7
0
/*-
 * _gnutls_privkey_import_system:
 * @pkey: The private key
 * @url: The URL of the key
 *
 * This function will import the given private key to the abstract
 * #gnutls_privkey_t type. 
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
 *   negative error value.
 *
 * Since: 3.4.0
 *
 -*/
int
_gnutls_privkey_import_system_url(gnutls_privkey_t pkey,
			          const char *url)
{
	uint8_t id[MAX_WID_SIZE];
	HCERTSTORE store = NULL;
	size_t id_size;
	const CERT_CONTEXT *cert = NULL;
	CRYPT_HASH_BLOB blob;
	CRYPT_KEY_PROV_INFO *kpi = NULL;
	NCRYPT_KEY_HANDLE nc = NULL;
	NCRYPT_PROV_HANDLE sctx = NULL;
	DWORD kpi_size;
	SECURITY_STATUS r;
	int ret, enc_too = 0;
	WCHAR algo_str[64];
	DWORD algo_str_size = 0;
	priv_st *priv;

	if (ncrypt_init == 0)
		return gnutls_assert_val(GNUTLS_E_UNIMPLEMENTED_FEATURE);

	if (url == NULL)
		return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);

	priv = gnutls_calloc(1, sizeof(*priv));
	if (priv == NULL)
		return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);

	id_size = sizeof(id);
	ret = get_id(url, id, &id_size, 0);
	if (ret < 0)
		return gnutls_assert_val(ret);

	blob.cbData = id_size;
	blob.pbData = id;

	store = CertOpenSystemStore(0, "MY");
	if (store == NULL) {
		gnutls_assert();
		ret = GNUTLS_E_FILE_ERROR;
		goto cleanup;
	}

	cert = CertFindCertificateInStore(store,
				X509_ASN_ENCODING,
				0,
				CERT_FIND_KEY_IDENTIFIER,
				&blob,
				NULL);

	if (cert == NULL) {
		char buf[64];
		_gnutls_debug_log("cannot find ID: %s from %s\n",
			      _gnutls_bin2hex(id, id_size,
					      buf, sizeof(buf), NULL),
				url);
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	kpi_size = 0;
	r = CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
					      NULL, &kpi_size);
	if (r == 0) {
		_gnutls_debug_log("error in getting context: %d from %s\n",
			      	  (int)GetLastError(), url);
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	kpi = gnutls_malloc(kpi_size);
	if (kpi == NULL) {
		gnutls_assert();
		ret = GNUTLS_E_MEMORY_ERROR;
		goto cleanup;
	}

	r = CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
					      kpi, &kpi_size);
	if (r == 0) {
		_gnutls_debug_log("error in getting context: %d from %s\n",
			      	  (int)GetLastError(), url);
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	r = pNCryptOpenStorageProvider(&sctx, kpi->pwszProvName, 0);
	if (FAILED(r)) {
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	r = pNCryptOpenKey(sctx, &nc, kpi->pwszContainerName, 0, 0);
	if (FAILED(r)) {
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	r = pNCryptGetProperty(nc, NCRYPT_ALGORITHM_PROPERTY,
				(BYTE*)algo_str, sizeof(algo_str),
				&algo_str_size, 0);
	if (FAILED(r)) {
		ret = gnutls_assert_val(GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
		goto cleanup;
	}

	if (StrCmpW(algo_str, BCRYPT_RSA_ALGORITHM) == 0) {
		priv->pk = GNUTLS_PK_RSA;
		priv->sign_algo = GNUTLS_SIGN_RSA_SHA256;
		enc_too = 1;
	} else if (StrCmpW(algo_str, BCRYPT_DSA_ALGORITHM) == 0) {
		priv->pk = GNUTLS_PK_DSA;
		priv->sign_algo = GNUTLS_SIGN_DSA_SHA1;
	} else if (StrCmpW(algo_str, BCRYPT_ECDSA_P256_ALGORITHM) == 0) {
		priv->pk = GNUTLS_PK_EC;
		priv->sign_algo = GNUTLS_SIGN_ECDSA_SHA256;
	} else if (StrCmpW(algo_str, BCRYPT_ECDSA_P384_ALGORITHM) == 0) {
		priv->pk = GNUTLS_PK_EC;
		priv->sign_algo = GNUTLS_SIGN_ECDSA_SHA384;
	} else if (StrCmpW(algo_str, BCRYPT_ECDSA_P521_ALGORITHM) == 0) {
		priv->pk = GNUTLS_PK_EC;
		priv->sign_algo = GNUTLS_SIGN_ECDSA_SHA512;
	} else {
		_gnutls_debug_log("unknown key algorithm: %ls\n", algo_str);
		ret = gnutls_assert_val(GNUTLS_E_UNKNOWN_PK_ALGORITHM);
		goto cleanup;
	}
	priv->nc = nc;

	ret = gnutls_privkey_import_ext3(pkey, priv, cng_sign,
					 (enc_too!=0)?cng_decrypt:NULL,
					 cng_deinit,
					 cng_info, 0);
	if (ret < 0) {
		gnutls_assert();
		goto cleanup;
	}

	ret = 0;
 cleanup:
	if (ret < 0) {
		if (nc != 0)
			pNCryptFreeObject(nc);
		gnutls_free(priv);
	}
	if (sctx != 0)
		pNCryptFreeObject(sctx);

	gnutls_free(kpi);
	CertCloseStore(store, 0);
	return ret;
}
示例#8
0
ApplicationState *ScoreKeeper::GetApplicationState(
		IN LPCWSTR InImageFilePath OPTIONAL,
		IN ULONG StateId OPTIONAL)
{
	std::map<ULONG, ApplicationState *>::iterator It;
	ApplicationState *State = NULL;

	if (++ExpirationCount % 100 == 0)
		ExpireStaleStates();

	//
	// If a state identifier was supplied, use that in preference.
	//
	if (StateId)
	{
		if ((It = ApplicationStateHash.find(
				StateId)) != ApplicationStateHash.end())
			State = (*It).second;
	}
	//
	// Otherwise, try to use the image file path if it was provided.
	//
	else if (InImageFilePath)
	{
		for (It = ApplicationStateHash.begin();
		     It != ApplicationStateHash.end();
		     It++)
		{
			if (!StrCmpW(
					(*It).second->GetImageFilePath(),
					InImageFilePath))
			{
				State = (*It).second;
				break;
			}
		}
	}

	//
	// If we couldn't find the state and an image file path was supplied, create
	// a new one.
	//
	if ((!State) &&
	    (InImageFilePath))
	{
		try
		{
			State = new ApplicationState(
					++CurrentStateId,
					InImageFilePath);
		} catch (...)
		{
		}

		//
		// Add its association to the hash.
		//
		if (State)
			ApplicationStateHash[State->GetStateId()] = State;
	}

	return State;
}